Repository navigation
feat: add organization member AI spend endpoint - #32203
Conversation
Docs previewLinks open this pull request's preview at https://pr-32203.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. |
| ], | ||
| "summary": "Get organization member AI spend", | ||
| "operationId": "get-organization-member-ai-spend", | ||
| "parameters": [ |
There was a problem hiding this comment.
Should we be able to specify the period start/end in this endpoint? We don't need to for the current ticket, but they're useful for the API to have.
There was a problem hiding this comment.
Agree it's not needed for 766. Adding optional period_start/period_end query params later wouldn't break existing callers, so it seems fine to defer.
| // @Param organization path string true "Organization ID or name" | ||
| // @Param user path string true "User ID, username, or me" | ||
| // @Success 200 {object} codersdk.OrganizationMemberAISpendStatus | ||
| // @Router /api/v2/organizations/{organization}/members/{user}/ai/spend [get] |
There was a problem hiding this comment.
Should this start out as experimental?
There was a problem hiding this comment.
The user spend endpoint it mirrors is in /api/v2, so keeping them together seems consistent. Is anything about this shape likely to change?
| // @Param user path string true "User ID, username, or me" | ||
| // @Success 200 {object} codersdk.OrganizationMemberAISpendStatus | ||
| // @Router /api/v2/organizations/{organization}/members/{user}/ai/spend [get] | ||
| func (api *API) organizationMemberAISpendStatus(rw http.ResponseWriter, r *http.Request) { |
There was a problem hiding this comment.
Run this locally, view an example trace, and upload that to the PR description.
| r.Get("/organizations/{organization}/members/{user}/workspace-quota", api.workspaceQuota) | ||
| }) | ||
|
|
||
| r.Group(func(r chi.Router) { |
There was a problem hiding this comment.
Do we really need a new group for this?!
There was a problem hiding this comment.
The neighbouring workspace-quota group deliberately uses ExtractUserParam (so removed members still resolve) and has no feature check. This route needs ExtractOrganizationMemberParam and RequireFeatureMW(FeatureAIBridge), so a separate group looks right to me.
mollymaefraser
left a comment
There was a problem hiding this comment.
Only nits/praise so approving 👍
| CurrentSpendMicros: spend.SpendMicros, | ||
| } | ||
| if effectiveGroup.Limit != nil { | ||
| resp.EffectiveBudget = &codersdk.AIBudgetLimit{ |
There was a problem hiding this comment.
nit: this could use aiBudgetLimitToSDK from #32202 instead of building AIBudgetLimit by hand.
| // OrganizationMemberAISpendStatus is a user's AI spend snapshot inside a | ||
| // single organization, resolved the same way AI Gateway resolves a request | ||
| // made in that organization. | ||
| type OrganizationMemberAISpendStatus struct { |
There was a problem hiding this comment.
UserOrganizationAISpend and OrganizationMemberAISpendStatus carry nearly the same data. Could they share a type, or is the difference intentional?
| // but not the user gets a 404, as on the user spend endpoint. | ||
| budgetPolicy := codersdk.NewAIBudgetPolicyFromString(api.DeploymentValues.AI.BridgeConfig.BudgetPolicy) | ||
| effectiveGroup, ok, err := budget.ResolveUserEffectiveGroup(ctx, api.Database, member.UserID, uuid.NullUUID{UUID: org.ID, Valid: true}, budgetPolicy) | ||
| if httpapi.Is404Error(err) { |
There was a problem hiding this comment.
Returning 404 both when the user isn't a member and when the caller can't read them looks right, and the org admin 200 and 404 tests cover it well.
92d08ca to
1efd43b
Compare
Add GET /api/v2/organizations/{organization}/members/{user}/ai/spend,
which returns a user's effective AI budget and current-period spend in a
single organization. The budget is resolved scoped to that organization,
matching how AI Gateway resolves a request made there.
Authorization matches the user spend endpoint: dbauthz requires user
read, so users can read their own spend and admins with user read can
read anyone's. Non-members get a 404.
Refs AIGOV-766
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Organization admins can read every user, so only the organization and membership middleware keep them out of organizations they don't administer. Cover both sides of that boundary, and narrow the docs sentence on who can read a member's spend to match. Refs AIGOV-766 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1efd43b to
46b8af8
Compare
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](https://linear.app/codercom/issue/AIGOV-766) <details> <summary>Screenshots</summary> #### Multiple organizations <img width="2530" height="1800" alt="image" src="https://github.com/user-attachments/assets/8b29ca6b-78b8-4a50-a5d8-0f1892bfb509" /> #### Organization picker with severity badges <img width="2530" height="1800" alt="image" src="https://github.com/user-attachments/assets/58ecc2b2-d7f0-4517-aaa0-bac6306f7ffe" /> #### Selected organization over its limit <img width="2530" height="1800" alt="image" src="https://github.com/user-attachments/assets/e4ef8647-db88-44dd-9f7a-22111f92527c" /> #### AI spend unavailable for the selected organization <img width="2530" height="1800" alt="image" src="https://github.com/user-attachments/assets/bbd51bd1-c250-4e0a-ae86-819185855f89" /> </details> --- *Generated by Coder Agents on behalf of @SasSwart.* --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Adds
GET /api/v2/organizations/{organization}/members/{user}/ai/spend, which returns a user's effective AI budget and current-period spend inside one organization. Admins, and users themselves, can use it to look up spend in a specific organization.The endpoint resolves the budget inside that organization only, the same way AI Gateway resolves a request made there. The response has the same shape as the user spend endpoint, plus
organization_id.Users can read their own spend, and admins can read the spend of a user whose membership in that organization they can read. The endpoint returns 404 when the user isn't a member of the organization, or when the caller can't read the user. It requires the AI Governance license.
Organization admins can read every user, so only the organization and membership checks keep them out of other organizations. The tests cover both sides: an organization admin reading a member of their own organization (200) and of another organization (404).
Also adds
Client.OrganizationMemberAISpendStatustocodersdk, and links the endpoint fromcost-controls.md.Stacked on #32202, which adds
GET /users/{user}/ai/spend/organizations. Review only the last two commits here.Refs AIGOV-766
Generated by Coder Agents on behalf of @SasSwart.