5075 Commits
Author SHA1 Message Date
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
Paweł Banaszewski c3e125f911 feat: record AI Gateway interception start and end (#29726)
Persist interception starts before forwarding. If start recording fails,
return 500 without contacting upstream.

Record the final outcome asynchronously with a five-second timeout. The
end record carries the categorized error (for upstream error statuses,
the response body truncated to 1024 bytes, or the status text when
empty) and the last pooled key used. Response completion does not wait
for recording. Graceful shutdown waits for inflight recordings.

Model, session ID, and token accounting remain unset.

Generated by Coder Agents on behalf of @pawbana.
2026-11-18 14:44:32 +00:00
Jaayden Halko 17a2b62205 feat: add an API to attach templates to chat projects (#30754)
Adds the API for attaching workspace templates to a chat project, on the
schema and queries in #32309. A project can attach templates, turn on a
limit that restricts its chats to them, and set a default template with
either a default preset or default parameter values. Attaching a
template never grants access to it: every reader is checked against the
template's own sharing. This PR stores and returns `limit_templates`;
#32310 enforces it.

- The limit is opt-in. `limit_templates` is off unless a request turns
it on, which is what every existing project gets.
- Templates are attached and detached one at a time with `PUT` and
`DELETE /chats/projects/{project}/templates/{template}`, so a caller
never replaces a list they can only partly see. Attaching needs project
`update` and template `use`. Detaching needs project `update` and
template `read`, and a template the caller cannot read is reported as
not found. `POST /chats/projects` accepts `template_ids`,
`limit_templates`, and `default_template` for the new project.
- `PATCH /chats/projects/{project}` sets `limit_templates` and
`default_template`, and no longer changes which templates are attached.
The default must be an attached template the caller can read, and its
preset must belong to the template's active version. Default parameter
names and values are checked against that version for templates on the
classic parameter flow; dynamic parameters are checked when a workspace
is built. Detaching the default template clears the default.
- Project responses list only the attached templates the caller can
read, as `templates`, and count the rest as `hidden_template_count`.
`default_template` is omitted when the caller cannot read it. Deleted,
deprecated, and agent-disabled templates are left out and are not
counted as hidden.
- Editing uses `chat_project:update`, which the project owner and the
project `admin` ACL role have.
- Attaching and detaching are audited as writes to the project, with the
template list before and after, including the templates attached while
creating a project. Changes to `limit_templates` and the default
template are part of the project's own audit diff.

Not included: showing which project members lack access to an attached
template, and MCP server attachments.

Stack (merge top to bottom):
- #32309
- #30754 👈
- #32310
- #30755
- #32371
- #32372
- #30756
- #32373
- #32374
- #32375
- #30898
- #32376
- #32377
- #32378
- #32379
2026-11-18 20:36:34 +07:00
Ethan feea5ab959 feat: add GPT-6.2 Astra and GPT-6.2 Sol to Agents and AI Gateway (#32370)
Closes CODAGT-1608

This adds `gpt-6.2-astra` and `gpt-6.2-sol` to the Agents known models
catalog, so they're suggested when an admin adds a chat model, and
regenerates the AI Gateway price book from models.dev so the gateway can
price them.

| Model | Input | Output | Cache read | Cache write |
|---|---|---|---|---|
| GPT-6.2 Astra | $8 | $40 | $0.40 | $10 |
| GPT-6.2 Sol | $2 | $10 | $0.10 | $2.50 |

Prices are per 1M tokens, and both models have a 1,050,000 token context
window and 128,000 max output tokens. They're in the catalog for OpenAI
(with a suggested effort of `medium`, same as `gpt-6-astra` and
`gpt-6.1-sol`), OpenRouter and Vercel. models.dev doesn't list them on
Azure or Bedrock yet, so I've left those out for now.

Both models also reject the `none` and `minimal` reasoning efforts. A
model config only sets a default and a maximum effort, so the picker
always offers both, and picking either one fails the turn:

```
Unsupported value: 'none' is not supported with the 'gpt-6.2-astra' model. Supported values are: 'low', 'medium', 'high', 'xhigh', and 'max'.
```

We already send `low` instead for `gpt-6-astra` and `gpt-6.1-sol`, so to
fix, we'll just do the same for the two new models. All four now live in
one list of model ID prefixes, rather than a helper each. I checked this
against the real models: all four return a 400 like the one above for
`none` and `minimal`, and accept `low`. `gpt-6-sol` and `gpt-6.1-terra`
still accept `none`, so they're left alone.

Regenerating the price book also brings in everything else models.dev
changed since the last weekly refresh, mostly on OpenRouter and Vercel:
22 other new entries (4 of them `-pro` and `-fast` variants of these
two), 29 it dropped and 51 price changes. 6 existing catalog entries get
new prices or limits the same way.
2026-11-19 00:33:46 +11:00
7c7e2e73cf feat: honor disable-model-invocation in uploaded skill content (#31159)
Addresses @ethanndickson's [review comment on
#30882](https://github.com/coder/coder/pull/30882#discussion_r4344815088):
the same `SKILL.md` file could be manual-only in Claude Code and the
project dialog but automatic in Coder, because the server and the
browser each handled `disable-model-invocation` in their own way.

The server now owns the key for personal, organization, and project
skills:

- When a create or update request leaves `model_invocable` unset,
`disable-model-invocation: true` in the content turns automatic use off,
and `false` turns it back on. The key is read with the function
workspace skills use, so a file gets the same setting in both places.
Only YAML booleans count, so a quoted `"true"` is ignored.
- An explicit `model_invocable` in the request always wins.
- New content without the key leaves the setting unchanged, so editing
text never turns it back on.
- Content is stored as uploaded. Every API response returns content
whose key agrees with `model_invocable`: when the stored file says
otherwise, the server replaces the value of the key or adds the key
before the first one, and leaves every other byte alone.
- **Download** and **Export all** save the content the API returns, so
the browser no longer edits the file. `withDisabledModelInvocation` is
removed.
- An upload is rejected with a 400 when the key holds a value the server
can't replace with a boolean, such as a list. A later change to
`model_invocable` can then always reach the file.

Two edges:

- Adding the key makes the returned file about 30 bytes larger, so a
file at the 64 KB upload limit can be too large to upload again.
- A skill stored before the upload check with a value the server can't
replace is returned as stored.

Workspace skills already honor the key since #31147.

#31160, the frontend PR on top of this one, adds the switch to the
personal and organization skill editors.

> Generated by an agent on behalf of the user

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-11-18 14:04:49 +07:00
Ethan da0bd0750f chore: remove most export_test.go shims (#32162)
Follow-up to https://github.com/coder/coder/pull/25601, where I missed
the other way agents avoid `*_internal_test.go`: an `export_test.go`
file that re-exports unexported symbols, just so a `package foo_test`
test can reach them. There were 13 of these on `main`, most recently
from #32063.

This PR removes 8 of them. Tests of package internals are now
`*_internal_test.go` files, with no changes beyond the package name and
the symbols they call. `messagepartbuffer` and `agentcontext` only
needed one small accessor each, so `Buffer.EpisodeCount` and
`Manager.Started` are just exported for real, and their tests stay where
they were.

To stop new ones appearing, the `testpackage` linter no longer skips
`export_test.go` (the 5 that are left are excluded by path), and
`AGENTS.md` and `.claude/docs/TESTING.md` now state the rule.

`export_test.go` is an agent idiom, and imo we should try and get rid of
it. So, once this PR is approved, we'll fix up all the remaining ones in
a follow-up PR, somehow, and undo the lint exclusion when we do.
2026-11-18 14:14:27 +11:00
Ethan 166b9d25e3 test(coderd): remove low-value cron and chatwebhook tests (#32164)
The tests from #32063 and #32062 are two to three times the size of the
code they cover, and a lot of them can't fail for a reason we'd care
about. This PR removes those, with no production changes.

In `coderd/schedule/cron`, two tests rebuilt the schedule rule a second
time to compare against, which was also the only use of
`export_test.go`, so that goes too. Most of the rest, in both packages,
are table rows that take the same branch as a row that stays. I also
dropped a copy of the webhook scheme list and a repeated-request test
that belongs at the route.

What's left is a row per reject branch, the RFC cases, the regression
test for the `Next` hang and the constant-time scan. I replayed each fix
commit from the two PRs against the smaller suite, and the pre-fix code
still fails a test for every one, other than a fix to the wording of a
zone error.

One row that stays is changed: the bearer wrong-scheme case used
`Basic`, which was only rejected because of where its space lands, so
nothing covered the scheme word. It's now `Digest`.

#32162 overlaps with this in `cron`. With the shim's users gone it no
longer needs to touch that package, so it's now stacked on top of this
PR.
2026-11-18 14:14:26 +11:00
Paweł Banaszewski a3f25a491e feat: forward bridged routes in AI Gateway proxy mode (#30226)
Enable bridged request forwarding in AI Gateway proxy mode. Responses
are captured through `TeeBuffer`.
Proxies are created per-request reusing transports.

Handle `http.ErrAbortHandler` inside the circuit-breaker wrapper so
aborted responses are classified by HTTP status before the panic is
propagated.

Generated by Coder Agents on behalf of @pawbana.
2026-11-17 18:02:24 +00:00
Mathias Fredriksson fe0b6e5de0 fix: take chat state from the stream only (#30478)
The chat page got a chat's messages, queue and status from three places:
REST pages, action responses and stream events. None of them had a
version, so the client could not tell which was newer and reconciled
them with rules of its own. A refetch or a response could replace newer
state from the stream, and a stream message that failed to parse lost
its events and left an error until a reload.

The server now returns snapshot_version on the newest messages page and
on stream events (#29662), which makes one copy enough. Each chat has a
store that loads the newest page once; after that, only stream events
and older pages change it. To reconnect, to return to a chat within five
minutes, or to recover from a failed parse, the client opens the stream
again at the highest version it applied. It refetches no messages, so no
response replaces what the stream set.

The client no longer reads messages or queue rows from action responses,
so a send, an edit or a queue change would show only once the stream
reports it. The store therefore shows the action's direct effect at the
click and keeps it until the stored state holds the result or the
request fails. It does not end at the next stream event of a kind,
because that event can report another change, and the user's change
would disappear and come back.

A sent message has no ID until the server creates it, so pending sends
are matched to new messages in click order, and a chat's send, edit and
queue requests run one at a time to keep that order. This assumes one
user in one client. A message from an agent, an automation or another
API client can end a pending send early, and the next stream event
corrects it.

The composer clears at the click, because the chat already shows the
sent message. It stays editable, so text typed during the request is
kept.

Closes CODAGT-903
2026-11-17 19:57:11 +02:00
Mathias Fredriksson 99e3bf91a7 fix(coderd/database/migrations): resolve duplicate version (#32329)
Main cannot initialize database migrations because #32309 reused version
000643, already taken by the skill display-name migration from #31747.

Renumber the later chat-project migration and its fixture to 000644,
preserving the earlier migration number. All three renames leave SQL
contents unchanged.
2026-11-17 17:26:27 +00:00
Susana Ferreira 3211ca066e feat: add organization unpriced AI models endpoint (#31753)
## Description

Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/model-prices/unpriced`
endpoint behind the "N models not set up" warning on the organization AI
spend page
([Figma](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=70-11964&t=KQwENGjcQvVT9qkh-4)).
It lists the models used in the period that still hold no price in the
organization, using the query from this stack.

## Changes

- Add the `organizationUnpricedAIModels` handler and
`ExperimentalClient.OrganizationUnpricedAIModels`:
- Reuses `aiSpendRetainedPeriod`, since token usage is subject to data
retention.
- Returns the applied period, `count`, and `models` (provider name,
display name, icon and type, model, token count), most unpriced tokens
first.
- Requires read on the organization's model prices (owners and
organization admins), so the UI only requests it for users who can set
prices.
- Add handler tests for the response, period validation, organization
scoping and role access.

Note: pagination will be added in a follow-up.

Closes AIGOV-730

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-17 15:34:04 +00:00
Jaayden Halko 1f1aa6ae3c feat: add chat project template schema and queries (#32309)
Adds the database layer for attaching workspace templates to chat
projects: the schema, the queries, their authorization, and the audit
type. Nothing calls the new queries yet, and the existing create and
update handlers pass the new parameters unset. The API, the limit's
enforcement, and the agent tools follow in the PRs above.

- Attachments live in a `chat_project_templates` table (`project_id`,
`template_id`, `created_by`, `created_at`), deleted with the project or
the template. `chat_projects` gains `limit_templates` (default `false`),
`default_template_id`, `default_template_version_preset_id`, and
`default_parameters jsonb`. A project stores a default preset or default
parameter values, not both.
- `InsertChatProjectTemplates` needs project `update` and `use` on every
template. It skips templates that are already attached, and templates
outside the project's organization, so an attachment never crosses
organizations. `DeleteChatProjectTemplate` needs project `update` and
template `read`, and clears the project's default when it detaches the
default template. Both checks are in dbauthz.
- `GetChatProjectTemplatesByProjectIDs` is authorized through the
project, and leaves out deleted, deprecated, and agent-disabled
templates. It does not check the caller's access to each template, so
callers do that before they expose one.
- `UpdateChatProjectByID` changes the template settings only when the
request sets them, so an update that omits them cannot write back a
stale snapshot.
- `AuditableChatProjectTemplates` is the audit form of a project's
attached templates, logged as a write to the project. The new
`chat_projects` columns are tracked in the project's own audit diff,
with the default parameter values masked because they may hold
credentials.

**NOTE**: the migration adds one table and four columns and changes no
existing rows. Existing projects keep unlimited template access.

Stack (merge top to bottom):
- #32309 👈
- #30754
- #32310
- #30755
- #30756
- #30898
2026-11-17 21:59:01 +07:00
Mathias Fredriksson c3ff770e8a fix(coderd/database): match workspace requester by owner ID when sorting (#32188)
GetWorkspaces sorted the requester's favorite and own workspaces first
by matching the owner's username. Usernames are unique only among
non-deleted users, and a deleted user keeps theirs, so a user who took a
deleted user's username saw that user's deleted workspaces and favorites
sorted as their own when listing deleted workspaces. Match by owner_id
instead, as the sort did before #22290.

The username form most likely worked around the sqlc CTE bug: with the
EXISTS (tasks) filter the query had then, sqlc without the coder/sqlc
fix rejected the bare owner_id as ambiguous. #29085 removed that filter,
so the owner_id form generates with either sqlc.
2026-11-17 13:41:57 +02:00
Jaayden Halko 4866d0fb1f feat: add display names to project skill actions (#31747)
closes CODAGT-1506

Project skill action chips show the skill's slug (`deploy-bot`,
`security-review`), because skill names must be kebab-case. This adds an
optional display name that labels the chip instead.

Project skills get a `display_name` column, set through `display_name`
on the create and update requests. It is limited to project skills (the
same rule as `action`), trimmed, single line, and at most 64 Unicode
code points. The chip, its tooltip, and the "More" menu show the display
name, sort by it, and fall back to the skill name when it is empty. When
a display name is set, the tooltip and the menu item also show the
`/name` slash command, so actions that share a display name stay
distinguishable. Clicking an action still inserts `/name`, and the `/`
menu is unchanged.

The project skill editor shows a **Display name** field under **Show as
action** only while that switch is on. Turning the switch off hides the
field but keeps its value, and saves omit `display_name` while the
action is off, so the stored value stays. The display name lives in the
database rather than SKILL.md frontmatter, so downloading and
re-importing a skill does not carry it.

To share the code-point length check with the editor, `countCharacters`
and `maxCharacters` move from `ChatProjectDialog.tsx` into
`site/src/utils/formUtils.ts`.

<img width="637" alt="Project skill editor with the Display name field
under Show as action"
src="https://raw.githubusercontent.com/coder/coder/assets/pr-skill-action-display-name/pr/edit.png"
/>

<img width="520" alt="Action chips labeled with display names, with the
tooltip open"
src="https://raw.githubusercontent.com/coder/coder/assets/pr-skill-action-display-name/pr/chips.png"
/>

Refs CODAGT-1506
2026-11-17 17:55:35 +07:00
Ethan 3795d72713 fix: search AI Gateway models and clients by substring (#32159)
Closes AIGOV-801

Typing `hai` into the model filter on the AI Gateway sessions page shows
the haiku models for a moment, then "No models found". Whilst the
debounced request is pending, the menu filters the options it already
has by a case-insensitive substring, but `GET /api/v2/ai-gateway/models`
only matched a case-sensitive prefix, and Bedrock identifiers start with
`anthropic.`. The client filter matched the same way, so it had the same
problem.

To fix, both endpoints now match a case-insensitive substring.

This needed one change to the model menu. When the page loads with a
model already in the filter, the menu used to look that model up on the
server, by searching for its name and taking the first result. That's
the same pattern as the user filter, where the lookup fetches the
avatar, but a model option needs nothing from the server, so all it did
was check that the model exists. With a substring search, the first
result for `claude-3-5-sonnet-20241022` can be
`anthropic.claude-3-5-sonnet-20241022-v2:0`, so the check would fail for
a model that does exist. The menu now skips the lookup and just shows
the model from the filter as selected. The only visible difference is
that a model name in the URL that doesn't exist now shows as selected,
instead of "All models". The client menu has the same lookup, which
still works, as no client name contains another, so I've left it alone.

The prefix match was added in #22230 (models) and #22694 (clients) so
the queries could use the B-tree indexes. That only works on a C
collation database, and only for models, as the clients query wraps the
column in `COALESCE`. On an `en_US.utf8` database it's a plain filter
either way. On a C collation database a model search with no matches
does get slower, from instant to a few seconds with 5M synthetic rows,
but I think that's worth it for a search that works.
2026-11-17 11:52:12 +11:00
McKayla はな 0be6e7a034 feat: add a setting for web terminal font size (#32027) 2026-11-16 15:03:30 -07:00
b0ae8adab5 feat(coderd): protect pending jobs only while the provisioner queue is moving (#32099)
Stops the pending job reaper from failing jobs in a queue that's still
moving. This is an alternative to #31469 that came out of Steven's
[review](https://github.com/coder/coder/pull/31469#pullrequestreview-5847958482)
asking whether 2h is enough, and it builds on George's work there.

A pending job past 30m is now only protected while a matching online
provisioner is making progress, meaning it finished a job in the last
30m or is running one that's still being updated. A moving queue never
gets reaped and a frozen one still does at 30m like today. There's no
absolute cap.

No migration since it uses the existing
`provisioner_jobs_worker_id_organization_id_completed_at_idx`. One
tradeoff is that a stuck build whose provisioner keeps heartbeating
counts as progress, so if every matching provisioner is stuck like that,
the queue waits until that build is canceled.

Still a draft so we can talk it through with Spike and Steven.

Part of CORE-586

---------

Co-authored-by: George Katsitadze <george.katsitadze@gmail.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 07:45:24 -06:00
Callum Styan d412c38afb perf: validate chat transitions from the locked row (#30886)
One of the main costs in terms of DB load from chats is extra round
trips during transactions. This results in locks being held for longer
periods of time -> an increase in lock waits for chats related queries.

One of the opportunities for reducing some of the round trips is to
eliminate extra chat row reads after we have just read the row in order
to lock it.

In this PR `ChatMachine.Update` now seeds the transaction struct with
the row returned by `LockChatAndBumpSnapshotVersion`, plus a queue count
taken right after it. We can then pass it into `Update` as an optional
parameter validate against it, so neither re-reads the chat row from the
database while the row lock is held.

`updateChat` (send, edit, promote, tool results, interrupt, compact,
clear, reconcile), hook failure, family archive, and the worker's
generation and task transitions use it instead of reloading the chat
under the lock.

This PR relative to main:
|measurement | main | this PR | percent change |
|-- | -- | -- | -- |
| Round trips under lock  | 180.9 | 142.0 | -39% |
| Statements under lock  | 86.1 | 66.6 | -23% |
| GetChatByID under lock | 54.1 | 35.8 | -34% |
| GetChatByID total | 75.5 | 57.1 | -25% |
| Statements  | 235.8 | 216.2 | -8% |

Generated by Coder Agents on behalf of @cstyan.
2026-11-13 09:59:39 -07:00
John T Skarbek 54fe847c6f chore: remove references to torn-down dev.coder.com instance (#31702)
The `dev.coder.com` instance has been torn down and now only redirects
to another instance. Nothing in the repo calls it. Every reference was a
test fixture, mock, story, Helm test input, docs example, or comment.

Replace all occurrences with `coder.example.com` and update the comments
that claimed the mocks were fetched from that instance. The Helm golden
files were updated to match their inputs.

Closes DOG-43

https://linear.app/codercom/issue/DOG-43/scan-codercoder-repo-for-remaining-references-to-devcodercom-and
2026-11-13 16:38:44 +00:00
Spike Curtis 4f6a56427e feat: report pubsub health from the pubsub backend (#31621)
Fills in the `pubsub` section of the deployment health report on the
server. Stacked on #31620.

- New `pubsub.ReportingPubsub` interface: `Pubsub` plus
`HealthReport(ctx) healthsdk.PubsubReport`. The `Pubsub` interface
itself is unchanged.
- The PostgreSQL, NATS and in-memory backends implement it. Each reports
its backend name (`postgres`, `nats` or `memory`) and its connection
state:
- **PostgreSQL:** tracks the `pq` listener's connected state from its
event callback. When it's not connected, the report has severity
`warning` and `EPS01`.
- **NATS:** warns with `EPS02` if the embedded server isn't `Running()`,
and with `EPS01` for each publish or subscribe connection whose
`Status()` isn't `CONNECTED`.
  - **In-memory:** always `ok`.
- `coderd.Options.Pubsub` is now a `ReportingPubsub`.
`ReplicaSyncPubsub` stays a plain `Pubsub`.
- `coderd/healthcheck` has a new `Pubsub` check, which counts toward
`healthy` and the overall severity like the other sections.
`formatHealthcheck` applies the dismissed setting for it.
- New health codes `EPS01` (not connected) and `EPS02` (embedded NATS
server not running), documented in
`docs/admin/monitoring/health-check.md`.
- Test helpers follow the type change: `coderdtest.Options.Pubsub` and
the pubsub returned by `dbtestutil.NewDB` are now `ReportingPubsub`, and
a few test wrappers embed `ReportingPubsub` instead of `Pubsub`.

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

- `HealthReport` returns a `healthsdk.PubsubReport` rather than filling
one in place. This matches the `healthcheck.Checker` methods. `ctx` is
unused for now.
- The healthcheck layer sets `Dismissed`, so backends don't need to know
about health settings.
- Problems are reported as warnings, not errors, so they show on the
health page without marking the deployment unhealthy. Both backends
reconnect on their own.
- Postgres connection state comes from the listener event callback, not
from `pq.Listener.Ping`, so the health check doesn't do database I/O.
Closing the pubsub also marks it disconnected.
- NATS `conn` gains `Status()`, which `*natsgo.Conn` already implements.
The pools are immutable after construction, so `HealthReport` reads them
without locking.
- The docs say the pubsub section appears in the JSON response, because
the health UI doesn't show it until a later PR in this stack.
- psmock is not regenerated: none of its users pass it to coderd.

</details>

---
Generated by Coder Agents on behalf of @spikecurtis.
2026-11-13 17:20:31 +01:00
Spike Curtis 2187ecd37e feat: add PubsubReport to healthsdk HealthcheckReport (#31620)
Adds pubsub to the deployment health report types in `healthsdk`:

- New top-level `pubsub` section (`PubsubReport`) in
`HealthcheckReport`. It embeds `BaseReport` and adds one field,
`backend` (string).
- New `HealthSectionPubsub` constant, added to `HealthSections` so the
section can be dismissed.
- `HealthcheckReport.Summarize` includes pubsub errors and warnings,
which `coder support bundle` prints.

This is the first PR in a stack for GRU-100. It only changes the SDK and
the files generated from it (Swagger, API docs, `typesGenerated.ts`),
plus the two frontend health mocks that need the new required field. The
server does not fill in this section yet. That comes in a follow-up PR.

<details>
<summary>Plan</summary>

- Add `PubsubReport { BaseReport; Backend string }` to
`codersdk/healthsdk`.
- Add `Pubsub PubsubReport \`json:"pubsub"\`` to `HealthcheckReport`.
- Add `HealthSectionPubsub` and include it in `HealthSections`.
- Include `Pubsub` in `HealthcheckReport.Summarize`, with test coverage.
- Regenerate TS types, Swagger and API docs.
- Follow-up PRs: populate the report in `coderd/healthcheck` (including
severity and dismissal handling) and update the health UI.

</details>

---
Generated by Coder Agents on behalf of @spikecurtis.
2026-11-13 17:20:31 +01:00
J. Scott MillerandGarrett Delfosse 38e74c4506 feat: add agent-plugins experiment and Agent API v2.17 plugin messages (#29320)
Linear:
[CODAGT-1101](https://linear.app/codercom/issue/CODAGT-1101/agent-plugins-read-only-support-behind-the-agent-plugins-experiment)

**tl;dr:** Adds the `agent-plugins` experiment and the Agent API v2.17
messages that carry Agent Plugins data from the agent to coderd. First
of eight stacked PRs adding read-only [Agent
Plugins](https://agent-plugins.org/) v1.0.0 support.

A plugin is a directory with a `plugin.json` manifest, skills under
`skills/`, and an optional `mcp.json`. Across the stack, the agent
discovers plugins in `plugins/` and `.agents/plugins/` under its scan
roots (for example `~/.coder/plugins/<name>`), chatd lists their skills
with plugin attribution, the agent runs the MCP servers of plugins in
the workspace working directory, and the Agents page shows plugin
attribution in the chat context. Hooks, commands, agents, install flows,
and org-managed plugins are out of scope. Background:
[research/agent-plugins-standard.md](https://github.com/coder/scott-misc/blob/main/research/agent-plugins-standard.md)
(internal).

This PR adds `codersdk.ExperimentAgentPlugins` and a `PluginBody` oneof
variant on `ContextResource` (tag 18) that carries the validated
manifest fields and nests the plugin's skills and MCP servers.
`Manifest` gains `agent_plugins_enabled` (field 23), which coderd sets
when the experiment is enabled; the agent discovers plugins only then.
coderd stores each nested resource as its own row with the plugin's name
in a new `plugin_name` column (migration 000642), which the hydrate, MCP
sync, and re-pin queries copy. With the experiment off,
`PushContextState` drops plugin resources and everything nested in them.
Otherwise it rejects pushes with plugin names that fail
`workspacesdk.ValidatePluginName` (the spec's name grammar, shared by
agent and coderd), OK plugins without a name or with a duplicate name, a
non-OK plugin that nests resources, nested entries of the wrong kind,
plugin skill sources outside `<plugin source>/skills/`, and plugin MCP
servers with an empty `server_name` or a source other than `<plugin
name>/<server_name>`. Nested resources count toward the 1000-resource
cap.

Agents now dial v2.17, so a new agent needs a coderd that supports it,
as with every Agent API minor. Turning the experiment off does not
remove plugin data already pinned to existing chats.

<!-- pr-map:start -->
<details><summary>PR map</summary>

`main..4b0cfc9657`

| Category | Files | + | - |
|---|---:|---:|---:|
| prod (backend) | 15 | 342 | 78 |
| test (backend) | 9 | 534 | 3 |
| migrations | 2 | 14 | 0 |
| generated (backend) | 7 | 1216 | 1027 |
| generated (frontend) | 1 | 2 | 0 |
| **Total** | 34 | 2108 | 1108 |

1. `coderd/agentapi/context.go` (+211/-51, API): drops plugin resources
when the experiment is off; otherwise validates plugin names and
nesting, and stores each nested skill and MCP server as its own row with
the plugin's name.
2. `agent/proto/agent.proto` (+39/-9, API): `PluginBody` with nested
`skills` and `mcp_servers`, and `Manifest.agent_plugins_enabled`.
3. `codersdk/workspacesdk/frontmatter.go` (+31/-0): `ValidatePluginName`
and `MaxPluginNameLength` (manifest name grammar).
4. `coderd/database/queries/chats.sql`, `workspaceagentcontext.sql`,
migration 000642 (+28/-7, DB): the `plugin_name` column on both context
resource tables, copied by the hydrate, MCP sync, and re-pin queries.
5. `codersdk/agentsdk/agentsdk.go`, `agent/agent.go` (+18/-4, API):
`Manifest.AgentPluginsEnabled` and `ConnectRPC217WithRole`; the agent
dials v2.17.
6. `coderd/agentapi/api.go`, `manifest.go` (+4): the manifest flag
follows the experiment.
7. `tailnet/proto/version.go` (+8/-1, API): Agent API v2.17.
8. `codersdk/deployment.go` (+4, API): the `agent-plugins` experiment.

</details>
<!-- pr-map:end -->

---

This PR was generated by Coder Agents on behalf of @jscottmiller.

Co-authored-by: Garrett Delfosse <delfossegarrett@gmail.com>
2026-11-13 10:39:16 -05:00
Susana Ferreira d611c60a9a feat: scope unpriced AI models to an organization and its prices (#31752)
## Description

Scopes `GetUnpricedAIModels` to an optional organization and checks
organization prices, so the unpriced models endpoint can list what an
organization still needs to price. Usage is attributed to an
organization through its token usage's effective group, the same as
spend.

## Changes

- Optional `organization_id`: when set, only that organization's usage
counts, and when null (the notification), all usage counts.
- A model still holds a price if it has a site-wide price for the
provider type, or an organization price (`ai_model_configs`, live and
with a price) for the provider in the usage's organization.
- dbauthz reads `ResourceAiModelPrice`, scoped to the organization when
one is given, like `GetAIModelPriceForProvider`.
- Table-driven query tests run every case for all organizations, org A
and org B.

<details>
<summary>Cases</summary>

Model X is on `anthropic-prod`. Y is the model the provider reports
serving for X. "Notif" is the deployment-wide notification, "UI A/B" is
the endpoint for org A/B.

| # | Prices | Usage | Notif before | Notif after | UI A | UI B |
|---|---|---|---|---|---|---|
| 1 | No price for X anywhere | A uses X, unpriced | ✅ | ✅ | ✅ | ❌ (B
didn't use X) |
| 2 | Site-wide price for X | A and B use X, priced | ❌ | ❌ | ❌ | ❌ |
| 3 | A priced X before the usage | Only A uses X, priced | ❌ | ❌ | ❌ |
❌ |
| 4 | A priced X after the usage | Only A uses X, unpriced when recorded
| ✅ (wrong) | ❌ | ❌ | ❌ |
| 5 | A priced X, B has none | A uses X (priced), B uses X (unpriced) |
✅ (because of B) | ✅ (because of B) | ❌ | ✅ |
| 6a | No price for X or Y when recorded, then Y priced site-wide | Only
A uses X, unpriced when recorded | ✅ | ✅ | ✅ | ❌ |
| 6b | Same as 6a | A and B use X, unpriced when recorded | ✅ | ✅ | ✅ |
✅ |
| 7a | No price for X, but a site-wide price for Y | A uses X, priced
through Y | ❌ | ❌ | ❌ | ❌ |
| 7b | No price for X, A priced Y, and B has none | A and B use X: A
priced through Y, B unpriced | ✅ (because of B) | ✅ (because of B) | ❌ |
✅ |

</details>

Note: pagination will be added in a follow-up.

Related to AIGOV-730

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 13:21:32 +00:00
Susana Ferreira 8c5921db5e fix: count unpriced AI model usage by when it was recorded (#31751)
## Description

Updates the unpriced AI models query behind the weekly owner
notification to count token usage by when it was recorded
(`token_usages.created_at`) in a `[period_start, period_end)` window,
consistent with the other AI spend queries. It also returns one row per
provider name and model instead of per provider type, so the unpriced
models endpoint later in this stack can reuse it. The notification
payload keeps the same format.

## Changes

- Rename `GetUnpricedAIModelsSince` to `GetUnpricedAIModels`. It used
`interceptions.started_at` with no end.
- Treat usage as unpriced only when no price was found (`cost_micros IS
NULL AND priced_model IS NULL`), so usage whose price was found but
whose cost could not be computed is not reported.
- Return one row per live provider name and model, with the provider's
display name, icon and type.
- The notification passes the last 7 days and merges rows by provider
type, since site-wide prices are keyed by type, so its payload keeps the
same shape.
- Table-driven query tests and a notification test for providers sharing
a type.

Related to AIGOV-730

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 13:21:32 +00:00
Mathias Fredriksson 5c9d74e019 perf(coderd/x/gitsync): poll merged PRs hourly (#31922)
Merged PRs cannot reopen, so their diff-status rows do not need the
two-minute TTL used for open and closed PRs. Use a one-hour TTL after
successful diff-status refreshes of merged PRs while retaining periodic
metadata updates.

Workspace git reports still set `stale_at` to the past so merged
diff-status rows remain eligible for the next worker tick.

Refs CODAGT-1543
2026-11-13 11:13:31 +00:00
Mathias Fredriksson d639ced1e0 fix: send only changed chat history over the stream (#29662)
A client could resume the chat stream only with after_id, a message
ID. A message ID does not identify what a client has received. A
reconnect could skip a message that another client sent, send no
history_reset for an edit the client missed, or resend the whole
history.

A client can now resume with the chat's snapshot_version, which the
newest messages page returns and the stream's events then include.
The stream sends what changed at that version or later. For an edit
it sends the ID of the edited message and the messages written
since, not the whole history. A stream opened without
snapshot_version sends the same events as before.

A write outside a chat state transition does not increase
snapshot_version, and a stream can miss it. The queries that only
tests used for such writes are removed.

When the stream cannot be set up, the server now returns 500 before
the WebSocket upgrade. It used to upgrade and send an error event,
which the web client shows as a chat error.

The Tasks to Chats migration guide told clients to reconnect with
after_id. It now describes snapshot_version.
2026-11-13 13:02:38 +02:00
Susana Ferreira 30abd0593c feat: add organization AI spend overview endpoint (#31709)
## Description

Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/spend` endpoint that
backs the new Overview tab of the organization AI spend page ([Figma
design](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=12-5152&t=YlCC7RGSMNrzMxVo-4)).
It returns the organization's spend summary, daily spend, and a page of
users with their per-group spend, using the queries from #31711.

## Changes

- Add the `organizationAISpend` handler and
`ExperimentalClient.OrganizationAISpend`:
- Reuses the period handling of `/ai/spend/users`: `period_start` and
`period_end` must be provided together and span at most 31 days, and the
default is the current budget period.
- Also requires both bounds at 00:00:00 UTC, since the daily spend
aggregate holds whole UTC days.
- Is not limited by the AI Gateway data retention window, since the
daily spend aggregate is not purged. `/ai/spend/users` and the export
keep the retention check, now in `aiSpendRetainedPeriod`.
- Returns `count`, `totals` (`spend_micros`, `median_spend_micros`),
`intervals` (daily spend, one interval per UTC day, zeros included), and
`users` (paginated with `limit`/`offset`, most spend first, with
per-group spend).
- Echoes the applied period, and reads every value in one read-only
repeatable-read transaction so the values agree.
- Extract `parseOrganizationAISpendPage`, shared with `/ai/spend/users`.
- Add handler tests.

Closes AIGOV-728

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 10:02:58 +00:00
Susana Ferreira 7db53f3b47 feat: add organization AI spend overview queries (#31711)
## Description

Adds 3 database queries for the organization AI spend overview. They
read the daily spend aggregate (`ai_user_daily_spend`), scoped to the
organization through each spend row's effective group, over a
`[period_start, period_end)` range of UTC days.

1. `GetOrganizationAISpendTotals`: the number of users with spend, the
total spend, and the median of the users' total spend.
2. `ListOrganizationAISpendPerUser`: paginated users, most spend first,
with one row for each group their spend was attributed to.
3. `GetOrganizationAISpendPerDay`: the spend for every UTC day in the
range, including days without spend.

Note: Only users with spend above zero are included, so users with only
unpriced usage are not listed.

## Changes

- dbauthz checks matching `/ai/spend/users` (read on organization group
members).
- Querier and dbauthz tests.

Related to AIGOV-728

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 10:02:58 +00:00
Ethan 73cf6bfc69 feat: show the prebuilds user in the Workspaces Owner filter (#31827)
Closes CLIENT-267

All prebuilt workspaces belong to the `prebuilds` system user, and the
docs tell admins to find them with `owner:prebuilds`. However, the Owner
filter on the Workspaces page never offers `prebuilds`, as its options
come from `GET /api/v2/users`, which hides system users. There was no
way to ask for them either, as the users search rejected
`include_system:true`.

So, the users search now accepts `include_system:true`, and the Owner
filter sends it. Without the term, `/users` behaves exactly as before,
and you still only get back users you're allowed to read.

The other endpoints that share the users search (org members, group
members and the MCP ACL picker) now accept the term too, but they still
hide system users. The template ACL picker reuses the `/users` handler,
so it'll list `prebuilds` if you ask for it.

<img width="697" height="313" alt="image"
src="https://github.com/user-attachments/assets/afdbfe89-f74c-46c5-8675-4aab231f7e25"
/>
2026-11-13 10:59:32 +11:00
Callum Styan c303114fae perf(coderd/database): batch chat authz fetch in GetChatDiffStatusesByChatIDs (#31880)
> Generated by Coder Agents on behalf of @cstyan.
2026-11-12 15:14:26 -07:00
Thomas Kosiewski 871eb9bd3e feat(coderd/schedule/cron): add Standard schedule constructor (#32063)
## Why

Automations store a five-field cron expression and an IANA time zone.
The scheduler and the management API will parse both with
`coderd/schedule/cron`, as the "Schedules" section of the [Automations
RFC](https://app.notion.com/p/3ded579be59281e39950e686df02fa3d) says.
This adds the parser they will call.

Part of CODAGT-1135.

## What changed

- `cron.Standard(spec, timeZone)` parses a five-field spec that runs on
the wall clock of an IANA zone. Every field can be restricted. It
returns an error for an empty spec, a wrong field count, a `CRON_TZ=` or
`TZ=` prefix, an empty or unknown zone, a zone name with an empty, `.`
or `..` segment such as `./localtime`, a name that starts with `posix/`
or `right/` (directories of zone data that some hosts have, with other
versions of the zones), `Local` (a Go name for the host's zone), a name
whose last segment is `localtime`, `posixrules` or `Factory` (files in a
host's zone data that are not zones), and a spec that never runs, such
as `0 0 30 2 *`.
- `Next` on a `Standard` schedule follows the RFC's daylight saving
rule. A repeated local time runs once, at its first instance. A
nonexistent local time runs at the first local time after the change.
`robfig/cron` does neither: in America/New_York it runs `30 1 * * *`
twice on 2026-11-01 and skips `30 2 * * *` on 2026-03-08. So `Standard`
walks the matching wall-clock readings and resolves each one to an
instant from the zone's UTC offsets. Every loop has a fixed bound, and
`Next` always returns a later time for a `Standard` schedule. It
searches at least 16 years ahead, past the eight years between two leap
days across 2100. `Weekly`, `Daily` and `TimeRange` keep their behavior.
- `Schedule.MinInterval()` returns the shortest distance between two
times of day at which the schedule runs, counted around the clock. One
time of day gives 24 hours. The management API will compare it with the
deployment's minimum interval.

## Scope

This PR adds no minimum interval policy and no configuration. Nothing
calls the new code yet. The scheduler loop and the API come in later
PRs.

## Tradeoffs

- `MinInterval` reads only the hour and minute fields, with no calendar.
The RFC allows a minimum interval of one minute to 24 hours, so the
value only has to be right below 24 hours, and a scan over the calendar
kept missing cases. While the zone's UTC offset does not change, no two
runs are closer than the value. The doc comment states two limits, and a
test pins each.
- A change of the UTC offset (daylight saving) can shorten a gap that
spans it by up to the size of the change: `1,58 1,3 * * *` in
America/New_York gives 57 minutes, and its runs on 2026-03-08 are 3
minutes apart.
- A pair of times across midnight counts even when the day fields never
match two days in a row: `0,58 0,23 * * 1` gives 2 minutes, but its runs
are 58 minutes apart at least, so a check can reject a schedule that the
minimum allows.
- The RFC rule, read as written, means a wildcard schedule such as `*/15
* * * *` does not run during the second pass of a repeated hour. In
America/New_York on 2026-11-01 it runs at 01:45 EDT and next at 02:00
EST.
- `Standard` resolves a reading from the zone's offsets and does not use
Go's zone period bounds, which are wrong after the last transition in a
zone's data.

## Live check

None. This is a library that nothing calls yet.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
2026-11-12 14:32:30 +01:00
Mathias Fredriksson 3086d4f4c0 fix: run queued messages on the chat's model when theirs is unavailable (#31632)
A queued message whose model was disabled, had its provider disabled,
or was deleted ran on the organization default, even when the chat was
on another available model, and the chat then moved to the default.

Promotion now tries the queued message's model, then the chat's last
model, then the organization default, the order a message sent without
a model already uses. Saving a queued edit without picking a model now
sends the picker's model when the row's model is no longer selectable,
as a history edit does.

Refs CODAGT-971
2026-11-12 12:48:35 +00:00
Mathias Fredriksson a48a8c0cd7 fix(coderd): skip validation for unexpired chat git tokens (#31921)
Avoid provider validation requests when OAuthToken().Valid() is true.
They count against the provider's API rate limit without changing which
access token the chat resolver returns.

Keep token refresh behavior for tokens within OAuth2's early-expiry
margin or past expiry, and preserve provider validation for other
external-auth callers.

Refs CODAGT-1543
2026-11-12 14:03:57 +02:00
Hugo Dutka decaf6e8c5 fix(coderd/x/chatd): shorten tool input validation errors (#32078)
Nested builtin tool input errors repeat an absolute schema path at every
recursion level. Unwrap the validator's error chain to retain only the
innermost path wrapper and its cause, with a comment explaining the
dependency's wrapping behavior. Also remove the redundant sentence about
exact property names and duplicate keys from the retry guidance.

Existing schema-validation tests now assert complete tool error messages
for root failures, nested properties, arrays, and maps. Validation
behavior and diagnostics embedded in the cause are preserved.

Refs #31541.
2026-11-12 11:50:42 +01:00
cdrciandgithub-actions[bot] eb6094979b chore: refresh AI model price book (#32072)
## Price book changes

32 models added, 18 models removed, 42 models changed.

<details>
<summary>Added</summary>

- anthropic/claude-fable-5-2
- azure/claude-fable-5-2
- bedrock/anthropic.claude-fable-5-2
- bedrock/global.anthropic.claude-fable-5-2
- bedrock/global.moonshotai.kimi-k3.1
- bedrock/us.anthropic.claude-fable-5-2
- bedrock/us.moonshotai.kimi-k3.1
- copilot/claude-fable-5.2
- copilot/gemini-4-carbon
- google/gemini-4-carbon
- openrouter/anthropic/claude-fable-5.2
- openrouter/baidu/ernie-5.5-flash-preview:free
- openrouter/baidu/ernie-light-dt-1.0-intl
- openrouter/google/gemini-4-carbon
- openrouter/google/gemini-omni-1.1-flash
- openrouter/google/gemini-omni-1.2-flash
- openrouter/kt/midm-k-3.0-pro
- openrouter/liquid/lfm-3-1.7b
- openrouter/liquid/lfm-3-1.7b:free
- openrouter/meta/muse-ember
- openrouter/motif-technologies/motif-3
- openrouter/nex-agi/nex-n2.6
- openrouter/thinkingmachines/inkling-2-small:free
- openrouter/unbiased/pareto-26.10-preview
- vercel/alibaba/qwen3.6-35b-a3b
- vercel/anthropic/claude-fable-5.2
- vercel/anthropic/claude-fable-5.2-fast
- vercel/deepseek/deepseek-v4.1-flash-1017-ultrafast
- vercel/google/gemini-4-carbon
- vercel/google/gemini-omni-1.2-flash
- vercel/humansand/ampersand-v0.1
- vercel/meta/muse-ember
</details>

<details>
<summary>Removed</summary>

- openrouter/bytedance-seed/seed-1.6
- openrouter/bytedance-seed/seed-1.6-flash
- openrouter/bytedance-seed/seed-2.0-code
- openrouter/inception/mercury-2
- openrouter/inception/mercury-2.5
- openrouter/inception/mercury-3
- openrouter/minimax/minimax-01
- openrouter/minimax/minimax-m1
- openrouter/minimax/minimax-m2
- openrouter/minimax/minimax-m2-her
- openrouter/minimax/minimax-m2.1
- openrouter/nvidia/nemotron-3.5-content-safety:free
- openrouter/qwen/qwen-2.5-7b-instruct
- openrouter/stealth/crouton-alpha
- openrouter/xingchen-agi/xing4.0-29b-a4b:free
- vercel/bytedance/seed-1.6
- vercel/bytedance/seed-1.8
- vercel/google/gemini-3.1-flash-image-preview
</details>

<details>
<summary>Changed</summary>

- openrouter/anthracite-org/magnum-v4-72b
- openrouter/deepseek/deepseek-chat
- openrouter/deepseek/deepseek-v4-flash
- openrouter/deepseek/deepseek-v4-flash-0731
- openrouter/deepseek/deepseek-v4-flash-vision-exp
- openrouter/deepseek/deepseek-v4-pro
- openrouter/deepseek/deepseek-v4-pro-0813
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/google/gemma-4-26b-a4b-it
- openrouter/ibm-granite/granite-4.2-8b
- openrouter/inclusionai/ling-3.1-flash
- openrouter/mancer/weaver
- openrouter/meta-llama/llama-3.1-8b-instruct
- openrouter/meta-llama/llama-3.2-3b-instruct
- openrouter/meta-llama/llama-3.3-70b-instruct
- openrouter/minimax/minimax-m2.5
- openrouter/minimax/minimax-m2.7
- openrouter/mistralai/mistral-small-3.2-24b-instruct
- openrouter/moonshotai/kimi-k2.5
- openrouter/moonshotai/kimi-k2.7-code
- openrouter/moonshotai/kimi-k3.1-pro
- openrouter/nvidia/nemotron-3-super-120b-a12b
- openrouter/nvidia/nemotron-3.5-super-vl
- openrouter/openai/gpt-oss-120b
- openrouter/qwen/qwen3-14b
- openrouter/qwen/qwen3-next-80b-a3b-instruct
- openrouter/qwen/qwen3.5-397b-a17b
- openrouter/qwen/qwen3.5-9b
- openrouter/qwen/qwen3.6-27b
- openrouter/reflection/beam-1.0-501b-a23b
- openrouter/undi95/remm-slerp-l2-13b
- openrouter/z-ai/glm-4.5-air
- openrouter/z-ai/glm-5.2
- openrouter/z-ai/glm-5.3-flash
- openrouter/~anthropic/claude-fable-latest
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-pro-latest
- openrouter/~deepseek/deepseek-v4-flash-latest
- openrouter/~moonshotai/kimi-latest
- openrouter/~z-ai/glm-flash-latest
- vercel/alibaba/qwen3.8-27b
- vercel/nvidia/nemotron-3.5-lightning
</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/43188102112).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-12 09:58:58 +00:00
Thomas Kosiewski 85e689c89c feat(coderd/x/chatd/chatwebhook): add bearer, github and standard_webhooks verifiers (#32062)
## Why

An automation webhook must prove that a request comes from the holder of
the automation's secret before Coder parses the JSON body. The approved
RFC ([Automations for Coder
Agents](https://app.notion.com/p/3ded579be59281e39950e686df02fa3d),
Webhooks section) puts that check behind one `WebhookVerifier` interface
with three schemes. This PR adds those verifiers as a pure Go package.
The webhook route that calls them comes in a later PR.

Part of CODAGT-1135.

## What changed

New leaf package `coderd/x/chatd/chatwebhook`:

- `WebhookVerifier`, with the three methods exactly as the RFC writes
them, and three verifiers: `bearer` (constant-time token compare, one or
more spaces after `Bearer` as in RFC 6750 section 2.1), `github`
(HMAC-SHA256 of the raw body in `X-Hub-Signature-256`) and
`standard_webhooks` (HMAC-SHA256 of `webhook-id.webhook-timestamp.body`,
`v1,` entries in `webhook-signature`, five-minute timestamp window,
`whsec_` secret).
- `Scheme` with the three RFC enum strings, and `NewVerifier(Scheme)`.
The package does not import `coderd/database`.
- Every `Verify` failure wraps `ErrRejected`, so the route can answer
`401`. Every `Verify` and `ValidateSecret` error is built from a fixed
string: it never holds the secret, the received token or a signature.
The package does not log. Only the `NewVerifier` error names the unknown
scheme.
- `GenerateSecret` reads 32 bytes from `crypto/rand` for `bearer` and
`github`. For `standard_webhooks` it returns `ok=false`, and
`ValidateSecret` checks the pasted `whsec_` secret.

## Scope

- No database, no HTTP route, no wiring, no new Go module. Nothing
imports the package yet, so `main` behaves as before with the
`chat-automations` experiment off.
- The map from the database enum to a verifier, and its "every enum
value has a verifier" test, belong to the route PR. It can call
`NewVerifier(chatwebhook.Scheme(automation.WebhookAuth))`. A
`NewVerifier` error is a server error, not a `401`.
- No deduplication by `webhook-id`, as in the RFC. The same valid
request verifies every time.

## Tradeoffs

- A pasted `whsec_` secret has no length bound. The spec describes
sender secrets of 24 to 64 bytes, but it does not tell a receiver to
reject others. A bound would lock out a sender that deviates, and it
protects only the owner from the sender's own key.
- The bearer verifier accepts one or more spaces between `Bearer` and
the token, as RFC 6750 section 2.1 and the API key middleware do. It
rejects a tab and an empty token. It also rejects trailing whitespace
after the token when it receives it, but an HTTP request cannot deliver
that: `net/http` strips trailing whitespace from the header value before
the verifier runs, so such a request is accepted with the right token.
- The signed Standard Webhooks content uses the `webhook-timestamp` text
as received. The reference Go library signs the reformatted number
instead. The two differ only for a timestamp with leading zeros, which a
conforming sender does not send.
- A `webhook-id` that contains `.` is rejected. The spec asks senders to
avoid it, because it makes `id.timestamp.body` ambiguous. A repeated
`Authorization`, `X-Hub-Signature-256`, `webhook-id` or
`webhook-timestamp` line is rejected for the same reason. Several
`webhook-signature` lines are read as one list.
- `TestSecretComparisonsAreConstantTime` reads the package source and
fails on `==`, `bytes.Equal` and similar on secrets. A correct
early-exit compare gives the same answers as a constant-time one, so a
request-level test cannot tell them apart. The scan is a guard against
the likely mistake, not a proof.

## Verification
- Test vectors come from the [GitHub
docs](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries)
and from `TestWebhookSign` in the [Standard Webhooks Go
library](https://github.com/standard-webhooks/standard-webhooks/blob/main/libraries/go/webhook_test.go).
The tests cite the URL beside each vector.
- Live lane: none. No route, CLI or UI reaches this code yet, so there
is no surface to exercise.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
2026-11-12 02:49:28 +01:00
Thomas Kosiewski e307f1d5cf feat: add the user-scoped chat-automations experiment (#32064)
## Why

The Automations RFC controls availability with one user-scoped
experiment. Its text: "The user-scoped `chat-automations` experiment
controls availability. Operators configure defaults with `--experiments`
and can change per-user rules while Coder is running. Each surface
checks the relevant caller or automation's owner, and experiment
evaluation fails closed." The later backend PRs (management routes, the
`manage_automations` tool, `Publish`) need that check first. This PR
registers the experiment and proves the per-user, fail-closed check.
Nothing consumes it yet.

Part of CODAGT-1135

## What changed

- Registers `chat-automations` in `ExperimentsKnown` and
`ExperimentsUserScoped`. An earlier experiment with this name was
removed in #30412, and this PR restores none of its consumers.
- Keeps it out of `ExperimentsSafe`, so `--experiments=*` does not turn
it on. Automations act with their owner's authority, and a test pins the
choice.
- Adds the name to the `userScopedExperimentStaticCheck` ruleguard rule,
so server code cannot decide it from the static list.
`TestExperimentsUserScopedRuleguard` keeps the rule in step with
`ExperimentsUserScoped`.
- Regenerates the swagger files, `docs/reference/api/schemas.md` and
`typesGenerated.ts`.
- Adds tests for the real experiment name. The evaluator tests cover the
startup default, stored `on`, `off` and condition rules for two users,
and an off decision on a rules read error, a malformed rule, an unknown
mode, an attribute read error, a condition error and a nil subject. A
coderd test with a real database checks the same per-user behavior
through `api.ExperimentEvaluator` and `GET /api/v2/experiments`.

## Scope

No routes, tool, UI or chatd change. I added no helper:
`Evaluator.Enabled(ctx, userID, ex)` already decides per user and fails
closed, and API handlers reach it through `api.ExperimentEvaluator`.
chatd has no evaluator handle on main, because #31327 removed the unused
field. The first chatd consumer adds it together with its read.

## Blast radius

With the experiment off, which is the default, behavior on main does not
change. Two things become visible. `GET
/api/experimental/experiments/rules` and `coder exp experiment-rules
list` show a `chat-automations` row, and an administrator can store a
rule for it. A deployment that already passes
`--experiments=chat-automations` sees three small differences: the
startup log reports an opted-in hidden experiment where it reported an
unknown one, the deployment Overview page stops flagging the name as
invalid, and the rules row shows the static default as on. Nothing reads
the experiment yet, so no feature turns on.

## Live check

A local `./scripts/develop.sh` deployment built from this head ran with
no flag, with `--experiments=*` and with
`--experiments=chat-automations`. `GET /api/v2/experiments` lists
`chat-automations` for the owner and for a member only when the startup
list or a rule turns it on, and `--experiments=*` does not turn it on. A
condition rule `user.username == "member"` turned it on for the member
and off for the owner without a restart, and `reset` restored the
startup default.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
2026-11-11 23:54:05 +01:00
Thomas Kosiewski b61ec4395e fix(coderd/coderdtest): read the swagger doc once in TestSwaggerEnumsNotNarrowed (#32065)
## Why

The `test-go-race-pg` job fails intermittently with `WARNING: DATA RACE`
in `swag.(*Spec).ReadDoc`, on pull requests whose changes do not cause
it. It failed CI runs 43102680650 and 43103681536 on two unrelated pull
requests. A green rerun of the same commit passes, so it hides as a
flake.

## Cause

swag's `Spec.ReadDoc` writes shared state, so parallel tests that each
call it race. #31829 addressed this by reading the spec once through
`swaggerDoc`, a `sync.OnceValue`. #30122 then added
`TestSwaggerEnumsNotNarrowed` with a direct
`apidoc.SwaggerInfo.ReadDoc()` call, which races with the tests that
still read the shared value.

## What changed

`TestSwaggerEnumsNotNarrowed` calls `swaggerDoc()`, like the other
tests. It was the only direct call outside the generated
`coderd/apidoc/docs.go`.

## Reproduction

- On `main` (412d998777), `go test -race -count=20 -run
'TestSwagger|TestChatModelPathParametersFormatted' ./coderd/coderdtest/`
fails with 2 data race reports. `TestChatModelPathParametersFormatted`,
`TestSwaggerParametersValid` and `TestSwaggerEnumsNotNarrowed` fail.
- With this change, the same command passes with no data race report.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
2026-11-11 23:50:14 +01:00
Ehab Younes 1126533c31 feat: export workspace last used time to Prometheus (#31346)
Add an opt-in coderd_workspace_last_used_timestamp_seconds gauge that
reports workspaces.last_used_at, the value the dormancy threshold
measures inactivity from. To enable it, set
--prometheus-collect-workspace-stats or
CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS.

A separate WorkspaceStats collector refreshes the gauge once a minute
in the background from a new GetWorkspaceLastUsedForMetrics query. Each
series has a workspace_id label, so a workspace that reuses a deleted
workspace's name starts a new series. Workspaces owned by deleted users
are excluded.

Closes CLIENT-1065
2026-11-11 15:02:18 +00:00
Molly Fraser 0a7ef88af9 feat: add option to disable the embedded AI Gateway (#31967)
Adds `--ai-gateway-embedded-enabled` /
`CODER_AI_GATEWAY_EMBEDDED_ENABLED` (default `true`) so standalone-only
deployments can stop `coderd` from starting the in-memory AI Gateway.

`CODER_AI_GATEWAY_ENABLED` stays the global switch: the AI Gateway
entitlement, `/api/v2/ai-gateway/serve`, and cost-control metrics still
depend only on it. The embedded daemon now starts only when both options
are `true`.

| `ENABLED` | `EMBEDDED_ENABLED` | Result |
|---|---|---|
| `true` | `true` | Unchanged |
| `true` | `false` | No embedded gateway; standalone gateways keep
working |
| `false` | any | No AI Gateway |

Refs AIGOV-514

## Open questions for reviewers

- **Coder Agents does not work with the embedded gateway disabled.**
`chatd` still starts, but model calls fail with "AI Gateway transport
factory is not configured" because there is no in-process transport.
AIGOV-597 (routing Agents through standalone gateways) was canceled. The
docs and option help state that Agents requires the embedded gateway. Is
that acceptable, or should `chatd` also be turned off in this mode?
- **Option name:** the ticket proposed
`CODER_AI_GATEWAY_EMBEDDED_ENABLED` tentatively. OK to keep?

## Verification

```
$ go test ./cli/ -run 'TestServer_AIGateway' -count=1
ok      github.com/coder/coder/v2/cli   0.518s
$ go test ./enterprise/coderd/ -run 'TestAIGatewayServe' -count=1
ok      github.com/coder/coder/v2/enterprise/coderd     0.755s
```

`TestServer_AIGatewayEmbedded` fails when the new check is removed.

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

- `codersdk/deployment.go`: new option and
`AIBridgeConfig.EmbeddedEnabled` field; updated `--ai-gateway-enabled`
description.
- `cli/server.go`: outer `if Enabled` sets up cost-control metrics and
the blocked-users collector (the standalone `/serve` endpoint uses these
too). Inner `if EmbeddedEnabled` creates the daemon, registers the
in-memory handler, and adds its cleanup.
- `cli/server_test.go`: `TestServer_AIGatewayEmbedded` covers the three
modes by checking for the embedded daemon's startup log.
- `enterprise/coderd/aibridgeserve_test.go`:
`TestAIGatewayServeEmbeddedDisabled` checks the entitlement and `/serve`
still work with embedded disabled.
- `docs/ai-governance/ai-gateway/standalone.md`: new "Disable the
embedded gateway" section.
- Remaining files are generated by `make gen`.
- Found during review: keeping metrics inside the embedded check would
have dropped cost-control metrics for standalone gateways.

</details>

---

Generated with Coder Agents; reviewed, revised, and verified by
@mollymaefraser.
2026-11-11 11:50:16 +00:00
Dean Sheather fb12d6018f fix!: redact agent environment variable values in API responses (#31932)
Workspace, build, and agent API responses (`/workspaces`,
`/workspacebuilds/{id}`, `/workspaceagents/{id}`, and so on) returned
agent environment variable values in plain text. Template authors often
pass credentials such as API tokens through `coder_env`, so anyone who
could read the workspace could read those secrets.

`db2sdk.WorkspaceAgent` now replaces every non-empty value with
`***REDACTED***` and keeps the keys. This is the same marker the support
bundle (`sanitizeEnv`) and the agent `/debug/manifest` endpoint already
use. The agent still gets the real values through its manifest
(`db2sdk.WorkspaceAgentEnvironment`), and nothing in the CLI or frontend
reads these values from the API.

Every value is redacted because neither `coder_env` nor
`coder_agent.env` in the Terraform provider has a sensitive flag, and
`proto.Env` has no field to carry one. Selective redaction would need
changes to the provider, the proto, and the database.

## For changelog

- Agent environment variable values are redacted in API responses
(#31932)

> Workspace, workspace build, workspace agent, and template version API
responses now return `***REDACTED***` for every non-empty agent
`environment_variables` value. Keys and empty values are unchanged. The
agent still receives the real values, so workspaces behave as before.
  >
> Migration: Update scripts and integrations that read agent environment
variable values from the API or from `coder list -o json`. Read the
values inside the workspace instead.

Closes ENG-1505 (coder/security#51)

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

- Confirmed the leak on `main` (e1c3a21d05): `db2sdk.WorkspaceAgent`
copied `dbAgent.EnvironmentVariables` straight into
`codersdk.WorkspaceAgent.EnvironmentVariables`. Every API path that
returns an agent goes through this function.
- Redact all non-empty values, not just some. There is no secret or
non-secret marker in `terraform-provider-coder` v2.20.0 (`coder_env` has
only `agent_id`, `name`, `value`, `merge_strategy`; `coder_agent.env` is
a plain map), and name heuristics fail in both directions.
- Use `***REDACTED***` to match the existing support bundle and
`/debug/manifest` redaction. Empty values are kept, which also matches
existing behavior.
- Redact in the SDK converter only, so the agent manifest path is
unaffected.
- Regression test `TestWorkspaceAgent/RedactsEnvironmentVariables`
covers the workspace, workspace agent, and workspace build endpoints. It
fails without the fix.

</details>

> Generated by Coder Agents on behalf of @deansheather.
2026-11-11 16:51:20 +11:00
Nick Vigilante 7301cee2c4 fix: list every enum value the API can return in the Swagger spec (#30122)
The API reference is generated from Swagger comments and struct tags,
and several `enums:"..."` tags narrowed a named enum type, so the docs
omitted values the server returns. For example, `User.status` listed
only `active` and `suspended`, not `dormant`, and
`TemplateVersion.warnings` listed `DEPRECATED_PARAMETERS`, which is not
a value of the type.

Remove 34 `enums` tags that narrow or duplicate a named type so the
referenced type's full value list is used. Tags that describe an
intentional subset stay: ACL role fields (which omit the `""` deleted
sentinel used only in update requests), `APIKey.scope`, and plain-string
fields. `Template.provisioner` keeps its tag because `.swaggo` replaces
`ProvisionerType` with `string`.

Also fix enum defects that break code generators:

- The provisioner jobs and daemons `status` query parameters listed
their enum twice (Swagger 2.0 requires unique `enum` items) or with the
wrong type. Both are now `[]codersdk.ProvisionerJobStatus` and
`[]codersdk.ProvisionerDaemonStatus`, matching what each handler parses,
including comma-separated values. The daemons route previously
documented job statuses, which the handler rejects with a 500.
- Replace the `_` zero placeholder of `WatchErrorCode` with `iota + 1`,
so the spec no longer lists 0 or `x-enum-varnames: ["_", ...]`. Wire
values are unchanged.

Where the narrowed tag hid values the server returns, the SDK type now
includes them: `LoginTypeOAuth2ProviderApp`, `BuildReasonAutodelete`,
and `MissingTemplateParameter` widen the generated TypeScript unions.
The dashboard attributes `autodelete` builds to Coder like other system
builds. `APIKey.login_type` and `AuthorizationCheck.action` set explicit
examples so the generated samples stay representative.

`TestSwaggerEnumsNotNarrowed` fails when a property's enum list drops
values of its named type (other than the 15 allowlisted intentional
subsets), lists a value the type lacks, or repeats a value.

Part of DOCS-1122, split from #30121.

---
🤖 Built with AI assistance.
2026-11-10 17:42:30 -05:00