Skip to content

feat(site): show AI spend per organization - #32204

Merged
SasSwart merged 4 commits into
aigov-766/org-member-ai-spendfrom
aigov-766/user-dropdown-org-spend
Nov 24, 2026
Merged

SasSwart merged 4 commits into
aigov-766/org-member-ai-spendfrom
aigov-766/user-dropdown-org-spend

Conversation

@SasSwart

@SasSwart SasSwart commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

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/spend for the site-wide spend, as before, and GET /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.

  • Organization selector: appears only when the per-organization response lists more than one organization. It's a menu item that expands a DropdownMenuRadioGroup inside 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 matches organization_id, or on the first entry if none matches. If a refetch drops the selected organization, it falls back the same way.
  • Avatar badge: the badge on the avatar, and its screen reader label, follow the selected organization.
  • Single organization, or no breakdown: users in one organization see the site-wide spend, as before. The menu also shows the site-wide spend, without a selector, while the per-organization request has no data, for example when it fails or the server predates it.
  • Exceeded state: any user at or over their limit, single-organization users included, sees an "AI spend" header with a red "Limit exceeded" label. Below the bar, the menu says when AI requests resume: "AI requests are paused until {period end}". A $0 budget counts as exceeded even with no spend, because AI Gateway blocks requests once spend reaches the limit. The shared getSeverity helper is unchanged, so other views still show $0 of $0 as normal. The normal and warning states look the same as before.
  • Invalid values: if the shown organization reports a negative spend or limit, the menu keeps the selector and shows "AI spend unavailable", so the user can still switch. A single-organization user with invalid values sees no spend section, as before.
  • Failed polls: when a refetch fails, the menu keeps the last spend and adds "Couldn't refresh AI spend:" followed by the server's error message, for whichever endpoint it's showing. Before, it hid the section, which would close an open selector while the user was choosing. UsageIndicator still hides spend on error.

A pure helper, getUserMenuSpend in viewedSpend.ts, decides which spend to show. The severity map moved into severityIndicators.tsx, next to a shared SeverityBadge. 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 getSeverity helper in site/src/utils/budget.ts still shows $0 of $0 as normal. This PR only changes the user menu. Two other screens use the shared helper:

  • The AI usage indicator on the Agents page (UsageIndicator) shows users their own spend. Should a $0 budget show as exceeded there too, to match the menu?
  • The group budget amounts (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.tsx checks 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

image

Organization picker with severity badges

image

Selected organization over its limit

image

AI spend unavailable for the selected organization

image

Generated by Coder Agents on behalf of @SasSwart.

@linear-code

linear-code Bot commented Nov 14, 2026

Copy link
Copy Markdown

AIGOV-766

@SasSwart
SasSwart added this pull request to stack #32205 November 14, 2026 12:50
@SasSwart
SasSwart temporarily deployed to docs-preview November 14, 2026 12:51 — with GitHub Actions Inactive
@github-actions

Copy link
Copy Markdown
Contributor

Docs preview

Links 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.

@SasSwart
SasSwart force-pushed the aigov-766/user-dropdown-org-spend branch from f496666 to da3823b Compare November 23, 2026 11:56
@SasSwart
SasSwart marked this pull request as ready for review November 23, 2026 12:38

@mollymaefraser mollymaefraser left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few Nits/Qs. Main change I think is needed is in UserDropdownAISpend.tsx lines 45-52.

Comment on lines +45 to +52
{exceeded && (
<div className="mt-1 text-xs text-content-primary">
AI requests are paused until{" "}
<span className="whitespace-nowrap">
{formatSpendPeriodEnd(periodEnd)}.
</span>
</div>
)}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"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).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 46cc81a

const error = menuSpend?.orgSelection
? byOrganizationQuery.error
: siteWideQuery.error;
const indicator = severityIndicators[getSpendSeverity(spend)];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +42 to +44
if (spend.spendLimit === 0) {
return "exceeded";
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 }],

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: There's no aria-controls. Also worth asking whether DropdownMenuSub was considered, since it keeps the parent menu open too.

SasSwart added a commit that referenced this pull request Nov 24, 2026
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>
SasSwart and others added 3 commits November 24, 2026 10:08
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.
@SasSwart
SasSwart force-pushed the aigov-766/user-dropdown-org-spend branch from da3823b to 7f3d163 Compare November 24, 2026 08:08
… 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 mollymaefraser left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

@SasSwart
SasSwart merged commit 4a7d214 into main Nov 24, 2026
32 checks passed
@SasSwart
SasSwart deleted the aigov-766/user-dropdown-org-spend branch November 24, 2026 09:53

This branch had an error being deployed

1 failed deployment
docs-preview — 46cc81a3 Deployed Nov 24, 2026 by SasSwart via cleanup #396
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants