Commit Graph
5116 Commits
Author SHA1 Message Date
Mathias Fredriksson 6239c3ac94 fix(coderd/database): poll only root chat git refs (#31920)
Diff-status rows on subagent chats still consume provider requests.
Move their refs to root chats so the root chat's Git panel shows them,
and limit diff-status refresh to rows on root chats.

Recognize a subagent chat when root_chat_id or parent_chat_id is set,
matching Chat.IsSubChat.

Keep existing root rows on conflict. Otherwise retain the most recently
refreshed row from a subagent chat, with its metadata and timestamps.
2026-11-30 16:21:47 +02:00
Ethan c95f3a58f9 chore: remove the remaining export_test.go shims (#32434)
Closes CODAGT-1607

Follow-up to #32162, which left 5 `export_test.go` shims behind:
`coderd`, `aibridged`, `chatd`, `chatstate` and `mcpclient`. This PR
removes them. It's stacked on #32433, which deals with the chat
workspace functions in `coderd`.

Same approach as before. Tests of package internals are now
`*_internal_test.go` files, with no changes beyond what the move forces,
and tests that only needed a constant just use the value. `chatstate`
needed one small accessor, so `AllowedExecutionTransitionOutputs` is
just exported for real, and its tests stay where they were.
Unfortunately the `mcpclient` connect budget test needs an unexported
timeout, so it moved to an internal file and builds its own server
there.

I've removed `TestConnectAll_LateServerReaped`,
`TestAllExecutionStates_Enumeration` and a few assertions instead of
moving them, as I couldn't find a breakage that only they would catch.

While here, I've dropped the test-only `reaperDone` hook from
`mcpclient`. The wait for a connect to finish within its budget is now a
small function of its own, with a test that a session which connects too
late still gets closed. Nothing checked that before.

With no shims left, the `testpackage` path exclusion is gone, so a new
`export_test.go` now fails lint.
2026-12-01 00:17:20 +11:00
Ethan 2d725a1ced refactor(coderd): move the chat start decision into the start tool (#32433)
Closes CODAGT-292
Relates to CODAGT-1607

`coderd/export_test.go` re-exported `chatCreateWorkspace`,
`chatStartWorkspace`, `chatStopWorkspace` and
`chatRenderTemplateParameters`, just so four tests could call them
directly. This PR removes those tests and their aliases, and the last
alias in that file goes in the next PR in the stack.

The start and stop tests only checked which template version the build
ends up on. That decision lived in `coderd`, behind the function the
tool calls, so the only way to test it was to call that function
directly. Now `start_workspace` makes the decision itself, much like
`coder start` does: it checks whether the template requires its active
version, sends that version with the build request, and tells the model
how to retry when the update needs parameters. All of that is covered by
the tool's own tests. With the decision gone, the start and stop
functions were identical, so both tools now share `chatBuildWorkspace`,
which just creates a build as the workspace owner.

Two small behaviour changes. `start_workspace` now returns `template_id`
whenever it asks the model to retry with parameters. Previously it was
missing for templates on the classic parameter flow, even though the
message says to use it. The tool also reads the template's setting
directly, like `coder start`, so chat updates on start too when the
setting is still on after a licence lapses.

`TestStartWorkspaceTool_EndToEnd` now starts a workspace whose active
version needs a new parameter, so we still know the whole flow works
against a real `coderd`.

`chatRenderTemplateParameters` keeps a direct test, it's just an
internal one now, against a database instead of a whole `coderd`. It no
longer checks the owner default, as that's already tested in the
renderer and in the tool. The bind failure test needs a real
transaction, so it moves to `chatd` and runs through the
`create_workspace` tool.
2026-12-01 00:17:20 +11:00
Dean Sheather 688a0f9b3e refactor: use go-jose for all JWT handling (#31931)
Closes ENG-1510.

First-party code used two JWT libraries: `go-jose/v4` (workspace apps,
jwtutils, tailnet resume, agent hooks, chats) and `golang-jwt/jwt/v4`
(licenses, Azure OIDC PKI, test signers, and `jwt.MapClaims` in
idpsync). This moves everything to go-jose and removes
`golang-jwt/jwt/v4` from `go.mod`.

- `enterprise/coderd/license`: verification uses `jwt.ParseSigned` with
an EdDSA allowlist and `kid` lookup. Time claims are validated with zero
leeway, matching golang-jwt's previous behavior instead of go-jose's 1
minute default. `ParseClaimsIgnoreNbf` still returns `ErrMultipleIssues`
for any verification or time-claim failure other than `nbf`. `Claims`
now embeds `jwtutils.RegisteredClaims`, so `ExpiresAt` becomes `Expiry`
and `NumericDate` uses `.Time()`.
- `coderd/oauthpki`: the Azure client assertion is signed with go-jose
and keeps the `typ: JWT` and `x5t` headers that the existing test
asserts.
- Test helpers (`coderdtest`, `oidctest`, `coderdenttest`) sign with
go-jose.
- `jwt.MapClaims` is replaced with `map[string]any`. No callers used its
methods.
- A depguard rule (`single_jwt_library`) rejects new
`github.com/golang-jwt/jwt` imports.

`golang-jwt/jwt/v5` stays as an indirect dependency through
`SherClockHolmes/webpush-go`.

<details>
<summary>Decision log</summary>

- **Why go-jose over golang-jwt:** `coderd/jwtutils/jwe.go` needs JWE,
which golang-jwt doesn't support, so only go-jose can be the single
library. go-jose was already used for the more security-sensitive token
paths, and `coreos/go-oidc` depends on it anyway. Its `ParseSigned`
requires an explicit algorithm allowlist. Moving the golang-jwt usages,
which were mostly `MapClaims`, was the smaller change.
- **Expiry edge case:** golang-jwt treated a license as expired at `now
>= exp`, and go-jose treats it as expired at `now > exp`. With
whole-second timestamps the difference is at most one second.
- **Not evaluated:** a comparison of CVE history or maintenance pace
between the two libraries.

</details>

Validation: `make pre-commit`. Tests: `enterprise/coderd/license`,
`enterprise/coderd` (license, trial, OIDC, and sync tests),
`enterprise/trialer`, `enterprise/coderd/usage`,
`enterprise/coderd/enidpsync`, `coderd/oauthpki`, `coderd/idpsync`,
`coderd/coderdtest/oidctest`, `coderd` (OIDC, login, Google instance
identity, and OAuth2 tests), `coderd/externalauth`,
`coderd/provisionerdserver`, `cli`. I confirmed the depguard rule flags
a `golang-jwt/jwt/v5` import.

> Generated with Coder Agents on behalf of @deansheather.
2026-11-30 11:23:42 +01:00
Ethan 6993824dd1 feat: allow scoped tokens to manage AI resources (#32653)
Closes CORE-916

A token can only be created with scopes from a hand-kept list of
requestable names, and that list has nothing for most Coder Agents
resources. As a result, a CI job that manages AI providers, MCP servers,
models or the system prompt, or one that just starts a chat, has to hold
an unscoped token.

This PR adds the names for `chat`, `ai_provider`, `mcp_server_config`
and `deployment_config`, the rest of `chat_model_config`, plus
`organization_member:read` and `assign_role:read`, which our Terraform
jobs also need.

I've tested locally that the calls of our dogfood Terraform plan and
apply jobs, and of `triage-via-chat-api.yaml`, all work with tokens that
hold only the scopes each job needs. That caught one bug, where `GET
/api/v2/organizations/{organization}/chats/models` returned a 403 to a
`chat_model_config:*` token, as the handler only accepted the exact
`chat_model_config:read` scope. It now accepts any scope that covers it.

Whilst here, I've corrected the description of
`deployment_config:update`, which the scopes reference gave as "Updating
health information."
2026-11-30 16:16:34 +11:00
Ethan ac92143dbe refactor!: remove the AI Gateway provider list route (#32651)
Relates to AIGOV-824

Stacked on #32650.

`GET /api/v2/ai-gateway/providers` was added in #28966, in September,
and first shipped in v2.38.0. It was a fix for the provider filter on
the AI Gateway sessions page. That filter called `GET
/api/v2/ai/providers`, which only owners could read, so the dropdown was
empty for auditors. Rather than open up the provider config, #28966
added a second route that returns just the `name`, `type`,
`display_name` and `icon` of every provider, deleted ones included, to
anyone who can read sessions, i.e. owners and auditors.

Now that `GET /api/v2/ai/providers` answers every signed-in user with
those same fields (#32650), the second route has no caller that it alone
can serve. Jake, who added it, and I agree that we should remove it
rather than keep two routes that list providers, so this PR does that.

The one thing only the old route did was return deleted providers, so
that sessions and spend recorded under a provider that has since been
deleted keep their label. So, `GET /api/v2/ai/providers` gains an
`include_deleted` query parameter. A deleted provider can share its name
with a live one, so each name appears once, as its live provider if
there is one, otherwise the most recently updated deleted one. Unlike
the old route, any caller can pass it, so members can now see the names
of deleted providers. A deleted provider comes back without its
configuration, for owners too.

The sessions provider filter and the Spend page now call `GET
/api/v2/ai/providers?include_deleted=true`, and show the same thing as
before. `codersdk.AIBridgeProvider`, `Client.AIBridgeListProviders` and
the `GetAIProviderFilterOptions` query go with the route.

## For changelog

- `GET /api/v2/ai-gateway/providers` has been removed (#32651)

> `GET /api/v2/ai-gateway/providers` has been removed, along with
`codersdk.AIBridgeProvider` and `Client.AIBridgeListProviders` in the Go
SDK. It listed providers only for users who can read AI Gateway
sessions, i.e. owners and auditors. `GET /api/v2/ai/providers` replaces
it, and now answers every signed-in user. Owners still get each
provider's full configuration from it, and everyone else gets the same
list with an empty `base_url`, an empty `api_keys` array, `null`
`settings` and no `status`.
  >
> Migration: Call `GET /api/v2/ai/providers?include_deleted=true`
instead. Each provider keeps its `name`, `type`, `display_name` and
`icon` fields, and `display_name` now holds the provider name when no
display name is set. In the Go SDK, `Client.AIProviders` now takes a
`codersdk.AIProvidersFilter`. Set its `IncludeDeleted` field to list
deleted providers too. An API token with an allow list needs
`ai_provider` in that list to call `GET /api/v2/ai/providers`, where the
removed route needed `aibridge_interception`.
2026-11-30 16:16:34 +11:00
Ethan fd74a160ec feat: let all users list AI providers (#32650)
Closes AIGOV-824

`GET /api/v2/ai/providers` now answers every signed-in user. Before, it
returned a 403 to anyone who isn't an owner.

Owners get exactly what they did before. Everyone else gets the same
list without each provider's configuration, i.e. `base_url`, `api_keys`,
`settings` and `status` come back empty:

```json
[
  {
    "id": "90f4a82a-c945-4598-93be-be9dde57c38d",
    "type": "openai",
    "name": "corp-openai",
    "display_name": "Corp OpenAI",
    "icon": "/icon/openai.svg",
    "enabled": true,
    "base_url": "",
    "api_keys": [],
    "settings": null,
    "created_at": "2026-11-24T11:56:44.789072Z",
    "updated_at": "2026-11-24T11:56:44.789072Z"
  }
]
```

Clients need the list to find out what a provider is called. They reach
a provider through AI Gateway at `/api/v2/ai-gateway/<provider-name>/`,
and the name is whatever an admin chose. Mux, for example, lists
providers with `GET /api/v2/ai/providers`, so a member's Mux only finds
providers that happen to have a default name.

To do this, I've split the permission in two. `ai_provider:read` now
only covers the fields that are filled in above, and every member holds
it, the same way they can read OAuth2 apps and workspace proxies. A
provider's base URL, keys and settings sit behind a new
`ai_provider:read_secret` permission, which only owners hold. `GET
/api/v2/ai/providers/{idOrName}` and the dashboard's AI settings pages
now check `ai_provider:read_secret`, so they're still owner only.

This doesn't show members much that's new. They can already read the
name, type, display name, icon and enabled state of every enabled
provider from `GET /api/v2/users/{user}/ai-provider-keys`, so the
additions are disabled providers and the two timestamps.

The next PR in the stack removes `GET /api/v2/ai-gateway/providers`,
which `GET /api/v2/ai/providers` replaces.
2026-11-30 16:16:33 +11:00
coder-automations[bot]andgithub-actions[bot] 273adb2a2b chore: refresh AI model price book (#32783)
## Price book changes

28 models added, 62 models removed, 71 models changed.

<details>
<summary>Added</summary>

- azure/fw-deepseek-v4.1-flash
- azure/fw-glm-5.3
- azure/fw-glm-5.3-flash
- azure/fw-kimi-k3
- azure/fw-kimi-k3.1-pro
- azure/fw-nemotron-3-ultra-nvfp4
- azure/fw-nemotron-lightning-3.5-30b-a3b
- azure/gpt-oss-120b
- azure/grok-4.7
- azure/kimi-k3.1-pro
- bedrock/ca.anthropic.claude-haiku-5-5
- bedrock/ca.anthropic.claude-sonnet-5-5
- bedrock/in.moonshotai.kimi-k3
- bedrock/in.moonshotai.kimi-k3.1
- bedrock/writer.palmyra-vision-7b
- openai/gpt-6-astra-healthcare
- openai/gpt-6.1-sol-healthcare
- openai/gpt-6.2-astra-healthcare
- openai/gpt-6.2-sol-healthcare
- openrouter/mistralai/pixtral-large-2502
- openrouter/radixark/daisyrose-27b
- openrouter/thinkingmachines/inkling-2-mini
- openrouter/tngtech/deepseek-r1t2-chimera
- openrouter/upstage/solar-mini-4-5
- openrouter/upstage/solar-pro-4-contributor
- openrouter/xiaomi/mimo-v2.6-flash-mopd
- vercel/google/gemini-4-neon-fast
- vercel/thinkingmachines/inkling-2-mini
</details>

<details>
<summary>Removed</summary>

- azure/claude-mythos-5
- azure/codex-mini
- azure/o1
- azure/o3
- azure/o3-mini
- azure/o4-mini
- azure/phi-4-reasoning-plus
- bedrock/apac.anthropic.claude-sonnet-4-20250514-v1:0
- bedrock/eu.anthropic.claude-fable-5
- bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0
- bedrock/global.anthropic.claude-sonnet-4-20250514-v1:0
- bedrock/jp.anthropic.claude-opus-5
- bedrock/jp.anthropic.claude-sonnet-5
- bedrock/us.amazon.nova-premier-v1:0
- bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0
- copilot/claude-opus-4.7
- copilot/claude-opus-5
- copilot/gemini-3.5-flash
- copilot/gemini-3.6-flash
- copilot/gemini-3.7-flash
- copilot/gpt-5-mini
- copilot/gpt-5.4
- copilot/gpt-5.4-mini
- copilot/gpt-5.5
- copilot/gpt-5.6-terra
- copilot/kimi-k2.7-code
- google/gemini-2.5-computer-use-preview-10-2025
- google/gemini-3.1-flash-lite-preview
- google/gemini-omni-flash-preview
- google/lyria-3-clip-preview
- google/lyria-3-pro-preview
- openai/gpt-3.5-turbo
- openai/gpt-4
- openai/gpt-4-turbo
- openai/gpt-4.1-nano
- openai/gpt-4o-2024-05-13
- openai/gpt-5.3-codex-spark
- openai/gpt-realtime-2.1
- openai/o1
- openai/o1-pro
- openai/o3-mini
- openai/o4-mini
- openrouter/cohere/north-mini-code:free
- openrouter/dots-studio/dots-3-note-preview:free
- openrouter/meituan/longcat-2.0
- openrouter/meta-llama/llama-3.2-1b-instruct
- openrouter/mistralai/mistral-medium-3
- openrouter/mistralai/mistral-medium-3.1
- openrouter/moonshotai/kimi-k2
- openrouter/moonshotai/kimi-k2-0905
- openrouter/moonshotai/kimi-k2-thinking
- openrouter/tencent/hy3-preview
- openrouter/thinkingmachines/inkling-2-small:free
- openrouter/unbiased/pareto-26.10
- openrouter/unbiased/pareto-26.10-preview
- openrouter/unbiased/pareto-26.9
- openrouter/x-ai/grok-build-0.1
- openrouter/xiaomi/mimo-v2.5
- openrouter/xiaomi/mimo-v2.5-pro
- openrouter/~unbiased/pareto-latest
- vercel/alibaba/qwen3-max-thinking
- vercel/spacexai/grok-build-0.1
</details>

<details>
<summary>Changed</summary>

- azure/deepseek-v4-flash
- azure/deepseek-v4-pro
- azure/grok-4-20-non-reasoning
- azure/grok-4-20-reasoning
- azure/kimi-k2.5
- azure/kimi-k2.6
- 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-fable-5
- bedrock/anthropic.claude-fable-5-1
- bedrock/anthropic.claude-fable-5-2
- bedrock/anthropic.claude-haiku-4-5-20251001-v1:0
- bedrock/anthropic.claude-haiku-5-5
- bedrock/anthropic.claude-opus-4-5-20251101-v1:0
- bedrock/anthropic.claude-opus-4-7
- bedrock/anthropic.claude-opus-4-8
- bedrock/anthropic.claude-opus-5
- bedrock/anthropic.claude-opus-5-5
- bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0
- bedrock/anthropic.claude-sonnet-5
- bedrock/anthropic.claude-sonnet-5-5
- bedrock/global.amazon.nova-2-lite-v1:0
- 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
- google/gemini-2.5-flash-image
- openrouter/deepseek/deepseek-chat-v3-0324
- openrouter/deepseek/deepseek-v4-flash-0731
- openrouter/deepseek/deepseek-v4-flash-vision-exp
- openrouter/deepseek/deepseek-v4-pro
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/deepseek/deepseek-v4.1-flash-1017
- openrouter/google/gemma-3-4b-it
- openrouter/gryphe/mythomax-l2-13b
- openrouter/inclusionai/ling-3.1-flash
- openrouter/meta-llama/llama-3.1-8b-instruct
- openrouter/meta-llama/llama-3.2-3b-instruct
- openrouter/minimax/minimax-m2.5
- openrouter/minimax/minimax-m2.7
- openrouter/minimax/minimax-m3
- openrouter/minimax/minimax-m3.1-flash
- openrouter/moonshotai/kimi-k2.7-code
- openrouter/moonshotai/kimi-k3.1-pro
- openrouter/nvidia/nemotron-3.5-super-vl
- openrouter/openai/gpt-oss-120b
- openrouter/openai/gpt-oss-20b
- openrouter/particle-ai/particle-1
- openrouter/qwen/qwen3-coder-30b-a3b-instruct
- openrouter/qwen/qwen3.5-27b
- openrouter/qwen/qwen3.5-397b-a17b
- openrouter/qwen/qwen3.5-9b
- openrouter/qwen/qwen3.6-35b-a3b
- openrouter/qwen/qwen3.8-27b
- openrouter/reflection/beam-1.0-501b-a23b
- openrouter/z-ai/glm-4.5-air
- openrouter/z-ai/glm-4.7
- openrouter/z-ai/glm-5.1
- openrouter/z-ai/glm-5.2
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-pro-latest
- openrouter/~deepseek/deepseek-v4-flash-latest
- openrouter/~z-ai/glm-flash-latest
- vercel/alibaba/qwen3.8-27b
- vercel/amazon/nova-lite
- vercel/amazon/nova-micro
- vercel/amazon/nova-pro
- vercel/deepseek/deepseek-v4-pro-0813
- vercel/minimax/minimax-m2.7
</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/45808292131).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-26 11:28:22 +00:00
Danielle Maywood 3fea25447a test(coderd): deflake queued reasoning effort test (#32782) 2026-11-26 10:30:36 +00:00
Mathias Fredriksson 856a8684cb fix: prevent channel shutdown send races (#29658)
Workspace update subscriptions and VPN tunnels could close a channel
while another goroutine was still sending on it, panicking with `send on
closed channel`. VPN senders could also block forever once nothing read
the channel.

- `coderd`: `sub.Close` no longer closes the updates channel, so a
pubsub callback still running cannot send on a closed channel.
- `vpn`: after Stop, the tunnel no longer closes the shared send
channel. The writer exits after writing the Stop response, so Stop is
the final frame, and its exit is what ends the senders below.
- `vpn`: a speaker send context ends when the speaker is canceled or the
writer exits, for example on a write error. RPCs, RPC replies, updates
and logs wait on it, so they return instead of blocking on a channel
nothing reads. Before, an update holding the updater mutex could block a
Stop the tunnel had already read. The updater context derives from it,
so the updater also stops after Stop when Start never succeeded.
- `vpn`: RPC response channels are buffered, so delivering a response no
longer deadlocks against a caller canceled at the same moment. That
deadlock exists on main for a canceled caller context, and the send
context adds a cancellation at shutdown. A response received before EOF
or writer exit is returned instead of an error.

<details>
<summary>Decisions and regression evidence</summary>

- Nothing observes the subscription channel closing: its only reader,
`WorkspaceUpdates` in `tailnet/service.go`, also stops on its stream
context and calls `Close` itself.
- The tunnel does not cancel its speaker after Stop. Senders return once
the writer has finished the Stop response rather than when it is handed
over, and a request the manager sends after Stop stays parked until
`Tunnel.Close`, as on main.
- `updater.stop` is unchanged: it cancels after closing the conn, so
logs the conn emits while closing reach the manager (the tunnel is the
only log sink with `UseAsLogger` on macOS).
`TestTunnel_StopForwardsCloseLogs` guards that ordering.
- RPCs wait on the send context directly instead of relying on
`recvLoopDone`. The receive loop cannot exit while it is handing a
request to a busy `requestLoop`, and closing a blocking file descriptor
may not interrupt its read. `recvFromSerdes` still delivers requests
after the writer exits, so a Stop it has already read is not dropped.
When only the writer has exited, RPCs return `io.ErrUnexpectedEOF`, as
for EOF. Every RPC return removes its response channel, so RPCs that
fail after the writer exits do not accumulate entries.
- Against main's production code:
- `TestWorkspaceUpdatesClose/{QueryInFlight,CallbackAfterClose}` and
`TestTunnel_StopConcurrentSenders` panic with `send on closed channel`.
  - `TestSpeaker_ResponseDuringCancellation` deadlocks.
  - `TestSerdes_StopClosesAfterResponse` receives a frame after Stop.
- `TestTunnel_StopAfterWriterExits` and
`TestSpeaker_RPCAfterWriterExits` stay blocked after the writer exits.
- `TestSpeaker_ResponseBeforeEOF`,
`TestSpeaker_ResponseBeforeWriterExits` and
`TestTunnel_StopForwardsCloseLogs` pass on main. They guard ordering the
fix depends on: each fails when that ordering is changed or the matching
part of the fix is removed.
- The regression tests pass 50 runs with `-race`. The `vpn` and
`tailnet` race suites pass.

</details>

> This PR was created with the help of Coder Agents for @mafredri and
will be reviewed by a human.
2026-11-26 10:53:41 +02:00
Mathias Fredriksson c7b144cc76 fix(coderd/x/chatd): prevent a chat stream relay deadlock on repeated episode selection (#31187)
Stacked on #31196, which must merge first.

When a chat's worker runs on the same replica as the stream, the chat
stream relay can deadlock with the in-process parts endpoint. Live model
output then stops on that stream until the client reconnects, while
saved messages, status and queue updates keep arriving.

The stream loop configures the relay forwarder after every newer
snapshot, and queueing a message, deleting or promoting a queued one,
interrupting, and recording a retry keep the episode. The forwarder sent
a selection each time, and the endpoint answers each one by sending the
episode again from `seq` 1, so K updates on an N-part episode moved
about K times N parts. While the stream loop reads slowly, the resent
parts fill the buffers and the endpoint's serve loop waits to send.
Three unread selections fill the pipe's one-slot channel, the endpoint's
selection reader and its one-slot channel to the serve loop, and the
forwarder's next `WriteControl` never returns.

- The forwarder sends a selection only on a new connection or when the
target changes. Before #31196, only a repeated selection restarted live
output after the part buffer dropped a slow subscriber.
- The endpoint's selection reader replaces an unread selection instead
of waiting, so the endpoint does not depend on how a client sends
selections. After the first change the forwarder cannot practically
reach the cycle, since it drops other episodes' parts without waiting.
Dropping one loses nothing, because every selection starts again from
`seq` 1.

<details>
<summary>Investigation and decision log</summary>

### Evidence

`TestStreamRelayForwarderSelectsOnlyChangedTargets` configures one
200-part episode 10 times: before the forwarder change it sees 10
selections and 2000 parts, after it 1 selection and 200 parts.
`TestStreamPartsEndpointLatestSelectionWinsWhileBlocked` fails in 10 of
10 runs without the reader change and with a 15-slot queue that replaces
nothing.
`TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures`
stalls the stream loop until the buffers fill, configures the same
episode 1000 times, then requires a new part to arrive; it fails in 20
of 20 runs with both changes reverted and passes with either one alone.
All three pass with `-race -count=20`.

A goroutine dump taken with the world stopped, from a test that used the
real forwarder, local dialer and part buffer with a 2000-part episode,
shows the four goroutines at the waits described above and every buffer
full. The deadlock formed in 20 of 20 runs under `-race`, after 4 to 384
same-episode selections. After the test read every buffered part, added
live parts, configured the relay 11 more times (once for a new episode)
and fired the buffer's send timeout, no part arrived.

```
F goroutine 73 [select]: streamPartsChannelClientTransport.WriteControl stream_parts_transport.go:142 <- (*streamRelayForwarder).loop.func4 stream_relay.go:148 <- loop stream_relay.go:207
R goroutine 74 [select]: streamPartsEndpoint.serve.func1() stream_parts.go:84
E goroutine 83 [select]: streamPartsChannelServerTransport.WriteEvents stream_parts_transport.go:120 <- streamPartsEndpoint.serve stream_parts.go:169
L goroutine 84 [select]: (*streamPartsTransportSession).readLoop stream_parts_transport.go:236
f.parts=128/128 s.parts=128/128 eventsCh=128/128 controlCh=1/1 SelectEpisode started=13 returned=12
```

A test goroutine in place of the stream loop dropped repeated parts and
spent a fixed sync time on each hint before it selected the same episode
again (200 hints, 3 runs per row, real clock):

| Sync time per hint | Hint interval | Deadlock formed |
|--------------------|---------------|-----------------|
| 1 ms               | 1 ms          | 1 of 3          |
| 5 ms               | 5 ms          | 1 of 3          |
| 1 ms               | 2 ms or 5 ms  | 0 of 6          |
| 5 ms               | 10 ms         | 0 of 3          |

The deadlock formed only when selections arrived about as fast as the
stream loop handled them. How often that happens in production is not
measured.

Selecting a new episode every time under the same pressure did not
deadlock in 300 of 300 iterations, because the forwarder drops parts of
other episodes without waiting for the stream loop. Over the WebSocket
transport with the pipeline full, 1263 selections over 2999 iterations
all returned; when the stream loop then stopped reading, the server
heartbeat closed the parts connection about 35 seconds after it opened,
and the forwarder dialed again once the stream loop read again.

### Decisions

- `WriteControl` keeps its waiting send: the reader no longer waits
after reading the pipe, so the send returns, and replacing there changed
no test result.
- Replaced `TestStreamRelayLivePartsAfterSameEpisodeReselects`, which
waited for full buffers before every selection and so relied on the
replays the forwarder change removes, with a test that fills the buffers
once by stalling the stream loop.
- Rejected: having the serve loop read selections while it waits in
`WriteEvents`. The serve loop would have to abandon a send in progress
and drop its part, a larger change with the same result.

</details>

> 🤖 This PR was created with the help of Coder Agents.
2026-11-25 18:28:55 +02:00
Mathias Fredriksson 1d565409e4 fix(coderd/x/chatd): keep slow part subscribers attached while the episode is open (#31196)
The message part buffer dropped a subscriber of an open episode whose
send waited 10 seconds. The parts endpoint read the closed channel as
the end of the episode and kept the connection open, so live output
stopped for the rest of the model call. Only on the cross-replica
WebSocket could a longer stall end it: the endpoint's heartbeat closes
the socket 15 to 30 s after the relay stops reading, and the relay
reconnects and replays once it reads again. That path is unchanged. The
stream loop stops reading when its writes to the browser block.

The timeout keeps an unresponsive subscriber from holding an episode in
memory, but only closed episodes wait for subscribers. It now starts at
the close, also for a send already waiting then.

A drop after the close only cuts short the live preview, which the saved
message or the error event replaces. The buffer has no logger, so it is
not logged.

Cost: a subscriber that stops reading an open episode holds its
goroutine and batch until it reads, is cancelled, its context ends, the
buffer closes, or `SubscriberSendTimeout` passes after the episode
closes.

> 🤖 This PR was created with the help of Coder Agents.
2026-11-25 16:26:23 +02:00
Mathias Fredriksson b044acbe2b fix(coderd/database/migrations): remove lock-retry blocks from chat migrations (#31167)
Migrations 000609, 000611 and 000615 start with a lock-retry block
(added in #30297 and #30412) that is meant to stop live chat traffic
from deadlocking with the migration. On a release upgrade it cannot do
that, and it can turn a failure into a 2-minute hang or cause a failure
that would otherwise not happen. This PR removes the blocks. A release
upgrade that runs 000607 to 000615 while chats are in use is unreliable
with or without them, so it needs chat traffic stopped, for example by
scaling the deployment to zero first.

`coder server` runs all pending migrations in one transaction, so every
migration's locks are held until the transaction commits. On a release
upgrade (from v2.38 or earlier), 000607 and 000608 lock `chats` before
any block runs. A chat request that writes `chat_messages` or
`chat_queued_messages`, or that reads `users`, holds a lock that a later
migration needs and then waits for `chats`. The block can release only
the locks it took, so it can avoid this deadlock only when its migration
takes the first chat lock of the upgrade. Postgres checks a waiting
request for a deadlock once, after `deadlock_timeout` (1 second by
default). The block pauses 100ms between 100ms lock attempts, so a check
that lands in a pause finds no deadlock, the request keeps its lock, and
the block retries until it fails the upgrade after 2 minutes, with the
request stuck until then.

Without the block, the outcome depends on timing. If the request's check
fires after the migration starts waiting for it, Postgres cancels the
request and the upgrade continues. If the request had already waited
longer than `deadlock_timeout`, its check found no deadlock, so Postgres
cancels the migration instead and the upgrade fails. Main does not
finish those cases either: its block was still retrying after a minute,
and it gives up at its 2-minute deadline.

000609 and 000611 return to their content before #30297, and 000615
loses the block in both directions. A block's migration takes the first
chat lock of an upgrade only when upgrading from a build of main at 608
through 614: dogfood, where the #30297 deploy failed, or a
`coder-preview` image built between 2026-10-02 and 2026-10-11. No
release stops in that range, and dogfood is already past 615.

v2.39 ships these migrations with the blocks. Editing them leaves every
schema unchanged: databases on v2.39 or later already ran them and do
not run them again, and `dump.sql` regenerates without a diff. The
change affects only databases upgrading from v2.38 or earlier.

WI-46 proposed the opposite direction: make the migrator survive live
chat traffic. The v2.38 upgrade thread concluded instead that old
replicas must be stopped before an upgrade runs migrations. So
`TestMigrationChatTablesConcurrentTraffic`, which tested the blocks
under chat traffic, is removed without a replacement, and its helpers
`async` and `dedicatedConn` move to `migration000638_test.go`, their
remaining caller.

<details>
<summary>Measurements</summary>

Each run starts chat requests while the upgrade transaction is open, on
the Postgres 13 test container with the default `deadlock_timeout`.
"Request canceled" means Postgres canceled the chat request as the
deadlock victim. "Stuck" means the migration was still retrying when the
run was stopped, after 10 seconds unless noted.

| Upgrade from | Migration | Chat requests | main | This PR |
|---|---|---|---|---|
| v2.38 (605) | 000609 | queued message insert | upgrade failed after
2m0s | request canceled after 1s, upgrade ok |
| v2.38 (605) | 000609 | chat message insert | stuck | request canceled
after 1s, upgrade ok |
| v2.38 (605) | 000609 | chat message insert that waited 1.2s before
000609 started | stuck (stopped after 1 minute) | migration canceled
after 1s |
| v2.38 (605) | 000609 | chat message insert and queued message insert |
stuck (stopped after 1 minute) | migration canceled after 2s |
| v2.38 (605) | 000615 | read `users`, then `chats` | stuck | request
canceled after 1s, upgrade ok |
| v2.38 (605) | 000615 | read `users`, then `chats`, plus a chat message
insert | stuck (stopped after 1 minute) | migration canceled after 2s |
| 607 (main build) | 000609 | queued or chat message insert | stuck |
request canceled after 1s, upgrade ok |
| 610 (main build) | 000615 | queued message insert | stuck | request
canceled after 1s, upgrade ok |
| 608, 610, 614 (main build) | 000609, 000611, 000615 as the first chat
lock | the four cases in `TestMigrationChatTablesConcurrentTraffic` | no
deadlock | 2, 1 and 1 of 4 deadlock; in the 000615 case Postgres
canceled the migration, in the others a chat request |

</details>

> 🤖 This PR was created with the help of Coder Agents, and has been
reviewed by a human. 🏂🏻
2026-11-25 12:43:48 +02:00
Ethan 389cfeef2f fix(coderd): generate chat titles for users without the owner role (#32738)
Automatic title generation only works for chats created by a user with
the Owner role. For anyone else the chat keeps its fallback title (the
first message, truncated), and the only sign is a warning in the coderd
logs:

```
[warn]  coderd.chatd.processor: failed to resolve model for automatic title generation ...
    error= resolve fallback chat model for title:
         - get AI provider:
         - unauthorized: rbac: forbidden: ...
```

`GenerateChatTitleForMessagesAsync` runs its goroutine as the user who
made the request, and resolving the title model reads the `ai_provider`
row, which only Owners can read. Setting a title generation model
override doesn't help, as resolving the override reads the provider too.

To fix, we'll run the goroutine as chatd, as `ProposeChatTitle` already
does for the same reason. The model config lookup still loads the chat
owner's subject, so the owner's access still decides which model the
title call can use. That lookup now has the owner's full scope, where
before it had the scope of the API key that made the request.

`TestPostChats_AutomaticTitleGeneration` now creates the chat as a
member and asserts on the stored title, instead of waiting for the title
request to reach the provider.

I've confirmed this on a dev server (`./scripts/develop.sh`, one OpenAI
provider, `gpt-4.1-mini` as the default model, no title generation model
override), creating chats through the API on the same database before
and after the fix:

| Commit | Chat created by | Title |
|---|---|---|
| `6603069e8b` (`main`) | `admin` (Owner) | Generated after 2s: "Why the
sky is blue" |
| `6603069e8b` (`main`) | `member` (no roles) | Still the fallback after
90s, and coderd logged `failed to resolve model for automatic title
generation` |
| `549cbdfafb` (this PR) | `member` (no roles) | Generated after 2s:
"Why the sea is salty" |

It also reproduces on dogfood, where I don't have the Owner role: a chat
I created there on `main` kept its fallback title.
2026-11-25 18:20:18 +11:00
Thomas Kosiewski d4e66907c4 refactor(coderd/x/chatd/chatwebhook): keep only the Standard Webhooks verifier (#32614)
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
2026-11-25 07:22:44 +01:00
Thomas Kosiewski 39a4b4d90c fix(coderd/schedule/cron): compare reserved zone names without case (#32087)
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
2026-11-25 00:27:48 +01:00
Thomas Kosiewski 13f5cc7872 fix(coderd/telemetry): give the reporter its own HTTP transport (#32160)
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
2026-11-25 00:27:35 +01:00
Bobby Ho 4186344631 test(coderd/provisionerdserver): start the MatchTags deadline after database setup (#32722)
## TL;DR

`TestAcquirer_MatchTags` sometimes fails with `context deadline
exceeded` before it checks anything. The test started its 10 second
deadline first and created its test database second. When the database
took 10 seconds or more to create, the deadline had already passed by
the time the test ran its first query. This PR starts the deadline after
the database exists, so slow database setup no longer fails the test.

Refs
https://linear.app/codercom/issue/CORE-713/flake-testacquirer-matchtagsuser-scoped-provisioner-and-user-scoped

<details>
<summary>How to navigate this PR</summary>

- One test file, no production code.
- Read `coderd/provisionerdserver/acquirer_test.go`, inside the subtest
loop of `TestAcquirer_MatchTags`. One line moves below
`dbtestutil.NewDB`, and a two-line comment says why.

</details>

<details>
<summary>Implementation</summary>

- `coderd/provisionerdserver/acquirer_test.go`: the `testutil.Context(t,
testutil.WaitShort)` line in `TestAcquirer_MatchTags` now comes after
`dbtestutil.NewDB(t)`.
- Nothing between the old and the new position uses the context, so what
the test checks is unchanged.
- `TestAcquirer_Store` in the same file already creates its database
first.
- The deadline is not made longer. A longer deadline would only make the
failure less likely, because database setup has no upper limit that a
fixed value could cover.
- Other tests in the repository create a short deadline before
`dbtestutil.NewDB` in the same way. They are left for a separate change.

</details>

<details>
<summary>Expected Output</summary>

- When creating the test database takes longer than 10 seconds, every
`TestAcquirer_MatchTags` subtest still passes.
- The test still gives each subtest 10 seconds for the part that checks
tag matching.
- A subtest with a wrong expectation still fails. A provisioner that
should not get a job, but is expected to, fails at the `AcquireJob`
assertion when the deadline ends.

</details>

<details>
<summary>Testing</summary>

- No test was added. The change is to the test itself.
- The recorded failure: `test-go-pg (windows-2022)` in the nightly
workflow, [job
111783661367](https://github.com/coder/coder/actions/runs/37316261411/job/111783661367).
The subtest failed at its first insert in the same millisecond the
pubsub became ready, after 10 to 14.6 seconds of setup.
- Reproduced on `main` on macOS with a local PostgreSQL 17. In a run of
20 repeats with `-parallel=16`, 16 subtests failed at the same line with
the same message. They were exactly the 16 whose database copy took over
10 seconds.
- With a temporary 10.5 second delay before database creation in every
subtest (not part of this PR):
  - `main`: 42 of 42 database subtests failed at the same line.
  - This change: 44 of 44 subtests passed.
- This change without the delay: 20 repeats passed, 440 of 440 subtests.
- Mutation check: with the expectation of one "no match" case set to
"match", that subtest failed at the `AcquireJob` assertion.
- On this branch: `go test ./coderd/provisionerdserver -run
'^TestAcquirer_' -count=3 -parallel=16` passes.
- Not covered: the Windows and macOS lanes run only in the nightly
workflow, so they have not run on this branch yet.

</details>
2026-11-24 15:45:38 -07:00
Bobby Ho f32341ea4e fix(coderd/notifications): do not fetch after a graceful stop (#32627)
## TL;DR

Fix a race condition where the notification sender could fetch another batch after graceful shutdown was requested, delaying shutdown and causing intermittent `TestBackpressure` failures.

Refs https://linear.app/codercom/issue/CORE-718/flake-testbackpressure

## Changes

- Check the graceful context before fetching a new batch.
- Allow in-flight batches to complete and persist their results before shutdown.
- Leave `quartz` and other `TickerFunc` callers unchanged.
- Add `TestNotifier_NoFetchAfterGracefulStop` to verify that a late ticker callback does not trigger another fetch.

## Testing

- New regression test fails without the fix and passes with it.
- Notifier tests pass with `-race -count=5`.
- `golangci-lint` reports zero issues.
- Reproduced the original CI failure under high concurrency.
- With an artificially widened race window: 10/10 failures before the fix, 0/20 after the fix.
- Database-backed tests were validated on an earlier commit but have not been rerun on this branch.
2026-11-24 12:46:12 -07:00
John T SkarbekandClaude Sonnet 5.5 27eecbf092 fix(coderd): stop logging whole objects in authorization denials (#32526)
Linear: [PLE-94](https://linear.app/codercom/issue/PLE-94). Dogfood Loki
holds plaintext credentials because several log call sites emit secrets.
This is one of three independent PRs split out of the original masking
change.

## Root cause
Both "requester is not authorized to access the object" warnings in
`coderd/authorize.go` logged `slog.F("object", object)`, the raw
`rbac.Objecter`. When the caller passes a database row, every field is
dumped, e.g. `oauth2_client_secret` on `database.MCPServerConfig`; any
Objecter row with a secret field leaks. `actor_name` was also the whole
`rbac.Subject` (expanded roles, groups and email), which duplicated the
`roles`, `actor_id` and `scope` fields; it dates to a mechanical rename
of `roles.ActorName` in #12816.

## Fix
Log `object.RBACObject()` (type, id, owner, org), and log
`roles.FriendlyName` (the username, or the name of an internal actor) as
`actor_name`.

Sibling PRs (independent, disjoint files):
- https://github.com/coder/coder/pull/32532
- https://github.com/coder/coder/pull/32533

## Follow-ups not included
- AI Gateway prompt, tool and thought content logged in
`aibridgedserver.go` (~511-613) and `aibridge/recorder/log_recorder.go`
- `rich_parameter_values` in `runner.go` (~443)
- Proxy `response_body` in `aibridgeproxyd.go` (~1102)
- Terraform `TF_LOG` output relayed to logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 14:37:36 -05:00
Susana Ferreira 7c7dd8fb63 chore: remove the retention start from the AI spend users response (#32687)
## Description

Only the old spend page read `retention_start` from the per-user AI
spend response, to limit its date picker. That page is gone, and the AI
Gateway retention endpoint now serves this purpose, so the field is
removed. The server still narrows a default period to the retention and
rejects an explicit one that starts before it.

Related to AIGOV-729

## Changes

- Remove `RetentionStart` from `codersdk.OrganizationAISpendReport`.
- Keep the retention start local to `aiSpendRetainedPeriod`, its only
reader.
- Regenerate the API docs and TypeScript types, and update the tests and
mocks.

Depends on #32686.

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-24 18:11:49 +00:00
Susana Ferreira dfe6402910 feat: add an AI Gateway data retention endpoint (#32659)
## Description

Pages that read raw AI Gateway data and have a date picker don't handle
data retention consistently. AI Sessions allows start dates whose data
is already purged. AI spend only learns the retention after a request.

The new AI spend page reads aggregated data, which is never purged, in
some views and raw data in others. For consistency, the Overview and
Detailed report tabs should accept the same date range, so both are
limited to the retention.

The retention is in the deployment config, but only Owners can read it.
This adds an experimental endpoint that returns only the retention, so
these pages can offer only retained dates.

## Changes

- Add `GET /api/experimental/ai-gateway/retention`, returning
`retention_ms`. Zero means data is never purged.
- Any authenticated user with the AI Gateway feature can read it, since
it holds no usage data.
- Add `codersdk.AIGatewayRetention` and the
`ExperimentalClient.AIGatewayRetention` method.

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-24 18:07:38 +00:00
Garrett Delfosse 74a15cbcaa feat: adopt OpenTelemetry GenAI semantic conventions for Coder Agents traces (#32411)
Aligns Coder Agents traces with the [OpenTelemetry GenAI semantic
conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) so
customers can ingest per-user model usage, spend, and tool activity
without custom mapping. Scope follows the requesting team's Slack ask:
agent spans, inference spans with token usage, GenAI attributes,
per-user attribution, and visibility into tools that cannot be reached.

Closes CODAGT-1523.

## Changes

- Span names follow the conventions: `chat_turn` becomes `invoke_agent
coder`, `stream` becomes `chat {model}`, and `tool_call` becomes
`execute_tool {tool}`. Every stage span now carries a `stage` attribute
with the old stage name, which matches the Prometheus `stage` label.
Metrics are unchanged.
- GenAI spans carry `gen_ai.operation.name`, `gen_ai.conversation.id`
(the chat ID), `user.id` (the chat owner), and `coder.organization.id`,
`coder.workspace.id`, `coder.chat.parent_id`, `coder.chat.root_id`.
- `chat` spans are `CLIENT` spans with the provider, request model, and
`gen_ai.request.stream` set at creation (so samplers can see them), plus
requested max tokens and temperature, response ID (including OpenAI
Responses metadata on non-streaming calls), the finish reason the
provider reported (omitted when none, kept when Coder rejects the
response), `gen_ai.output.type=json` for native OpenAI structured
output, and token usage with cache read/write (only when nonzero) and
reasoning breakdown. `gen_ai.usage.input_tokens` includes cached tokens,
as the spec requires. Fantasy reports them separately (Google providers
use the OpenAI-compatible client, which does the same).
- `execute_tool` spans carry the tool name, call ID, and type
(`function` for built-in tools, `extension` for MCP and caller tools),
all set at creation.
- Every model call records a `chat` span: assistant streams
(`stage=stream`), and, as `stage=model_call`, the advisor, compaction
summaries plus titles, status labels, and chat summaries (via
`StageTracer.TraceModelCalls` in `resolveModelCall`). `model_call` has
no histogram, so the `stream` metric is unchanged.
- Failed spans get `error.type`. A tool that returns an error result, as
MCP clients do for an unreachable server, ends its span with
`error.type=tool_error` without recording the result text.
- GenAI attributes carry metadata only; prompts, responses, and tool
payloads are not recorded. The docs note that other spans and events in
the trace, such as AI Gateway spans and server log events, can contain
content.
- Docs state known limits: Anthropic server-tool responses undercount
input tokens in both spans and AI Gateway cost control (the client keeps
first-iteration occupancy), the OpenAI-compatible client drops reported
cache writes, request attributes are what Coder requested, and the
exporter is OTLP/gRPC, plaintext unless a certificate is configured.
- New docs page:
`docs/coder-agents/platform-controls/opentelemetry-tracing.md`.
- `coderd/x/chatd/ARCHITECTURE.md` gains a GenAI semantic conventions
subsection under Lifecycle tracing.

Existing attributes (`provider`, `model`, `chat_id`, `tool_name`, ...)
are kept so current queries on attributes keep working. Queries on span
names need to switch to the `stage` attribute or the new names.

<details>
<summary>Decision log</summary>

- **Convention version:** semconv v1.41.0, the last core release that
ships the GenAI attributes. Later releases moved them to
`semantic-conventions-genai`. The PR uses the Go constants from
`go.opentelemetry.io/otel/semconv/v1.41.0`, which is already in the
module graph. No experiment gate: chatd is already under `x/`, and the
docs page notes that the conventions may change.
- **Rename vs. attributes only:** spans are renamed because the
conventions define the span names. The `stage` attribute keeps lifecycle
identity stable for dashboards and tests.
- **Agent name:** `gen_ai.agent.name=coder` for root chats and subagents
alike. `chat_kind` and `coder.chat.parent_id` tell them apart.
- **Provider name mapping:** configured provider type to well-known
values (`openai`, `anthropic`, `azure.ai.openai`, `aws.bedrock`,
`gcp.gemini`). Anthropic providers with Bedrock settings report
`aws.bedrock`. The `invoke_agent` span gets the provider after `prepare`
resolves the turn's model, since the turn span starts first. Other types
(`openrouter`, `openai-compat`, `vercel`, `copilot`) are passed through
as-is.
- **No content capture:** `gen_ai.input.messages`,
`gen_ai.output.messages`, and tool arguments/results are opt-in in the
conventions and not needed for usage and spend attribution, so they are
left for a follow-up behind an explicit deployment flag.
- **Out of scope:** GenAI metrics (`gen_ai.client.token.usage`,
`gen_ai.client.operation.duration`), an aggregated token total on the
`invoke_agent` span, a cost attribute, span links between subagent and
parent traces, and correlation IDs with AI Gateway interceptions (an
open question in the issue). Subagent turns join the parent only through
`coder.chat.root_id`; a span link needs the spawning span context
persisted across chats and runners. Spans carry tokens, not cost; cost
stays in the existing cost API.
- **Identity snapshot:** chat identity is taken when the turn opens. A
workspace created mid-turn appears on spans from the next turn.

</details>

---

Generated by Coder Agents on behalf of @f0ssel.
2026-11-24 11:41:03 -05:00
John T SkarbekandClaude Sonnet 5.5 c484ad2be4 fix: keep the provisioner key secret out of request paths and logs (#32532)
Linear: [PLE-94](https://linear.app/codercom/issue/PLE-94). One of three
independent PRs split out of the original masking change.

## Root cause
`codersdk.Client.GetProvisionerKey` sent the real provisioner key secret
in the URL path (`/api/v2/provisionerkeys/<key>`) as well as in the
`Coder-Provisioner-Daemon-Key` header. The path ends up in proxy/access
logs, the server request logger (`path`, `params_provisionerkey`) and
the SDK's `sdk request` debug log. The server ignores the path value:
the route uses `ExtractProvisionerDaemonAuthenticated` and
`fetchProvisionerKey` returns the header-authenticated key. Nothing
reads `{provisionerkey}` on that route (`ExtractProvisionerKeyParam` is
only mounted on the org-scoped route, where the value is a key name).

## Fix
- The SDK now sends a fixed placeholder segment,
`/api/v2/provisionerkeys/me`; the secret travels only in the header. Old
servers ignore the path, and old clients still work with new servers.
- `loggermw` masks the `provisionerkey` route param (keeping at most a 4
character prefix) in `params_*` and `path` as a backstop for old
clients. It only applies when the route pattern is the top-level
`/provisionerkeys/{provisionerkey}`; the org-scoped
`/organizations/{organization}/provisionerkeys/{provisionerkey}` carries
a key name and is left alone.
- Swagger annotation and generated docs now describe the path param as
an ignored placeholder (edited by hand, not via `make gen`).

Sibling PRs (independent, disjoint files):
- https://github.com/coder/coder/pull/32526
- https://github.com/coder/coder/pull/32533

## Follow-ups not included
- AI Gateway prompt, tool and thought content logged in
`aibridgedserver.go` (~511-613) and `aibridge/recorder/log_recorder.go`
- `rich_parameter_values` in `runner.go` (~443)
- Proxy `response_body` in `aibridgeproxyd.go` (~1102)
- Terraform `TF_LOG` output relayed to logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 08:11:09 -05:00
Garrett DelfosseandGarrett Delfosse d1487f62f1 fix: resume workspace context push after coderd rejects it (#32534)
When coderd rejected a workspace context push, the agent kept resending
the same snapshot until it restarted, so fixing the bad file on disk did
not resume sync.

Each retry now rebuilds the request from the newest snapshot. coderd
returns `InvalidArgument` for validation failures, and the agent then
waits for the next change instead of retrying. `Initial` stays set until
a push succeeds. A new agent talking to an old coderd gets no code and
keeps retrying, now with the newest snapshot.

Fixes CODAGT-1640. Touches `agent/agentcontext/push.go`, as #31831 does.

<details>
<summary>Plan context</summary>

This is unit A1 of the Agent Plugins plan (CODAGT-1101, parent
CODAGT-1639): fix workspace-context bugs on main before adapting the
plugins stack, because plugins add more ways for coderd to reject a
push.

- Scope: retry with the newest snapshot when files change; coderd marks
validation errors as permanent so the agent waits for the next change.
- Not included: showing the rejection in the chat or the context panel.
- Verify: unit tests with a fake pusher and a mock clock. Revert: plain
revert, no data.

</details>

---

Generated by Coder Agents on behalf of @f0ssel.

---------

Co-authored-by: Garrett Delfosse <garrett@coder.com>
2026-11-24 13:14:03 +02:00
52427e8fd6 test(coderd/x/chatd): give TestProjectSkillsFollowProjectAccess a longer context (#32276)
`TestProjectSkillsFollowProjectAccess` runs six sequential model turns
on one context created with `testutil.WaitLong` (25s). In a recent CI
run ([job](https://github.com/coder/coder/actions/runs/43909622615)) the
turns took about 35s, so the context expired just as the last turn was
sent. The chat finished normally (its final update was published about
4s later), but every `GetChatByID(ctx, …)` inside `waitForChatProcessed`
then returned a deadline error, which the condition treats as not yet
processed, so `require.Eventually` failed with "Condition never
satisfied".

Use `testutil.WaitSuperLong`, as other multi-turn chatd tests do.

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VpiVZBgFqiSdRKrH8dPSPT)_

Co-authored-by: Garrett <garrett@coder.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:10:36 +02:00
Sas SwartandClaude Opus 5.5 dcbe84a23b feat: add organization member AI spend endpoint (#32203)
Adds `GET /api/v2/organizations/{organization}/members/{user}/ai/spend`,
which returns a user's effective AI budget and current-period spend
inside one organization. Admins, and users themselves, can use it to
look up spend in a specific organization.

The endpoint resolves the budget inside that organization only, the same
way AI Gateway resolves a request made there. The response has the same
shape as the user spend endpoint, plus `organization_id`.

Users can read their own spend, and admins can read the spend of a user
whose membership in that organization they can read. The endpoint
returns 404 when the user isn't a member of the organization, or when
the caller can't read the user. It requires the AI Governance license.

Organization admins can read every user, so only the organization and
membership checks keep them out of other organizations. The tests cover
both sides: an organization admin reading a member of their own
organization (200) and of another organization (404).

Also adds `Client.OrganizationMemberAISpendStatus` to `codersdk`, and
links the endpoint from `cost-controls.md`.

Stacked on #32202, which adds `GET
/users/{user}/ai/spend/organizations`. Review only the last two commits
here.

Refs [AIGOV-766](https://linear.app/codercom/issue/AIGOV-766)

---

*Generated by Coder Agents on behalf of @SasSwart.*

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:53:23 +02:00
Susana Ferreira 1b9f2d8181 feat!: add the client to the AI spend CSV export (#32474)
## Description

Adds the client to the stable `GET
/api/v2/organizations/{organization}/ai/spend/export` CSV export, so the
Detailed report page (https://github.com/coder/coder/pull/32482) can
export the same data with the same filters.

## Changes

- `ExportOrganizationAISpend` groups rows by client as well, and takes a
`client` filter. Usage without a recorded client is reported as
`Unknown`, like `/ai/spend/users`.
- The export accepts a `client` query parameter, and adds a `client`
column at the end of the CSV, so existing columns keep their position.
- `OrganizationAISpendDetailsFilter` takes a `Client`.
- Update the Spend export docs and the query and handler tests.

## Breaking change

The AI spend CSV export (`GET
/api/v2/organizations/{organization}/ai/spend/export`) now has a
`client` column at the end, and splits rows by it.

If you rely on one row per user, group, model and provider, sum
`cost_micros` and the token columns across clients to get the previous
totals.

Closes AIGOV-733

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-24 09:48:47 +00:00
Sas SwartandClaude Opus 5.5 c236edcb8d feat: add per-organization AI spend endpoint (#32202)
Adds `GET /api/v2/users/{user}/ai/spend/organizations`, which returns a
user's AI budget and current-period spend in each of their
organizations. The avatar menu uses it to show spend to users who belong
to more than one organization (#32204).

The response lists each organization the user is a current member of and
the caller can read, sorted by name. Each entry has the effective group,
budget, and spend that AI Gateway resolves for a request in that
organization. When no group budget applies, the effective group is the
organization's `Everyone` group. `organization_id` names the
organization of the user's site-wide effective group, so the menu opens
on the numbers the user sees today. It's null when that organization
isn't in the list.

`GET /users/{user}/ai/spend` is unchanged. Its API docs now say that it
resolves the site-wide effective group, and point to the new endpoint
for the per-organization breakdown.

dbauthz filters the user's organizations to those the caller can read,
so an organization-scoped admin only sees the organizations they
administer. The handler queries spend only for those organizations. A
new query, `GetUserAISpendByEffectiveGroupsSince`, reads the spend for
all of them in one call. It reads existing tables, so there's no
migration, and dbauthz checks it the same way as `GetUserAISpendSince`:
the caller must be able to read the user.

Refs [AIGOV-766](https://linear.app/codercom/issue/AIGOV-766)

<details>
<summary>Decisions</summary>

- **Separate endpoint.** An earlier version of this PR added
`organizations` and `organization_id` to `GET /users/{user}/ai/spend`.
Following review, the breakdown moved to its own route ([AIGOV-766
comment](https://linear.app/codercom/issue/AIGOV-766/show-spend-per-org-to-users-in-several-orgs#comment-6855c55c)).
Because the breakdown depends on who is asking, a dedicated route keeps
the existing endpoint's response the same for every caller.
- **`organization_id` on the new response.** The comment's schema left
it out, but its frontend notes and its test rely on it, so the response
includes it.
- **Existing endpoint left as on `main`.** An organization-scoped admin
can still see a user's site-wide effective group, budget, and spend
through `GET /users/{user}/ai/spend`, even when that group is in another
organization. The earlier version of this PR hid those fields; this
version keeps the existing behavior, as the review asked.
- **Authorization check.** dbauthz post-filters
`GetOrganizationsByUserID` with `read` on each organization. The
endpoint itself requires read on the user, as the existing spend
endpoint does.
- **Empty result.** A caller who can read the user but none of their
organizations gets `200` with an empty `organizations` list and a null
`organization_id`, so the response doesn't reveal that memberships
exist.
- **Per-organization spend.** Each entry reports spend on the user's
current effective group in that organization, which is what budget
enforcement compares.

</details>

---

*Generated by Coder Agents on behalf of @SasSwart.*

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:08:06 +02:00
Bobby Ho c5af20be31 test: copy test databases by file and start test deadlines after setup (#32426)
## Summary

Mitigate Windows nightly timeout bursts caused by slow test database creation. Multiple tests were hitting `context deadline exceeded` because their 10-second deadlines started before database setup completed.

Refs https://linear.app/codercom/issue/CORE-615

## Changes

- Use `STRATEGY FILE_COPY` for test database creation on PostgreSQL 15+, avoiding the more expensive default `WAL_LOG` strategy. PostgreSQL 13/14 remain unchanged.
- Cache the PostgreSQL version lookup, preserving existing behavior if detection fails.
- Log database copies exceeding 2 seconds, including duration and strategy.
- Move context creation after database/server setup in affected WebPush, OIDC, notification, and prebuild tests, without changing timeout values.
- Add unit tests for PostgreSQL version-based strategy selection.

Test-only changes across 6 files; no production code changes.

## Validation

- Local PostgreSQL 17.10 tests pass, including WebPush, prebuild reconciliation, OIDC, and notifications.
- `go vet` and `golangci-lint` report no issues.
- Local OIDC comparison:
  - Default strategy: 3–5 failures/run.
  - `FILE_COPY` with partial context fixes: 1–2 failures/run.
  - **Final implementation: 0 failures across 5 runs**, with maximum database creation time reduced from 13.3s to 8.9s.

## Remaining Work

- Run `nightly-gauntlet` repeatedly to verify improvements on Windows and macOS.
- Compare WAL volume, checkpoint overhead, and test durations. `FILE_COPY` increases checkpoints, though local database creation was faster.
- Confirm PostgreSQL 13 and 17 Linux jobs pass.

**Status:** Draft pending nightly validation.
2026-11-23 10:58:04 -07:00
Bobby Ho 5b82b04a78 fix(coderd): use a port outside the OS range in the TCP dial failure test (#32541)
## Summary

Fixes a flaky `TestServerTailnet_ReverseProxy_TCPDialFailure` (~2% CI failure rate) caused by a port race.

Previously, `testutil.RandomPort` selected a port by briefly opening and closing a listener. Another parallel test could claim that port before the connection attempt, causing an unexpected success instead of a connection refusal.

This PR introduces `closedPort`, which selects an unused port from **20000–29999**, outside the default ephemeral port ranges on Linux, macOS, and Windows. It checks both `127.0.0.1` and `::1`, since the agent may attempt either address.

Refs [CORE-756](https://linear.app/codercom/issue/CORE-756/flake-testservertailnet-reverseproxy-tcpdialfailure)

## Changes

- Add `closedPort` in `coderd/tailnet_test.go` and replace the `testutil.RandomPort` call.
- Skip ports already accepting connections on IPv4 or IPv6.
- Keep existing assertions unchanged. No production code changes.

**Limitation:** This mitigates rather than eliminates the race. Another process could explicitly bind the selected port after the check, although the OS will not assign it automatically as an ephemeral port.

## Testing

| Scenario | Result |
|---|---|
| Before fix: 9,600 parallel Linux runs | 1 failure |
| After fix: 9,600 parallel Linux runs | **0 failures** |
| Ports 20000 and 20001 occupied | Pass; selects 20002 |
| Remove expected dial log fields | Test fails as expected |
| macOS: 20 consecutive runs | Pass |
| `golangci-lint` | 0 issues |

Windows remains untested.

## Expected Behavior

The test continues to verify that a failed TCP dial returns HTTP 502 and logs `agent_id`, `dial_phase=tcp_dial`, and `tcp_dial_after`, while reducing failures caused by port collisions.
2026-11-23 09:08:10 -07:00
Kiryl e35a124b0d feat: report database migration outcome (#31849)
Nothing said how a migration run ended. On failure, the CLI printed the
PostgreSQL error with the failing SQL, but not which migration failed or
whether anything was saved.

After a failed run, the reporter asks PostgreSQL how the transaction
ended (`pg_xact_status` on the captured transaction ID, plus the saved
schema version). Every run logs one outcome line: committed, rolled
back, committed before failure, unknown, lock timeout, dirty schema, or
failed before start. Every failure line has an `error` field.

The error names the failed migration and gives PostgreSQL's short
message and SQLSTATE, without the SQL or detail text, which can contain
row values.

```
[info]  committed database migrations  status=success  count=2  from_version=1  final_version=3  transaction_status=committed  total_duration_ms=0
[erro]  migration failed, transaction rolled back, no changes saved  status=failure  count=1  version=3  name=step_3  final_version=1  sqlstate=23505  transaction_status=aborted  total_duration_ms=0  failed_duration_ms=0  error="migration 3 (step_3): migration failed: duplicate key value violates unique constraint \"a_pkey\" (sqlstate=23505)"
```


Closes ENT-236

_Written with Claude Code and Coder Agents, reviewed and tested by
@kirstaeff._
2026-11-23 13:50:50 +01:00
Hugo Dutka 5f5c30eafb fix(coderd/x/chatd): prefer native subagents over ACP harnesses (#32604)
Agents sometimes call `acp_spawn_agent` when a native subagent
(`spawn_agent`) could do the job, even when the requested model is
available natively.

This adds one line to the `<acp-subagents>` system prompt block: "Prefer
using non-ACP subagents unless the user asks for an ACP harness or if
the requested model is only available through ACP."

Tests reference `acpSubagentPromptBlock` by constant rather than by
text, so no test changes are needed.
2026-11-23 12:11:44 +00:00
Kiryl 6a45e8c8d1 feat: log migration progress and heartbeat (#31789)
Migrations run at server startup with no output, so admins can't tell
which migration is running, whether it waits on a lock, or how far it
got.

This adds a reporter to the migration driver. It logs:

- the pending migrations, and each step with its position and duration;
- the migration lock (debug level);
- a heartbeat every 10s during a lock wait or a long step, with the
connection state from `pg_stat_activity` and the blocking sessions.

The migration transaction is named `coder-migrate/<version>`, so other
instances and admins can see it. Heartbeat queries run on their own
connection and never delay the migration.

API: `Up(db, opts...)`, with `WithFS` (replaces `UpWithFS`) and
`WithLogger`. Without a logger, nothing is logged. Server startup turns
it on in #31790.

```
[info]  database migration required  from_version=1  target_version=3  pending=2
[info]  applying database migration  version=3  name=step_3  position=2  total=2
[info]  still applying database migration  elapsed_ms=1000  state=waiting_on_lock  wait_event=relation  blocked_by=[blocker]  version=3  name=step_3  position=2  total=2
[info]  database migration applied, pending commit  version=3  name=step_3  position=2  total=2  duration_ms=1000
```

Tests compare log output with golden files in
`coderd/database/migrations/testdata/reporter`.

Closes ENT-235

_Written with Claude Code and Coder Agents, reviewed and tested by
@kirstaeff._
2026-11-23 12:52:00 +01:00
49cd380e67 test(coderd/x/chatd): ignore non-hook requests in hook consumers (#32277)
`TestPreToolUseHookAllow/passthrough` failed in CI
([job](https://github.com/coder/coder/actions/runs/43909622615/job/133447870881))
because its hook consumer received five requests with empty bodies:
`json.NewDecoder(r.Body).Decode` returned `EOF` each time. Every real
hook delivery in the test succeeded, and its other assertions passed.

The dispatcher only sends POSTs with a non-empty JSON body and an
`Authorization: Bearer` token, so those requests did not come from this
test's dispatcher. The likely source is port reuse. The package's tests
run in parallel, and a closed `httptest` server's port can be handed to
a new server while another test's client (for example an MCP
streamable-HTTP client reconnecting its GET stream) is still retrying
it. The logs don't show which client sent them.

The hook consumers in the chatd tests now answer anything that is not a
POST with a bearer token with 404, instead of failing the test while
decoding it. This uses a shared `isHookRequest` helper.
`TestHookDispatcherRequiresExperiment`, which asserts the consumer gets
no hook requests, now counts only hook deliveries.

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VpiVZBgFqiSdRKrH8dPSPT)_

Co-authored-by: Garrett <garrett@coder.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:47:45 +02:00
Ethan 0992cdefe6 test(coderd/mcp): fix TestMCPHTTP_E2E_TemplateBrowserOnly on Windows (#32510)
Closes CORE-901

`TestMCPHTTP_E2E_TemplateBrowserOnly` fails on Windows in the [nightly
gauntlet](https://github.com/coder/coder/actions/runs/44456110594/job/135331397178).
The test reads `/tmp/file.txt` through the agent, which isn't an
absolute path on Windows, so the agent rejects it before we ever make
the template browser-only.

To fix, we'll build the path with `filepath.Join(os.TempDir(), ...)`,
the same as the other workspace tool tests.
`TestMCPHTTP_E2E_WorkspaceSSHAuthz` gets the same change, as I assume
that's where the `/tmp` path was copied from. It only passes on Windows
today because the dial is refused before the agent sees the path. The
failing assertion also didn't say why the tool call failed, so it now
includes the tool's error.

The test was added in #30578, and PR CI doesn't run this package on
Windows, so I've only run the fix on Linux.
2026-11-23 16:01:09 +11:00
Jeremy Ruppel 0ecf0d80b4 fix(coderd): attribute template builder create errors to request fields (#32559)
The template builder's create endpoint now attaches `validations` to its
name conflict (409) and missing organization (404) responses, naming the
`name` and `organization_id` fields. This matches the regular
create-template endpoint, which already returns a `name` validation on
conflict.

With this, the builder UI in #32492 can show these errors inline on
their fields through `getFormHelpers(form, createError)` instead of
mapping HTTP status codes to fields.

The 404 returned when the user can see the organization but cannot
create templates in it still has no field validation. It falls back to
the form-level alert.

> [!NOTE]
> Generated by Coder Agents on behalf of @jeremyruppel.
2026-11-20 16:36:32 -05:00
Susana Ferreira 13381e306d feat: paginate the organization unpriced AI models endpoint (#32170)
## Description

Paginates the experimental `GET
/api/experimental/organizations/{organization}/ai/model-prices/unpriced`
endpoint from #31753. The list is keyed by the requested model, which
clients set, so it has no upper bound.

## Changes

- `GetUnpricedAIModels` takes `limit_opt` and `offset_opt`, and each row
carries the `count` of every model. A zero limit returns every model, so
the unpriced models notification is unchanged.
- The endpoint reads `limit` and `offset` with
`parseOrganizationAISpendPage` (default 10, maximum 100), as the other
AI spend endpoints do.
- `count` is now the number of models over every page.
- `ExperimentalClient.OrganizationUnpricedAIModels` takes an
`OrganizationAISpendPage`.
- Add query and handler tests for pagination.

Related to AIGOV-730

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-20 17:48:01 +00:00
Bobby Ho cf68914831 fix(coderd): let only one request create the first user (#32417)
Prevent multiple Owner accounts from being created during concurrent first-user setup requests.

Refs https://linear.app/codercom/issue/CORE-853

Use a transaction-scoped PostgreSQL advisory lock shared by password setup and GitHub/OIDC first sign-ins. Recheck the user count under the lock to ensure only one account receives the Owner role, while preserving existing responses for subsequent requests.

- Add a stable, backport-safe lock ID and shared first-user setup helper.
- Apply locking only when no users exist, leaving normal sign-ins unaffected.
- Use `READ COMMITTED` isolation to ensure accurate counts regardless of database defaults.
- Keep validation and trial licence requests outside the lock.
- Preserve existing API responses, status codes, and telemetry behavior.

**Testing**
- Add concurrent password, OAuth, and mixed-path tests verifying exactly one Owner.
- Cover lock contention, cancellation, isolation levels, telemetry, and lock bypass.
- Verify tests fail when locking is removed.
- Pass targeted race tests, 124 related tests, lint, and `intxcheck`.

**Known limitation:** A burst of concurrent OAuth sign-ins on an empty deployment could exhaust the database connection pool while waiting for the lock. This remains unverified and is outside the scope of this fix.

**Note:** Stacked on #32324; will be rebased onto `main` after it merges.
2026-11-20 09:12:05 -07:00
Spike Curtis 9ef61e5797 feat: add wsrelated tags to Workspace and its sub-structs (#32437)
Adds `wsrelated` struct tags to `codersdk.Workspace` and every struct it
contains, recording which `include_related` path populates each field.
These tags will drive generated API docs; nothing in production reads
them yet, so there is no behavior change.

RFC:
https://app.notion.com/p/coderhq/Lite-Workspace-API-Requests-3aad579be5928060b5e7cc65c539717f?source=copy_link#3acd579be592808a84dace3da215b099

Tag conventions:

- `wsrelated:""`: always returned. 
- `wsrelated:"a,b"`: requires every listed path. Only
`Workspace.Outdated` (`template,latest_build`) uses this.
- Subtree tags: when every field of a struct would carry the same tag,
only the parent field is tagged, so doc generation can stop descending
there. Deprecated, unset fields count as covered.
- No tag on a field of a tagged struct: not returned as part of a
workspace. This covers `ProvisionerJob.WorkerName`, `AvailableWorkers`,
`Metadata`, and `WorkspaceAgent.Metadata` (only set by the list
endpoint's `include_agent_metadata`).

---

_Generated by Coder Agents on behalf of @spikecurtis._
2026-11-20 17:01:33 +01:00
Bobby Ho 88d3494b9a feat: require a setup token to create the first user on a tunnel (#32324)
fix(security): require setup token for first user on tunnels

Prevent unauthorized users from claiming Owner access on public `try.coder.app` tunnels before initial setup.

- Generate a setup token at startup when using a tunnel with no existing users.
- Require the token for first-user creation via the API, web UI, and CLI.
- Block GitHub/OIDC first-user signup until setup is complete.
- Support custom tokens via `--setup-token` / `CODER_SETUP_TOKEN` and non-interactive CLI setup.
- Update development scripts, documentation, and tests.
- Preserve existing behavior for deployments with an access URL or existing users.

Validated with automated tests and 23/23 manual scenarios using a real tunnel.

Refs CORE-784
2026-11-19 20:22:21 -07:00
Susana Ferreira 8705d80fe0 feat: add provider, model, and client spend to the AI spend users endpoint (#32330)
## Description

Extends the experimental `GET
/api/experimental/organizations/{organization}/ai/spend/users` endpoint
with the per-user details behind the AI spend overview and the detailed
report. Each user now returns their spend per provider, model, and
client, and whether each has unpriced usage.

## Changes

- Rewrite `ListOrganizationAISpendUsers` with `GROUPING SETS`, returning
one row per user and provider, model, or client:
  - Adds the `user_ids` and `group_id` filters.
  - Pages, counts, and totals users, not their rows.
- Reads the provider display name, icon, and type from `ai_providers`,
including deleted providers. The live provider wins when a name was
reused, like `GetAIProviderFilterOptions`.
- Update the SDK and handler:
- Each user returns `provider_spend`, `model_spend`, and `client_spend`,
most expensive first, each with `has_unpriced_usage`.
  - `totals` returns `has_unpriced_usage`.
- Remove the `providers`, `clients`, and `models` name arrays and
`unpriced_usage_count`.
  - Accept `user_ids` (comma-separated, maximum 100) and `group_id`.
- Return more than 100 `user_ids` on the group members AI spend endpoint
as a validation error, like `/ai/spend/users`.
- Switch the Spend page to the new fields, with no UI changes.
- Update the query and handler tests.

<details>
<summary>Dogfood performance</summary>

- Benchmarked on **dogfood**, comparing the existing query on **main**
with the updated query in **this PR**.
- Tested **1, 7, 15 and 30-day windows**, ending at **November 18, 2026,
00:00 UTC**, exclusive.
- Each query ran **five times per window**, one at a time, with query
order and window order rotated across rounds to reduce ordering bias.

The table shows PostgreSQL execution time in **seconds, average
(min-max)**.

| Days | Main | This PR |
|------|-----:|--------:|
| 1 | 0.288 (0.199-0.501) | 0.223 (0.184-0.275) |
| 7 | 11.413 (4.076-40.003) | 4.107 (3.529-4.828) |
| 15 | 9.961 (8.053-16.917) | 7.253 (6.873-7.736) |
| 30 | 14.979 (12.276-23.177) | 8.499 (7.813-9.169) |

All five runs are included. Main's first seven-day run took **40.003s**
with unusually high read I/O time, which raises its average. Cache and
concurrent load can affect these results.

</details>

Closes AIGOV-734

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-19 14:59:20 +00:00
coder-automations[bot]andgithub-actions[bot] 11b33b4c26 chore: refresh AI model price book (#32436)
## Price book changes

17 models added, 0 models removed, 19 models changed.

<details>
<summary>Added</summary>

- azure/gpt-6.2-astra
- azure/gpt-6.2-sol
- bedrock/global.openai.gpt-6.2-astra
- bedrock/global.openai.gpt-6.2-sol
- bedrock/openai.gpt-6.2-astra
- bedrock/openai.gpt-6.2-sol
- bedrock/us.openai.gpt-6.2-astra
- bedrock/us.openai.gpt-6.2-sol
- copilot/gemini-4-neon
- copilot/gpt-6.2-astra
- copilot/gpt-6.2-sol
- copilot/mai-code-2
- copilot/mai-code-2-flash
- google/gemini-4-neon
- openrouter/google/gemini-4-neon
- vercel/google/gemini-4-neon
- vercel/scaledown/extract-1
</details>

<details>
<summary>Changed</summary>

- openrouter/deepseek/deepseek-r1-0528
- openrouter/deepseek/deepseek-v4-flash-0731
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/deepseek/deepseek-v4.1-flash-1017
- openrouter/google/gemma-3-27b-it
- openrouter/google/gemma-4-26b-a4b-it
- openrouter/minimax/minimax-m3.1-flash
- openrouter/moonshotai/kimi-k2.7-code
- openrouter/moonshotai/kimi-k3
- openrouter/moonshotai/kimi-k3.1-pro
- openrouter/qwen/qwen3.5-27b
- openrouter/qwen/qwen3.5-9b
- openrouter/reflection/beam-1.0-501b-a23b
- openrouter/xiaomi/mimo-v2.5-pro
- openrouter/z-ai/glm-5.1
- openrouter/z-ai/glm-5.3-flash
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-v4-flash-latest
- openrouter/~moonshotai/kimi-latest
</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/44492971443).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-19 14:30:51 +00:00
Molly Fraser 7f245d8296 chore!: remove legacy AI Gateway metric aliases (#32381)
Removes the deprecated `coder_aibridged_*` and `coder_aibridgeproxyd_*`
Prometheus metric aliases, which were scheduled for removal in v2.37.
The embedded AI Gateway and AI Gateway Proxy now emit only
`coder_ai_gateway_*` and `coder_ai_gateway_proxy_*`.

- Replace `NewMetricAliasRegisterer` with
`prometheus.WrapRegistererWithPrefix` in `cli/server.go` and
`enterprise/cli/aibridgeproxyd.go`.
- Delete `coderd/prometheusmetrics/metricalias.go` and its test (no
remaining callers).
- Drop alias support from the metrics docs scanner.
- Update the AI Gateway monitoring and rebranding migration docs: legacy
names are removed as of v2.40.

**Breaking:** dashboards and alerts that still use the legacy names stop
matching. The monitoring docs show a temporary `metric_relabel_configs`
bridge.

Closes AIGOV-447.

<details>
<summary>Implementation plan</summary>

| File | Change |
|---|---|
| `cli/server.go` | Remove the `TODO(deprecation)` comment; register
embedded gateway metrics with
`prometheus.WrapRegistererWithPrefix(aibridgemetrics.PrometheusMetricPrefix,
...)`. |
| `enterprise/cli/aibridgeproxyd.go` | Same swap with the
`coder_ai_gateway_proxy_` prefix; drop the unused `prometheusmetrics`
import. |
| `coderd/prometheusmetrics/metricalias.go`, `metricalias_test.go` |
Delete; the two call sites above were the only callers. |
| `scripts/metricsdocgen/scanner/prefix.go` | Remove
`NewMetricAliasRegisterer` from `prefixFuncs`. |
| `scripts/metricsdocgen/scanner/scanner_test.go` | Remove the alias
fixture and the legacy-alias assertion; the remaining literal-prefix
case already covers plain `WrapRegistererWithPrefix`. |
| `scripts/metricsdocgen/README.md` | Drop the
`NewMetricAliasRegisterer` mention. |
| `docs/ai-governance/ai-gateway/monitoring.md` | State that legacy
names are no longer emitted as of v2.40; reword the relabel snippet as a
temporary bridge and explain its cost. |
| `docs/ai-governance/ai-gateway/rebranding-migration.md` | Mark metrics
as "No (removed in v2.40)"; rewrite the Metrics section; remove the
now-obsolete "dropping the old names" section. |

Release note: the `!` title applies `release/breaking`, so the change is
listed under breaking changes in the v2.40 release notes.

Verification: `make gen` (no metrics reference changes), `make lint`,
`pnpm run format-docs`, `pnpm run lint-docs`, doc-check and test-audit
self-review, and targeted tests for `enterprise/cli` (AI Gateway /
proxy), `cli` (AI Gateway), `scripts/metricsdocgen`, and
`coderd/prometheusmetrics`.

</details>

Code written by @mollymaefraser, with Coder Agents used as a guide.
2026-11-19 13:24:00 +00:00
Molly Fraser 4bccdc4ed6 feat: show and filter by organization in AI Gateway sessions API (#32057)
Adds an `organization` filter to `GET /api/v2/ai-gateway/sessions` (and
its `/api/v2/aibridge/sessions` alias) and returns the organization an
interception was attributed to, and how it was chosen, on sessions,
threads and agentic actions, as proposed in the surface definitions on
AIGOV-754. No migration: `aibridge_interceptions.organization_id` and
`organization_source` already exist (000634).

The filter accepts an organization name or ID and keeps sessions with at
least one interception in that organization; the count uses the same
rule so pagination totals match. Each session, on the list and detail
responses, lists the organizations its interceptions were attributed to,
ordered by name, with the distinct sources used for each, or `[]` when
none was stored. Each thread carries the organization of its root
interception and each agentic action carries its own, or null when none
was stored. The new filter is listed in the AI Gateway monitoring docs.

Refs AIGOV-754

## Open questions for reviewers

- **Multi-org sessions** (AIGOV-776): the filter is row-level, like
provider and model. A session spanning two orgs is listed under each
org's filter, and with the filter on, `threads`, `started_at` and
`ended_at` only cover the matching interceptions, while providers,
models, tokens and `organizations` cover the whole session. Is that the
desired behavior?
- **Unknown org ID:** an unknown org name returns 400, but an unknown
org ID returns an empty page, because `parseOrganization` does not look
up UUIDs. This matches workspaces and templates, but the spec says 400.

## Notes for reviewers
- `aiBridgeSessionOrganizations` returns an empty list if the
organizations JSON from the query can’t be decoded, rather than failing
the whole request. The field is supplementary, so a decoding problem
shouldn’t take down the sessions list, but it does mean a SQL bug here
would show up as empty data rather than an error. The alternative is to
log the error before returning the empty list.
- A thread’s organization is taken from its root interception only. If
later requests in the same thread were attributed to a different
organization, that shows on each agentic action’s own organization
field.

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

- `coderd/database/queries/aibridge.sql`:
- `@organization_id` filter in `CountAIBridgeSessions` and the
`session_page` CTE of `ListAIBridgeSessions`.
- New `sorg` lateral in `ListAIBridgeSessions` that groups the session's
interceptions by organization, collects distinct sources, joins
`organizations` (deleted orgs still resolve) and returns a JSON array.
- `ListAIBridgeSessionThreads` resolves the organization name, display
name and icon through a `LEFT JOIN LATERAL` in the final `SELECT`. A
plain join on `organizations` is not safe there: the query has two
`@authorize_filter` placeholders, and the injected filter can reference
a bare `id`, which would be ambiguous next to `organizations.id`. The
lateral only exposes the three selected columns. This answers the
authorize-filter open question from the surface proposal.
- `coderd/database/modelqueries.go`: the hand-written
`ListAuthorizedAIBridgeSessions`, `CountAuthorizedAIBridgeSessions` and
`ListAuthorizedAIBridgeSessionThreads` gain the new argument and scan
columns. The compiler does not catch a mismatch here; it fails at
runtime.
- `enterprise/coderd/aibridge.go`: pass `OrganizationID` into
`CountAIBridgeSessionsParams`, which is built field by field, and list
the `organization` key in `@Param q`.
- `coderd/searchquery/search.go`: `organization` key via
`parseOrganization`.
- `codersdk/aibridge.go`: `AIBridgeInterceptionOrganizationSource` enum,
`AIBridgeInterceptionOrganization`, `AIBridgeSessionOrganization`, new
response fields and `AIBridgeListSessionsFilter.Organization`, per the
proposed Go definitions.
- `coderd/database/db2sdk/db2sdk.go`: decode the session organizations
JSON, never returning nil; `AIBridgeInterceptionOrganizationSource`
converter; build one organization per interception while grouping thread
rows, and use it for the thread (root interception) and each agentic
action.
- `site/`: add `organizations: []` to two frontend mocks, now that the
field is required in the generated types.
- `docs/ai-governance/ai-gateway/monitoring.md`: `organization` added to
the sessions API query filters.
- Tests: `TestAIBridgeSessions` (name and ID parsing),
`TestAIBridgeListSessions/Filters` (by name and ID, checks count and
page), `FilterErrors/UnknownOrganization`,
`TestAIBridgeListSessions/Organizations` (multi-org ordering and
sources, no-org session returns `[]`, filtering by either org returns
the multi-org session and never the no-org one),
`TestAIBridgeGetSessionThreads/Organizations` (thread uses the root's
org, each action its own, null when none, session `organizations` on the
detail endpoint), and `TestAIBridgeInterceptionOrganizationSource`
(every database source maps to an SDK value).
- Remaining files are generated by `make gen`.

</details>

---

Code written by @mollymaefraser, with Coder Agents used as a guide:
explaining the existing code path, reviewing each step, and running
tests.
2026-11-19 09:07:56 +00:00
Taruj Goyal 734a0cae07 feat: scope browser-only connections to a template (#30578)
Add per-template `browser_only` enforcement while preserving `CODER_BROWSER_ONLY` as a deployment-wide override.

Refs #29157. Supersedes #29204 (closed by stale bot). Rebased onto current `main`, with migration renumbered to `000643`.

### Changes

- Add `templates.browser_only` (default `false`) to the database, SDK, and template create/update APIs.
- Require the `browser_only` entitlement to enable the setting, but allow disabling and continue enforcement after license expiry.
- Reject agent coordinate connections with 409 and enforce per-template tunnel restrictions through `AuthorizeTunnel`.
- Return non-fatal tunnel policy errors in both AGPL coordinator and pgcoord, preserving other active tunnels on shared connections.
- Exclude browser-only workspaces from Desktop workspace updates and enforce the restriction in MCP agent connections.
- Fix `TestMigration000617ConnectionLogsMethod` to use raw SQL, avoiding schema compatibility issues.

### Open questions

- **Naming:** Keep `browser_only` or use `require_browser_connections`?
- **Performance:** `AuthorizeTunnel` adds a database query under the coordinator mutex. Consider a narrower query if needed.
- **Feature reporting:** Should the feature report as enabled when any template uses it?

### Out of scope

Dashboard UI, CLI flag, and Terraform provider support (requires a separate `coder/terraform-provider-coderd` change).

### Verification

- Relevant unit and integration tests passed, including coordinate rejection, tunnel isolation, workspace filtering, and non-fatal policy errors in both coordinators.
- `golangci-lint` passed with no issues.
- Regenerated database, SDK TypeScript, Swagger/API reference, and audit-log artifacts.
- Not manually verified with Coder Desktop, multi-node deployments, workspace proxies, or UI.

### AI disclosure

Most changes and the rebase were completed with Claude Code (Opus 5/5.5), following the [AI contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING).
2026-11-18 22:07:12 +00:00
Jon Ayers f66c82d939 feat: add dbcrypt support for oauth_extra (#32344)
The `oauth_extra_key` can sometimes contain sensitive data so we should
encrypt
2026-11-18 14:59:28 -06:00
Jeremy Ruppel e049627258 test(coderd/templatebuilder): fix ETXTBSY flake in TestQuickstartCppInstallGuard (#32403)
`TestQuickstartCppInstallGuard` wrote stub executables in parallel
subtests and then executed them through the quickstart install script. A
concurrent fork could inherit a stub's write fd, so the exec failed with
`Text file busy` (golang/go#22315). The stubs are now bash functions
prepended to the script, so the test does not write or execute any
files.

This PR also adds `TestBaseBundlesReferencedFiles`. It walks each base's
rendered `main.tf` HCL and checks that every `file()`/`templatefile()`
path is bundled in `BaseExtraFiles`. It replaces the hand-written
`AWSLinuxExtraFiles` and `AzureLinuxExtraFiles` subtests.

Fixes CLIENT-1102

<details>
<summary>Plan and decision log</summary>

### Fix CLIENT-1102: flake in TestQuickstartCppInstallGuard

#### Problem

`TestQuickstartCppInstallGuard` wrote stub executables in parallel
subtests, then executed the quickstart install script. A concurrent fork
could inherit a stub's write fd, so executing a stub failed with
`ETXTBSY` (golang/go#22315).

#### Decision log

1. Hold `syscall.ForkLock` while writing stubs. Rejected: it keeps the
file setup and protects only this process.
2. Replace the stub files with bash functions, so no file is written or
executed. Implemented.
3. Delete the test and only check that the files are referenced. Tried,
then reverted after review: the test is the only regression test for the
C/C++ install guard (#30374), and running scripts from Go tests is not
against repo policy.
4. Keep the reference check as a separate test. It covers a different
contract: every file that a base's `main.tf` passes to
`file()`/`templatefile()` must be bundled.

#### Change

- `TestQuickstartCppInstallGuard`: define the stubs as bash functions
prepended to the script. `PATH` is an empty temp dir, `sudo` echoes its
arguments, and the test checks stdout for `SUDO: apt-get install`.
- Add `TestBaseBundlesReferencedFiles`: one parallel subtest per base.
Each renders `main.tf` with `testRenderContext`, walks the parsed HCL
for `file()`/`templatefile()` calls, evaluates the path with
`path.module = "."`, and checks that it is a key of `BaseExtraFiles`,
which `Compose` passes through unchanged. A path that is not a literal
fails the test, and so does a base that bundles files without
referencing any of them. Calls in comments and heredocs are ignored.
- Remove the `AWSLinuxExtraFiles` and `AzureLinuxExtraFiles` subtests,
which only listed file names by hand and are now covered by
`TestBaseBundlesReferencedFiles`.

#### Verification

- With the guard set back to gcc only, `MissingCmake` and `OnlyGcc`
fail.
- `go test ./coderd/templatebuilder -run
'^TestQuickstartCppInstallGuard$' -count=500 -cpu=8` passes, as does the
whole package with `-count=20 -cpu=8`.
- Reference check mutations: a renamed quickstart reference, a removed
aws-linux file, and a misspelled DigitalOcean reference each fail the
subtest for that base with a short message. A path that is not a literal
fails. A call in a comment is ignored.
- `golangci-lint` (0 issues), `gofmt`, `git diff --check`.

</details>

---

_Generated with Coder Agents on behalf of @jeremyruppel._
2026-11-18 14:59:15 -05:00
Nick Vigilanteandcoder[bot] 579b9995e8 fix: document WebSocket routes as 101 responses in the Swagger spec (#30125)
Six WebSocket routes were documented as `200` responses: `chats/watch`,
`chats/{chat}/stream`, `chats/{chat}/stream/git`,
`chats/{chat}/stream/parts`, `workspaces/{workspace}/watch-ws`, and
`workspaceagents/{workspaceagent}/watch-metadata-ws`.

Mark them `@Success 101`, matching the other WebSocket routes, and
describe each message. `chats/{chat}/stream` and `stream/parts` send a
JSON array batch of events per message, so they keep `{array}`; the
others send one event per message.

Also document that the previous template version route returns `204`
with no body when there is no previous version.

Part of DOCS-1122, split from #30121.

<details>
<summary>CI flakes unrelated to this change</summary>

On `d23267b7c3`, two checks failed in code this PR does not touch.

-
[`TestChatTurnStopsAtStepLimit/Default`](https://github.com/coder/coder/actions/runs/40809166900/job/123235512188)
in `coderd/x/chatd` (test-go-pg, ubuntu): this PR changes only Swagger
comment annotations and generated docs, and does not touch the `chatd`
package.
-
[`updateWorkspace.spec.ts:76`](https://github.com/coder/coder/actions/runs/40809166900/job/123235512158)
(test-e2e): this PR changes no UI code, and the test exercises workspace
parameter updates.

</details>

---
🤖 Built with AI assistance.

---------

Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com>
2026-11-18 14:05:18 -05:00
Srinija Kakumanu 05d8c8d4f8 fix(coderd): list endpoints return 500 for API keys with ID-scoped allow lists (#32145)
> [!NOTE]
> This PR was generated by Coder Agents on behalf of @ksrinija.

## Ticket Link

Fixes
[CORE-780](https://linear.app/codercom/issue/CORE-780/bug-list-endpoints-return-500-column-reference-id-is-ambiguous-for-api)

## Description

List endpoints returned 500 with `pq: column reference "id" is
ambiguous` for API keys whose scope has an ID-scoped allow list (for
example `--allow template:<uuid>`). The SQL authorization filters for
workspaces, templates, audit logs and connection logs used the shared
`resourceIDMatcher()`, which emits an unqualified `id`. Their list and
count queries join other tables that also have an `id` column. The ID
check is only generated for specific IDs, so wildcard allow lists
(`template:*`) and tokens without allow lists were not affected.

This PR qualifies the column in each affected converter in
`coderd/rbac/regosql/configs.go`: `workspaces.id`, `t.id`,
`audit_logs.id` and `connection_logs.id`. This follows the existing
pattern used by `chatResourceIDMatcher()` (`chats_expanded.id`) and
`ChatModelConfigConverter` (`cmc.id`).

<details>
<summary>Decision log</summary>

- **Inline qualified matchers instead of changing
`resourceIDMatcher()`.** Other converters share the helper and query
different tables and aliases, so no single prefix inside it is correct
for all of them.
- **Remaining converters checked; none affected.** `UserConverter`,
`MCPServerConfigConverter` and `OrganizationSkillConverter` filter
single-table queries. `AIBridgeInterceptionConverter`'s queries either
read one table or join subqueries that do not expose an `id` column.
`NoACLConverter` and `DefaultVariableConverter` are only used in tests.
This was checked against the query SQL, not run against Postgres.
- **`AIBridgeInterceptionConverter` must keep a bare `id`.** Its queries
refer to the table both as `aibridge_interceptions` and by the alias
`ai`, so qualifying it with either name would break the others.
- **Possible follow-up, not in scope:** change `resourceIDMatcher()` to
take a column argument so each converter names its column explicitly.
Pending team discussion.
- **Tests:** string-match cases in `compile_test.go` document the exact
SQL each converter generates, and need no database fixtures. A
Postgres-backed test (`TestAllowListIDScopedListEndpoints`) also runs
all 4 affected queries, so a later alias or join change that breaks the
qualified column is caught. Both were kept after review discussion.

</details>

## Testing Done

- **SQL generation tests:** added `WorkspaceAllowList`,
`TemplateAllowList`, `AuditLogAllowList` and `ConnectionLogAllowList` to
`TestRegoQueries` in `coderd/rbac/regosql/compile_test.go`. Each
compiles an ID-scoped allow list with the affected converter and checks
the exact generated SQL.
- **Postgres regression test:** added
`TestAllowListIDScopedListEndpoints` in
`coderd/database/dbauthz/allowlist_test.go`. It runs `GetWorkspaces`,
`GetTemplatesWithFilter`, `GetAuditLogsOffset` and
`GetConnectionLogsOffset` against Postgres with the real RBAC authorizer
and an allow list naming one row of each type. Each subtest checks that
the query succeeds and returns only the allow-listed row, out of two.
This catches future alias or join changes that the string tests cannot.
- **Confirmed both tests catch the bug:** with `configs.go` reverted to
`main`, all 4 `TestRegoQueries` cases fail because the generated SQL
contains the bare `id`, and all 4 Postgres subtests fail with `pq:
column reference "id" is ambiguous`. With the fix, all pass.
- **Existing tests:** `go test ./coderd/rbac/...
./coderd/database/dbauthz/...` passes.
- **Lint:** the repo's pre-commit checks (`make pre-commit`, including
`golangci-lint`) pass.
- **CI:** <fill in once checks finish on `e64c7f69c9`>
2026-11-18 09:58:29 -05:00