Commit Graph
5087 Commits
Author SHA1 Message Date
Bobby Ho c5af20be31 test: copy test databases by file and start test deadlines after setup (#32426)
## Summary

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

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

## Changes

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

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

## Validation

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

## Remaining Work

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

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

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

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

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

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

## Changes

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

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

## Testing

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

Windows remains untested.

## Expected Behavior

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

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

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

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


Closes ENT-236

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

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

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

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

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

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

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

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

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

Closes ENT-235

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

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

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

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

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

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

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

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

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

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

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

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

## Changes

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

Related to AIGOV-730

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

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

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

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

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

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

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

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

Tag conventions:

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

---

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

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

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

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

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

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

## Changes

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

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

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

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

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

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

</details>

Closes AIGOV-734

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

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

<details>
<summary>Added</summary>

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

<details>
<summary>Changed</summary>

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

## Review notes

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

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

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

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

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

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

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

Closes AIGOV-447.

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

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

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

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

</details>

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

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

Refs AIGOV-754

## Open questions for reviewers

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

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

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

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

</details>

---

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

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

### Changes

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

### Open questions

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

### Out of scope

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

### Verification

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

### AI disclosure

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

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

Fixes CLIENT-1102

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

### Fix CLIENT-1102: flake in TestQuickstartCppInstallGuard

#### Problem

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

#### Decision log

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

#### Change

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

#### Verification

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

</details>

---

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

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

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

Part of DOCS-1122, split from #30121.

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

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

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

</details>

---
🤖 Built with AI assistance.

---------

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

## Ticket Link

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

## Description

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

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

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

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

</details>

## Testing Done

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