feat: add the organization AI spend client method and report fixture (#29627)
Adds `API.getOrganizationAISpendUsers(organizationId, params)` for `GET
/api/v2/organizations/{organization}/ai/spend/users` (period, provider,
model, client filters plus `limit`/`offset`), the
`MockOrganizationAISpendReport` fixture, and a shared
`codersdk.MaxAISpendPeriodDays` constant that the enterprise export
handler now reads and that `make gen` emits into `typesGenerated.ts`.
The model-list endpoint also accepts a literal `model` prefix. The
backend escapes SQL LIKE characters, while `q` keeps its existing search
syntax. Supplying both nonempty parameters returns 400. The filter menu
adopts this parameter in #29632.
## Why
The frontend caps custom ranges at the same 31-day limit the server
enforces; one SDK constant keeps the two from drifting. The fixture is
what every later test and story renders. Literal model identifiers
should not require search-language quoting or SQL escaping in the
frontend.
## What to scrutinize
- `enterprise/coderd/aibridge.go`: `maxAISpendExportPeriod` is now
derived from the SDK constant, same value as before.
- `MockOrganizationAISpendUser` is not exported yet; the table PR
exports it for its stories (knip fails on exports without a consumer).
## Generated files
`site/src/api/typesGenerated.ts`, `coderd/apidoc/docs.go`,
`coderd/apidoc/swagger.json`, and `docs/reference/api/aigateway.md` via
`make gen`.
## Validation
`pnpm test src/api/api.test.ts -t getOrganizationAISpendUsers` (new
case), `go test ./enterprise/coderd/ -run TestAIBridgeListModels
-count=1 -v`, repository pre-commit including `make gen` with no drift.
Model tests cover literal punctuation, prefix matching, existing `q`
behavior, and conflicting parameters.
## Delivery record
Published head `8d9a4faa0aa` passed per-layer integration checks and
commit hooks. The composed head `d899228f798` passed format, check, full
frontend lint, 125 unit tests, and 86 story tests. Pre-push hooks were
skipped as requested. See #28964 for audit findings, their disposition,
and historical UAT limits. No exact-head live UAT or new independent
re-review is claimed.
## Stack context
PR 3 of 9. The stack adds a **User spend** page under **Admin settings**
> **AI** > **User spend**: total and per-user AI Gateway spend for one
organization over a reporting period, read from `GET
/api/v2/organizations/{organization}/ai/spend/users` (#29129, merged).
It is #28964 split into one-concern PRs. Historical UAT covers earlier
heads only; live UAT has not been rerun after these review fixes. Bottom
to top: DateRangePicker limits, shared dimension badge, API client
method, spend table, page view, page container, reporting period,
dimension filters, route and navigation (#28964).
> Xum prepared this PR on behalf of @ibetitsmike.
This commit is contained in:
1 parent
f7b93d341b
commit
80eee58d1d
10 files changed
+281
-2
No files matched your search
Generated
+14
@@ -770,6 +770,20 @@ const docTemplate = `{
|
||||
],
|
||||
"summary": "List AI Gateway models",
|
||||
"operationId": "list-ai-gateway-models",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Search query in the format ` + "`" + `key:value` + "`" + `. Available keys are: model. A bare term searches by model prefix.",
|
||||
"name": "q",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Literal model identifier prefix. Cannot be combined with q.",
|
||||
"name": "model",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
|
||||
Generated
+14
@@ -673,6 +673,20 @@
|
||||
"tags": ["AI Gateway"],
|
||||
"summary": "List AI Gateway models",
|
||||
"operationId": "list-ai-gateway-models",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Search query in the format `key:value`. Available keys are: model. A bare term searches by model prefix.",
|
||||
"name": "q",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Literal model identifier prefix. Cannot be combined with q.",
|
||||
"name": "model",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
|
||||
@@ -20,6 +20,9 @@ import (
|
||||
// $1,000,000 per member per budget period.
|
||||
const MaxAISpendLimitMicros int64 = 1_000_000_000_000
|
||||
|
||||
// MaxAISpendPeriodDays bounds explicit AI spend reporting windows.
|
||||
const MaxAISpendPeriodDays = 31
|
||||
|
||||
// AIBudgetLimitSource identifies which tier produced the user's
|
||||
// effective budget limit.
|
||||
type AIBudgetLimitSource string
|
||||
@@ -417,6 +420,36 @@ func (c *Client) AIBridgeGetSessionThreads(ctx context.Context, sessionID string
|
||||
return resp, ReadBodyAsJSON(res, &resp)
|
||||
}
|
||||
|
||||
// AIBridgeListModelsFilter narrows the distinct models visible to the caller.
|
||||
// @typescript-ignore AIBridgeListModelsFilter
|
||||
type AIBridgeListModelsFilter struct {
|
||||
// Limit defaults to 100, max is 1000.
|
||||
Pagination Pagination
|
||||
// Model keeps only identifiers starting with this literal prefix.
|
||||
Model string
|
||||
}
|
||||
|
||||
// AIBridgeListModels returns the distinct AI models visible to the caller.
|
||||
func (c *Client) AIBridgeListModels(ctx context.Context, filter AIBridgeListModelsFilter) ([]string, error) {
|
||||
res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/models", nil, filter.Pagination.asRequestOption(), func(r *http.Request) {
|
||||
if filter.Model == "" {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
q.Set("model", filter.Model)
|
||||
r.URL.RawQuery = q.Encode()
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, ReadBodyAsError(res)
|
||||
}
|
||||
var models []string
|
||||
return models, ReadBodyAsJSON(res, &models)
|
||||
}
|
||||
|
||||
// AIBridgeListClients returns the distinct AI clients visible to the caller.
|
||||
func (c *Client) AIBridgeListClients(ctx context.Context) ([]string, error) {
|
||||
res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/clients", nil)
|
||||
|
||||
Generated
+7
@@ -55,6 +55,13 @@ curl -X GET http://coder-server:8080/api/v2/ai-gateway/models \
|
||||
|
||||
Alias: also available at /api/v2/aibridge/models for backward compatibility.
|
||||
|
||||
### Parameters
|
||||
|
||||
| Name | In | Type | Required | Description |
|
||||
|---------|-------|--------|----------|----------------------------------------------------------------------------------------------------------|
|
||||
| `q` | query | string | false | Search query in the format `key:value`. Available keys are: model. A bare term searches by model prefix. |
|
||||
| `model` | query | string | false | Literal model identifier prefix. Cannot be combined with q. |
|
||||
|
||||
### Example responses
|
||||
|
||||
> 200 Response
|
||||
|
||||
@@ -46,7 +46,7 @@ const (
|
||||
maxGroupMembersAISpendUserIDs = 100
|
||||
// maxAISpendExportPeriod bounds an explicit AI spend export window to at
|
||||
// most 31 days, matching the maximum length of the monthly default period.
|
||||
maxAISpendExportPeriod = 31 * 24 * time.Hour
|
||||
maxAISpendExportPeriod = codersdk.MaxAISpendPeriodDays * 24 * time.Hour
|
||||
// The per-user spend report lists users, not events, so its pages are small.
|
||||
defaultOrganizationAISpendLimit = 10
|
||||
maxOrganizationAISpendLimit = 100
|
||||
@@ -503,6 +503,10 @@ func (api *API) aiBridgeGetSessionThreads(rw http.ResponseWriter, r *http.Reques
|
||||
httpapi.Write(ctx, rw, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// likePatternEscaper makes a string match itself under a Postgres LIKE
|
||||
// pattern, which uses backslash as its default escape character.
|
||||
var likePatternEscaper = strings.NewReplacer(`\`, `\\`, "%", `\%`, "_", `\_`)
|
||||
|
||||
// aiBridgeListModels returns all AI Bridge models a user can see.
|
||||
//
|
||||
// @Summary List AI Gateway models
|
||||
@@ -511,6 +515,8 @@ func (api *API) aiBridgeGetSessionThreads(rw http.ResponseWriter, r *http.Reques
|
||||
// @Security CoderSessionToken
|
||||
// @Produce json
|
||||
// @Tags AI Gateway
|
||||
// @Param q query string false "Search query in the format `key:value`. Available keys are: model. A bare term searches by model prefix."
|
||||
// @Param model query string false "Literal model identifier prefix. Cannot be combined with q."
|
||||
// @Success 200 {array} string
|
||||
// @Router /api/v2/ai-gateway/models [get]
|
||||
func (api *API) aiBridgeListModels(rw http.ResponseWriter, r *http.Request) {
|
||||
@@ -534,8 +540,15 @@ func (api *API) aiBridgeListModels(rw http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
queryStr := r.URL.Query().Get("q")
|
||||
filter, errs := searchquery.AIBridgeModels(queryStr, page)
|
||||
modelPrefix := r.URL.Query().Get("model")
|
||||
if queryStr != "" && modelPrefix != "" {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: "Query parameters \"q\" and \"model\" cannot be combined.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
filter, errs := searchquery.AIBridgeModels(queryStr, page)
|
||||
if len(errs) > 0 {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: "Invalid AI Gateway models search query.",
|
||||
@@ -543,6 +556,12 @@ func (api *API) aiBridgeListModels(rw http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
return
|
||||
}
|
||||
// The search grammar cannot carry every recorded identifier (quotes end a
|
||||
// quoted value) and the query matches with LIKE, so the explicit parameter
|
||||
// escapes the pattern characters to match the identifier literally.
|
||||
if modelPrefix != "" {
|
||||
filter.Model = likePatternEscaper.Replace(modelPrefix)
|
||||
}
|
||||
|
||||
models, err := api.Database.ListAIBridgeModels(ctx, filter)
|
||||
if err != nil {
|
||||
|
||||
@@ -1300,6 +1300,89 @@ func TestAIBridgeListSessions(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestAIBridgeListModels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dv := coderdtest.DeploymentValues(t)
|
||||
dv.AI.BridgeConfig.Enabled = serpent.Bool(true)
|
||||
client, db, firstUser := coderdenttest.NewWithDatabase(t, &coderdenttest.Options{
|
||||
Options: &coderdtest.Options{
|
||||
DeploymentValues: dv,
|
||||
},
|
||||
LicenseOptions: &coderdenttest.LicenseOptions{
|
||||
Features: license.Features{
|
||||
codersdk.FeatureAIBridge: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
now := dbtime.Now()
|
||||
endedAt := now.Add(time.Minute)
|
||||
models := []string{
|
||||
"us.anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
`=HYPERLINK("http://insecure/","invoice")`,
|
||||
"gpt-4",
|
||||
"gpt_4",
|
||||
"gpt%4",
|
||||
`gpt\4`,
|
||||
}
|
||||
for _, model := range models {
|
||||
dbgen.AIBridgeInterception(t, db, database.InsertAIBridgeInterceptionParams{
|
||||
InitiatorID: firstUser.UserID,
|
||||
StartedAt: now,
|
||||
Model: model,
|
||||
}, &endedAt)
|
||||
}
|
||||
dbgen.AIBridgeInterception(t, db, database.InsertAIBridgeInterceptionParams{
|
||||
InitiatorID: firstUser.UserID,
|
||||
StartedAt: now,
|
||||
Model: "gpt-5",
|
||||
}, nil)
|
||||
|
||||
t.Run("ModelMatchesLiterally", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
for _, model := range models {
|
||||
got, err := client.AIBridgeListModels(ctx, codersdk.AIBridgeListModelsFilter{Model: model})
|
||||
require.NoError(t, err, model)
|
||||
require.Equal(t, []string{model}, got, model)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ModelIsAPrefix", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
got, err := client.AIBridgeListModels(ctx, codersdk.AIBridgeListModelsFilter{Model: "gpt"})
|
||||
require.NoError(t, err)
|
||||
require.ElementsMatch(t, []string{"gpt-4", "gpt_4", "gpt%4", `gpt\4`}, got)
|
||||
})
|
||||
|
||||
t.Run("SearchQueryKeepsPatternMatching", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
res, err := client.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/models", nil, func(r *http.Request) {
|
||||
r.URL.RawQuery = "q=gpt_4"
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
||||
var got []string
|
||||
require.NoError(t, json.NewDecoder(res.Body).Decode(&got))
|
||||
require.ElementsMatch(t, []string{"gpt-4", "gpt_4", "gpt%4", `gpt\4`}, got)
|
||||
})
|
||||
|
||||
t.Run("RejectsSearchQueryWithModel", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
res, err := client.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/models", nil, func(r *http.Request) {
|
||||
r.URL.RawQuery = "q=gpt&model=gpt"
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
require.Equal(t, http.StatusBadRequest, res.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAIBridgeListClients(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
MockChatModelACL,
|
||||
MockMCPServerConfigACL,
|
||||
MockMCPServerConfigACLAvailable,
|
||||
MockOrganizationAISpendReport,
|
||||
MockProvisionerJob,
|
||||
MockStoppedWorkspace,
|
||||
MockTemplate,
|
||||
@@ -264,6 +265,51 @@ describe("api.ts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOrganizationAISpendUsers", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("passes the filters and page to the per-user spend endpoint", async () => {
|
||||
const getSpy = vi
|
||||
.spyOn(axiosInstance, "get")
|
||||
.mockResolvedValueOnce({ data: MockOrganizationAISpendReport });
|
||||
|
||||
const result = await API.getOrganizationAISpendUsers("my-org", {
|
||||
period_start: "2026-07-01T00:00:00Z",
|
||||
period_end: "2026-08-01T00:00:00Z",
|
||||
provider_name: "openai",
|
||||
limit: 10,
|
||||
offset: 20,
|
||||
});
|
||||
|
||||
expect(getSpy).toHaveBeenCalledTimes(1);
|
||||
const [url] = getSpy.mock.calls[0];
|
||||
expect(url).toContain("/api/v2/organizations/my-org/ai/spend/users?");
|
||||
expect(url).toContain("provider_name=openai");
|
||||
expect(url).toContain("limit=10");
|
||||
expect(url).toContain("offset=20");
|
||||
expect(result).toStrictEqual(MockOrganizationAISpendReport);
|
||||
});
|
||||
|
||||
it("omits a zero limit and offset so the server applies its defaults", async () => {
|
||||
const getSpy = vi
|
||||
.spyOn(axiosInstance, "get")
|
||||
.mockResolvedValueOnce({ data: MockOrganizationAISpendReport });
|
||||
|
||||
await API.getOrganizationAISpendUsers("my-org", {
|
||||
provider_name: "openai",
|
||||
limit: 0,
|
||||
offset: 0,
|
||||
});
|
||||
|
||||
const [url] = getSpy.mock.calls[0];
|
||||
expect(url).toBe(
|
||||
"/api/v2/organizations/my-org/ai/spend/users?provider_name=openai",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("update", () => {
|
||||
describe("given a running workspace", () => {
|
||||
it("stops with current version before starting with the latest version", async () => {
|
||||
|
||||
@@ -423,6 +423,9 @@ export class ParameterValidationError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
type OrganizationAISpendParams = TypesGen.OrganizationAISpendFilter &
|
||||
TypesGen.OrganizationAISpendPage;
|
||||
|
||||
export type GetProvisionerJobsParams = {
|
||||
status?: string;
|
||||
limit?: number;
|
||||
@@ -3103,6 +3106,25 @@ class ApiMethods {
|
||||
return response.data;
|
||||
};
|
||||
|
||||
getOrganizationAISpendUsers = async (
|
||||
organizationId: string,
|
||||
{ limit, offset, ...filter }: OrganizationAISpendParams,
|
||||
): Promise<TypesGen.OrganizationAISpendReport> => {
|
||||
// Like the Go SDK, a zero page value means the server default; the
|
||||
// endpoint rejects an explicit limit=0.
|
||||
const url = getURLWithSearchParams(
|
||||
`/api/v2/organizations/${organizationId}/ai/spend/users`,
|
||||
{
|
||||
...filter,
|
||||
limit: limit !== undefined && limit > 0 ? limit : undefined,
|
||||
offset: offset !== undefined && offset > 0 ? offset : undefined,
|
||||
},
|
||||
);
|
||||
const response =
|
||||
await this.axios.get<TypesGen.OrganizationAISpendReport>(url);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
getAIProviders = async (): Promise<TypesGen.AIProvider[]> => {
|
||||
const response = await this.axios.get<TypesGen.AIProvider[]>(
|
||||
"/api/v2/ai/providers",
|
||||
|
||||
Generated
+6
@@ -6126,6 +6126,12 @@ export const MaxAIModelPricesBytes = 1048576; // 1 MiB
|
||||
*/
|
||||
export const MaxAISpendLimitMicros = 1000000000000;
|
||||
|
||||
// From codersdk/aibridge.go
|
||||
/**
|
||||
* MaxAISpendPeriodDays bounds explicit AI spend reporting windows.
|
||||
*/
|
||||
export const MaxAISpendPeriodDays = 31;
|
||||
|
||||
// From codersdk/chats.go
|
||||
/**
|
||||
* MaxChatFileIDs is the number of most recent attachments a chat
|
||||
|
||||
@@ -5596,6 +5596,41 @@ export const MockAIProviderCopilot: TypesGen.AIProvider = {
|
||||
updated_at: "2026-05-14T10:00:00Z",
|
||||
};
|
||||
|
||||
const MockOrganizationAISpendUser: TypesGen.OrganizationAISpendUser = {
|
||||
user_id: MockUserOwner.id,
|
||||
username: MockUserOwner.username,
|
||||
name: "Test User",
|
||||
avatar_url: "https://avatars.githubusercontent.com/u/95932066?s=200&v=4",
|
||||
cost_micros: 2_500_000,
|
||||
unpriced_usage_count: 0,
|
||||
providers: ["anthropic", "openai"],
|
||||
clients: ["Claude Code", "Cursor"],
|
||||
models: ["claude-opus-4-6", "gpt-5.4"],
|
||||
};
|
||||
|
||||
export const MockOrganizationAISpendReport: TypesGen.OrganizationAISpendReport =
|
||||
{
|
||||
period_start: "2026-02-10T00:00:00Z",
|
||||
period_end: "2026-03-12T00:00:00Z",
|
||||
retention_start: "2026-01-11T15:30:00Z",
|
||||
count: 2,
|
||||
totals: { cost_micros: 3_500_000, unpriced_usage_count: 0 },
|
||||
users: [
|
||||
MockOrganizationAISpendUser,
|
||||
{
|
||||
...MockOrganizationAISpendUser,
|
||||
user_id: "5e1a2b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b",
|
||||
username: "alice",
|
||||
name: "Alice Liddell",
|
||||
avatar_url: "",
|
||||
cost_micros: 1_000_000,
|
||||
providers: ["anthropic"],
|
||||
clients: ["Unknown"],
|
||||
models: ["claude-opus-4-6"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const MockAIProviders: TypesGen.AIProvider[] = [
|
||||
MockAIProviderOpenAI,
|
||||
MockAIProviderAnthropic,
|
||||
|
||||
Reference in new issue
Block a user