Commit Graph
4624 Commits
Author SHA1 Message Date
Thomas Kosiewski 60cc826f2b feat: sign forwarded MCP identity headers (#29669) 2026-09-22 11:11:08 +02:00
Michael Suchacz efd8e8ca12 fix(coderd): require read and update chat permissions for delegated chat owners (#29684)
`POST /api/v2/chats` with `owner_id` (#29581) checks that the delegated
owner holds `chat:create` before creating the chat under the owner's
context. Creation also inserts the first message (`chat:update`) and
reads the chat back (`chat:read`) inside the same transaction, so an
owner whose custom organization role grants only `chat:create` passed
the preflight and then failed inside the transaction with a generic 403
instead of the intended 400 `Chat owner does not have permission to use
chats.` The transaction rolls back, so no chat is left behind; only the
status code and message were wrong.

The preflight now requires create, read, and update for the owner.
Regular organization members hold all three through the member role, so
this only changes the response for service accounts and custom roles
with partial chat grants.

Found by Codex on the 2.37 backport (#29683), which carries this same
commit. The code is identical on main.

## Validation

- `TestPostChats_OwnerID/OwnerWithCreateOnlyChatPermission`: red on the
unfixed head (403 instead of 400), green with the fix.
- `go test ./coderd/ -run 'TestPostChats|TestPatchChat' -count=1`: pass.
- Pre-commit hook (gen, fmt, lint, slim build) passed on this commit.

> Xum opened this PR on behalf of @ibetitsmike.
2026-09-21 20:05:43 +00:00
Michael Suchacz e35cbe2a7f fix(coderd/x/chatd): stream compaction summaries (#28886)
Chats could get permanently stuck once their context crossed the
compaction threshold on adaptive-thinking Claude models: every
compaction attempt failed with `compaction produced an empty summary`,
and both automatic and manual compaction take the same path, so the chat
could never recover.

## Problem

`compactionSummaryCall` deliberately set `MaxOutputTokens = nil` because
the summary request was non-streaming and the Anthropic SDK rejects
non-streaming requests whose `max_tokens` implies a completion longer
than ten minutes. But a nil cap makes fantasy's Anthropic provider
silently default to 4096 output tokens, and adaptive-thinking Claude
models can spend that entire budget on a thinking block, leaving zero
summary text.

## Fix

- Stream the compaction summary request. Streaming lifts the Anthropic
SDK's non-streaming duration restriction, which was the only reason the
cap was nil'd.
- Keep the resolved output cap (32k default) on the summary call instead
of nil'ing it.
- When the summary comes back empty with truncation evidence (length
finish reason, or reasoning with no text), fail with `compaction summary
was truncated at the output token cap` instead of the generic
empty-summary error, so the next occurrence is attributable at a glance.

Unit tests cover text-block joining and the truncation classification;
the compaction e2e fixtures now serve streamed summaries and assert the
summary request streams with `max_tokens: 32000`. Dogfood UAT on a
deployment built from this branch verified manual compaction with Claude
Opus 5 (adaptive thinking, twice, with reload persistence) and an OpenAI
regression chat.

> 🤖 Opened by [Xum](https://mux.coder.com) on behalf of @ibetitsmike.
2026-09-21 21:28:45 +02:00
Spike Curtis 8475a1defb refactor(coderd): enforce workspace template authz in singleWorkspaceData (#29665)
Part of the lite `codersdk.Workspace` work
([GRU-82](https://linear.app/codercom/issue/GRU-82),
[RFC](https://app.notion.com/p/coderhq/Lite-Workspace-API-Requests-3aad579be5928060b5e7cc65c539717f)).

`api.workspaceData` omits templates the actor cannot read and leaves
each caller to check `len(data.templates) == 0` and fail the request
itself. Now that `workspaceData` receives the `wsrelated.Config`, it
knows whether the template was requested, so the authorization check can
live closer to the data.

This adds `singleWorkspaceData`, a thin wrapper for single-workspace
fetches that returns `errWorkspaceTemplateUnauthorized` when the
template was requested but is absent (i.e. unreadable). The five
single-workspace callers route through it and map that error to the
response their endpoint requires:

- get workspace by ID → `403`
- get workspace by owner/name → `404` (preserves existence concealment)
- create/put workspace → `403`
- watch workspace (SSE) → forbidden error event

The batch `workspaceData` keeps its RBAC-filtering behavior so the
**list** endpoint can still skip workspaces whose template the actor
cannot read, rather than failing the whole request. Field selection
(`Config`) and authorization policy are kept separate: the strict check
is a property of the single-workspace wrapper, not of `All()`.

<details>
<summary>Design note</summary>

The check tests membership by the workspace's `TemplateID` rather than
only `len(templates) == 0`, and only real query failures (not RBAC
omissions) propagate as generic errors, so a genuine DB error is never
mistaken for an authorization denial.
</details>

### Testing

- New `TestSingleWorkspaceData` (mocked `database.Store`): template
readable, template requested-but-unauthorized (sentinel), template not
requested (no error), and a real query error (not the sentinel).
- Existing `TestWorkspace`, `TestWorkspaceByOwnerAndName`,
`TestWorkspaceWatcher`, and `TestWorkspaceIncludeRelated` pass
unchanged.

---

*Generated by Coder Agents on behalf of @spikecurtis.*
2026-09-21 21:06:06 +02:00
Michael Suchacz af0ef00f91 feat: add owner_id to CreateChatRequest to create chats for another user (#29581)
Owners and owner-level service accounts can now start a Coder Agents
chat on behalf of another user by setting `owner_id` on `POST
/api/v2/chats`. The field is optional and defaults to the caller, so
existing clients are unaffected. A delegated owner must be an active,
non-system member of the requested organization; anything else returns
400 `Chat owner must be an active member of the organization.` once the
caller has passed the authorization gates below.

A chat runs entirely with its owner's credentials (synthetic API key,
workspace access, OIDC and provider tokens), so creating one for someone
else is acting as that user. On top of org-scoped `chat:create` for the
owner, the caller must hold the authority to create API keys for that
user, which is what the token endpoint demands to mint their session.
Org admins therefore cannot use it; site owners and owner-role service
accounts can. For the same reason the workspace binding, model config,
and MCP server IDs are validated as the owner rather than the caller,
and the owner must themselves hold `chat:create` (organization service
accounts do not). The initial user message is attributed to the caller
through `chatd.CreateOptions.CreatedBy`.

An earlier revision of this PR exposed the same behavior as `POST
/api/v2/users/{user}/chats`; that route and
`codersdk.Client.CreateUserChat` were removed in `62a8be3dd32` in favor
of the request field. An explicit zero `owner_id` is rejected with 400
rather than silently defaulting to the caller. Coverage lives in
`TestPostChats_OwnerID`.

<details>
<summary>Review record (path-based revision, gates unchanged)</summary>

- Two-axis code review (Standards, Spec) plus a simplicity audit ran as
Xum sub-agents on `1f3189898f0`. The Spec axis found the workspace
binding was authorized as the caller, fixed in `363d45281d8` with
red-green coverage in `WorkspaceNotAccessibleToOwner`. The additional
API-key gate and the `CreatedBy` attribution go beyond the workspaces
pattern and were kept deliberately for the reasons above.
- Codex review on `363d45281d8`: one P2, suspended, dormant, or system
users could be targeted and would get a chat that can never run because
AI Bridge refuses to authorize them. Fixed in `c065437e359` with
`OwnerSuspended` (red on the old head); thread replied to and resolved.
- Codex review on `c065437e359`: one P2, an explicit or
personal-override model config the caller can read but the owner cannot
was accepted and chatd would silently fall back to the default model at
run time. Fixed in `aa88b608182` by resolving the model config and MCP
server IDs under the owner's context, with
`ModelConfigNotAccessibleToOwner` (red on the old head); thread replied
to and resolved.
- Codex review on `aa88b608182`: one P2, an organization service account
(which deliberately holds no chat permissions) could be targeted because
the chat permission check ran as the caller. Fixed in `a6fe8075c30` by
also requiring the owner subject to hold `chat:create`, with
`OwnerWithoutChatPermission` (red on the old head); thread replied to
and resolved.
- Codex review on `a6fe8075c30`: one P2, the active/non-system check was
skipped when the caller could not read the owner's user object. Fixed in
`0dd8bb4dd44` by moving the check behind the authorization gates with a
system-restricted lookup; thread replied to and resolved. In
`62a8be3dd32` that lookup became a single `OrganizationMembers` query,
which also covers membership and excludes system and deleted users.
- Codex review on `62a8be3dd32` (the `owner_id` revision): two P2s. An
explicit zero `owner_id` was treated as omitted and created the chat for
the caller; fixed in `f54b4f33d36` with a 400 and `OwnerIDNil` (red on
the old head). Creation and the read-back still ran as the caller while
the preflight ran as the owner; fixed in the same commit by passing
`ownerCtx` to `CreateChat`, `GetChatByID`, title generation, and the
file-metadata fetch. That second scenario is unreachable today (only the
built-in `owner` role holds `api_key:create` for others, and site-wide
custom roles are refused by both the API and dbauthz), so it has no
dedicated red test. Both threads replied to and resolved.
</details>

<details>
<summary>Remote UAT record (path-based revision)</summary>

Remote UAT on dogfood (chat `d7442df3-693f-4403-805f-2de52f7bdbed`, Xum
sub-agent as critical runner) tested head `21ed6b389cc`, the last
path-based revision. Licensed dev server, real Haiku 4.5 model, 77
logged API requests, 23 inspected screenshots. Endorsed verdict:
**PASS**. Site owner creates a chat for member X: X sees it, gets real
answers to the admin prompt and to follow-ups, and state survives reload
and mid-response refresh. The creating admin gets `403 Only the chat
owner may send messages.` and a read-only view; an unrelated member gets
404. Org admin, member, user-admin, and template-admin callers get 403;
owner-role service account 201. Suspended, dormant, and service-account
targets 400; owner-inaccessible workspace, model config, or MCP server
400; 300 KiB body 413. The `owner_id` revision changes only how the
owner is supplied and the non-member response (400 instead of 404); the
authorization and eligibility gates it exercised are unchanged and
covered by `TestPostChats_OwnerID`.

Non-blocking findings for the author's judgment, none of them
regressions of this PR:
1. X's UI shows no author on the admin-written first message and offers
X "Edit" on it; `created_by` carries the admin but the frontend does not
surface it.
2. A site owner who is not a member of the organization can still create
a chat for its members (201), while a self-owned `POST /chats` returns
403 for the same organization; same asymmetry as `postUserWorkspaces`.
3. The creating admin can archive, rename, and interrupt X's chat
although it cannot message it (pre-existing chat authz).
4. Owner-inaccessible model config or MCP server is reported as "not
found or disabled" with no hint that the owner, not the caller, lacks
access.
5. Dormant (never logged in) targets are refused because AI Bridge
rejects non-active users; a new hire cannot be given a chat until first
login.
6. The endpoint docs list only 201 and 413.
</details>

> Xum (an AI agent) acted on behalf of @ibetitsmike for this PR.
2026-09-21 20:49:10 +02:00
Mathias Fredriksson cd2481615d fix(coderd/x/chatd): clarify chat delegation ownership (#29041)
The delegation guidance encouraged parallel activity without defining
ownership between the parent and child, and corrections default to
queued delivery, so a parent could keep working against an assignment
the child had not received.

Give each delegated task one owner. The parent continues independent
work, waits with wait_agent when its next step depends on the child's
result, and treats the report's findings as read context. Corrections
and handoffs interrupt; a handoff is acknowledged only by the child's
response through wait_agent. Agent selection stays in the spawn
description instead of a second copy in planning guidance. Wording only;
tool arguments and execution behavior are unchanged.

Refs CODAGT-1079
2026-09-21 18:20:22 +00:00
Michael Suchacz a970c6c92e fix: list one Unknown AI Gateway client for missing and literal values (#29635)
`ListAIBridgeClients` grouped by the raw `client` column while selecting
`COALESCE(client, 'Unknown')`, so interceptions with no client and
interceptions whose client is literally `Unknown` produced two identical
`Unknown` entries in the client filter. Group by the coalesced value
instead.

## Validation

`go test ./enterprise/coderd -run '^TestAIBridgeListClients$'` (adds an
interception with a literal `Unknown` client and expects a single
entry), `make gen` with no drift (regenerates `queries.sql.go` and
`querier.go`).

Split out of #28964, where the spend page's client filter surfaced it.

> Xum prepared this PR on behalf of @ibetitsmike.
2026-09-21 18:03:22 +02:00
Michael Suchacz 988520477e feat!: remove the experimental chat API mounts after the transition window (#29548)
Remove the `/api/experimental` duplicates of the promoted chat API.
#28496 double-mounted the chat, organization chat and MCP server, member
model-override, AI provider key, and MCP OAuth2 disconnect routes under
both prefixes for the one-release compatibility window decided in
CODAGT-921; that window closed with v2.37.0, so these routes now answer
only on `/api/v2`. The change also deletes what existed only for the
dual mount: the `chatAPIPrefix` plumbing, the shared cross-prefix files
rate limiter (`RateLimitByAPICompatibilityEndpoint`), the 410 tombstones
for the legacy `chats/providers` and `chats/user-provider-configs`
collections with their `ExperimentalClient` SDK methods, and the
`/providers` and `/user-provider-configs` 404 reservations on `/api/v2`.
Signed chat file download URLs now point at `/api/v2`.

Routes that were never promoted stay on `/api/experimental`: the
experiment-gated `chats/config/advisor` and
`chats/config/computer-use-provider`, `chats/{chat}/stream/desktop`,
`chats/{chat}/debug/runs`, and the MCP OAuth2 callback, whose path is
pinned as a registered redirect URI with external providers. The
frontend already calls `/api/v2` for every promoted route, so only
`typesGenerated.ts` changes. Because the experimental mount no longer
reserves the removed collection segments, requests such as `GET
/api/experimental/chats/models` now fall into the `{chat}` wildcard and
return 400 instead of 404; the experimental prefix carries no stability
guarantee and the compatibility window is over, so no new reservations
were added.

`coderd/x/chatd/ARCHITECTURE.md` now describes the single `/api/v2`
mount and the remaining experimental routes, and its endpoint headings
use the `/api/v2` paths.

Closes CODAGT-922
(https://linear.app/codercom/issue/CODAGT-922/remove-experimental-chats-api-paths-after-transition-window).
Refs #28496.

## Delivery record

- Remote dogfood UAT (Coder Agents chat
https://dogfood.cdr.dev/agents/c016b549-201a-4eca-a50f-3c0b7c339db6):
verdict PASS on b008976a4dfba3524b220ca846ea3c3492e9cc9c. The branch was
since rebased onto main (which had a duplicate migration 000596 until
#29568) and gained one docs-only commit
(`coderd/x/chatd/ARCHITECTURE.md` only); the current head 666332f579
carries the same code diff, so the tested branch code is unchanged.
Covered the Agents UI end to end on `/api/v2` (chat, streaming reply,
reload mid-stream, file upload and download, debug runs panel), the
admin AI settings pages with persisted saves, 45 curl route checks
across both prefixes, websocket handshakes, the frozen MCP callback
redirect URI, and the files rate limiter. One low-severity note: the
400-versus-404 behavior for removed experimental collection paths
described above.
- Codex review on b008976a4d (draft marked ready): no findings. Codex
review on the current head 666332f579 (requested via `@codex review`):
one P1 thread asking for TODO markers instead of the direct
`ARCHITECTURE.md` edit; replied and resolved because the PR author
reviewed the earlier TODO markers and directed this replacement text. No
unresolved threads. CI is green on 666332f579 (run 35376339802;
`test-go-pg-17` passed on rerun after a Docker Hub timeout in
`TestSSH_Container/OK`).

> [!NOTE]
> Xum acted on @ibetitsmike's behalf in this pull request.
2026-09-21 17:42:31 +02:00
Michael Suchacz c1b3ee7895 fix: select an AI Gateway client only on an exact match (#29636)
`useClientFilterMenu` resolved the selected option by searching clients
with `q: value` and taking the first result, so with no value selected
(or a prefix that matches another client) the filter displayed a client
that was never chosen. Require the first result to equal the value.

Split out of #28964, where the spend page rendered the filter with no
selection and showed the first client as selected.

> Xum prepared this PR on behalf of @ibetitsmike.
2026-09-21 16:44:16 +02:00
Paweł Banaszewski f69f545429 chore: clean up ChatProviderAPIKeysFromDeploymentValues (#29666)
Removes not needed `ChatProviderAPIKeysFromDeploymentValues` function.
2026-09-21 16:40:35 +02:00
Michael Suchacz 2bf0f567d8 feat: add OpenAI Pro reasoning mode to chat model configs (#29584)
Adds `provider_options.openai.reasoning_mode` (`pro`) to chat model
configs so admins can turn on OpenAI's Pro reasoning mode for a model,
alongside the other OpenAI request options on the model form such as
`service_tier`. The field is offered for any model on an OpenAI
provider; the field description says Pro is supported from the GPT-5.6
Sol generation and that requests fail when Pro is set on a model that
does not support it. There is deliberately no supported-model list
anywhere: a newly released model that supports Pro works with no code
change, and OpenAI rejects the request when the model does not.
Validation rejects only values other than `pro`, non-OpenAI providers,
and configs that explicitly force plain sampling
(`reasoning_model=false`) or Chat Completions
(`use_responses_api=false`), including partial updates that move a
configured model onto such a provider or transport.

A configured mode implies the Responses API and reasoning-model
treatment when `openai_config` leaves those unset
(`chatprovider.effectiveOpenAIConfig`), so an alias the pinned SDK has
never seen, such as `gpt-daybreak-blue-latest`, still gets `effort` and
`summary` and drops `temperature`. The same effective config feeds the
client options and the recorded transport, so the two cannot disagree.

The pinned fantasy OpenAI provider options do not carry
`reasoning.mode`, so the mode is applied as a client-scoped `openai-go`
request option when the model client is built rather than per call. The
SDK merges pre-serialization `WithJSONSet` overlays by top-level key, so
the key is escaped (`reasoning\.mode`) to add `mode` to the existing
`reasoning` object instead of replacing `effort` and `summary`.
`TestResolveModelCallReasoningModeWire` pins the resulting request body
for streaming and non-streaming calls and checks that the fixed
computer-use model does not inherit the mode; AI Gateway forwarding of
the `reasoning` object is covered in `aibridge`. Because the option is
bound to the model client, every call made through a Pro model config
carries it, including title generation and quick generation when those
fall back to the chat's model; deployments that want cheaper auxiliary
calls should point the title generation override at another model.

Frontend: the field renders through the existing schema-driven provider
options with no hand-written field logic. Two generic changes:
`visible_for_providers` is now honored for provider fields the way it
already was for general fields (render and payload), so the
OpenAI-scoped select does not appear or serialize for Azure, which
shares the OpenAI field group; and the add/update model save toasts now
carry the server's error detail, so a rejected combination such as Pro
with Use Responses API at Off tells the admin which field to change.

Docs: `docs/ai-coder/agents/models.md` gains a Reasoning Mode row in the
OpenAI provider-specific options table (from the documentation check
comment
https://github.com/coder/coder/pull/29584#issuecomment-5752457808), and
its Azure note now says Azure OpenAI lacks that one option.

Not changed: `coderd/x/chatd/ARCHITECTURE.md`. Its OpenAI transport
selection table needs a `reasoning_mode` row (client-applied, neither
transport) to match `TestProviderOptionsTransportParity`; left for the
human author.

<details>
<summary>Delivery record</summary>

- Local validation on every pushed head: targeted Go tests (chatopenai,
chatprovider, chatd wire test, aibridge integration test, coderd DB
tests for persistence, invalid input, and partial updates), red/green on
the wire test (injection removed, and unescaped key), Vitest
(`modelConfigFormLogic`, `ModelForm`), Storybook tests for
`ModelFormProviderConfig`, biome, tsc, oxlint, golangci-lint on touched
packages, pre-commit hook.
- Codex round 1 on `e7dbaefeafc`: 3 findings (Storybook assertions,
ARCHITECTURE.md TODO, `gpt-daybreak-blue-latest` alias). Disposition:
assertions moved to Vitest and alias accepted in `8fccf111111`;
ARCHITECTURE.md left untouched by author instruction. Threads replied to
and resolved.
- Codex round 2 on `8fccf111111`: 1 finding (fixture naming, FE9),
renamed in `23449e92317`. Round 3 on `23449e92317`: 1 finding (fixture
location, FE9), moved to `testHelpers/chatModels.ts` in `c3bd5aa370f`.
Round 4 on `c3bd5aa370f`: "Didn't find any major issues"
(https://github.com/coder/coder/pull/29584#issuecomment-5735119236). All
threads resolved.
- Remote UAT round 1 (chat
https://dogfood.cdr.dev/agents/f5ed1d16-be1d-4d39-952b-126a6a829ef1)
exercised `e7dbaefeafc`: endorsed PASS. Real `gpt-5.6-sol` turns showed
`"mode": "pro"` / `"standard"` / no key in the Debug tab with effort and
summary intact; 14 POST and 6 PATCH rejections captured; UI select
visibility, persistence, reload, and clearing verified. Low,
non-blocking notes: the `gpt-5.6` alias revert in the model identifier
field is pre-existing; Pro is dropped silently when a model or transport
change makes it unsupported; Pro applies to auxiliary calls (see above).
- Remote UAT round 2 on `c3bd5aa370f` (same chat, alias and core
re-verify): core PASS, alias FAIL. With `gpt-daybreak-blue-latest` the
request carried `{"mode": "pro"}` without the configured effort and
summary and kept sending `temperature` (provider 400 then retry on quick
generation and title calls), because the SDK does not classify the alias
as a reasoning model. Fixed in `d4c338de767`: a configured mode now
implies a reasoning model unless `openai_config.reasoning_model` is set,
and a mode on a config that forces plain sampling is rejected. Alias
UI/API behavior, rejections, and known-model Pro/Default turns all
passed on `c3bd5aa370f`.
- Codex round 5 on `d4c338de767`: "Didn't find any major issues"
(https://github.com/coder/coder/pull/29584#issuecomment-5736190356).
Zero unresolved threads. CI green on `d4c338de767`.
- Remote UAT round 3 on `d4c338de767` (same chat): endorsed PASS. Alias
runs are single-attempt 200s with `{"effort", "summary", "mode": "pro"}`
and no `temperature` (quick generation and title calls no longer retry);
`reasoning_model=false` plus a mode is rejected by POST and PATCH with
the stored config unchanged; the Reasoning Model override at Off hides
the select and drops the mode on save; `gpt-5.6-sol` Pro turn unchanged.
Remaining low notes, none introduced here: rejection detail for a
non-OpenAI provider names the model rather than the provider; Pro is
dropped silently when an override makes it unsupported; `PATCH
model_config` replaces the whole object (pre-existing on main).

- coder-frontend-review on `d4c338de767` (8 role reviewers, 3 passes):
13 failing checkpoints, chiefly a TS mirror of the Go model regex, the
`json_name === "reasoning_mode"` gate duplicated in the render filter
and payload builder, a defaulted `model` parameter, and comment and type
nits. Fixed in `554c90d5fd9`: the pattern and provider scope are
generated onto the field schema, one predicate is shared by both call
sites, `buildModelConfigFromForm(provider, model, form)` requires the
model, and the ModelForm test also asserts the select disappears for an
unsupported model. Red/green: stripping `supported_models` or
`visible_for_providers` from the generated schema fails 21 and 1 Vitest
cases respectively. Declined with rationale: RO4 (move the fixture to
`ModelsPage/testFixtures.ts`; FE9 in `FRONTEND_PATTERNS.md` names
`testHelpers/chatModels.ts`, and Codex round 3 required it) and a DF5
nit to gate on the committed identifier and warn when a saved mode is
dropped (behavior change, separate follow-up). Final pass: all
checkpoints PASS or N/A.
- Remote UAT round 4 on `554c90d5fd9` (same chat, focused regression
after the frontend-review refactor): endorsed PASS. All six claims held
(Pro round trip with effort and tier intact; unsupported identifiers
hide the select and a save drops the stale mode while keeping the other
options; Azure never shows or saves it; the alias shows it only with the
Responses override On; Reasoning Model Off hides it and drops it; three
real `gpt-5.6-sol` Pro turns were single-attempt 200s with
`{"effort","summary","mode":"pro"}` and no `temperature`). Probes aimed
at the refactor also passed: `gpt-5X6-sol` is rejected (dot escaping
survived the JSON round trip), whitespace-padded identifiers still
match, the other 11 OpenAI fields and the Anthropic section still
render. Remaining low notes are carried over from round 3 plus one
naming note ("Reasoning Mode" versus "Reasoning Model"). The final head
`abb58df77d8` differs from `554c90d5fd9` only in `ModelForm.test.tsx`,
so it ships the same production code.
- Codex round 6 on `554c90d5fd9`: 1 finding
(https://github.com/coder/coder/pull/29584#pullrequestreview-5260492465):
the two `toBeInTheDocument` assertions added in the frontend-review
round violate FE1. Confirmed against `site/AGENTS.md`; removed in
`abb58df77d8` (test-only, 7 deletions; the payload assertion keeps the
behavior coverage and the `ProviderConfigOpenAI` story captures the
hidden state). Thread replied to and resolved.
- Codex round 7 on `abb58df77d8`: "Didn't find any major issues"
(https://github.com/coder/coder/pull/29584#issuecomment-5749626071).
Zero unresolved threads. CI green on `abb58df77d8` (23 success, 8
skipped, `required` pass).

- Design change on `e99152e5c57` (owner direction: no model gating;
"none or pro" for any model; tooltip states the GPT-5.6 Sol constraint
and that requests fail on unsupported models). Removed
`codersdk.ChatModelReasoningModeModels`, the generated
`supported_models`, `isFieldApplicableToModel`, the
`gpt-daybreak-blue-latest` special case, and the `standard` enum value;
`ValidateReasoningMode(provider, config)` no longer takes the model;
`effectiveOpenAIConfig` makes a mode imply Responses and reasoning-model
treatment. PR footprint went from +1130/-22 to +769/-18. Local
validation: `go test` for chatopenai, chatprovider, chatd wire test, and
the coderd API tests (persistence now covers `gpt-5.6-sol`, `gpt-4o`,
`gpt-daybreak-blue-latest`, `gpt-7-nova`; invalid input now rejects
`standard`), golangci-lint on touched packages, Vitest (187 tests across
`modules/aiModels` and `ModelsPage`), biome, tsc, pre-commit hook.
- coder-frontend-review on `e99152e5c57` (8 roles, 1 pass plus a TS and
CD confirmation pass): 9 failing checkpoints (SD4, CD1, CD3, CD4, TS3,
TS7 x2, RO3, RO5, TN4, DF5). Fixed in `e06bfbe4299`: the ModelForm test
edits `mockGPT5` so its provider matches the selected provider state,
types the update mock like the sibling story, and drops an unused route;
the story spreads `mockGPT5` with a saved mode instead of a dedicated
shared fixture (`MockGPT56Pro` removed, `testHelpers/chatModels.ts` back
to base); a `ProviderConfigAzure` story captures the panel without
`reasoning_mode`; comment nits. Left as a nit with justification: RO3
(the one-line `!hidden && isFieldVisibleForProvider` predicate now
appears in both `getVisibleProviderFields` and
`getVisibleGeneralFields`; hoisting a helper for two call sites is not
worth it). Confirmation pass: TS all PASS; CD flagged one wording nit,
fixed before commit.
- CI green on `e06bfbe4299` (23 success, 8 skipped, `required` pass).
- Codex round 8 on `e06bfbe4299`: 1 P2 finding
(https://github.com/coder/coder/pull/29584#discussion_r4057659673): the
form still offers Pro with Use Responses API or Reasoning Model at Off,
a combination the server rejects, and the failure was not actionable.
Disposition: the select stays visible by owner direction (no client-side
gating of this field beyond the provider scope; an explicit rejection is
preferred over the earlier silent drop), and `e2b43c3aee7` makes the
add/update save toasts show the server detail so the admin sees which
field to change. Thread replied to and resolved; zero unresolved
threads.
- Remote UAT round 5 on `e06bfbe4299` (same chat): endorsed PASS with
two UI issues to land before release. All seven probes passed: the
select offers only Default and Pro for `gpt-5.6-sol` and `gpt-4o` with
the tooltip text verbatim; Pro saves on `gpt-4o` and the real turn fails
visibly with the provider's "reasoning.mode is not supported with this
model" after a single 400 attempt, and works again once Pro is cleared;
`gpt-daybreak-blue-latest` with Pro and no overrides is a single 200 to
`/v1/responses` with `{effort, summary, mode: "pro"}` and no
`temperature`; the `gpt-5.6-sol` Pro turn is unchanged; POST and PATCH
reject `standard`, `PRO`, empty, Responses Off, Reasoning Model Off, and
Azure, openai-compat, and Anthropic providers with the stored config
unchanged, while a model-only PATCH to `gpt-4o` now succeeds; the Azure
form shows no Reasoning Mode; the alias with an explicit Responses
override still works. Reservations: (1) medium, the UI conflict path
only showed "Invalid model config." without the detail (fixed in
`e2b43c3aee7`, not yet UAT-exercised); (2) low-medium, a dev-DB row
still holding `standard` from round 2 renders an empty red select whose
message is the whole field description plus "has an invalid value." and
blocks saving unrelated fields (pre-existing generic behavior of
`yupTestForField` using the description as the label; no released data
can hold `standard`, so no migration); (3) low, no hint next to older
identifiers (documented design); (4) low, a chat on such a stored row
fails with a generic headline (pre-existing).
- Final head `e2b43c3aee7` differs from `e06bfbe4299` only in the two
save-toast handlers (`AddModelPage.tsx`, `UpdateModelPage.tsx`, 8
insertions). CI is green on `e2b43c3aee7` (skipped=8, success=23,
`required` success). Codex has not run on `e2b43c3aee7`.
- Remote UAT round 6 on `e2b43c3aee7` (same chat,
https://dogfood.cdr.dev/agents/f5ed1d16-be1d-4d39-952b-126a6a829ef1,
settled 2026-09-20T19:02Z): endorsed PASS on the exact final head. Build
proven by `/api/v2/buildinfo` (`v2.37.2-devel+e2b43c3aee`,
`external_url` at the full SHA) and the UI badge. The round 5 toast
issue is resolved: Add and Update saves with Pro plus Use Responses API
Off or Reasoning Model Off show "Invalid model config." with the server
detail as the description, one 400 each, nothing stored. Compact
regression of every round 5 probe held (dropdown and tooltip; Pro on
`gpt-4o` fails visibly with the provider's `reasoning.mode is not
supported with this model` and works after clearing; alias with and
without the Responses override and `gpt-5.6-sol` all send `{effort,
summary, mode: "pro"}` with no `temperature` in a single 200; POST and
PATCH rejection matrices with stored config unchanged; Azure form
without the field). Legacy `standard` row: fails closed on chat, and
re-picking Pro or Default saves. Remaining notes, none blocking: the
malformed validation copy for an invalid stored enum (pre-existing
`yupTestForField` label choice, dev-DB rows only), Pro offered for
models that cannot accept it (documented design), and a pre-existing
`quickgen` status quirk on `gpt-4o` unrelated to this field. Secret scan
clean.
- Final head `4f3c6106dfe` adds one docs-only commit on top of
`e2b43c3aee7` (`docs/ai-coder/agents/models.md`, 9 insertions, 8
deletions, no code). Remote UAT round 6 exercised `e2b43c3aee7`; the
docs commit is not UAT-relevant. Validated with
`markdown-table-formatter`, `markdownlint-cli2`, and the pre-commit hook
(`fmt/markdown`, `lint/markdown`, `lint/emdash`, `lint/typos`). CI is
green on `4f3c6106dfe` (success=24, skipped=7, `required` success) and
the documentation check re-run marked its item addressed
(https://github.com/coder/coder/pull/29584#issuecomment-5752457808).
- Review tally for this PR: Codex 8 completed rounds;
coder-frontend-review 34 role passes (24 on `d4c338de767`, 10 on
`e99152e5c57`); remote UAT 5 rounds; no human review yet. This is far
past the six-review guardrail, so no further Codex or agent review has
been requested. Whether to spend another Codex pass on `e2b43c3aee7` is
an owner decision; human review is still required before merge.

</details>

> Xum acted on behalf of @ibetitsmike.
2026-09-21 15:58:18 +02:00
Spike Curtis c5c7f9d8b2 fix(coderd): remove stale coderd/wsrelated import in test (#29655)
Fixes a broken `main`: `coderd/workspacebuilds_internal_test.go` had two
`wsrelated` imports after the stacked include_related PRs squash-merged.
The stale `github.com/coder/coder/v2/coderd/wsrelated` path no longer
exists (the package moved to `codersdk/wsrelated` in #29540), so the
`coderd` test package failed to compile.

Removes the dangling import; the file already imports the correct
`codersdk/wsrelated`.

### Verification

- `go build ./coderd/` and `go test ./coderd/ -run '^$'` (compile the
test package) both succeed.

---

*Generated by Coder Agents on behalf of @spikecurtis.*
2026-09-21 11:04:12 +00:00
Paweł Banaszewski 44eb71f922 chore: move aibridge proxy code and helpers to separate packages (#29573)
Move the stateless AI Gateway router into `aibridge/x/proxy`.
Extract shared routing helpers into `aibridge/routing` and move provider
and recorder helpers to their owning packages. Update callers and tests
without changing behavior.

Generated by Coder Agents.
2026-09-21 12:26:09 +02:00
Spike Curtis 9a29aab2ee feat: add include_related option to client.Workspace in codersdk (#29540)
Part of the lite `codersdk.Workspace` work
([GRU-82](https://linear.app/codercom/issue/GRU-82),
[RFC](https://app.notion.com/p/coderhq/Lite-Workspace-API-Requests-3aad579be5928060b5e7cc65c539717f)).
Stacked on #29539, which wired `include_related` into `GET
/api/v2/workspaces/{workspace}`.

Adds `include_related` support to the `codersdk` client, expressed with
the typed selection tree so only supported selections are representable:

- Moves the `wsrelated` package from `coderd/` to `codersdk/` so both
the server and the client can share `wsrelated.Config`. `coderd` already
depends on `codersdk`, so this only changes import paths on the server
side.
- Adds `Config.QueryParam`, which encodes a selection into the
`include_related` value: the dotted path of each selected node that has
no selected descendants. Selecting a node implies its ancestors, so
`Parse` round-trips the result back into an equal `Config` (covered by a
round-trip test).
- `WorkspaceOptions` gains `IncludeRelated *wsrelated.Config`. A nil
value omits the parameter (server returns everything, unchanged); a
non-nil value is encoded via `QueryParam`, and a zero `Config` loads
only the workspace.
- `Client.Workspace` now accepts optional `WorkspaceOptions`, backward
compatible with existing `client.Workspace(ctx, id)` calls.

### Testing

- `codersdk` internal test asserts `WorkspaceOptions.asRequestOption`
sets `include_related` from the selection, following the existing
`WorkspaceFilter` test pattern rather than spinning up a server.
- `wsrelated` tests cover `QueryParam` output and a `Parse`/`QueryParam`
round trip.

`make gen` regenerated the `WorkspaceOptions` TypeScript type. Because
the wire representation of `include_related` is a comma-separated
string, `scripts/apitypings` maps `wsrelated.Config` to `string` in
TypeScript, so `include_related?: string` rather than a nested object
the frontend cannot serialize. `api.getWorkspace` already forwards
`WorkspaceOptions` as query params, and a frontend test in `api.test.ts`
confirms `include_related` is sent through.

---

*Generated by Coder Agents on behalf of @spikecurtis.*
2026-09-21 11:53:11 +02:00
Spike Curtis 29ae50d9c9 feat: accept include_related query param on get workspace by ID (#29539)
Part of the lite `codersdk.Workspace` work
([GRU-82](https://linear.app/codercom/issue/GRU-82),
[RFC](https://app.notion.com/p/coderhq/Lite-Workspace-API-Requests-3aad579be5928060b5e7cc65c539717f)).
Follows #28639, which added the `wsrelated` package and parser.

Wires the `include_related` query parameter into `GET
/api/v2/workspaces/{workspace}`, the first endpoint to accept it. When
present, the value is parsed with `wsrelated.Parse` and the resulting
selection is threaded into `workspaceData`, so only the requested
related data is queried. Omitting the parameter is backward compatible
and returns everything (`wsrelated.All`). An invalid value returns
`400`.

Because related data can now be omitted, the handler no longer assumes
the build and template are present: it uses zero values when they are
absent, and only enforces the template read-authorization check (`403`)
when the template was actually requested.

### Partial-build conversion

`convertWorkspaceBuilds` now tolerates a build whose provisioner job or
template version was deliberately omitted from the selection, so
selections such as `latest_build` (build only) or
`latest_build.resources.*` (resources without the job) convert correctly
instead of erroring. The omitted fields are left zero (empty `Job`,
empty `TemplateVersionName`). Resources are keyed by the build's `JobID`
rather than the fetched job row, so they load independently of whether
the job is selected. The integrity error is preserved for full-data
callers: when a job or template version is requested but missing,
conversion still fails. The selection config (`wsrelated.LatestBuild`)
is threaded into `convertWorkspaceBuilds` to distinguish "not requested"
from "missing".

Only this endpoint is wired; the other endpoints that produce
`codersdk.Workspace` objects, and the codersdk client functions, come in
later PRs.

---

*Generated by Coder Agents on behalf of @spikecurtis.*
2026-09-21 10:50:01 +02:00
Michael Suchacz 53ad29512d fix: route chat quickgen side calls through the title generation model (#29622)
Chat sublabels were falling back to "Finished latest turn" for most
turns on some models. On dogfood, 95% of Claude Fable 5.1 chats over the
last 7 days showed the fallback (341/357) while Opus 4.8 sat at 3%. The
end-of-turn status label and the whole-chat summary were generated on
the chat's own model, and Anthropic rejects the forced tool call that
Fantasy's object generation relies on with `400 tool_choice: type "tool"
and "any" are not supported for this model.` on every `claude-fable-5-1`
request (about 3k such 400s in 7 days). OpenAI-compatible reasoning
models such as solstice-1 fail the same call differently, answering with
text at the 64-token cap. Title generation kept working because it
already resolves a dedicated model: the organization `title_generation`
override (Haiku 4.5 on dogfood), then a preferred small model, then the
chat model. The failures were only visible at Debug level.

Route every quickgen side call (turn status label, chat summary,
automatic and manual title) through one shared resolver,
`resolveQuickgenModel`, with that same order: `title_generation`
override, then an enabled preferred small model, then the chat's model
as a last resort. The preferred-model match now also accepts dated
snapshot IDs such as `claude-haiku-4-5-20251001`, which is how admins
commonly configure Haiku. Candidate failures for labels, summaries, and
titles are logged at Warn with provider and model. The admin settings
copy and the models doc now say that the title generation override also
governs status labels and summaries.

Known tradeoff: when the resolved quickgen model itself is unusable at
call time (for example an invalid provider key on the small model), the
side calls fail and the generic label is shown; there is deliberately no
second call on the chat's model.

Refs
https://linear.app/codercom/issue/CODAGT-1077/fix-agent-turn-status-label-generation-failures

## Delivery record

- Remote dogfood UAT, Coder Agents chat
https://dogfood.cdr.dev/agents/87bab92b-bd54-4d5c-aba2-8147eaedfa49
(real Anthropic and OpenAI models through the dev AI gateway, UI driven
through Playwright). Round 1 on b4cc6fc336: FAIL, a dated Haiku config
(`claude-haiku-4-5-20251001`) did not match the preferred-model list, so
labels still fell back to Fable; fixed in cb5f0e0eaf. Round 2 on
cb5f0e0eaf: PASS (override set, override cleared with the dated Haiku
config, single-model fallback, auto and manual titles, summary
regeneration, Warn logging, plus edge cases). Later heads add only UI
copy, docs, and a Storybook play-function cleanup on top of the
UAT-tested SHA and were not re-exercised remotely.
- Codex review: pass 1 on 0ec37f6492 raised one P1 (assertions inside a
Storybook play function), fixed in 409eac5211 and the thread resolved;
pass 2 on 409eac5211: "Didn't find any major issues", zero unresolved
threads. CI green on 409eac5211.

> Xum (an AI coding agent) authored this PR on behalf of @ibetitsmike.
2026-09-20 23:18:12 +02:00
Ehab Younes 9974294ca9 feat: report arbitrary workspace agent session types (#28338)
Report session counts as a dynamic app-name map from the agent, the SSH CLI, and the workspace usage API, so a new IDE flows end to end without a schema, proto, or server change.

- Report through `Stats.session_counts` on Agent API v2.11. Older agents keep reporting through the deprecated count fields.
- Accept arbitrary names from `coder ssh --usage-app` and the workspace usage API. A name the registry does not recognize keeps its identity and is attributed to the `unknown` family.
- Add reconnecting PTY counts to the map without overwriting the counts SSH reported.
- Normalize and merge names before applying the deterministic 64-name cap, ordered by known apps, then count, then name. Overflow sums into `unknown`, and non-positive counts cannot cancel valid activity.
- Strip control characters, treat whitespace-only HTTP app names as absent, and require the exact environment variable prefix when you extract an SSH session type.
- Count overflow entries in `coderd_agentstats_session_counts_overflow_total` and keep raw payloads out of logs.
- Change the usage API's `app_name` to a string, and update the SDK types and API reference.

closes #27410
2026-09-19 00:32:51 +02:00
Michael Suchacz cc8c76651e fix: use workspaces when chat capabilities are insufficient (#29579)
Chatd's guidance discouraged workspace creation even when the chat
lacked the tools or context needed to finish a request. Make a suitable
workspace the fallback when missing tools, skills, MCPs, or context
block progress, while preferring existing capabilities when sufficient.

Align the system prompt, workspace awareness, planning guidance, tool
description, regression tests, and user documentation. Preserve
template-selection guardrails and delegated-agent restrictions.

**Open review finding:** workspace readiness can precede initial
MCP/context discovery. The wording now acknowledges this limitation; a
runtime synchronization fix is pending a scope decision.

<details>
<summary>Implementation and verification context</summary>

- Coding requests authorize necessary workspace setup without a separate
workspace request; self-contained examples remain workspace-free when
existing capabilities suffice.
- Detached root chats create a workspace; attached stopped workspaces
use start_workspace. Persisted awareness describes the initial state
rather than claiming the chat remains detached.
- Delegated chats report workspace needs to their parent. Provisioning
does not unlock workspace MCP tools in Plan Mode.
- Use actually exposed capabilities; do not assume readiness means all
skills, MCP tools, and context have loaded, or recreate workspaces to
retry discovery.
- Prompt, workspace-creation, template-selection, setup-failure, Plan
Mode MCP boundary, and API prompt-composition tests pass. The creation
E2E now verifies published instructions, skills, and MCP tools appear in
request two with no extra user turn; repeated and race runs pass. This
does not establish live-model compliance or discovery readiness.
- Full make pre-commit passes, including generation, formatting, lint,
and the slim build. All CI checks pass on f4f61333ce (23 passed, 8
skipped), and Codex reports no major issues on that commit.
- Codex review iterations corrected prompt/tool conflicts. The alleged
immutable-per-turn tool catalog was disproved by the per-task generation
lifecycle. The narrower initial-discovery race remains open: no existing
chatd-visible signal distinguishes pending discovery from completed
empty or failed discovery.

</details>

Generated by Coder Agents on behalf of @ibetitsmike.
2026-09-18 17:47:53 -04:00
Michael SuchaczandPaul Frybarger 19e2b0415a fix(coderd/x/chatd): preserve tool definitions during compaction (#29436)
Supersedes #28883 by @pfrybar. His commit is carried with authorship
intact (rebased onto main as 32d261f94f); the second commit adds the
overflow fallback found while testing it.

## Problem

Compaction rebuilt the summary request without the conversation's tool
definitions, so the summary prompt no longer shared the turn's prefix
and providers could not reuse the cached context (measurements in
#28883).

Sending the tools with the summary makes that request at least as large
as the generation it summarizes. At a model's real context window
(gpt-3.5-turbo-0125, 16385 tokens) the summary request was rejected with
`Your input exceeds the context window of this model.` on the same
overflow compaction exists to recover from. The chat stayed in `error`,
and both manual `/compact` and the automatic retrigger failed the same
way, so the chat was stuck.

## Fix

`generateCompactionSummary` sends the prepared tool definitions with the
summary request. When the provider rejects that request for size, it
regenerates the summary once without tools, which is the request shape
compaction used before and still fits whenever the history alone does.
The context-window check reuses fantasy's classification and also
matches bad-request wordings fantasy does not parse (OpenAI Responses
API, Anthropic, `context_length_exceeded`).

`BuildToolDefinitions` moves into its own file in `chatloop` so the turn
and the summary share one construction path.

On Anthropic the summary prompt now carries the same `cache_control`
breakpoints as the turn; without them Anthropic never reads the cache,
so the shared tool and history prefix would have been pure cost there. A
compaction override that resolves to a different model shares no prompt
cache and may not support the chat model's provider-native tools, so its
summary request carries no tool definitions; an override resolving to
the chat model itself keeps them. HTTP 413 counts as a size rejection
for the tool-less retry.

## Testing

- Unit:
`TestGenerateCompactionSummaryRetriesWithoutToolsWhenContextTooLarge`,
`TestGenerateCompactionSummaryDoesNotRetryOtherFailures`,
`TestGenerateCompactionSummaryAppliesAnthropicPromptCaching`,
`TestIsContextTooLargeError`, `TestBuildToolDefinitions*`.
- End to end: `TestActiveServer_ManualCompaction/retries the summary
without tools when the prompt exceeds the context window` asserts two
summary requests (with tools, then none), the chat returns to `waiting`
with `last_error` cleared, and the summary is persisted.
- Red-green: with the retry disabled the unit test fails on the returned
provider error and the e2e chat never leaves `error`; with the phrase
matching disabled the Responses, Anthropic, and error-code classifier
cases fail.

## Review record

- Local standards and spec review at 99f7e80a0a9 (pre-rebase content of
8799db2f0e): switched `errors.As` to `errors.AsType`, removed two
comments restating test names, trimmed the phrase list to
provider-attested wordings. Rebase onto main resolved one test-file
conflict (both sides deleted different tests) and inlined the
`chattest.AnthropicErrorResponse` helper that main removed in #29008.
- Codex round 1 on 8799db2f0e: one P1, parent tool definitions sent to
a compaction override on a different provider. Mechanism verified
partially (fantasy skips foreign provider-defined tools with a warning;
`web_search` translates across providers and schemas can be rejected).
Fixed in a7fa7a61e4 by dropping tool definitions when the override is a
separate provider instance, with a red-green case in
`TestActiveServer_CompactionModelOverride`. Thread resolved.
- Codex round 2 on a7fa7a61e4: P1 override tools should drop for any
different model (agreed, guard replaced by an unconditional drop); P2
HTTP 413 should take the tool-less retry (agreed); P2 Anthropic summary
request had no cache breakpoints so the tools bought no cache hit
(confirmed in code, matches earlier dogfood `cache_read=0`). All three
fixed in e7bd72390c with red-green unit and e2e assertions. Threads
resolved.
- Codex round 3 on e7bd72390c: P2 keep tools when the override resolves
to the chat model (agreed, fixed in 6d8d8d6f71 with a red-green e2e
case); P1 missing ARCHITECTURE.md TODO items for the changed compaction
flow (agreed, added in 6d8d8d6f71 per the chatd rule); P2 summary tool
set may differ from the triggering request after a `find_tools`
activation (mechanism confirmed, declined as a cache-efficiency edge
case with the overflow path covered by the retry). Threads resolved.
- Codex round 4 on 6d8d8d6f71: "Didn't find any major issues", reviewed
commit `6d8d8d6f71`, zero unresolved threads. CI green on the same head
(Storybook rerun once after Pixel returned HTTP 500 while uploading
snapshots; this branch has no `site/` changes).

> Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike.

---------

Co-authored-by: Paul Frybarger <pfrybar@frymail.net>
2026-09-18 23:19:00 +02:00
Michael Suchacz ceed0df682 chore: add DeepSeek V4.1 Flash and other missed models to the known models catalog (#29585)
Add the models that landed on models.dev since the September 4 curation
pass (#28955), plus cross-provider gaps where a model was curated on one
provider but not on the others that serve it, so they appear as
suggestions when an admin adds a chat model in `/agents` settings.

| Model | Added to |
|---|---|
| GPT-6 Astra | azure, openrouter, vercel (already curated on openai) |
| Claude Mythos 5.1 | anthropic. Not on models.dev, so injected in
`overrides.jq` as a copy of `claude-fable-5-1`, mirroring the existing
`claude-mythos-5` injection. Anthropic's pricing page lists Mythos 5.1
at the same rates as Fable 5.1, including the reduced cache-read rate. |
| DeepSeek V4.1 Flash | openrouter, vercel |
| Gemini 3.8 / 3.7 / 3.6 Flash | openrouter, vercel (no Google models
were curated on either gateway) |
| Gemini 3.1 Pro Preview, Gemini Flash-Lite Latest, Gemini 3.5 Flash
Lite | google (the catalog had no Pro or Lite tier) |
| Claude Mythos 5 | azure (left pending in #28887) |
| Claude Opus 4.7 | azure, bedrock (plus `global.` alias), openrouter,
vercel |
| GPT-5.5, GPT-5.4 mini | openrouter, vercel |
| GPT-5.4, GPT-5.4 mini, GPT-5.3 Codex | azure |
| Grok 4.6, Qwen3.8 Flash, GLM 5.3 Flash, MiniMax M3, Kimi K2.7 Code |
openrouter, vercel |

Mythos 5.1 uses `reasoningEffort: high` like Fable 5.1 and is added to
the Anthropic thinking-mode pin in `knownModelsGenerated.test.ts`.
Gateway entries follow the existing convention: no reasoning default and
upstream display names. New entries sort ahead of the models they
supersede.

Deliberately not added: `openai.*` models on Bedrock (chatd's Bedrock
provider wraps the Anthropic client, so they cannot be used from Coder
Agents), models.dev's `~`-prefixed rolling aliases on OpenRouter, and
`copilot` (unsupported in chatd).

`knownModelsGenerated.json` and
`coderd/aibridge/prices/data/prices.json` are regenerated with `make
gen/aibridge-prices` from the same models.dev snapshot. Apart from the
`claude-mythos-5-1` row, the `prices.json` changes are upstream drift
since the last weekly refresh, the same content the scheduled refresh PR
would produce.

Validation: `go test ./scripts/aibridgepricesgen/...
./coderd/aibridge/prices/...` and `pnpm test src/modules/aiModels/` (174
tests) pass.

> Xum opened this PR on behalf of @ibetitsmike.
2026-09-18 21:04:59 +02:00
Bobby Ho 55da502938 feat: allow admins to configure an OAuth2 app's scope allowlist (#29313)
Add backend support for scope allowlists on admin-created OAuth2 apps, previously available only through DCR.

- Add optional, space-separated `scope` to create/update requests and return canonicalized, deduplicated scopes in app responses.
- On create, omitted or empty `scope` means unrestricted. On update, `scope` replaces the allowlist; omission preserves it, and an empty string clears it to unrestricted.
- Keep scope enforcement unchanged. Add tests for scope round-trips, DCR canonicalization parity, and authorization narrowing.
- Include generated SDK and docs updates. The UI scope picker follows in a separate PR.

Part of [PLAT-475](https://linear.app/codercom/issue/PLAT-475).
2026-09-18 11:58:49 -07:00
McKayla はな 66a433985e feat: add user workspace search filter (#29442) 2026-09-18 12:57:21 -06:00
McKayla はな 8e159a8053 chore: remove stale TODO shims and dead code (#29252) 2026-09-18 10:27:26 -06:00
blinkagent[bot]andblink-so[bot] eec491530d fix(coderd/database): renumber duplicate migration 000596 to 000597 (#29568)
Two migrations landed on `main` with the same number:

- `000596_template_usage_stats_session_usage.{up,down}.sql` (#29109)
- `000596_aibridge_workspace_context.{up,down}.sql` (#29235)

This makes golang-migrate fail to initialize the source driver:

```
failed to init driver with path .: duplicate migration file: 000596_template_usage_stats_session_usage.down.sql
```

Every job that touches the database is failing on `main` as a result
(gen, sqlc-vet, E2E, offline docs lint, PostgreSQL 17,
Linux/macOS/Windows test suites, race), plus
`coderd/database/gen/dump/main.go` panics.

This renames the later-merged AI Gateway migration to `000597`. The SQL
content is unchanged — it is a pure rename, so no schema dump or fixture
regeneration is required. `migration000596_test.go` and the
`testdata/fixtures/000596_template_usage_stats_session_usage.up.sql`
fixture belong to the earlier migration and are untouched.

Verified the source driver now initializes and resolves `597` as the
final version.

Created on behalf of @ibetitsmike

cc @johnstcn @EhabY

Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
2026-09-18 15:35:04 +00:00
Paweł Banaszewski c47eb47393 feat: add stateless AI Gateway proxy mode (#29349)
Adds proxy mode to the AI Gateway. No AI provider is supported in this
mode yet.
2026-09-18 16:47:16 +02:00
Susana Ferreira c8b22a9d80 feat: add filters to the AI spend CSV endpoint (#29414)
## Description

Update the existing CSV export endpoint and SDK to accept user,
effective group, provider name, and model filters.

## Changes

- Pass the requested filters to the database query.
- Validate filters alongside the existing time window.
- Continue downloading all matching rows without pagination.

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-09-18 15:26:24 +01:00
Susana Ferreira dadbbe39ff feat: add filters and pagination to the AI spend database query (#29412)
## Description

Extend the existing organization AI spend export query with filtering
and pagination.

## Changes

- Add user, effective group, provider name, and model filters.
- Return the total matching-row count before pagination.
- Require organization-wide group-member read access.
- Keep existing CSV exports unpaginated.

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-09-18 15:26:24 +01:00
Cian Johnston 19076beb8d feat: attribute AI Gateway usage to workspaces (#29235)
- Adds nullable `workspace_id` to AI Gateway interceptions without a
foreign key or index.
- Derives direct attribution from strictly parsed server-minted workspace
session-token names, excluding user-created tokens and validating the
embedded owner.
- Derives delegated Coder Agents attribution from the persisted chat
workspace ID.
- Records `workspace_id` through the additive v1.3 gateway protocol and
structured interception logs.
- Exposes attribution in session details through
`interception_attributions`, including tool-less interceptions and null
values for unknown attribution.

Closes AIGOV-637

Generated by Coder Agents.
2026-09-18 15:22:02 +01:00
Ehab Younes 817fc77612 feat: store session usage per app and family in template usage stats (#29109)
Store per-app session minutes in a child table instead of fixed family-minute columns, so adding an IDE no longer needs a rollup schema change. API, Prometheus, and telemetry output are unchanged.

- Add `template_usage_stats_session_apps`, keyed by start time, template, user, and app name, replacing the `ssh_mins`, `sftp_mins`, `reconnecting_pty_mins`, `vscode_mins`, and `jetbrains_mins` columns.
- Group app names into families at read time through the `codersdk` registry, so the registry never reaches SQL and attribution covers all history rather than only the buckets the rollup still revisits.
- Group `GetTemplateInsightsByTemplate` by app name so that Prometheus and the API report a family identically.
- Drop the `@app_families` query parameter and its dbauthz validation.
- Report a family total as the sum of its apps rather than the distinct minutes any of them was active. Numbers are unchanged today, because every agent reports one canonical name per family.
- Keep the child table window index-usable and count minutes with `COUNT(DISTINCT)` in the grouping, so a dashboard-sized range uses an index scan and a large deployment does not spill the sort to disk.

Part of #27410
2026-09-18 15:26:47 +02:00
Spike Curtis aae145bdc9 feat: make NATS pubsub opt-out via no_nats_pubsub experiment (#29283)
Makes the embedded NATS pubsub an opt-out feature instead of opt-in. The
`nats_pubsub` experiment is removed and replaced with a `no_nats_pubsub`
experiment, so NATS pubsub is now the default and can be disabled to
fall back to PostgreSQL pubsub.

NATS clustering requires this replica's routable address, resolved into
`clusterHost` from either `--cluster-host` (`CODER_CLUSTER_HOST`) or the
DERP relay URL. When neither is set (allowed when DERP is disabled on
the primary), NATS cannot form a cluster, so startup logs a big error
and falls back to PostgreSQL pubsub. The NATS cluster CA is only
minted/rotated when NATS clustering is actually active (experiment not
set and a cluster host is present).

<details>
<summary>Implementation notes</summary>

- `codersdk/deployment.go`: removed `ExperimentNATSPubsub`
(`nats_pubsub`), added `ExperimentNoNATSPubsub` (`no_nats_pubsub`,
display name "No NATS Pubsub").
- `cli/server.go`: NATS is used by default unless `no_nats_pubsub` is
enabled; if `clusterHost` is empty, log an error and keep the PostgreSQL
pubsub.
- `coderd/coderd.go`: gate NATS CA minting/rotation on
`!ExperimentNoNATSPubsub && ClusterHost != ""` (i.e. only when NATS
clustering is active).
- `enterprise/coderd/licenses.go`: updated a stale comment.
- `enterprise/coderd/coderd_test.go`: `TestMultiReplica_NATSPubsubPeers`
no longer sets the removed experiment.
- Regenerated `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
`docs/reference/api/schemas.md`, `site/src/api/typesGenerated.ts`.

</details>

---
*This PR was generated by Coder Agents on behalf of @spikecurtis.*
2026-09-18 12:58:06 +00:00
Ethan 77479408b4 feat: make the Coder Agents stream silence timeout configurable (#29394)
The `chatloop` stream silence guard cancels and retries a model attempt
after `10m` of silence, and it was hard-coded. It's armed before the
request opens, so it also bounds time to first token, and slow local
models (e.g. `llama-server` on a large prompt) can spend longer than
that on prompt processing alone, meaning every attempt just gets
cancelled and retried.

This PR adds `--chat-stream-silence-timeout` /
`CODER_CHAT_STREAM_SILENCE_TIMEOUT` (default `10m`) and passes it to
both the main loop and the advisor. Setting it to `0` disables the guard
entirely, and anything above `24h` is rejected, which also keeps the
watchdog arithmetic below from overflowing.

Whilst doing this I ran into the runner's `15m` task watchdog, which
kept counting during an open stream. That silently cancelled any healthy
stream longer than `15m`, and would've stopped a silence timeout above
`15m` from ever firing. To fix, the silence guard now kicks the watchdog
out to `max(15m, silence + 5m)` whenever it arms or sees a part. Silent
streams still fail through the guard, healthy streams can run for as
long as they like, and hang detection is unchanged everywhere else. With
the guard disabled there's nothing to kick against, so arming it just
stops the watchdog for the rest of the attempt. That does mean the DB
write after the stream isn't bounded either when `0` is set; I think
that's fine for an opt-in setting, and a user can still stop the chat
from the UI if it wedges there.

I did consider removing the guard entirely, but the provider HTTP
clients have no timeout, so a provider that holds the connection open
would only ever be caught as a generic task hang, which is what #25782
was fixing.
2026-09-18 15:24:15 +10:00
Ben Potter 82e602e092 fix(coderd): surface external auth login link when creating a workspace (#28992)
When a template requires a non-optional external auth provider that the
workspace owner hasn't linked yet, `create_workspace` rejects the
request with a 403, but the error never included a way to actually
resolve it. The web UI and CLI don't hit this path in practice, since
they preflight-check `/templateversions/{id}/external-auth` and render a
login button before ever submitting. Coder Agents' `create_workspace`
chat tool has no such preflight, so it's the one place a real user hits
this error, and the assistant could only repeat "external authentication
is required" with no way forward.

`requireWorkspaceOwnerExternalAuth` now includes each missing provider's
authenticate URL in the error `Detail`, and the chatd `create_workspace`
tool's `responseErrorResult` adds an `action_required` hint so the model
reliably tells the user to open the link and retry, instead of just
echoing the raw error.

Fixes
[CODAGT-1011](https://linear.app/codercom/issue/CODAGT-1011/external-authentication-is-required-is-a-dead-end-in-coder-agents)


![Demo](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/recording.gif)

<details>
<summary>Full recording and thumbnail</summary>

-
[mp4](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/recording.mp4)
-
[Thumbnail](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/thumbnail.jpg)
</details>

<details>
<summary>Implementation notes</summary>

- Only the free-text `Detail` string changed. The `Validations` shape
(`Field: "external_auth"`, `Detail: provider.ID`) is untouched, since
it's a separate, tested, machine-readable contract that other code may
rely on.
- Recorded against a local dev instance with a dummy GitHub OAuth
client, so the clip ends right after the assistant surfaces the link.
Following the link past Coder's own external-auth page would fail
regardless of this fix, since there's no real OAuth client secret
configured in that environment.
- Generated by Coder Agents on behalf of @bpmct.
</details>
2026-09-17 19:04:55 -05:00
Steven Masley a90ad83af3 feat!: add a hidden flag to disable dynamic parameter closure evaluation (#29356)
**What changed**
Dynamic parameter rendering now evaluates only the coder parameter blocks and what they reference. Other root-module resources are skipped. Parameter, preset, and tag values are unchanged; optimizing rendering on large templates.

**How to revert**
Set `CODER_DYNAMIC_PARAMETERS_FULL_EVALUATION=true` (or `--dynamic-parameters-full-evaluation`) on `coder server` to restore full evaluation. The flag is hidden and needs no restart of workspaces. If you need it, please [open an issue](https://github.com/coder/coder/issues/new) with the template so we can fix the root cause.

**Troubleshooting**
Symptoms would be a parameter default, option list, preset value, or workspace tag that shows as unknown or empty after upgrading, when it was populated before. Confirm by setting the flag above; if the value comes back, report it. Templates written in `.tf.json` are not affected (they always use full evaluation).

**Why**
Rendering re-ran the entire template graph on every parameter change in the workspace form, which dominated latency on large templates. Resources a workspace would create cannot feed a parameter, so evaluating them is wasted work. The optimization lives in coder/preview#226 (coder/trivy#74); this PR adds the deployment-level escape hatch.

---

- `CODER_DYNAMIC_PARAMETERS_FULL_EVALUATION` / `--dynamic-parameters-full-evaluation` (hidden, default `false`) on `DeploymentValues`.
- `dynamicparameters.PreviewOptions(dv)` maps it to `preview.OptionFullEvaluation()`; `dynamicparameters.WithPreviewOptions` threads it through the loader to `preview.Preview`.
- Wired at the three render paths that hold deployment values: the template version tags extractor, the dynamic parameters websocket, and `wsbuilder` builds created from `coderd` (which call `.DeploymentValues(...)`).

Not covered: the autobuild lifecycle executor and the enterprise prebuilds reconciler construct `wsbuilder` without deployment values, so builds started from those paths use preview's default regardless of the flag. Those only re-render for builds, not the keystroke websocket path the optimization targets.

Prepared with Coder Agents assistance.
2026-09-17 14:33:37 -05:00
Michael Suchacz 26524addda test(coderd/database/migrations): step one migration chain for per-migration tests (#29460)
`coderd/database/migrations` was one of the slowest packages in
`test-go-pg` (about 120s at 92% slot utilization). Most of that was
fixed per-test overhead: `testSQLDB` cloned the migrated template
database and then dropped its whole schema, which cost 2-3s per test,
and each `TestMigration000xxx` then stepped the full chain to its
version.

This change creates the test databases from Postgres' stock `template1`
(`dbtestutil.WithDBFrom`), runs the independent per-migration cases as
subtests of one `TestMigrationChain` that steps the chain once in
version order (each case still calls `next()` and asserts its migration
version; assertions are unchanged), and drops `TestMigrate/Twice`, which
the final `Up` of `UpDownUp` already covers. Cases that apply raw
migration SQL without recording the version, assert whole-table counts,
need `UNIQUE` values another case commits, or need an empty database for
a single-transaction chain stay standalone; they also got faster from
the cheaper database setup.

## Before / After

Local, `go test -count=1 -tags=testsmallbatch -parallel=8
./coderd/database/migrations/`:

| | Before | After |
|---|---|---|
| Package wall time | 23.1s | 7.7s |
| Summed top-level test time | about 176s | about 45s |
| TestMigrate (Once / Parallel / Twice / UpDownUp) | 3.8 / 3.7 / 3.7 /
8.5s | 1.5 / 1.4 / removed / 3.8s |
| TestMigrateUpWithFixtures (4 subtests) | 6.0 to 7.7s each | 3.1 to
3.6s each |
| 14 chained TestMigration000xxx cases | 2.9 to 6.1s each | one 4.7s
TestMigrationChain |
| 14 standalone TestMigration000xxx cases | 0.9 to 8.2s each | 0.7 to
6.2s each |

## Validation

- `go test -count=1 -tags=testsmallbatch -parallel=8
./coderd/database/migrations/` passes (7.7s; 8.6s when re-run on this
rebased head)
- `go test -race -count=1 ./coderd/database/migrations/` passes
- `go test -race -count=2 -shuffle=on -run TestMigrationChain` passes
(shared-fixture leakage check)
- `golangci-lint run ./coderd/database/migrations/...` reports 0 issues
- Repository pre-commit hook (gen, fmt, lint/go) passed on the commit

Part of the test-suite speedup series (see #29457); independent of the
other PRs.

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `6cb9e3602e7` against base `9d973372774` on the same
machine: `coderd/database/migrations` 19.09s to 11.94s (plain) and 8.43s
(`-v` rerun); the speedup there is 1.6x to 2.3x rather than the 3x seen
on the development host, so expect the CI package to land around 50-70s
rather than 40s. `-race -count=3 -shuffle=on -run
'TestMigrationChain|TestMigrate'`: pass; `go test -short` skips
`TestMigrationChain` (`ok 3.9s`); no `Twice` subtest remains and the 14
per-migration tests still run. Endorsed verdict: PASS (speed claim
reproduces within tolerance).


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 20:40:43 +02:00
Michael Suchacz d8041a040c test(coderd/database/dbtestutil): disable Postgres JIT for test databases (#29465)
On near-empty test databases the planner misestimates some queries so
badly that they exceed `jit_above_cost`, and Postgres then LLVM-compiles
them on every call. For `GetUserStatusCounts` that is about 275ms of a
290ms execution (`EXPLAIN (ANALYZE)` on an empty database estimates 5.7M
rows for the `dates_of_interest x relevant_status_changes` nested loop;
actual rows: 61). Multiplied by the 925 leaves of
`TestGetUserStatusCounts`, that single test was 85% of the
`coderd/database` package time.

JIT is an execution optimization with no semantic effect, so
`dbtestutil.NewDB` now runs `ALTER DATABASE <db> SET jit = off` on each
per-test database, next to the existing timezone setting. Database-level
settings are not copied by `CREATE DATABASE ... TEMPLATE`, so this has
to run per clone, which is where the timezone statement already runs;
the `CODER_PG_CONNECTION_URL` path goes through the same function.

## Before / After

Local, `go test -count=1 -tags=testsmallbatch -parallel=8` (shared host,
load about 50):

| | Before | After |
|---|---|---|
| `./coderd/database/ -run '^TestGetUserStatusCounts$'` | `ok 63.2s` |
`ok 6.4s` |
| `./coderd/database/` | `ok 57.2s` | `ok 10.0s` |
| `./coderd/database/dbauthz/` | `ok 7.4s` / `14.0s` | `ok 10.3s` /
`7.6s` (noise) |
| `./coderd/database/dbpurge/` | `ok 4.1s` | `ok 3.8s` |
| `./coderd/httpmw/` | `ok 1.3s` | `ok 1.0s` |

Only `coderd/database` (172s in the baseline CI job) is expected to move
materially; the other packages are listed to show no regression.

## Validation

- The five runs above pass; `TestGetUserStatusCounts` still runs its 925
subtests
- `golangci-lint run ./coderd/database/dbtestutil/...` with a fresh
cache: 0 issues
- Repository pre-commit hook passed on the commit

Production note, not addressed here: with `jit=on` (the default in the
pgdg builds) production pays the same per-call compilation for
`GetUserStatusCounts`; the query shape (`generate_series` cross join
with no statistics on the CTE) deserves its own fix.

Part of the test-suite speedup series (see #29457). Independent of the
other PRs; #29464 (fixture sharing in the same test) composes with it.

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `353879f5d12` against base `9d973372774` on the same machine
(its base time, 56.4s for the package, matches the table above):
`./coderd/database/ -run '^TestGetUserStatusCounts$'` 46.97s to 13.81s
(925 subtests pass on both); `./coderd/database/` 56.43s to 20.49s
(32.48s on a first run); `dbauthz`, `dbpurge`, `httpmw` unchanged;
`-race -count=2 -shuffle=on`: pass. A live `pg_db_role_setting` query
during a test run showed `{TimeZone=...,jit=off}` on every per-test
database and nothing on the `tpl_` template, as intended. The standalone
speedup there is 3.4x for the test and about 2x for the package, less
than the 10x and 5.7x in the table above, which came from a single run
on the development host: on the dogfood host the per-test database clone
dominates once JIT is off. The headline numbers (test 0.6s, package
7.5s) are reached together with #29464, which removes the per-leaf
clone. Endorsed verdict: PASS on behavior; the table above overstates
the standalone gain.


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 20:32:09 +02:00
Michael Suchacz 143aa93d73 test(coderd/notifications): share one pipeline across golden templates (#29459)
`TestNotificationTemplates_Golden` built a coderd server, a second
database and a mock SMTP server for each of its 86 template and method
cases. The rendered output only depends on the recipient row and the
appearance settings, so the test now builds one database, one recipient,
one manager and one mock SMTP and webhook server for the whole run, and
gives an isolated pipeline only to the two templates that render a
different recipient or appearance
(`TemplateUserRequestedOneTimePasscode`,
`TemplateWorkspaceDeleted_CustomAppearance`). Deliveries are serialized
per method because the mock SMTP backend records a single message. Test
names, the `-update` flag and `make gen/golden-files` are unchanged, and
the golden files are byte-identical.

## Before / After

Local, `go test -count=1 -tags=testsmallbatch -parallel=8`, Postgres on
localhost:

| Measurement | Before | After |
|---|---|---|
| `TestNotificationTemplates_Golden` (`ok` line for `-run`) | 5.09s |
1.33s |
| `coderd/notifications` package | 6.55s | 2.84s |
| Sum of the 86 leaf subtest durations (slot time) | 38.4s | 8.3s |

## Validation

- `go test -count=1 -tags=testsmallbatch -parallel=8
./coderd/notifications/ -run '^TestNotificationTemplates_Golden$'` and
the whole package pass
- `TZ=UTC go test ./coderd/notifications -run="Test.*Golden$" -update`
leaves `git status --porcelain coderd/notifications/testdata` empty
- `go test -race -count=2 -shuffle=on -run
'^TestNotificationTemplates_Golden$' ./coderd/notifications/` passes
- `golangci-lint run ./coderd/notifications/...` reports 0 issues

Part of the test-suite speedup series (see #29457); independent of the
other PRs.

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `e44b489be9e` against base `9d973372774` on the same
machine: `coderd/notifications` 7.53s to 2.92s; `-race -count=3
-shuffle=on -run '^TestNotificationTemplates_Golden$'`: pass; `TZ=UTC go
test ./coderd/notifications -run="Test.*Golden$" -update` followed by
`git status --porcelain coderd/notifications/testdata`: empty. Endorsed
verdict: PASS.


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 20:28:06 +02:00
Michael Suchacz 3a945fe37a test(coderd/database): share one database across TestGetUserStatusCounts subtests (#29464)
`TestGetUserStatusCounts` cloned a Postgres database for each of its 756
leaf subtests (6 timezones x 7 report dates x 18 scenarios). The leaves
only need query isolation, so they now run inside a rolled-back
transaction on one shared database via a new
`dbtestutil.StartRolledBackTx` helper (the rollback counterpart of the
existing `StartTx`). Fixtures, assertions, subtest names and parallelism
are unchanged.

One database per scenario, as first sketched, does not work here: every
fixture derives from the case's `reportUntil` and the query aggregates
over all users, so users from different dates cannot coexist in one
database without changing every expected count. Per-transaction
isolation keeps the fixtures byte-identical. The two deleted-user
scenarios set `deleted_at` through the Store (`UpdateUserStatus` with
the intended `updated_at`, which the deletion trigger copies into
`user_deleted`) instead of raw SQL, because a transaction-bound Store
cannot run raw statements; the resulting `user_status_changes` and
`user_deleted` rows are the same as before.

## Before / After

Local, `go test -count=1 -tags=testsmallbatch -parallel=8`:

| | Before | After |
|---|---|---|
| `dbtestutil.NewDB` calls in the test | 756 | 1 |
| `./coderd/database/ -run '^TestGetUserStatusCounts$'` | `ok 63.2s` |
`ok 28.2s` |
| `./coderd/database/` | `ok 57.2s` | `ok 33.0s` |
| Subtests (`=== RUN`) | 925 | 925 |
| Sum of subtest durations | 503s | 222s |
| Together with #29465 (`jit = off` in dbtestutil) | | test `ok 0.7s`,
package `ok 9.7s` |

The remaining 28s is the query itself being JIT-compiled per call, which
#29465 removes; the two changes compose.

## Validation

- `go test -count=1 -tags=testsmallbatch -parallel=8 ./coderd/database/
-run '^TestGetUserStatusCounts$' -v` passes with 925 subtests
- `go test -count=2 -shuffle=on -race -run '^TestGetUserStatusCounts$'
./coderd/database/` passes (shared-fixture leakage check)
- `golangci-lint run` on `coderd/database/` and
`coderd/database/dbtestutil/`: 0 issues
- Repository pre-commit hook passed on the commit

Part of the test-suite speedup series (see #29457).

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `16c8d556c4d` against base `9d973372774` on the same
machine: `./coderd/database/ -run '^TestGetUserStatusCounts$'` 46.97s to
15.05s (925 subtests, 925 pass on both); `./coderd/database/` 56.43s to
22.66s; `-race -count=2 -shuffle=on` on the test: pass; `-parallel=1`:
`ok 23.3s` (the rolled-back transactions do not deadlock when
serialized). With #29465 cherry-picked on top: test `ok 0.58s`, package
`ok 7.49s`. Endorsed verdict: PASS.


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 20:26:57 +02:00
Steven Masley e2ecefb9c7 fix(coderd): recover cache after failed key fetch (#29427)
Context or other transient errors to release cache fetching blocks. Unit
tests added to verify.

Linear: https://linear.app/codercom/issue/PLAT-597
2026-09-17 18:01:13 +00:00
Michael Suchacz 26e4429362 test: fold near-identical test bodies into tables across eight packages (#29463)
Folds groups of near-identical test bodies (same parent, same parallel
flag, differing only in inputs and expected values) into table-driven
tests in eight packages: `coderd/templatebuilder`, `scripts/develop`,
`agent/agentfiles`, `coderd/x/chatd/chatloop`,
`coderd/x/chatd/chatdebug`, `enterprise/aibridgeproxyd`, `cli`, and
`coderd/database/db2sdk`. One commit per package.

Every case keeps its previous subtest name, `t.Parallel()` placement is
unchanged, and the set of `=== RUN` names is identical except where
standalone `TestX_Y` funcs became `TestX/Y` subtests (chatloop: 9 funcs
into `TestExecuteLocalTools_BatchRuntime`; chatdebug: 15 funcs into two
tables). Members whose bodies differ in more than data stayed as they
were (listed per package in the commit messages). In `agent/agentfiles`
the four `TestFuzzyReplace_*` funcs were already tables, so the shared
request plumbing was hoisted into one helper instead of merging the
funcs and losing their per-rule docs. Net -1035 lines across 9 test
files; runtime is unchanged (all sub-100ms unit tests).

| Package | Diff | Funcs removed | Subtests | RUN lines |
|---|---|---|---|---|
| coderd/templatebuilder | +237 / -291 | 0 | 31 -> 31 | 33 -> 33 |
| scripts/develop | +194 / -246 | 0 | 27 -> 27 | 28 -> 28 |
| agent/agentfiles | +117 / -260 | 0 | unchanged | 58 -> 58 |
| coderd/x/chatd/chatloop | +224 / -306 | 9 | 3 -> 12 | 14 -> 15 |
| coderd/x/chatd/chatdebug | +251 / -537 | 13 | 0 -> 15 | 42 -> 44 |
| enterprise/aibridgeproxyd | +287 / -419 | 0 | 31 -> 31 | 32 -> 32 |
| cli | +143 / -326 | 0 | 15 -> 15 | 16 -> 16 |
| coderd/database/db2sdk | +130 / -233 | 0 | 9 -> 9 | 10 -> 10 |

## Validation

- Per package: `go test -count=1 -tags=testsmallbatch -parallel=8
./<pkg>/ -run <regex> -v` before and after, with the `=== RUN` name sets
diffed
- `go test -race -count=2 -shuffle=on` on each converted test: pass
- `golangci-lint run ./<pkg>/...` with a fresh cache: 0 issues in all
eight packages
- Repository pre-commit hook (including lint/go) passed on every commit

Part of the test-suite speedup series (see #29457); independent of the
other PRs.

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `d7c55d6b0e8` against base `9d973372774`: all eight packages
pass on the head and under `-race -count=3 -shuffle=on`; package times
are sub-second on both sides (unchanged). `=== RUN` name sets: chatloop
15 to 16 lines with all nine `TestExecuteLocalTools_<X>` leaves
surviving as `TestExecuteLocalTools_BatchRuntime/<X>`; chatdebug 42 to
44; `aibridgeproxyd` `TestNew` 32 to 32, byte-identical sorted list. One
correction to the text above: seven chatdebug leaves are renamed, not
preserved verbatim (`TestRecordingTransport_*UnknownLength*` became
`TestRecordingTransport_UnknownLengthClose/<name without
"UnknownLength">`), so `-run` filters keyed on those old names need
updating. Endorsed verdict: PASS.


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 19:26:18 +02:00
Michael Suchacz d2e94e299a chore: delete dead functions and skip-only or duplicated tests (#29461) 2026-09-17 18:14:08 +02:00
Michael Suchacz 7a27db2635 fix(coderd): fetch the DERP map immediately in the server tailnet (#29462) 2026-09-17 18:12:24 +02:00
Jake Howell dd4f5ae48a fix: load AI Gateway session provider filter without AIProvider read (#28966)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

The Provider filter on `/ai-gateway` called the owner-only
provider-config API (`GET /api/v2/ai/providers`). Site auditors can read
sessions but not that config, so the dropdown was empty, and typing
`provider_name:…` failed the whole sessions list because search looked
up the name with the same permission.

- Add `GET /api/v2/ai-gateway/providers`, returning display metadata
only (`name`, `type`, `display_name`, `icon`) from `ai_providers`,
including disabled and soft-deleted rows that past sessions still
reference. When a name was reused, the live row wins.
- Authorize it in `dbauthz` on `aibridge_interception` read rather than
`ai_provider` read, so owners and auditors get labels and icons without
access to configuration. Members get 404.
- Match `provider_name` as a plain string in session search instead of
looking up `ai_providers`. Unknown names return an empty page, not a
validation error.
- Point the Provider dropdown at the new endpoint; filter by name, show
`display_name`, and render the icon from `type`/`icon`.

The endpoint reads the small `ai_providers` table instead of grouping
`aibridge_interceptions`, so it needs no new index and does not inherit
the scan cost noted for the models/clients lists. It is registered only
under `/ai-gateway`, not the legacy `/aibridge` alias.
2026-09-17 15:29:21 +00:00
Michael Suchacz 8397680687 fix: keep text and image together in MCP tool results (#29332)
## Problem

MCP tool results that mix text and an image (Playwright's default
`browser_take_screenshot` returns `[text, image]`) were reduced to text
only in both MCP conversion paths, so screenshots never reached the
model. The generic tool renderer also showed media results as a JSON
dump of base64.

## Fix

- `mcpclient` and `chattool`: keep all text plus the first usable binary
item. Error flags survive empty and MIME-less results. Only one binary
payload is represented; additional images are still dropped.
- `chatloop`: at execution time, cap tool media at the 10 MiB attachment
limit and correct or reject declared image types by byte signature
(sniffing, not decoding).
- `chatd` prompt build and `chatprovider`: at generation and compaction,
replace media the destination provider cannot accept with the text plus
an omission note (Anthropic/Bedrock: JPEG, PNG, GIF, WebP under the
inline cap; OpenAI/Azure and Google: their image allowlists, applying
the configured vendor's rules behind `openai-compat`). Persisted history
is unchanged, so the UI keeps the payload and provider switches keep
working.
- `site`: results flagged `is_media` render through `ToolResultMedia`
(image with the existing lightbox, or a short notice for non-image
media, plus the text). Unflagged media-shaped JSON stays in the JSON
viewer.
- `go.mod`: pin [coder/fantasy
`9a3598480a71`](https://github.com/coder/fantasy/commit/9a3598480a71e45901bfcfbf566ffa42c6bbdd63),
main's `a511353f83eb` plus the batch-order fix `460d4fdd113b` (Chat
Completions and compatible transports emit every tool result before
synthetic user images). The fix lives on
`mike/mcp-tool-media-batch-order`; no upstream PR yet.

## Validation

Round 3 dogfood UAT on this head, `522bd76a58a`: **PASS**
([chat](https://dogfood.cdr.dev/agents/5e617636-c6f2-46fc-96e5-97ae35ed822e),
real Playwright MCP, Claude Haiku 4.5 and GPT-4o mini through the AI
gateway). Verified in the UI and on the wire: image plus text render
together, the lightbox opens and closes, both survive a reload; audio
shows a notice instead of base64; media-shaped JSON stays in the JSON
viewer; BMP on OpenAI Responses and Chat Completions reaches the model
as text plus an omission note; SVG and PNG histories switch from
Anthropic to OpenAI; cross-provider compaction through the organization
override works; a result over 10 MiB persists only text plus a note, and
a 5.5 MiB PNG is substituted for Anthropic yet still renders in the UI.
Google is not routable on the dogfood gateway (404), so it was not
exercised. The remote agent's own FAIL was a probe artifact (the code
viewer renders in a shadow root) and was overturned on its screenshots
by the independent runner. Rounds 1 and 2 (`65db84a`, `5001de7`) covered
the same API surface earlier.

Known limits: signature sniffing does not catch a truncated PNG with a
valid header (providers return 400 for it), and only the first binary
item of a result is kept. Pre-existing and out of scope: chatd opens a
new MCP session per generation action, so Playwright's default
per-session browser loses page state between steps (UAT used
`--cdp-endpoint`).

Reviews:

| Review | Head | Outcome |
|---|---|---|
| Codex 1 to 5 | `472914f` to `bcf4c72` | 16 findings (empty binary
promoted over text, no provider caps, SVG on Anthropic, provider-switch
gap, Bedrock labels, unbounded media, unvalidated bytes, renderer
gating, lightbox test), all fixed |
| Codex 6, 7 | `8a9a9e0`, `5001de7` | no major issues; one Responses
audio concern [refuted with a live
probe](https://github.com/coder/coder/pull/29332#discussion_r4018514197)
|
|
[Codex](https://github.com/coder/coder/pull/29332#pullrequestreview-5226106293)
| `83e1a10` | two P2s refuted with serializer captures
([MIME](https://github.com/coder/coder/pull/29332#discussion_r4029188332),
[advisor](https://github.com/coder/coder/pull/29332#discussion_r4029160781));
[reassessment](https://github.com/coder/coder/pull/29332#issuecomment-5702295886)
clean |
| Codex | `522bd76` | [no major
issues](https://github.com/coder/coder/pull/29332#issuecomment-5713663081)
on the rewritten tests |
| @DanielleMaywood | `472914f`, `5001de7` | renderer restructure and
explicit audio mapping done; lazy slice cloning removed; two threads
left open for her re-check |

Local pre-push hooks were skipped per Mike's instruction; CI is the
gate.

> Xum acted on Mike's (@ibetitsmike) behalf to create this PR.
2026-09-17 15:09:19 +02:00
Hugo Dutka e9201ee4df fix(coderd/x/chatd): correct worker intervals (#29334)
Addresses
https://linear.app/codercom/issue/CODAGT-916/chat-heartbeat-interval-staleness-and-others-are-set-to-wrong-values
2026-09-17 11:30:14 +02:00
cdrciandgithub-actions[bot] b36311eae8 chore: refresh AI model price book (#29471)
## Price book changes

36 models added, 13 models removed, 96 models changed.

<details>
<summary>Added</summary>

- bedrock/apac.anthropic.claude-sonnet-4-20250514-v1:0
- bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0
- bedrock/global.anthropic.claude-sonnet-4-20250514-v1:0
- bedrock/google.gemma-4-26b-a4b
- bedrock/google.gemma-4-31b
- bedrock/google.gemma-4-e2b
- bedrock/in.openai.gpt-5.6-luna
- bedrock/in.openai.gpt-5.6-terra
- bedrock/us-gov.openai.gpt-oss-120b-1:0
- bedrock/us-gov.openai.gpt-oss-20b-1:0
- bedrock/us.amazon.nova-premier-v1:0
- bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0
- openrouter/inclusionai/ling-3.0-flash-vl
- openrouter/inclusionai/ling-3.0-flash-vl:free
- openrouter/inference-net/schematron-v2-small
- openrouter/inference-net/schematron-v2-turbo
- openrouter/sakana/fugu-max
- openrouter/sakana/fugu-ultra-v2
- openrouter/stealth/union-alpha
- openrouter/z-ai/glm-5.2:free
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-pro-latest
- openrouter/~openai/gpt-astra-latest
- openrouter/~openai/gpt-luna-latest
- openrouter/~openai/gpt-sol-latest
- openrouter/~openai/gpt-terra-latest
- vercel/bytedance/seed-2.1-turbo
- vercel/deepseek/deepseek-v4.1-flash
- vercel/google/gemini-3.8-live
- vercel/google/gemini-3.8-live-extended-thinking
- vercel/inclusionai/ling-3.0-flash-vl
- vercel/inclusionai/ling-3.0-flash-vl-free
- vercel/inference-net/schematron-v2-small
- vercel/inference-net/schematron-v2-turbo
- vercel/sakana/fugu-max
- vercel/sakana/fugu-ultra-v2
</details>

<details>
<summary>Removed</summary>

- openrouter/google/gemini-2.5-pro-preview-05-06
- openrouter/openai/gpt-4-turbo-preview
- openrouter/~openai/gpt-latest
- vercel/alibaba/qwen3.8-flash-next
- vercel/deepseek/deepseek-v4.1-flash-beta
- vercel/kwaipilot/kat-coder-air-v2.5
- vercel/kwaipilot/kat-coder-pro-v1
- vercel/kwaipilot/kat-coder-pro-v2
- vercel/kwaipilot/kat-coder-pro-v2.5
- vercel/mistral/devstral-2
- vercel/mistral/devstral-small-2
- vercel/mistral/mistral-medium
- vercel/mistral/pixtral-12b
</details>

<details>
<summary>Changed</summary>

- bedrock/amazon.nova-2-lite-v1:0
- bedrock/amazon.nova-lite-v1:0
- bedrock/amazon.nova-micro-v1:0
- bedrock/amazon.nova-pro-v1:0
- bedrock/anthropic.claude-opus-4-6-v1
- bedrock/anthropic.claude-sonnet-4-6
- bedrock/apac.amazon.nova-lite-v1:0
- bedrock/apac.amazon.nova-micro-v1:0
- bedrock/apac.amazon.nova-pro-v1:0
- bedrock/au.anthropic.claude-haiku-4-5-20251001-v1:0
- bedrock/au.anthropic.claude-opus-4-6-v1
- bedrock/au.anthropic.claude-opus-4-8
- bedrock/au.anthropic.claude-opus-5
- bedrock/au.anthropic.claude-sonnet-4-5-20250929-v1:0
- bedrock/au.anthropic.claude-sonnet-5
- bedrock/ca.amazon.nova-lite-v1:0
- bedrock/eu.amazon.nova-2-lite-v1:0
- bedrock/eu.amazon.nova-lite-v1:0
- bedrock/eu.amazon.nova-micro-v1:0
- bedrock/eu.amazon.nova-pro-v1:0
- bedrock/global.amazon.nova-2-lite-v1:0
- bedrock/google.gemma-3-12b-it
- bedrock/google.gemma-3-27b-it
- bedrock/jp.amazon.nova-2-lite-v1:0
- bedrock/jp.anthropic.claude-haiku-4-5-20251001-v1:0
- bedrock/jp.anthropic.claude-opus-4-7
- bedrock/jp.anthropic.claude-opus-4-8
- bedrock/jp.anthropic.claude-opus-5
- bedrock/jp.anthropic.claude-sonnet-4-5-20250929-v1:0
- bedrock/jp.anthropic.claude-sonnet-4-6
- bedrock/jp.anthropic.claude-sonnet-5
- bedrock/mistral.voxtral-small-24b-2507
- bedrock/qwen.qwen3-coder-480b-a35b-v1:0
- bedrock/qwen.qwen3-coder-next
- bedrock/qwen.qwen3-next-80b-a3b
- bedrock/qwen.qwen3-vl-235b-a22b
- bedrock/us.amazon.nova-2-lite-v1:0
- bedrock/us.amazon.nova-lite-v1:0
- bedrock/us.amazon.nova-micro-v1:0
- bedrock/us.amazon.nova-pro-v1:0
- bedrock/us.anthropic.claude-fable-5
- bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0
- bedrock/us.anthropic.claude-opus-4-5-20251101-v1:0
- bedrock/us.anthropic.claude-opus-4-6-v1
- bedrock/us.anthropic.claude-opus-4-7
- bedrock/us.anthropic.claude-opus-4-8
- bedrock/us.anthropic.claude-opus-5
- bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0
- bedrock/us.anthropic.claude-sonnet-4-6
- bedrock/us.anthropic.claude-sonnet-5
- openrouter/deepseek/deepseek-chat-v3-0324
- openrouter/deepseek/deepseek-v4-flash-0731
- openrouter/deepseek/deepseek-v4-pro
- openrouter/deepseek/deepseek-v4-pro-0813
- openrouter/google/gemma-4-26b-a4b-it
- openrouter/gryphe/mythomax-l2-13b
- openrouter/meta-llama/llama-4-maverick
- openrouter/meta/muse-glimmer-30b
- openrouter/minimax/minimax-m1
- openrouter/minimax/minimax-m2.5
- openrouter/mistralai/mistral-small-3.2-24b-instruct
- openrouter/moonshotai/kimi-k2.7-code
- openrouter/nvidia/nemotron-3-nano-30b-a3b
- openrouter/nvidia/nemotron-3-super-120b-a12b
- openrouter/qwen/qwen3-14b
- openrouter/qwen/qwen3-235b-a22b-2507
- openrouter/qwen/qwen3-30b-a3b-instruct-2507
- openrouter/qwen/qwen3-vl-30b-a3b-instruct
- openrouter/qwen/qwen3.5-35b-a3b
- openrouter/qwen/qwen3.8-27b
- openrouter/upstage/solar-pro4
- openrouter/z-ai/glm-4.6
- openrouter/z-ai/glm-5.2
- openrouter/z-ai/glm-5.3-flash
- openrouter/~deepseek/deepseek-v4-flash-latest
- openrouter/~moonshotai/kimi-latest
- openrouter/~z-ai/glm-latest
- vercel/alibaba/qwen-3.6-max-preview
- vercel/alibaba/qwen3.5-flash
- vercel/alibaba/qwen3.5-plus
- vercel/alibaba/qwen3.6-plus
- vercel/alibaba/qwen3.8-flash
- vercel/alibaba/qwen3.8-max
- vercel/amazon/nova-lite
- vercel/amazon/nova-micro
- vercel/amazon/nova-pro
- vercel/deepseek/deepseek-v3.2
- vercel/inclusionai/ling-3.0-flash
- vercel/mistral/ministral-14b
- vercel/mistral/mistral-large-3
- vercel/mistral/mistral-medium-3.5
- vercel/mistral/mistral-nemo
- vercel/mistral/mistral-small
- vercel/moonshotai/kimi-k2.5
- vercel/nvidia/nemotron-3-nano-30b-a3b
- vercel/openai/gpt-oss-20b
</details>

## Review notes

Regenerated by `make gen/aibridge-prices` from the live
[models.dev](https://models.dev) catalog. Both artifacts come from one
snapshot, so they ship together:

- `coderd/aibridge/prices/data/prices.json`
- `site/src/modules/aiModels/knownModels/knownModelsGenerated.json`

These are customer-visible cost numbers taken from upstream data, so
this PR is never merged automatically. The summary above lists what
moved; check the diff for exact figures before approving.

Opened automatically by the [aigateway-prices-refresh
workflow](https://github.com/coder/coder/actions/runs/35203280221).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-09-17 10:28:05 +01:00
Paweł Banaszewski 263f2c207e feat: register AI Gateway proxy experiment and share provider helpers (#29347)
- Add `ai-gateway-reverse-proxy` experiment and update generated API
types and documentation. The experiment has no runtime effect yet.
- Extract shared (will be used by next PRs in stack) provider routing
and key-pool enumeration helpers.
- Log unsupported routes at Debug level.
2026-09-17 10:27:48 +02:00
Michael Suchacz 9d97337277 feat: list organization AI spend by user (#29129)
Third of a four-PR stack that reworks the AI spend page onto the
released organization spend export, `GET
/api/v2/organizations/{organization}/ai/spend/export`, and a sibling
per-user endpoint, `GET
/api/v2/organizations/{organization}/ai/spend/users`, instead of the
deployment-wide `/api/v2/ai-gateway/spend/*` endpoints this stack
previously proposed. Every PR in the stack was rewritten in place from
current main; the head branch name predates the rework. The export's
accounting rules are unchanged: token usage by `created_at` in
`[period_start, period_end)`, attributed to the organization through the
effective budget group, so the page reconciles with the CSV and with
daily budget accounting.

Adds `GET /api/v2/organizations/{organization}/ai/spend/users`, a
paginated per-user report beside the CSV export. It accepts the export's
period parameters and the optional `provider_name`, `model`, and
`client` filters (`client` matches after `COALESCE(client, 'Unknown')`,
as the AI Gateway sessions listing does), and it authorizes identically
through `ResourceGroupMember` in the organization. The response is
`OrganizationAISpendReport`: the applied period bounds,
`retention_start` when retention is enabled (so the page can bound its
date picker), the user count, a `totals` object over every matching
user, and one page of users (`limit` default 10, max 100; `offset` >=
0), each with cost, unpriced usage count, providers, and clients. Each
user row also lists the sorted distinct models they spent through
(e73049f, added on request after the review round).

The period rules (provided together, at most 31 days, within retention,
default narrowed to retention) are shared with the export through the
caller's query parser. As a result the export now rejects unknown query
parameters whether or not a period is given; previously the
excess-parameter check only ran in the explicit-period branch. The
export's parameters and output are otherwise unchanged; the CSV itself
is not filterable.

The JSON rows are per user while the CSV keeps its user x group x
provider x model grain. That is deliberate: the page is the only JSON
consumer, and an explicit `group_by` can be added later without changing
this contract. A page past the last user still carries the window
totals, read from the first page.

Query cost, measured on PostgreSQL 13 with 400k token usages and 200k
interceptions across 4 organizations (31-day window of about 52k usages
for the target organization): `ListOrganizationAISpendUsers` 128 ms
unfiltered and 68 ms filtered by provider. Token usage is read through
the existing partial index on `(effective_group_id, created_at)`; no new
index is needed. The provider and client aggregates were added after
this measurement.

Tests cover pagination validation (including the export rejecting page
parameters), report contents and filters against the CSV, retention
narrowing and rejection, retention disabled, and the role matrix (Owner,
User Admin, Auditor, Org Admin, Org User Admin OK; member 403; other
organization 404).

Previous revisions served this report from the export endpoint through
`Accept` negotiation and also added the dimension filters to the CSV
export (#29220, #29224); the separate endpoint replaces the former, and
the CSV filters were dropped because the page does not use them.

> Xum prepared this PR on behalf of @ibetitsmike.

Codex on e73049f: P2 on the moving `now - retention` lower bound for
clients that echo the default window while paging. Declined: it is the
released CSV export's contract, the report echoes `retention_start`, and
the page never echoes the default window; the handler and tests now use
`OrganizationAISpendPage` (8cdc127).
2026-09-17 04:32:16 +00:00
Michael Suchacz 2e03073938 feat(coderd/database): add paginated organization AI spend user query (#29219)
First of a four-PR stack that reworks the AI spend page onto the
released organization spend export, `GET
/api/v2/organizations/{organization}/ai/spend/export`, and a sibling
per-user endpoint, `GET
/api/v2/organizations/{organization}/ai/spend/users`, instead of the
deployment-wide `/api/v2/ai-gateway/spend/*` endpoints this stack
previously proposed. Every PR in the stack was rewritten in place from
current main; the head branch name predates the rework. The export's
accounting rules are unchanged: token usage by `created_at` in
`[period_start, period_end)`, attributed to the organization through the
effective budget group, so the page reconciles with the CSV and with
daily budget accounting.

Adds `ListOrganizationAISpendUsers`, the per-user aggregate behind the
users endpoint. It shares the export query's joins and predicates,
groups to one row per user with priced cost, a count of unpriced usage,
and the sorted distinct providers, clients, and models the user spent
through (a missing client is reported as `Unknown`, as in the sessions
list), carries the window totals (`count`, `total_cost_micros`,
`total_unpriced_usage_count`) as window aggregates ahead of
`LIMIT`/`OFFSET`, and orders by cost, then username, then user ID.
Because every row carries those totals, dbauthz requires read access to
every group member in the organization before running the query, instead
of filtering rows by the caller's own membership.

Includes the dbauthz wrapper and test, the dbmetrics and dbmock
regeneration, and querier tests for grouping, totals across pages,
filters, providers, clients, and models, shifted period windows
(including token usage recorded outside the window of the interception
that produced it), and organization isolation.

> Xum prepared this PR on behalf of @ibetitsmike.
2026-09-17 04:32:15 +00:00
Jake Howell d671150abc feat: filter templates using classic parameters (#29171)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Adds a `compatibility-mode` template filter and exposes it as a
templates page preset.

The classic parameters warning now links administrators to the filtered
template list so they can identify and update affected templates.
2026-09-17 11:11:38 +10:00
Bobby Ho 7f09a66a12 fix(coderd/coderdtest): disable IPv6 dial on the embedded DERP node (#29437)
Set IPv6: "none" on the coderdtest DERP node, matching tailnettest, to prevent unnecessary IPv6 dials. This fixes intermittent macOS goleak failures in support/TestRun, where slow socket cleanup leaves a derphttp.dialNode goroutine running after the IPv4 dial succeeds.

Fixes PLAT-289.
2026-09-16 15:35:51 -07:00