Commit Graph
15726 Commits
Author SHA1 Message Date
Jake Howell 6c42309ccb feat(site): modernize OAuth2 applications settings UI (#27562)
Follow up to #27561 

Modernizes the Deployment Settings OAuth2 Applications create/edit/list
UI to match the AI Providers pattern: fat page views, card layout, and a
Formik + Yup form using shared field primitives.

- Rework CreateOAuth2AppPageView / EditOAuth2AppPageView into fat views
with provider-style layout (back link, avatar + title, bordered cards,
cancel/submit footer)
- Rewrite OAuth2AppForm with Formik/Yup, FormField descriptions, and
IconPickerField (live header avatar on create/edit)
- Order edit page as settings → endpoints (Client ID / Auth / Token via
CodeExample) → secrets
- Align list page row styling and add a Callback URL column
- Update Storybook stories for the new fat-view + form validation
behavior

| Old | New |
| --- | --- |
| <img width="2936" height="1802" alt="old-oauth2-application-create"
src="https://github.com/user-attachments/assets/98c1dec1-c273-43a7-a517-a31ae48bc17c"
/> | <img width="2936" height="1802" alt="new-oauth2-application-create"
src="https://github.com/user-attachments/assets/9d2e1d6b-6905-469f-b9e0-cf8ae3b14f3d"
/> |
| <img width="2936" height="1802" alt="old-oauth2-application-list"
src="https://github.com/user-attachments/assets/3d38daab-1d93-4acb-bff0-d7299da884fd"
/> | <img width="2936" height="1802" alt="new-oauth2-application-list"
src="https://github.com/user-attachments/assets/b3cc56ac-a810-4742-9ea7-27e20caa9bb7"
/> |
| <img width="2936" height="2030" alt="old-oauth2-application-update"
src="https://github.com/user-attachments/assets/544ad92b-ae2b-4b10-907d-c94bcc3d12c4"
/> | <img width="2936" height="3470" alt="new-oauth2-application-update"
src="https://github.com/user-attachments/assets/6e4d228d-8deb-4934-989a-b9c98b633509"
/> |
2026-07-30 02:46:09 +10:00
Jake Howell 659fb48a1d fix: demui <OAuth2AppForm /> (#27561)
This pull-request removes the MUI styles from the `<OAuth2AppForm />`
and adjacent components.
2026-07-30 00:47:06 +10:00
Jake Howell 0b93731ebf fix(site): reflect submitting state during batch update (#27630)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell.

## Problem

When bulk updating workspaces, the confirmation modal's **Update**
button never entered a submitting/loading state, so there was no
feedback that the update was actually in progress.

## Root cause

The `BatchUpdateModalForm` shows a spinner when its `isProcessing` prop
is `true`. That prop is fed by `batchActions.isProcessing` from
`useBatchActions`. However, the `isProcessing` value was OR-ing together
every mutation's `isPending` flag **except** `updateAllMutation` — the
one that actually performs the batch update:

```ts
isProcessing:
  favoriteAllMutation.isPending ||
  unfavoriteAllMutation.isPending ||
  startAllMutation.isPending ||
  stopAllMutation.isPending ||
  deleteAllMutation.isPending,
  // updateAllMutation.isPending was missing
```

As a result, the button stayed idle for the entire duration of a bulk
update.

## Fix

Include `updateAllMutation.isPending` in the `isProcessing` derivation
so the button spinner and disabled state correctly reflect an in-flight
batch update.

## Testing

- [ ] Manually verify the Update button shows the spinner and is
disabled while a bulk update runs.
2026-07-30 00:46:33 +10:00
Michael Suchacz 4bf9b9d1e6 feat(site): surface chat lifecycle hook outcomes in the chats UI (#27430)
Surfaces chat lifecycle hook outcomes in the chats UI. Final PR of the
lifecycle hooks stack (#27401, #27428, #27429), all now merged.

- Show hook notices attached to their user message as timeline notes
(`role="note"` so historical notices stay out of the screen reader's
assertive live region), and show an info tooltip for notices on queued
messages.
- Cache the full inserted message batch from send and edit responses so
hook-inserted messages survive stream reconnects and queue promotion.
- Reconcile the promoted queue head after sending to an errored chat so
a missed or delayed queue update neither duplicates nor hides messages,
and clear the stale error status so the Thinking indicator appears
before the websocket status event.
- Ignore an authoritative queue snapshot that still contains a
just-promoted message: queued messages are delete-only, so such a
snapshot predates the promotion and would both re-show the promoted
message and drop messages queued since. Fresh snapshots apply in full
and clear the suppression.
- Cache the store's reconciled queue on `queue_update` instead of the
raw event, so a stale update cannot re-show a promoted message after
REST re-hydration.
- Refresh chat details when a send or edit fails, because a failed hook
dispatch can move the chat to the error state.
- Surface tool result error text in the tool rows: the execute failure
tooltip shows the actual error instead of a hardcoded "Command failed",
and a failed `write_file` renders an error label with the result error
text instead of "Wrote <file>" with an args-derived diff of content that
was never written. This makes hook tool denials legible in the timeline,
and benefits every failed execute or write.

- Label a tool call blocked by `pre_tool_use` as failed instead of `Ran
<command>`, matching what the write and edit tools already do. The
wording derives from the tool-result error flag, so a command that ran
and exited non-zero is unaffected.
- Render a hook notice below the message it annotates rather than above
it, which reads correctly for a "your prompt was rewritten" card.
- Give both hook outcomes their own treatment on the create path, where
they previously fell through to the generic error alert and an expected
policy decision appeared with a stack trace, response data, and a
workspaces action. Classification keys on the structured response body
rather than the status code, so ordinary permission errors keep their
existing rendering.

- Unrelated to the hooks work, de-flake `SchedulePage.test.tsx`. Its
`fillForm` helper wrapped an already-retrying `findByLabelText` in
`waitFor`, so the two 1s budgets raced and a slow first render failed
`test-js` with "Timed out in waitFor". This is separable from the rest
of the PR if you would rather it land on its own.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-29 16:45:11 +02:00
Ehab Younes e3a5a697ab fix(site): refresh group member budgets after overrides (#27553)
Group member budget rows remained stale after saving or deleting a user override because the cached member-spend query was not refreshed.

Invalidate the affected user's override query and only cached group-member spend queries whose user ID list contains that user. This refreshes relevant rows without invalidating unrelated groups.
2026-07-29 17:09:15 +03:00
Susana Ferreira 3deecb481e chore: remove ai-gateway-cost-control experiment flag (#27579)
## Description

Closes
[AIGOV-443](https://linear.app/codercom/issue/AIGOV-443/remove-ai-gateway-cost-control-experiment-flag-once-feature-is-stable).

The AI Gateway cost control feature is planned for GA on the upcoming
release, so this removes the `ExperimentAIGatewayCostControl` experiment
and all of its gating. The cost control API endpoints remain gated by
the `FeatureAIBridge` license feature (the AI Governance add-on), so
this only drops the experiment layer.

## Changes

- **`codersdk/deployment.go`**: remove the
`ExperimentAIGatewayCostControl` const, its `DisplayName()` case, and
its `ExperimentsKnown` entry.
- **`enterprise/coderd/coderd.go`**: remove the
`httpmw.RequireExperiment(...)` gating from the AI cost control routes.
They keep `RequireFeatureMW(codersdk.FeatureAIBridge)`. Affected
endpoints:
  - `GET /organizations/{organization}/groups/ai/spend`
- `GET
/organizations/{organization}/groups/{groupName}/members/ai/spend`
  - `GET /organizations/{organization}/ai/spend/export`
  - `GET /groups/{group}/members/ai/spend`
  - `GET /groups/{group}/ai/spend`
- `GET/PUT/DELETE /users/{user}/ai/budget/override` and `GET
/users/{user}/ai/spend`
- **`enterprise/coderd/aibridge_test.go`**: drop the experiment from
test setup and remove the now-obsolete `RequiresExperiment`
negative-path tests.
- **Frontend (`site/src/...`)**: remove the `ai-gateway-cost-control`
experiment checks from the cost control UI (Groups pages, user dropdown)
and their stories/mocks. The feature is now driven solely by the
`aibridge` feature visibility.
- **Generated**: regenerated `coderd/apidoc/*`,
`docs/reference/api/schemas.md`, and `site/src/api/typesGenerated.ts`.

## Out of scope

The dogfood `CODER_EXPERIMENTS` config lives in a separate infra repo,
not `coder/coder`. Leaving `ai-gateway-cost-control` there is harmless:
unknown experiment values are logged as `"ignoring unknown experiment"`
at startup and otherwise ignored, so no ordering dependency or breakage.
That cleanup can be a follow-up.

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

- Verified how unknown experiments are handled in `coderd/coderd.go`
`ReadExperiments`: unknown values produce a warning log and are inert,
so removing the definition before the dogfood config is updated is safe.
- Noticed the group `ai/budget` routes (`/groups/{group}/ai/budget`)
were already gated only by `FeatureAIBridge`, never by the experiment.
After this change all cost control routes are uniformly feature-gated,
resolving that inconsistency.
- Removed an obsolete `RequiresExperiment` subtest in
`TestUserAISpendStatus` that only asserted a 403 from the experiment
gate; with the gate gone it would no longer be blocked pre-RBAC.

</details>

---

_This PR was created by Coder Agents on behalf of @ssncferreira._
2026-07-29 14:59:58 +01:00
Susana Ferreira d6a5c8e9f8 refactor: make user AI budget and spend endpoints consistent (#27611)
## Description

Makes the user AI cost control endpoints consistent.

## Changes

- Replaces the flat `spend_limit_micros` and `limit_source` fields on
`GET /users/{user}/ai/spend` with a nested `effective_budget`, reusing
the type behind `group_budget`. The flat pair made it possible to encode
a limit without a source.
- Renames `AIGroupBudget` to `AIBudgetLimit`, since it also carries
`user_override` limits and is no longer group-specific. The type name is
not part of the wire format.
- Moves `/users/{user}/ai/budget` to `/users/{user}/ai/budget/override`.
The endpoint only ever managed the per-user override, which the type,
the handlers, and the operation IDs all already said; the path was the
only place that didn't.

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-29 14:01:32 +01:00
Susana Ferreira e71249a821 fix: ai cost control cap configurable AI spend limit (#27640)
## Problem

A configured AI spend limit was only validated as `gte=0`, with no upper
bound. The group spend query multiplies the per-member limit by the
number of attributed members, so a large enough limit overflows `bigint`
and fails the whole query, returning an error for every group in the
request rather than just the misconfigured one.

## Changes

- Add `MaxAISpendLimitMicros`, $1,000,000 per member per budget period.
- Reject group budgets and per-user overrides above the maximum with a
400 naming the limit.
- Bound both budget forms in the UI so they show the valid range before
submitting.

Follow-up
https://github.com/coder/coder/pull/27589#discussion_r3668956350
Depends on https://github.com/coder/coder/pull/27589

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by
@ssncferreira
2026-07-29 14:00:13 +01:00
Matt Vollmer 4987afada7 docs: present AI Governance as included with Premium (#27545)
## Summary

AI Governance is now included with Premium licenses instead of being
sold as a separate per-user add-on. This updates `docs/` to describe the
new packaging, removes "Add-On" from AI Governance references, and
refreshes the editions architecture diagram.

## Changes

- **`docs/ai-coder/ai-governance.md`**: title is now "AI Governance";
rewrote the licensing statements (previously "a separate, per-user
license... not included with a Premium subscription and must be
purchased separately") to state it is included with Premium. The
usage-pool section now attributes the shared Agent Workspace Build pool
to Premium deployments.
- **Repeated admonition (28 files under `ai-coder/agent-firewall/` and
`ai-coder/ai-gateway/`)**: replaced "requires the AI Governance Add-On /
as of Coder v2.32, deployments without the add-on..." with "is part of
AI Governance, which is included with a Premium license." The v2.32
add-on gate no longer applies; the gate is now Premium vs. Community.
- **`docs/ai-coder/index.md`, `security.md`, `tasks.md`,
`usage-data-reporting.md`, `admin/licensing/index.md`,
`install/releases/esr-2.29-2.34-upgrade.md`,
`ai-gateway/ai-gateway-proxy/setup.md`,
`ai-gateway/clients/claude-code.md`**: reworded add-on references to
Premium inclusion.
- **`docs/manifest.json`**: nav title "AI Governance Add-On" → "AI
Governance", updated two descriptions, and swapped the 25 `"state": ["ai
governance add-on"]` badges to `["premium"]` so the sidebar badge reads
"Premium" instead of "AI Governance Add-On".
- **`docs/images/single-region-architecture.png`**: refreshed the
diagram in the **Community and Premium editions** tab on
[Architecture](https://coder.com/docs/admin/infrastructure/architecture).
Also deleted the unreferenced `single-region-architecture.svg` copy.

## Follow-ups outside this PR

- The `"ai governance add-on"` doc-state badge is defined in
`coder/coder.com` (`src/utils/docs/state.ts`). After this merges, no
manifest entry uses that key, so it becomes dead config and can be
removed there.
- `enterprise/coderd/license/license.go:564-572` still warns admins that
"The AI Governance add-on is required to use AI Gateway." That backend
string will contradict these docs once shipped.

## Verification

- `pnpm run lint-docs`: 0 errors across 504 files
- `make lint/emdash`: clean
- Vale on the changed Markdown files: 0 errors; remaining warnings are
pre-existing gerund headings on untouched lines
- `docs/manifest.json` validated as JSON
- Confirmed the deleted SVG had no references anywhere in the repo

---

PR generated with Coder Agents on behalf of @mattvollmer.
2026-07-29 08:45:20 -04:00
Michael Suchacz fb30674806 fix(site/src/pages/AgentsPage): order chat transcript by message id (#27620)
## Context

Follow-up to #27495 (append-order guarantee for `chat_messages.id`) and
#27619 (prompt query ordering), both merged. This PR applies the same id
ordering to the transcript the user actually sees.

## Why?

`buildOrderedMessageIDs` in `chatStore.ts` sorted by `created_at`, which
is `now()` and therefore shared by every row in an insert batch. It
builds `orderedMessageIDs`, which is what the transcript renders, so it
re-imposed the ordering the backend PRs remove.

The failure needs the merge path, not a plain fetch. Initial REST
hydration already sorts by numeric id before reaching the store, and
`Array.prototype.sort` is stable, so a single correctly ordered response
rendered correctly. But `upsertDurableMessages` copies the existing
message `Map`, appends new ids, and re-sorts. `Map` iteration is
insertion ordered, so when a refetch or reconnect merges earlier ids
into a map that already holds later ones, the stable timestamp sort
faithfully preserves the wrong order.

This also makes the store consistent with `useChatStore.ts` and
`api/queries/chatMessageEdits.ts`, which already sort by `id`.

## Changes

`buildOrderedMessageIDs` now calls `toSorted` with an `id` comparator
inlined at its single call site, and the `byMessageCreatedAt` helper is
gone. `ChatMessage.id` is a `number` in `typesGenerated.ts`, backed by a
Go `int64`, so numeric subtraction is correct.

## Testing

Two vitest cases, both verified red by restoring the timestamp
comparator:

- `sorts messages by id when created_at disagrees with append order`
returned `[2,1]`.
- `orders merged messages by id rather than by arrival` returned
`[3,4,1,2]`, the exact inversion the merge path produces.

`MergedMessagesRenderInIDOrder` in `ChatPageContent.stories.tsx` covers
the same merge path through the rendered timeline.

All 334 `ChatConversation` unit tests and the 4 `ChatPageContent`
storybook interaction tests pass, and `tsc -p .` plus biome are clean.

> Opened by Mux on behalf of Mike.
2026-07-29 12:43:11 +00:00
Michael Suchacz 1c722ff969 fix(coderd/database): order the chat prompt query and its boundary by id (#27619)
## Stack context

Follows #27495 (merged), which gives `chat_messages.id` an append-order
guarantee and moves the history reads onto it. This PR applies the same
fix to the query that builds the model prompt.

## Why?

`GetChatMessagesForPromptByChatID` mixed two orderings. It selected the
compaction boundary with `created_at DESC, id DESC`, then applied that
boundary with an `id >` comparison, and returned rows with `created_at
ASC, id ASC`.

`created_at` is `now()`, so it is the transaction start time. Every row
in one insert batch shares it, and concurrent transactions can commit in
the opposite order to the one they started in. Two consequences, both
reaching the provider:

- **Malformed prompts.** A tool result could be ordered ahead of the
assistant message that requested it.
`chatprompt.injectMissingToolResults` does not repair this: it only
handles tool rows already contiguous after an assistant row, and adds
missing results. It never moves a tool row that precedes its assistant,
and nothing re-sorts the rows in Go.
- **Wrong compaction boundary.** The boundary is picked by timestamp but
compared by id, so a stale compressed summary could be retained while
the actual latest one was dropped.

## Changes

Both the boundary CTE and the outer query order by `id`. The `id >`
predicate is unchanged, which is the point: the ordering now matches the
comparison that was always being made.

**The boundary index was dead, so it is rebuilt to match.**
`idx_chat_messages_compressed_summary_boundary` was created for exactly
this lookup, but its predicate requires `role = 'system'` while
compaction writes its summary with the user role
(`message_conversion.go:334`, the only writer of `compressed = true`).
It matched zero rows, and no other query can use it. Migration `000560`
rebuilds it as `(chat_id, id DESC) WHERE compressed AND NOT deleted AND
visibility = 'model'`, which also matches the new order key.

Measured on PostgreSQL 13 with a 20k-message chat, 11 summaries, and 14
sibling chats so `chat_id` is selective:

| boundary lookup | plan | buffers |
|---|---|---|
| old predicate | Index Scan `idx_chat_messages_chat`, 19,989 rows
filtered | 267 |
| rebuilt index | Index Only Scan | 2 |

Not in scope: the outer `SELECT` still inspects every row of the chat,
because its `role = 'system' AND compressed = FALSE` disjunct has no
lower `id` bound. That predates this PR and needs a query rewrite rather
than an index.

## Testing

Two subtests, both verified red by reverting the `ORDER BY` and
regenerating:

- `OrdersByIDWhenTimestampsDisagree` returned `[4,3,2,1]` instead of
`[1,2,3,4]`, placing the tool result before the assistant call.
- `CompactionBoundaryUsesID` selected the stale summary and leaked the
messages between the two summaries into the prompt.

Existing subtests pass unchanged. Migration up/down tests pass, and the
rebuilt index was verified red-green: restoring the old predicate
returns the plan to a 267-buffer scan, and the old predicate matches 0
rows in the fixture.

> Opened by Mux on behalf of Mike.
2026-07-29 14:04:59 +02:00
Cian Johnston b371262e5c fix(aibridge): handle sonnet 5 adaptive thinking in bedrock (#27339)
Adds sonnet 5 to the list of models that require adaptive thinking for
Bedrock InvokeModel.

Smoke-tested locally.

> Obligatory disclosure: a Coder agent helped with this.
2026-07-29 12:40:24 +01:00
Michael Suchacz c17bed25e0 feat: wire chat lifecycle hooks into chatd (#27429)
Wires chat lifecycle hooks into chatd, gated by the
`agent-lifecycle-hooks` experiment. Part of the lifecycle hooks stack
(#27401, #27428, #27430). See `docs/admin/setup/chat-lifecycle-hooks.md`
for the consumer-facing contract.

## Summary

When a hook URL is configured, chatd dispatches `session_start`,
`user_prompt_submit`, `pre_tool_use`, `post_tool_use`, `pre_compact`,
`post_compact`, and `stop` events to the consumer and applies its
responses.

## Design

- **Stateless**: Coder stores no hook dispatch or decision state.
Delivery is at least once; consumers deduplicate on stable payload
identifiers (chat ID, event type, tool-use ID) and answer duplicates
with the same decision.
- **Admission-time prompt effects**: `user_prompt_submit` dispatches
exactly once per submission (create, send, queue, edit, subagent spawn)
and folds its effects into the stored prompt as typed message parts:
original-or-overridden user parts, then model-only `hook-context`, then
a user-visible `hook-notice`. Hook context is stripped from every
client-facing conversion; hook notices are excluded from model prompts.
The server rejects hook parts in client-submitted content.
- **Tool gating**: `pre_tool_use` allow can override tool input; deny
becomes a synthetic denied tool result, with any returned model context
persisted as a model-only transcript row so it never reaches clients.
The denial text identifies an external policy (the deployment's
lifecycle hook) as the source and marks the decision as persistent, so
the model explains the denial instead of retrying it or misreporting it
as an infrastructure failure.
- **Fail closed**: a dispatch failure rejects the triggering request or
moves the chat to the error state in the same transaction as the
affected step, so a runnable state is never published with unapproved
content.
- **Admission before persistence**: `pre_tool_use` is dispatched for the
calls the model produced, before the assistant message is stored. See
"Staged tool admission" below.
- **Fresh dispatch per tool call**: every non-provider-executed tool
call is decided by its own `pre_tool_use` dispatch; Coder never reuses
an earlier decision on the consumer's behalf. Retries re-dispatch the
same logical event.

## Structure

All hook dispatch flows through one seam: entry points build a
`chathooks.Chat` (chat identity) and a `chathooks.Message` (event
details) and call `Trigger.Trigger`, the only component that talks to
the dispatcher. The integration lives in the `coderd/x/chatd/chathooks`
subpackage, split by responsibility:

- `trigger.go`: the trigger seam; builds the wire envelope per event,
normalizes deny into a typed error, and holds the package's single
enabled-check.
- `effects.go`: pure conversion of hook results into transcript rows and
prompt parts.
- `errors.go`: failure classification (dispatch error messages, denial
mapping, tool-result dispatch-failure scanning).
- `tooluse.go`: the tool-call gate (`pre_tool_use` preflight,
`post_tool_use` payloads, applying admitted input to the step).

Server-bound glue stays in `coderd/x/chatd/hook_server.go`: the
chat-parking dispatch error handlers, the step-commit row insertion
wrappers, and the dynamic post-tool-use state loader, which depends on
chatd validation types.

This PR adopts the `codersdk/x/agenthooks` and
`coderd/x/agenthooks/dispatch` import paths introduced at the tip of
#27401; intermediate commits still reference the pre-move paths and are
not individually buildable.

## Staged tool admission

`pre_tool_use` originally ran at tool execution time, which is after the
assistant message carrying the tool call was already committed. An
`input_override` therefore had to rewrite stored message content in
place. @hugodutka pointed out that chatd treats message content as
immutable, and that the rewrite was a shortcut rather than a
requirement.

It was also a correctness problem in its own right: the rewrite only
updated the database, so the transcript could show one input while a
different one had executed.

The hook now runs before the step is persisted:

```text
provider stream ends (tool calls complete, in memory)
  -> pre_tool_use dispatch per call
  -> ONE transaction: assistant row with admitted inputs, synthetic denials, hook rows
  -> execute
```

The step is inserted once, carrying the input the tool runs with.
`UpdateChatMessageContentByID` and `Tx.UpdateMessageContent` are deleted
from #27428, so message content stays immutable.

Two consequences, both intentional:

- **Clients converge rather than wait.** Tool-call parts still stream
live, so a rewritten call briefly shows the model's proposed input
before the committed message replaces it. The chat store already clears
stream state when an assistant message arrives, so the stored input wins
with no frontend change and no added latency before tool cards appear.
- **A call already in history was already admitted.** Execution consumes
the stored input instead of dispatching a second decision, which keeps
one dispatch and one set of hook effects per call. A consumer policy
change between admission and execution applies to later calls, not to
calls already admitted.

The per-chat debug endpoint still records the provider's original tool
input. Its purpose is to report provider behavior, and it requires an
explicit per-chat debug flag; the invariant here covers the transcript.

## Configuration

Adds `chat-hook-url`, `chat-hook-secret`, `chat-hook-timeout`, and
`chat-hook-enabled` deployment options with startup validation. The
flags are hidden from `coder server --help` while the feature is
experimental; the setup guide documents them.

## Tool input validation

Built-in tool arguments reach a consumer as raw JSON with key spelling
preserved, but the tools decode those bytes with Go, which matches
struct fields case-insensitively and keeps the last match. A policy
reading `path` could therefore authorize one value while the tool
executed another, and a lone case variant such as `{"PATH":"/secret"}`
was invisible to a policy checking for `path`.

Coder now rejects a built-in tool call whose input repeats a key or
spells a schema property with different capitalization, before the
`pre_tool_use` dispatch, so a consumer is never asked to authorize bytes
whose meaning depends on the reader. Rejected calls produce an error
result the model can retry; unambiguous calls in the same batch still
run. A consumer-authored `input_override` is rechecked after the
dispatch and fails the turn closed, because the model cannot correct it.
Dynamic and MCP inputs are excluded because the client and the workspace
agent execute those calls rather than coderd.

Two paths needed more than a schema check. Execution resolves a
deprecated tool name to its canonical tool, so validation resolves
aliases first. The `edit_files` decoder also reads `search` and
`replace`, which its schema does not advertise, so those aliases are now
matched exactly and their case variants ignored.

A hook denial now returns a structured 403 carrying `kind:
"hook_denied"`, mirroring the dispatch-failure response that already
carries its own kind. Without it a client cannot tell a policy decision
apart from a generic failure, and the chat UI titled a denial "Request
failed". Adding a kind needs no migration: `ChatErrorKind` is persisted
only inside the JSONB `chats.last_error` column, whose decoder accepts
unknown kinds.

The hook docs also correct the tool-input convergence window. A batch
dispatches sequentially before the assistant row commits, so the
original input stays visible for a span that scales with the number of
tool calls in the step rather than a single hook timeout.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-29 11:39:12 +00:00
Michael Suchacz 91c7232d97 feat: add chat suffix messages, idle failure, and content update support (#27428)
Adds generic chat state and query capabilities that the lifecycle hooks
integration (#27429) builds on. Part of the lifecycle hooks stack
(#27401, #27429, #27430).

- `chatstate`: `EditMessage` accepts caller-provided suffix messages
inserted after the replacement in the same transaction, transitions can
carry a typed error kind, and `FinishError` is also allowed from waiting
chats so admission-time failures can park an idle chat in error.
- `chatstate`: `ValidateToolResults` holds the submitted-tool-result
rules (duplicate, invalid JSON, missing, unexpected) in one place, so
`CompleteRequiresAction` and API-level prechecks reject the same
payloads with the same typed causes.
- `database`: `InsertChat` accepts an optional caller-provided ID.

No hook-specific state or behavior is introduced here; these primitives
are usable by any caller.

An earlier revision added a message-content rewrite primitive so a
`pre_tool_use` override could update an already-committed tool call.
Message content is immutable by design, and @hugodutka pushed back on
changing that. The rewrite is gone: #27429 now dispatches the hook
before the assistant message is stored, so the stored input is the one
that runs and nothing needs updating.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-29 13:16:29 +02:00
Cian Johnston 5d2a69d85a fix(coderd/x/chatd/chaterror): extract plain-text provider error bodies (#27597)
Follows up #27538.

Fixes an issue where `chaterror` would not classify a plain-text
aibridge budget error 403 as ChatErrorKindUsageLimit.

Root cause: Anthropic adapter drops the body from
`ProviderError.Message`, and `providerErrorResponseMessage` extracted
only JSON.

- Parses the dumped response with `http.ReadResponse` (strips headers,
de-chunks, leaves non-dump payloads like Google's raw messages whole).
- When JSON extraction yields nothing, falls back to the trimmed first
line of the body.
- Falls back on `Content-Type: text/plain` only, and never on valid JSON
as `Detail` is user-facing.
- Adds an end-to-end regression test that Anthropic-shaped 403 budget
error → `usage_limit`, not retryable (was `auth`).
- Adds table-driven test cases: HTML skipped, whitespace skipped,
first-line-only, JSON-without-message, chunked, Google raw message.

---

> Generated by Coder Agents on behalf of @johnstcn.
2026-07-29 10:38:15 +01:00
Susana Ferreira 0b4095085e fix: report combined member limit in group AI spend (#27589)
## Problem

The organization groups page showed each group's AI budget as the
group's per-member limit, so the total it displayed was effectively
group members × group budget. That ignores per-user budget overrides
charged to the group, so a group where one member has an override
reported a limit that doesn't match what its members can actually spend.

## Changes

- Add `total_spend_limit_micros` to the organization groups AI spend
payload, the combined budget of the members attributed to the group,
with each member's override replacing their share.
- Return `null` for the total when the group has no budget, since its
members spend without a cap.
- Both the organization groups and single group spend endpoints report
the new field, as they share the same query.
- Use the total as the denominator on the groups page AI budget column.

Depends on #27568
2026-07-29 09:16:37 +01:00
Michael Suchacz e96d8646e2 fix(coderd): give chat message ids an append-order guarantee (#27495)
Chat message ordering was derived from `created_at`, which is `now()`
and therefore the transaction start time. That makes it unusable as an
append-order column for two independent reasons: every row in one
`InsertChatMessages` batch shares a single timestamp, and two concurrent
transactions can commit in the opposite order to the one they started
in.

This PR gives `chat_messages.id` a real append-order guarantee and moves
the history reads onto it.

## Changes

**`InsertChatMessages` had no input-order guarantee.** Callers index the
returned slice by input position. That only worked because PostgreSQL
happens to evaluate the `BIGSERIAL` default in row order. Ids are now
allocated up front and the k-th smallest is assigned to input index k,
so the pairing does not depend on where the column default is evaluated.
Returned rows are explicitly `ORDER BY id`.

**Three history reads now order by `id`.**

| Query | Was | Now |
|---|---|---|
| `GetChatMessagesByChatID` | `created_at ASC` | `id ASC` |
| `GetChatMessagesByRevisionForStream` | `created_at ASC, id ASC` | `id
ASC` |
| `GetLastChatMessageByRole` | `created_at DESC, id DESC` | `id DESC` |

`GetChatMessagesByChatID` paginated by `id` while ordering by
`created_at`, which is incoherent on its own terms.

The other two matter because of who consumes them. The stream query
supplies incremental updates on the same socket that emits a full
`GetChatMessagesByChatID` snapshot on history reset, so once that
snapshot moved to `id` the two disagreed under timestamp skew.
`GetLastChatMessageByRole` returns an id that is then used as an id
cursor, both as `AfterID` when synthesizing tool cancellations and as
`chats.last_read_message_id`, where a stale anchor leaves later
assistant messages permanently unread.

A tie-breaker would not have fixed either one. It only resolves equal
timestamps; leading with `created_at` is the actual defect.

**`GetLastChatMessageByRole` loses its index, so this adds one.** `ORDER
BY created_at DESC, id DESC` could take an ordered scan of
`idx_chat_messages_chat_created`. Nothing in the schema can supply
`ORDER BY id DESC LIMIT 1` for a given `chat_id` and `role`, so the
planner switches to a backward scan of the primary key and filters every
newer row in the table, scanning all of it when the chat has no message
in that role, which is the routine case for a fresh chat. Migration
`000559` adds `(chat_id, role, id DESC) WHERE deleted = false`, the same
shape as the existing `idx_chat_messages_user_prompts`. This matters
because the query is hot: it runs on every stream connect and
disconnect, and once per turn when synthesizing tool cancellations.

`GetChatMessagesForPromptByChatID` has the same defect and is fixed in
the stacked PR, because its compaction boundary change is semantic and
deserves a separate review. Auto-archive stays timestamp-based
deliberately: it measures activity, not order.

Wrapping the insert in a CTE (needed because `INSERT` cannot take `ORDER
BY`) makes sqlc synthesize `InsertChatMessagesRow`. It is structurally
identical to `ChatMessage`, so the call sites use a direct struct
conversion that stops compiling if the two ever diverge.

## Testing

Behavior tests write `created_at` values inverted against id order, so a
reader that leads with `created_at` returns the batch backwards. All
three queries were verified red by reverting the `ORDER BY` and
regenerating: the stream query returned `[3,2,1]` for `[1,2,3]`, and
`GetLastChatMessageByRole` picked id 1 instead of id 3.

`TestInsertChatMessagesOrderContract` asserts against the generated SQL,
covering what a behavior test cannot: PostgreSQL evaluates the id
default in row order anyway, so a batch still looks ordered once the
guarantee is removed.

`TestChatMessagesSequenceCacheIsOne` guards the cross-batch half of the
invariant. Ids follow chat row lock order only while the sequence hands
out one value at a time; sequence cache blocks are per session, so with
a cache above one a backend holding stale cached values can lock second
and still commit lower ids. Bumping a sequence cache is an ordinary
throughput tweak, and it would silently corrupt history order.

The index was checked on a 200k row fixture. Without it, the zero-match
lookup filters all 200,000 rows over 2763 buffers; with it, the plan is
an index scan with both `chat_id` and `role` in the index condition, no
sort node, and 3 buffers.

Note that the within-batch mapping does not depend on the cache size. It
is established by `ROW_NUMBER() OVER (ORDER BY id)` over the allocated
ids, so it holds regardless of `nextval` evaluation order.

## Note on the deleted subagent hand-sort

The subagent history reader's hand-sort stays deleted, but calling it
redundant was imprecise. It sorted by `created_at` then `id`, so it is
only equivalent to `id` ordering when the two agree. When they disagree
the old code selected a different "latest assistant". This is a
deliberate behavior change to match the new invariant, not dead-code
removal.

> Opened by Mux on behalf of Mike.
2026-07-29 07:17:42 +00:00
Jaayden Halko 06ceb4253d feat: add agent runtime hour license claims and entitlement feature (#27459)
Licenses can now carry three agent runtime hour claims:
`agent_runtime_hours_allocation`, `agent_runtime_hours_limit_soft`, and
`agent_runtime_hours_limit_hard` (unit: hours). They surface as the new
usage-period feature `agent_runtime_hours` in `GET
/api/v2/entitlements`, where `limit` carries the allocation and the new
optional `soft_limit` / `hard_limit` fields on `codersdk.Feature` carry
the thresholds.

Invalid combinations reject the entire license via `validateClaims`
(both at upload and when computing entitlements for stored licenses):
soft/hard without allocation, negative allocation, soft outside `0 <=
soft < allocation`, or `hard < allocation`.

Soft and hard limits are not comparison inputs in `Feature.Compare`;
they ride along with whichever license wins (newest `iat`, existing
behavior). None of the three claim names is a feature name, so old
servers ignore them via the existing unknown-claim tolerance, protecting
rollout of licenses minted with the new claims.

The claim name constants defined in `enterprise/coderd/license` are the
canonical contract for `github.com/coder/license` (X1).

Part of
[CODAGT-837](https://linear.app/codercom/issue/CODAGT-837/a1-agent-runtime-license-claims-and-entitlement-feature).
Blocks B4 (usage wiring + warnings), C1 (hard-limit admission gate), F1
(licenses page), A4 (managed-agent coexistence), X1 (licensor).

Out of scope, handled by follow-up issues: `Actual` usage wiring,
threshold warnings, admission gating, premium defaults, and FE surfacing
beyond regenerated types.

<details>
<summary>Implementation plan and decision log</summary>

## Decisions (confirmed by jaayden, 2026-07-23)

1. **Claim names / unit:**
   - `agent_runtime_hours_allocation` - allocation (unit: hours, int64)
   - `agent_runtime_hours_limit_soft` - soft limit
   - `agent_runtime_hours_limit_hard` - hard limit
- None of the three claim names is itself a `FeatureName`; all three map
to the single new usage-period feature `agent_runtime_hours`
(`FeatureAgentRuntimeHours`), mirroring how `managed_agent_limit_soft`
mapped onto `managed_agent_limit`. Old servers therefore ignore all
three claims via the `FeatureNamesMap` check.
2. **Reject-license.** Invalid claim combinations reject the whole
license via `validateClaims` (upload returns 400 via
`ParseClaimsIgnoreNbf`; already-stored licenses produce an `Invalid
license ... parsing claims` entitlements error and contribute nothing).

## Design notes

- `codersdk.Feature` had a `SoftLimit` field until 051ed34580 ("feat:
convert soft_limit to limit", #22048) collapsed managed-agent soft/hard
into a single `limit`. This reintroduces soft/hard as optional fields
without changing managed-agent behavior.
- Existing usage-period machinery populates `UsagePeriod` from
`nbf`/`exp` (`usagePeriodStart`/`usagePeriodEnd` in
`LicensesEntitlements`); reused unchanged, consistent with managed
agents.
- `Entitlements.AddFeature` replaces whole `Feature` structs (no
merging), so soft/hard automatically ride along with the winning
license. No `Feature.Compare` logic change; doc updates plus tests pin
that soft/hard are not comparison inputs.
- The feature name itself is not accepted as a claim; the allocation
must come from the dedicated claim so it is validated against soft/hard
(prevents a validation bypass where a direct feature-name claim could
win precedence with unvalidated thresholds).
- The generic "enabled but not entitled/expired" warning loop skips the
feature, mirroring `FeatureManagedAgentLimit`; usage-based warnings
arrive with B4.
- No premium default for this feature (unlike managed agents).

## Changes

1. `codersdk/deployment.go`: new `FeatureAgentRuntimeHours` (in
`FeatureNames`, `UsesLimit()`, `UsesUsagePeriod()`, keeping it out of
`FeatureSet` expansion); `Feature.SoftLimit`/`Feature.HardLimit`
(`soft_limit`/`hard_limit`, omitempty); doc updates for `UsagePeriod`
and `Compare`.
2. `enterprise/coderd/license/license.go`: canonical claim constants;
validation helper called from `validateClaims`; al-la-carte loop maps
the allocation claim to the feature and attaches soft/hard from the
companion claims; skips for the companion claims and the raw feature
name; generic warning loop skip.
3. `enterprise/coderd/coderdenttest`: `AgentRuntimeHours(allocation)`
builder.
4. Tests:
- `TestAgentRuntimeHoursLicenses`: entitled/grace round-trips (including
JSON field assertions), allocation-only, explicit zero,
`IssuedAtRanking` mirror, soft/hard ride-along with a newer
allocation-only license, direct feature-name claim ignored,
unknown-claims compatibility (old-server simulation).
- `TestAgentRuntimeHoursClaimValidation`: table of valid/invalid claim
combinations against `ParseClaims`, plus stored-license entitlements
error.
- `TestPostLicense`: API-level 400 rejection and a happy-path POST +
`GET /api/v2/entitlements` round-trip.
- `TestFeatureComparison`: soft/hard ignored in comparison; newest `iat`
wins over larger soft/hard.
5. `make gen`: regenerated `site/src/api/typesGenerated.ts`,
`coderd/apidoc/*`, `docs/reference/api/*`.

## Verification

- `go test ./enterprise/coderd/license/ ./codersdk/` and `go test
./enterprise/coderd/ -run 'TestPostLicense|TestEntitlements'` pass.
- `golangci-lint` clean on changed packages; `make lint/emdash` clean;
FE `tsc --noEmit` clean.
- Independent agent review of the diff found no blockers; its minor
findings (direct feature-name claim validation bypass, precedence test
gap, missing API happy-path test) were addressed.

</details>

> [!NOTE]
> Generated by Coder Agents on behalf of @jaaydenh (Linear CODAGT-837
agent session).
2026-07-29 07:58:30 +01:00
Jake Howell d072aa7bd0 feat(site): confirm before batch stopping workspaces (#27631)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell.

## What

Bulk stopping workspaces from the workspaces table currently fires
immediately with no confirmation, whereas the single-row **Stop** action
and the bulk **Delete** / **Update** actions all show a dialog first.
This adds a confirmation dialog to the bulk **Stop** action so it
matches the rest.

## How

- Added `BatchStopConfirmation`, a small `ConfirmDialog` wrapper
mirroring the wording of the single-workspace stop confirmation but
pluralized for the selected count.
- Wired it into `WorkspacesPage`: `onBatchStopTransition` now opens the
dialog (`setActiveBatchAction("stop")`) instead of calling
`batchActions.stop(...)` directly, and the actual stop runs on confirm.
Added `"stop"` to the `BatchAction` union.

No change to the underlying `batchActions.stop` behavior (still only
stops `running` workspaces).

<details>
<summary>Reviewer notes</summary>

Before: `onBatchStopTransition={() =>
batchActions.stop(checkedWorkspaces)}` — no confirmation.

After: opens `BatchStopConfirmation`; confirm calls
`batchActions.stop(checkedWorkspaces)` then clears the active action,
consistent with how `BatchDeleteConfirmation` and `BatchUpdateModalForm`
are handled.

</details>

---
_Opened as a draft. Disclosure: this PR was generated by Coder Agents on
behalf of @jakehwll._
2026-07-29 04:26:09 +00:00
Bobby Ho fbac602456 feat!: add admin-controlled dynamic client registration toggle (#27316)
`POST /oauth2/register` (RFC 7591 Dynamic Client Registration) has
exactly one gate today: `ExperimentOAuth2`, a static, process-lifetime
flag that wraps the entire `/oauth2/*` route tree as an all-or-nothing
switch. That flag is scheduled for removal at GA, which would leave DCR
with zero admin control at all once it is gone.

Add a persistent, DCR-specific `oauth2_dcr_enabled` deployment setting,
independent of the experiment system, so admin control over DCR survives
GA. `POST /oauth2/register` checks the flag and rejects new
registrations with an RFC 7591-shaped `403` when disabled; discovery
metadata (`GET /.well-known/oauth-authorization-server`) conditionally
omits `registration_endpoint`. A new audited `GET`/`PUT
/api/v2/oauth2-provider/settings` endpoint lets an owner toggle it live,
no restart required. The setting defaults to disabled, matching the
canonical design proposal; disabling only stops new self-registrations,
clients that already registered continue to authorize and exchange
tokens normally.

Address issue described in
[ENG-3056](https://linear.app/codercom/issue/ENG-3056/oauth2-dcr-admin-configurable-enabledisable).

## Where this sits in the request path

```mermaid
sequenceDiagram
    autonumber
    participant A as Admin
    participant S as coderd
    participant DB as site_configs<br/>(oauth2_dcr_enabled)
    participant C as OAuth2/MCP Client

    Note over A,S: Admin toggles DCR (new)
    A->>S: PUT /api/v2/oauth2-provider/settings<br/>{dynamic_client_registration_enabled: false}
    S->>S: authorizeContext(ActionUpdate, ResourceDeploymentConfig)
    S->>DB: UPSERT oauth2_dcr_enabled = false
    S-->>A: 200 OK (audited)

    Note over C,S: Client discovery + registration afterward
    C->>S: GET /.well-known/oauth-authorization-server
    S->>DB: GetOAuth2DCREnabled (system ctx, every request, no cache)
    DB-->>S: false
    S-->>C: 200 metadata, registration_endpoint omitted

    C->>S: POST /oauth2/register
    S->>DB: GetOAuth2DCREnabled (system ctx, every request, no cache)
    DB-->>S: false
    S-->>C: 403 invalid_request,<br/>"Dynamic client registration is disabled"

    Note over C,S: A client that registered before the change is unaffected
    C->>S: GET /oauth2/authorize?client_id=...
    Note over S: no DCR-enabled check on this path
    S-->>C: 200 (proceeds normally)

    C->>S: PUT/DELETE /oauth2/clients/{client_id} (RFC 7592 self-management)
    Note over S: no DCR-enabled check on this path either
    S-->>C: 200 (proceeds normally)
```

## Files changed: manual vs. generated

Reviewers should focus on the **manual** files. The **generated** ones
are `make gen` output that follows mechanically from the manual changes
and don't need direct review.

<details>
<summary><b>Manual files (26)</b> — click to expand, grouped the same
way as "Suggested review order" below</summary>

**1. Database**

| File | What changed |
|---|---|
| `coderd/database/queries/siteconfig.sql` | New
`GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled` query pair on the
existing generic `site_configs` table. No schema change. |
| `coderd/database/dbauthz/dbauthz.go` | RBAC check
(`rbac.ResourceDeploymentConfig`) on the two new query methods; extends
the `subjectSystemOAuth2` system-actor role with read-only
`ResourceDeploymentConfig` access, needed so the public
discovery/registration endpoints can read the flag via
`dbauthz.AsSystemOAuth2`. |
| `coderd/database/dbauthz/dbauthz_test.go` | RBAC assertion coverage
for `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled` in the
method-coverage test suite. |

**2. Request gating (the actual feature)**

| File | What changed |
|---|---|
| `coderd/oauth2provider/registration.go` | The actual gate:
`CreateDynamicClientRegistration` reads the flag first and returns an
RFC 7591-shaped `403` when disabled (defaults disabled if never
configured). |
| `coderd/oauth2provider/registration_test.go` | New unit test,
`TestCreateDynamicClientRegistration_DCREnabled`: calls the handler
directly (no HTTP server), covering enabled / explicitly disabled /
never-configured. |
| `coderd/oauth2provider/metadata.go` | `GetAuthorizationServerMetadata`
conditionally omits `registration_endpoint` from discovery metadata when
DCR is disabled. |
| `coderd/oauth2provider/metadata_test.go` | New unit test,
`TestGetAuthorizationServerMetadata_DCREnabled`: same three states, for
the discovery handler. |

**3. Admin settings endpoint**

| File | What changed |
|---|---|
| `codersdk/oauth2.go` | New `OAuth2ProviderSettings` SDK type plus
`Client.OAuth2ProviderSettings`/`PutOAuth2ProviderSettings` methods. |
| `coderd/oauth2.go` | New
`oauth2ProviderSettings`/`putOAuth2ProviderSettings` admin handlers
(audited via `audit.InitRequest`); updates the
`GetAuthorizationServerMetadata` call site to pass `api.Database`. |
| `coderd/coderd.go` | Registers `GET`/`PUT
/api/v2/oauth2-provider/settings`. |
| `coderd/oauth2_provider_settings_test.go` | New test file: admin
`GET`/`PUT` round-trip, default-disabled-before-any-`PUT`, and `403` for
a non-owner on both `GET` and `PUT`. |

**4. Audit wiring**

| File | What changed |
|---|---|
| `coderd/database/types.go` | New `database.OAuth2ProviderSettings`
audit-only struct (mirrors `NotificationsSettings`). |
| `coderd/audit/diff.go` | Adds the new struct to the `Auditable` type
union. |
| `coderd/audit/request.go` | Adds the new struct to all four dispatch
switches (`ResourceTarget`, `ResourceID`, `ResourceType`,
`ResourceRequiresOrgID`). |
| `codersdk/audit.go` | New API-facing
`ResourceTypeOAuth2ProviderSettings` constant and its `FriendlyString`
case. |
| `enterprise/audit/table.go` | Field-level audit action map
(`ActionTrack`/`ActionIgnore`) for the new struct. |
|
`coderd/database/migrations/000546_audit_oauth2_provider_settings.up.sql`
| Adds `oauth2_provider_settings` to the `resource_type` Postgres enum,
required for the audit wiring above (`resource_type` is a real enum, not
a Go-only value). |
|
`coderd/database/migrations/000546_audit_oauth2_provider_settings.down.sql`
| No-op (`ALTER TYPE ... ADD VALUE` can't be reverted). |

**5. Test-suite ripple from the disabled-by-default flip**

| File | What changed |
|---|---|
| `coderd/oauth2provider/oauth2providertest/helpers.go` | New shared
test helper, `EnableDCR`, since DCR now defaults to disabled and many
pre-existing tests need it turned on to register a client. |
| `coderd/oauth2_test.go` | Adds
`TestOAuth2DynamicClientRegistrationDisabled` (registers a client,
disables DCR, verifies new registration is rejected while the existing
client's self-management, authorize, and token exchange all keep
working); calls `EnableDCR` in every pre-existing test that registers a
client. |
| `coderd/oauth2_error_compliance_test.go` | Calls `EnableDCR` in every
test that registers a client, so RFC-error-format assertions aren't
masked by the new disabled-by-default gate. |
| `coderd/oauth2_metadata_validation_test.go` | Same: `EnableDCR` added
to every registration-dependent test. |
| `coderd/oauth2_security_test.go` | Same. |
| `coderd/oauth2provider/validation_test.go` | Same (near-duplicate of
`oauth2_metadata_validation_test.go` in a different package). |
| `coderd/oauth2provider/provider_test.go` | Same. |
| `coderd/mcp/mcp_e2e_test.go` | Same, for the MCP end-to-end
dynamic-registration flow test. |

</details>

<details>
<summary><b>Generated files (12)</b> — from <code>make gen</code>, no
need to review directly</summary>

`coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
`coderd/database/dbmetrics/querymetrics.go`,
`coderd/database/dbmock/dbmock.go`, `coderd/database/dump.sql`,
`coderd/database/models.go`, `coderd/database/querier.go`,
`coderd/database/queries.sql.go`, `docs/admin/security/audit-logs.md`,
`docs/reference/api/enterprise.md`, `docs/reference/api/schemas.md`,
`site/src/api/typesGenerated.ts`.

</details>

## Suggested review order

### 1. Database

Establishes the persisted setting and its RBAC rule; everything else
builds on `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled`.

1. `coderd/database/queries/siteconfig.sql` — the two new queries. Same
boolean-encoding pattern as the existing
`oauth2_github_default_eligible` key right above them in the same file.
2. `coderd/database/dbauthz/dbauthz.go` — the RBAC wrapper for those two
queries, plus the `subjectSystemOAuth2` role extension (search this file
for `ResourceDeploymentConfig`, it appears in both spots).
3. `coderd/database/dbauthz/dbauthz_test.go` — asserts the RBAC checks
from (2) actually fire.

### 2. Request gating (the actual feature)

Where `POST /oauth2/register` and discovery metadata change behavior.

1. `coderd/oauth2provider/registration.go` — the primary gate. Read this
first; it's the feature.
2. `coderd/oauth2provider/registration_test.go` — its new unit test,
exercising the gate's three states directly against the handler.
3. `coderd/oauth2provider/metadata.go` — the same gating pattern applied
to the discovery `GET` endpoint.
4. `coderd/oauth2provider/metadata_test.go` — its new unit test.

### 3. Admin settings endpoint

How an owner flips the setting live.

1. `codersdk/oauth2.go` — the `OAuth2ProviderSettings` SDK type and
`Client` methods first; this is the public contract everything below
implements against.
2. `coderd/oauth2.go` — the `GET`/`PUT` handlers themselves.
3. `coderd/coderd.go` — route registration, to see where those handlers
get wired in.
4. `coderd/oauth2_provider_settings_test.go` — round-trip and permission
tests.

### 4. Audit wiring

Plumbing required so step 3's `PUT` is auditable; mechanical except for
(3).

1. `coderd/database/types.go` — the audit-only struct; everything else
in this layer exists to plumb it through.
2. `coderd/audit/diff.go` — adds it to the `Auditable` type union (the
compiler enforces this one).
3. `coderd/audit/request.go` — the four dispatch switches; the one part
of this layer worth reading closely.
4. `codersdk/audit.go` — the API-facing resource type constant.
5. `enterprise/audit/table.go` — the field-action map.
6.
`coderd/database/migrations/000546_audit_oauth2_provider_settings.{up,down}.sql`
— read last; a consequence of needing a new `resource_type` enum value
for (1)-(5), not a design decision of its own.

### 5. Test-suite ripple from the disabled-by-default flip

1. `coderd/oauth2provider/oauth2providertest/helpers.go` — the new
`EnableDCR` helper. Read first to understand the fix pattern before
seeing it applied repeatedly.
2. `coderd/oauth2_test.go` — next, since it also contains the new
`TestOAuth2DynamicClientRegistrationDisabled`, not just `EnableDCR` call
sites.
3. The rest, in any order, they're mechanical repeats of the same
one-line addition: `coderd/oauth2_error_compliance_test.go`,
`coderd/oauth2_metadata_validation_test.go`,
`coderd/oauth2_security_test.go`,
`coderd/oauth2provider/validation_test.go`,
`coderd/oauth2provider/provider_test.go`, `coderd/mcp/mcp_e2e_test.go`.

## Explicitly out of scope

Per the design proposal: rate limiting on `POST /oauth2/register`
(tracked separately), retroactively affecting already-registered clients
when DCR is disabled (this only gates new self-registration), and an
Initial Access Token requirement (a separate, follow-up ticket).
2026-07-28 16:59:33 -07:00
J. Scott Miller ce769680ba feat(site): hide workspace resources when lacking workspace-create permission (#27278)
Context: experiment `minimum-implicit-member ` added the ability to set
the default member-roles at a per-organization level. This, along with
the related PR stacked listed below, will be used to enable "gateway
accounts", which are accounts that are entitled to use the AI Gateway
but not create or use workspaces. The Workspaces tab is intentionally
left visible for now.

Hides the "New workspace" button and the empty-state creation CTA on the
Workspaces page for users who cannot create a workspace in any
organization, and guards the creation page itself.

Adds a shared `createWorkspace` authorization check (`workspace`
resource, `create` action, `owner_id: me`, `any_org: true`) to
`site/permissions.json` and threads the result through
`WorkspacesPageView`, `WorkspacesTable`, and `WorkspacesEmpty`. Users
without the permission see an empty state explaining they don't have
permission to create workspaces instead of a dead-end CTA. The create
CTAs on the Templates pages were already gated by per-organization
checks; this brings the Workspaces page in line.

`CreateWorkspacePage` is also gated: it adds an org-scoped
`createWorkspaceForUserID` check to its existing authorization batch and
wraps the view in `RequirePermission`, so a direct URL shows the
standard denial dialog instead of a form that 403s on submit. Users who
can create workspaces for others (`createWorkspaceForAny`) still see the
form.

To see this behavior, enable the experiment. As an admin, visit
Organization -> Roles, and remove "Organization Workspace Access" from
the default roles. Login as a user that is not granted workspace access
via a member role.

Storybook coverage: `CannotCreateWorkspace` (empty state + hidden
button), `CannotCreateWorkspaceWithWorkspaces` (button hidden while the
table renders), `CannotCreateWorkspaceWithFilter` (pins the filter empty
state's priority over the no-permission one), and `PermissionDenied` for
the CreateWorkspacePage gate. The Go SSR permissions test also asserts
the new `createWorkspace` entry.

## Stack

This PR is independent but related to the gateway-accounts stack:

1. **#27279**: permission-based license seat counting. Behind the
`permission-based-licensing` experiment and gated on the AI Governance
add-on, `user_limit` counts only users the RBAC engine authorizes to
create workspaces.
2. **#27280**: adds the `organization-ai-gateway-access` org role
carrying the AI Bridge interception permissions (extracted from the
member floors, backfilled into org default roles by migration) and
enforces it at AI Gateway authentication; bridge usage stops claiming AI
Governance seats under the experiment.
3. ~~**#27281**: gates workspace ACL grants on matching member-level
capability (each granted action only takes effect while the recipient
holds that action in the org), so workspace sharing is ineffective for
(and rejected toward) users without workspace capabilities, evaluated
live on every authorization.~~ Tabled - excluded from the
gateway-accounts MVP.

This PR (#27278) stands alone: it hides the Workspaces page create CTAs
for users without workspace-create permission and can merge in any
order.
2026-07-28 18:09:54 -05:00
dylanhuff-at-coder efbf802319 feat: add bulk secret import upload to Add secret dialog (PLAT-240) (#26725)
Adds a file dropzone to the create branch of the Add secret dialog
(final PR in the PLAT-240 stack, after #26723 and #26724). The browser
reads the file, derives the format from the extension
(`.env`/`.json`/`.yaml`/`.yml`), and imports via `POST /secrets/batch`;
per-entry backend errors surface in an alert and the success toast flags
secrets imported without an env name. Storybook play stories and vitests
cover the flow.

Also documents the upload flow in `docs/user-guides/user-secrets.md`.

Closes https://linear.app/codercom/issue/PLAT-240

> Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder.
2026-07-28 15:30:15 -07:00
dylanhuff-at-coder 0b2a6cac78 feat: add coder secret import for bulk secret files (#27534)
Adds `coder secret import <file>` to bulk-import dotenv, JSON, or YAML
secrets through the existing batch API. The command infers the format
from the extension or accepts `--input-format`, supports non-interactive
stdin, validates files locally before upload, and warns when imported
keys cannot be injected as environment variables.

Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder.
2026-07-28 14:37:29 -07:00
1a6a8be96c feat: log tailnet tunnels to the connection log (#27423)
Co-authored-by: Chris DiGiamo <cd@anthropic.com>
Co-authored-by: Chris DiGiamo <cdigiamo@anthropic.com>
2026-07-28 15:30:12 -05:00
George KandBobby Ho 8cc7f2bb0e fix(coderd): reject workspace proxy hostname prefixes (#27544)
A workspace proxy hostname prefix could be accepted as a valid proxy
access URL. An authenticated user could then be redirected to an
attacker-controlled domain with an application-connect API key in the
URL.

Require proxy access URL matches to have a hostname boundary after the
candidate hostname, allowing only the end of the URL, a port, or a
path.

Add regression coverage for proxy access URL and wildcard hostname
prefixes.

Refs: https://linear.app/codercom/issue/PLAT-384

---------

Co-authored-by: Bobby Ho <bobbidinho@gmail.com>
2026-07-28 13:20:59 -07:00
Andrew Aquino 09a69e624a feat: search users by display name (#27398)
Free-text member search previously matched only username and email, so
typing a person's display name returned no results even though the UI
shows the display name as the primary label. This broadens the free-text
`@search` filter to also match `users.name`.

The change is in three queries: `GetUsers`,
`PaginatedOrganizationMembers`, and `GetGroupMembersByGroupIDPaginated`.
This covers every server-filtered surface: the Users page, the
Organization Members page, the Group Members page, and the
`UserAutocomplete` / `WorkspaceUserAutocomplete` pickers (which query
`GetUsers` with `q`). The org member picker (`MemberAutocomplete`)
filters client-side via cmdk, so display name is added to its
`keywords`.

Explicit filters (`name:`, `username`/`email`) and pagination counts are
unchanged; the group members count still comes from the filtered
`COUNT(*) OVER()` in the same query.

Refs DEVEX-484
Refs DEVEX-565

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

## Problem

Member search (both the global Users page and the Organization Members
page) matches only on `username` and `email`. It does not match on the
user's display name (`users.name`), even though the Organization Members
table shows `name` as the primary title. So typing a person's full name
in the search box returns nothing.

Today a bare search term (`alice`) is routed to the SQL `@search`
filter, which only checks `email`/`username`. Display name is only
matched if the user explicitly types `name:alice`, which is
undiscoverable.

## Design decision

Include `name` in the free-text `@search` condition in the affected SQL
queries. A bare term then matches `email OR username OR name`, using the
same case-insensitive substring `ILIKE` already in place. This keeps the
existing explicit `name:` filter working.

Tradeoff: this broadens the meaning of free-text `search` globally
(anything using these queries now also matches display name). This is
the intended behavior, confirmed against DEVEX-565 (display name search
in the user picker).

## Affected files

Backend:
- `coderd/database/queries/users.sql` (`GetUsers`)
- `coderd/database/queries/organizationmembers.sql`
(`PaginatedOrganizationMembers`)
- `coderd/database/queries/groupmembers.sql`
(`GetGroupMembersByGroupIDPaginated`)
- `coderd/database/queries.sql.go` regenerated via `make gen`

Frontend:
- `site/src/components/UserAutocomplete/UserAutocomplete.tsx` (add
`name` to client-side cmdk keywords)

Tests:
- `coderd/coderdtest/users.go` (shared `UsersFilter` helper): added a
`DisplayNameSearch` case and extended search-based expectations to
include `name`. Exercised by `TestGetUsersFilter`,
`TestGetOrgMembersFilter`, and `TestGetGroupMembersFilter`.

Docs:
- `docs/admin/users/index.md`: documented that free-text search matches
username, email, and display name.

## Frontend surface coverage

| Surface | Sends | Backend | Query |
|---|---|---|---|
| Users page | `q` | `GET /users` | `GetUsers` |
| Organization Members page | `q` | paginated members |
`PaginatedOrganizationMembers` |
| Group Members page | `q` | `groupMembers` |
`GetGroupMembersByGroupIDPaginated` |
| User pickers (server-filtered) | `q` | `GET /users` | `GetUsers` |
| Org member picker (client-filtered) | local cmdk | n/a | keyword
change |

## Out of scope

- Trigram/similarity (fuzzy) matching; keeps `ILIKE` substring
semantics.
- Sort/pagination ordering (still `LOWER(username)`).

</details>

---
_Created by Coder Agents on behalf of @aqandrew._
2026-07-28 12:13:58 -07:00
Callum Styan e657d2ab9d chore(scaletest/prebuilds): reduce workspace poll interval to 5s (#27548) 2026-07-28 10:10:19 -07:00
Steven Masley 206938154a chore: remove emyrk from coderowners of commonly touched rbac (#27596) 2026-07-28 16:16:59 +00:00
Cian Johnston 75fd7bc09a fix: remove chatd usage limit enforcement (#27535)
This PR surgically removes enforcement of Agents spend limits:
- Adjusts the relevant function that checks usage to always return nil
- Deletes tests that expect a usage limit error.
2026-07-28 17:14:12 +01:00
Mathias Fredriksson eb905702c8 fix(coderd/util/syncmap): match sync.Map semantics in the typed wrapper (#27582)
Fixes CODAGT-869
2026-07-28 19:05:59 +03:00
Zach 85984ff142 feat: add enable/disable support for user secrets (#27537)
Users can now disable a secret to stop it from being injected into
workspaces without deleting it, and re-enable it later. Disabled secrets
stay visible and editable everywhere they already appear.

An enabled secret must have at least one injection target; a secret with
no target can be stored only while disabled. Existing target-less secrets
are migrated to disabled to preserve current behavior.

Support spans the REST API, SDK, CLI, dashboard, and audit log.
2026-07-28 09:58:33 -06:00
Marcin Tojek 3c61a9a939 chore(docs): update release docs for v2.34.7 (#27591)
Automated docs update for v2.34.7 release.

Created by `releasetui`.
2026-07-28 16:51:31 +01:00
Danielle Maywood be226409b8 fix: delete the unused ChatMessagePart.Signature field (#27588) 2026-07-28 16:26:19 +01:00
Jake Howell 5f72c1525e chore(site): demui <ScheduleForm /> component (#27563)
This pull-request deMUIs the `/settings/schedule` page for users. 

| Old | New |
| --- | --- |
| <img width="1041" height="371" alt="PREVIEW_QUIET_HOURS_OLD"
src="https://github.com/user-attachments/assets/15e1e285-a33e-475e-beab-924a53152e00"
/> | <img width="1041" height="406" alt="PREVIEW_QUIET_HOURS_NEW"
src="https://github.com/user-attachments/assets/27daa080-b3e9-4615-9ad3-eefa0d55295b"
/> |
2026-07-29 01:06:38 +10:00
Jake Howell 448fe10d82 fix: remove @mui/material from formUtils.stories.tsx (#27503)
This pull-request removes the material dependency from
`formUtils.stories.tsx`. Just a lil bit of dead code we can clean up 🙂.
2026-07-28 23:39:28 +10:00
Michael Suchacz 8ea2586189 feat: add chat lifecycle hook dispatch backend (#27401)
Adds the chat lifecycle hook wire contract and dispatch plumbing, first
PR of the lifecycle hooks stack (followed by #27428, #27429, #27430).

- `codersdk/x/agenthooks`: event and response wire types, JWT creation
and verification with the shared secret (HS256, request body digest,
expiry and not-before freshness checks), and an HTTP handler helper so
consumers only implement the events they use. The `codersdk/x` location
marks the consumer SDK as experimental.
- `coderd/x/agenthooks/dispatch`: a stateless dispatcher that signs and
posts hook events, enforces a concurrency cap under one configured
timeout that bounds both the capacity wait and both post attempts,
retries one connection failure with the same JWT, sends a distinctive
`coderd-agenthooks/<version>` User-Agent, and records Prometheus
metrics. Delivery is at least once; consumers own durable decision
state, audit records, and deduplication keyed by the stable payload
identifiers. Nothing is persisted by Coder.
- Response bodies decode strictly: unknown fields, duplicate JSON keys
(including inside `input_override`), and trailing data fail the dispatch
closed as protocol errors instead of silently reading as allow.
- `coderd/util/xnet`: shared timeout and connection error classification
used by the dispatcher retry logic. Transient HTTP/2 stream aborts count
as connection errors, so the documented single retry also applies to h2
consumers, which is the shape Go's default transport negotiates against
any TLS consumer. Deterministic protocol failures stay terminal. Only
the struct form of a stream error is matched, because `net/http` bundles
its own HTTP/2 types and `h2_error.go` bridges only that shape.
- `scripts/agenthooks-server`: a reference consumer that logs events and
demonstrates consumer-owned pre-tool decision deduplication. It requires
an explicitly configured JWT audience rather than deriving one from the
request, and its startup output names the mode it is running in so an
operator can see that the example policy flags need `-log-only=false`.
- `scripts/apitypings`: generate TypeScript types for the hook wire
contract.

Dispatch failures log without the error's stack frames, since a failed
dispatch is an expected, operator-visible condition.

Nothing dispatches these events yet; chatd wiring lands in #27429.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-28 13:59:37 +02:00
Jake Howell bd5d640f1e fix(coderd/database/migrations): resolve duplicate 000554 migration collision (#27581)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell.

## Problem

`main` currently has **two migrations sharing version `000554`**:

- `000554_aibridge_token_usage_spend_export_index.{up,down}.sql`
- `000554_legacy_none_login_to_password.{up,down}.sql` (from #26851)

Both merged around the same time. #26851 was renumbered to `000554` when
`000553` was the latest, but `aibridge_token_usage_spend_export_index`
claimed `000554` and merged too, leaving a duplicate version number on
`main`. Duplicate migration versions break the migration sequence.

## Fix

Renumber the legacy none login migration to the next free slot,
`000555`, leaving the aibridge migration at `000554`:

- `000554_legacy_none_login_to_password.{up,down}.sql` ->
`000555_legacy_none_login_to_password.{up,down}.sql`
- `migrate_test.go`: `TestMigration000554...` ->
`TestMigration000555...`, `priorMigrationVersion` `553` -> `554`, and
the `os.ReadFile` filename.

The migration is data-only and unchanged; only its version number moves.
`TestMigration000555LegacyNoneLoginToPassword` passes locally.

The same collision exists on `release/2.36` via the backport (#27578),
which has been renumbered to `000555` to match.

Resolves [DEVEX-226] follow-up.

[DEVEX-226]: https://linear.app/issue/DEVEX-226
2026-07-28 11:35:36 +00:00
dependabot[bot] 2dc850d085 chore: bump github.com/valyala/fasthttp from 1.72.0 to 1.73.0 (#27575)
Bumps [github.com/valyala/fasthttp](https://github.com/valyala/fasthttp)
from 1.72.0 to 1.73.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/valyala/fasthttp/releases">github.com/valyala/fasthttp's
releases</a>.</em></p>
<blockquote>
<h2>v1.73.0</h2>
<h2>What's Changed</h2>
<ul>
<li>test: fix host comparison in FuzzURIParse by <a
href="https://github.com/ReneWerner87"><code>@​ReneWerner87</code></a>
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2313">valyala/fasthttp#2313</a></li>
<li>perf: avoid redundant scans when parsing request headers by <a
href="https://github.com/ReneWerner87"><code>@​ReneWerner87</code></a>
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2312">valyala/fasthttp#2312</a></li>
<li>Fix temp file leak in SaveMultipartFile on cross-device rename
failure by <a
href="https://github.com/itxaiohanglover"><code>@​itxaiohanglover</code></a>
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2311">valyala/fasthttp#2311</a></li>
<li>re-enable forcetypeassert by <a
href="https://github.com/Harshal96"><code>@​Harshal96</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2316">valyala/fasthttp#2316</a></li>
<li>test: normalize Go test names by <a
href="https://github.com/Harshal96"><code>@​Harshal96</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2317">valyala/fasthttp#2317</a></li>
<li>feat: prefix sentinel error strings by <a
href="https://github.com/Harshal96"><code>@​Harshal96</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2319">valyala/fasthttp#2319</a></li>
<li>fix(pprofhandler): use exact path matching to prevent debug data
exposure by <a
href="https://github.com/xbrxr03"><code>@​xbrxr03</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2302">valyala/fasthttp#2302</a></li>
<li>avoid following a symlink when writing the FS compressed cache by <a
href="https://github.com/alhudz"><code>@​alhudz</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2321">valyala/fasthttp#2321</a></li>
<li>refactor: improve internal interface names by <a
href="https://github.com/Harshal96"><code>@​Harshal96</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2318">valyala/fasthttp#2318</a></li>
<li>fix: lowercase error strings by <a
href="https://github.com/Harshal96"><code>@​Harshal96</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2320">valyala/fasthttp#2320</a></li>
<li>perf: reduce redundant scans and allocations in hot paths by <a
href="https://github.com/ReneWerner87"><code>@​ReneWerner87</code></a>
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2322">valyala/fasthttp#2322</a></li>
<li>validate domain and path cookie attribute values on parse by <a
href="https://github.com/alhudz"><code>@​alhudz</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2315">valyala/fasthttp#2315</a></li>
<li>chore(deps): bump securego/gosec from 2.27.1 to 2.28.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2328">valyala/fasthttp#2328</a></li>
<li>chore(deps): bump actions/setup-go from 6 to 7 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2329">valyala/fasthttp#2329</a></li>
<li>fix: preserve pre-set status code in NewFastHTTPHandler by <a
href="https://github.com/xbrxr03"><code>@​xbrxr03</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2323">valyala/fasthttp#2323</a></li>
<li>chore(deps): bump github.com/klauspost/compress from 1.19.0 to
1.19.1 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2331">valyala/fasthttp#2331</a></li>
<li>reject backslash '..' traversal in fs handler on windows by <a
href="https://github.com/alhudz"><code>@​alhudz</code></a> in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2327">valyala/fasthttp#2327</a></li>
<li>fix: reject Windows alternate data stream paths in FS by <a
href="https://github.com/dev-willbird1936"><code>@​dev-willbird1936</code></a>
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2335">valyala/fasthttp#2335</a></li>
<li>chore(deps): bump golangci/golangci-lint-action from 9.2.1 to 9.3.0
by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2307">valyala/fasthttp#2307</a></li>
<li>chore(deps): bump github.com/andybalholm/brotli from 1.2.1 to 1.2.2
by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2308">valyala/fasthttp#2308</a></li>
<li>chore(deps): bump github.com/klauspost/compress from 1.18.6 to
1.18.7 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2309">valyala/fasthttp#2309</a></li>
<li>chore(deps): bump github.com/klauspost/compress from 1.18.7 to
1.19.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2314">valyala/fasthttp#2314</a></li>
<li>chore(deps): bump golang.org/x/sys from 0.46.0 to 0.47.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2326">valyala/fasthttp#2326</a></li>
<li>chore(deps): bump golang.org/x/crypto from 0.53.0 to 0.54.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2324">valyala/fasthttp#2324</a></li>
<li>chore(deps): bump golang.org/x/net from 0.56.0 to 0.57.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2325">valyala/fasthttp#2325</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/itxaiohanglover"><code>@​itxaiohanglover</code></a>
made their first contribution in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2311">valyala/fasthttp#2311</a></li>
<li><a href="https://github.com/Harshal96"><code>@​Harshal96</code></a>
made their first contribution in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2316">valyala/fasthttp#2316</a></li>
<li><a
href="https://github.com/dev-willbird1936"><code>@​dev-willbird1936</code></a>
made their first contribution in <a
href="https://redirect.github.com/valyala/fasthttp/pull/2335">valyala/fasthttp#2335</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/valyala/fasthttp/compare/v1.72.0...v1.73.0">https://github.com/valyala/fasthttp/compare/v1.72.0...v1.73.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/valyala/fasthttp/commit/f83ac8c3560feccaa017ba86dd9b95ad004790f2"><code>f83ac8c</code></a>
Optimize bounds checks in hot paths</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/d9babd95c5f3d26ff26cfc528ca77f165df2f95f"><code>d9babd9</code></a>
fix: reject Windows alternate data stream paths in FS (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2335">#2335</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/e7cf856857a46388b9e03507b8d4b6d5bc3d69dd"><code>e7cf856</code></a>
reject backslash '..' traversal in fs handler on windows (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2327">#2327</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/165a4c81aada474f8566a66a5d4c2dee35fee37e"><code>165a4c8</code></a>
Improve AppendUnquotedArg with optimised bounds check</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/7a1349da70685cce500515263c20ec389f8f69e1"><code>7a1349d</code></a>
chore(deps): bump github.com/klauspost/compress from 1.19.0 to 1.19.1
(<a
href="https://redirect.github.com/valyala/fasthttp/issues/2331">#2331</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/f1ad91d51977febd2730b9e0d79c7d241c5e430c"><code>f1ad91d</code></a>
fix: preserve pre-set status code in NewFastHTTPHandler (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2323">#2323</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/5f57d8fda4c2c9e3092f82e13f589a92ed48d347"><code>5f57d8f</code></a>
chore(deps): bump actions/setup-go from 6 to 7 (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2329">#2329</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/3aa940dfd248799878cd9ef46f6dfcec89a37f8d"><code>3aa940d</code></a>
chore(deps): bump securego/gosec from 2.27.1 to 2.28.0 (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2328">#2328</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/7a012e987a372bf40d3eedf6caeb2f4c6162ff40"><code>7a012e9</code></a>
validate domain and path cookie attribute values on parse (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2315">#2315</a>)</li>
<li><a
href="https://github.com/valyala/fasthttp/commit/9cf733f7dc3533354eb6d495fcf0af93bdcb2f03"><code>9cf733f</code></a>
perf: reduce redundant scans and allocations in hot paths (<a
href="https://redirect.github.com/valyala/fasthttp/issues/2322">#2322</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/valyala/fasthttp/compare/v1.72.0...v1.73.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/valyala/fasthttp&package-manager=go_modules&previous-version=1.72.0&new-version=1.73.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-28 11:18:19 +00:00
dependabot[bot] 300ad74f05 chore: bump github.com/aws/aws-sdk-go-v2 from 1.42.1 to 1.43.0 (#27576)
Bumps
[github.com/aws/aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2)
from 1.42.1 to 1.43.0.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/4fef3455fe2dcb5ea3de4e9fbacf889b84c8a255"><code>4fef345</code></a>
Release 2026-07-21</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/62754193b1dfd903e741ad656a3e43cda43e3d6c"><code>6275419</code></a>
Regenerated Clients</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/f8598305ac9db1544afae331c09df396ee2f7b3e"><code>f859830</code></a>
Update API model</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/278591d8fcdcb1f3ec22c3562dcd648b169f4a31"><code>278591d</code></a>
Add an option to clients to disable clock skew (<a
href="https://redirect.github.com/aws/aws-sdk-go-v2/issues/3483">#3483</a>)</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/d132ac727d15f1c7ff251e0b6739c0e9362ae322"><code>d132ac7</code></a>
Fix Clock Skew according to internal specification (<a
href="https://redirect.github.com/aws/aws-sdk-go-v2/issues/3472">#3472</a>)</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/03519c98d97b40b31ab42755e4bc6d26e39af5d6"><code>03519c9</code></a>
Release 2026-07-20</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/dda3efb63a49f64351f314aa8b6266dee9efbfc2"><code>dda3efb</code></a>
Regenerated Clients</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/348cec09e4e0e856665f55f5e548135388a4ef25"><code>348cec0</code></a>
Update API model</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/f4fd2723ed647078bced4bdf4b83e6a61c379546"><code>f4fd272</code></a>
Release 2026-07-17</li>
<li><a
href="https://github.com/aws/aws-sdk-go-v2/commit/8e4cbc854bca2c82b351089583123964fb4f392a"><code>8e4cbc8</code></a>
Regenerated Clients</li>
<li>Additional commits viewable in <a
href="https://github.com/aws/aws-sdk-go-v2/compare/v1.42.1...v1.43.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/aws/aws-sdk-go-v2&package-manager=go_modules&previous-version=1.42.1&new-version=1.43.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-28 11:18:10 +00:00
dependabot[bot] 5b1fdc9d5e chore: bump google.golang.org/api from 0.289.0 to 0.290.0 (#27573)
Bumps
[google.golang.org/api](https://github.com/googleapis/google-api-go-client)
from 0.289.0 to 0.290.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/googleapis/google-api-go-client/releases">google.golang.org/api's
releases</a>.</em></p>
<blockquote>
<h2>v0.290.0</h2>
<h2><a
href="https://github.com/googleapis/google-api-go-client/compare/v0.289.0...v0.290.0">0.290.0</a>
(2026-07-20)</h2>
<h3>Features</h3>
<ul>
<li><strong>all:</strong> Auto-regenerate discovery clients (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3661">#3661</a>)
(<a
href="https://github.com/googleapis/google-api-go-client/commit/dea11c224ee6b69cc88ebd03460e95cf11f8733c">dea11c2</a>)</li>
<li><strong>all:</strong> Auto-regenerate discovery clients (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3663">#3663</a>)
(<a
href="https://github.com/googleapis/google-api-go-client/commit/93d30d482d74cf2f49ada20c06fcdfa9ceb0ed87">93d30d4</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md">google.golang.org/api's
changelog</a>.</em></p>
<blockquote>
<h2><a
href="https://github.com/googleapis/google-api-go-client/compare/v0.289.0...v0.290.0">0.290.0</a>
(2026-07-20)</h2>
<h3>Features</h3>
<ul>
<li><strong>all:</strong> Auto-regenerate discovery clients (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3661">#3661</a>)
(<a
href="https://github.com/googleapis/google-api-go-client/commit/dea11c224ee6b69cc88ebd03460e95cf11f8733c">dea11c2</a>)</li>
<li><strong>all:</strong> Auto-regenerate discovery clients (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3663">#3663</a>)
(<a
href="https://github.com/googleapis/google-api-go-client/commit/93d30d482d74cf2f49ada20c06fcdfa9ceb0ed87">93d30d4</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/googleapis/google-api-go-client/commit/b1b12e7c28c287baa23edf8941b2f4a8071c97a9"><code>b1b12e7</code></a>
chore(main): release 0.290.0 (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3662">#3662</a>)</li>
<li><a
href="https://github.com/googleapis/google-api-go-client/commit/153c78e85b81c1a98919bc8abf26a3055996d5ce"><code>153c78e</code></a>
chore: expand CODEOWNERS (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3664">#3664</a>)</li>
<li><a
href="https://github.com/googleapis/google-api-go-client/commit/93d30d482d74cf2f49ada20c06fcdfa9ceb0ed87"><code>93d30d4</code></a>
feat(all): auto-regenerate discovery clients (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3663">#3663</a>)</li>
<li><a
href="https://github.com/googleapis/google-api-go-client/commit/dea11c224ee6b69cc88ebd03460e95cf11f8733c"><code>dea11c2</code></a>
feat(all): auto-regenerate discovery clients (<a
href="https://redirect.github.com/googleapis/google-api-go-client/issues/3661">#3661</a>)</li>
<li>See full diff in <a
href="https://github.com/googleapis/google-api-go-client/compare/v0.289.0...v0.290.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=google.golang.org/api&package-manager=go_modules&previous-version=0.289.0&new-version=0.290.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-28 11:17:59 +00:00
dependabot[bot] fa15461d67 chore: bump github.com/coder/terraform-provider-coder/v2 from 2.18.0 to 2.19.0 (#27574)
Bumps
[github.com/coder/terraform-provider-coder/v2](https://github.com/coder/terraform-provider-coder)
from 2.18.0 to 2.19.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/coder/terraform-provider-coder/releases">github.com/coder/terraform-provider-coder/v2's
releases</a>.</em></p>
<blockquote>
<h2>v2.19.0</h2>
<h2>What's Changed</h2>
<ul>
<li>chore: add check-latest to setup-go for reliable Go version
resolution by <a
href="https://github.com/denisra"><code>@​denisra</code></a> in <a
href="https://redirect.github.com/coder/terraform-provider-coder/pull/529">coder/terraform-provider-coder#529</a></li>
<li>build(deps): Bump golang.org/x/mod from 0.36.0 to 0.38.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/coder/terraform-provider-coder/pull/524">coder/terraform-provider-coder#524</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/denisra"><code>@​denisra</code></a> made
their first contribution in <a
href="https://redirect.github.com/coder/terraform-provider-coder/pull/529">coder/terraform-provider-coder#529</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/coder/terraform-provider-coder/compare/v2.18.0...v2.19.0">https://github.com/coder/terraform-provider-coder/compare/v2.18.0...v2.19.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/coder/terraform-provider-coder/commit/fd21951c3e89b52658e58361388540bbd97cd2c2"><code>fd21951</code></a>
build(deps): Bump golang.org/x/mod from 0.36.0 to 0.38.0 (<a
href="https://redirect.github.com/coder/terraform-provider-coder/issues/524">#524</a>)</li>
<li><a
href="https://github.com/coder/terraform-provider-coder/commit/756e3a855206aec7151c1bc6f132a259533f7bb6"><code>756e3a8</code></a>
chore: add check-latest to setup-go for reliable Go version resolution
(<a
href="https://redirect.github.com/coder/terraform-provider-coder/issues/529">#529</a>)</li>
<li>See full diff in <a
href="https://github.com/coder/terraform-provider-coder/compare/v2.18.0...v2.19.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/coder/terraform-provider-coder/v2&package-manager=go_modules&previous-version=2.18.0&new-version=2.19.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-28 11:16:42 +00:00
Jake HowellandSushant P 0e104f38e0 fix!: deprecate login_type=none, convert existing users to password login (#26851)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Deprecates `login_type=none` (legacy passwordless machine users) in
favour of premium **service accounts**, and migrates existing accounts
off the deprecated path while preserving their identity. Resolves
[DEVEX-226].

## What this does

- **Creation is gated** — `POST /users` and `coder users create` reject
`login_type=none` (and the deprecated `--disable-login`) unless a
service account is requested.
- **Existing users are converted** — migration
`000554_legacy_none_login_to_password` rewrites legacy non-system,
non–service-account `login_type='none'` accounts to
`login_type='password'`. Email addresses are **preserved** and existing
API tokens remain valid. Admins can set a password if interactive login
is desired.

## Why convert to `password` and not `is_service_account`?

Migration `000433_add_is_service_account_to_users` adds two CHECK
constraints:

- `users_email_not_empty`: `(is_service_account = true) = (email = '')`
- `users_service_account_login_type`: `is_service_account = false OR
login_type = 'none'`

Turning a real, email-bearing `login_type=none` user into a service
account would require **blanking their email**. Converting to `password`
instead preserves the account and its email.

> ⚠️ **Breaking / one-way.** The `down` migration cannot restore which
users originally had `login_type='none'`.


Decision log

- **Goal:** move existing `login_type=none` users off the deprecated
path while preserving their identity/email.
- **Constraint discovered:** the `is_service_account` CHECK constraints
(migration `000433`) make a literal `none → service account` conversion
require blanking emails, so this PR converts to `password` instead to
keep emails intact.
- **Implementation:** creation-gating in `cli/usercreate.go` and
`coderd/users.go`, matching test updates, plus the
`000554_legacy_none_login_to_password.{up,down}.sql` migration.
- **CI fix:** the branch was behind `main` and its migration originally
numbered `000534`, which collided with main's
`000534_drop_chat_model_configs_provider`. Merged `main` and renumbered
to `000554` (next free after main's `000553`). `make gen` produces no
drift (the migration is data-only).



> The service-account conversion alternative (#27182, which blanked
emails) was closed in favour of this password-preserving approach.
>
> Docs follow-up: #27333.

[DEVEX-226]: https://linear.app/issue/DEVEX-226

---------

Co-authored-by: Sushant P <zenithwolf1000@users.noreply.github.com>
2026-07-28 21:05:50 +10:00
Susana Ferreira ed37483ff7 feat: add group AI spend endpoint (#27568)
## Description

Adds `GET /api/v2/groups/{group}/ai/spend`, returning the AI spend limit
and aggregate spend for a single group over the current budget period.
The period is derived from the deployment's configured budget period
rather than being caller-specified, matching the other AI spend
endpoints.

## Changes

- Add the `groupAISpend` handler and route, gated by the
`aigateway-cost-control` experiment and the `AIBridge` feature.
- Reuse the existing `GetOrganizationGroupsAISpend` query with a single
group ID, so no new query or authorization path is introduced.
- Add the `GroupAISpend` codersdk type and client method.

Closes
https://linear.app/codercom/issue/AIGOV-475/implement-apiv2groupsgroupaispend

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-28 11:32:51 +01:00
Michael Suchacz e83f018f5f feat(site/src/pages/AISettingsPage/SpendPage): announce cost controls move to AI Governance (#27543)
Adds an informational banner to the AI settings **Spend** tab announcing
that cost controls features move to AI Governance in v2.37, with a link
to the AI Gateway cost controls docs.

Banner copy:

> Cost controls features will move to AI Governance in v2.37. [Read more
here](https://coder.com/docs/ai-coder/ai-gateway/cost-controls)

The link uses the existing `docs()` helper from `#/utils/docs`, so it
resolves the deployment's configured `docs-url` meta tag and otherwise
falls back to a version-pinned `coder.com/docs/@<version>` URL. This
matches how sibling AI settings pages link out (for example
`GatewayKeysPageView` and `ProvidersPageView`).

It points at `/ai-coder/ai-gateway/cost-controls`, the AI Gateway Cost
Controls page added in #27570. That page is present on `main` and the
URL resolves, so the banner links to live documentation.

The banner renders on the main Spend tab. It is intentionally not shown
in the per-user spend drill-in sub-view, which returns early from a
separate component.

## Validation

- Extended the existing `SpendWithLimitsAndUsers` story to assert the
banner copy and the resolved docs `href`. Both assertions were verified
to fail when the banner is removed and when the link points somewhere
else.
- Storybook story tests for `SpendPageView.stories.tsx` pass (12 tests),
plus `tsc -p .`, `biome check`, and `lint:compiler` clean.
- `make pre-commit` passed through the git hooks.

> Mux opened this PR on Mike's behalf.
2026-07-28 12:32:14 +02:00
Susana Ferreira e96e7cfec2 docs(docs): add AI Gateway cost controls placeholder page (#27570)
## Summary

Adds a placeholder "Cost Controls" page under AI Gateway in the docs,
plus its `manifest.json` navigation entry. This is a stub with a title
only; the full content will be written in a follow-up.

Relates to
[AIGOV-476](https://linear.app/codercom/issue/AIGOV-476/add-documentation-for-ai-bridge-cost-controls).

Related to [internal slack
thread](https://codercom.slack.com/archives/C096PFVBZKN/p1785150528587409).

## Changes

- Add `docs/ai-coder/ai-gateway/cost-controls.md` placeholder page
- Register the page in `docs/manifest.json` under AI Gateway (after
Monitoring)

---
> [!NOTE]
> This PR was generated with Coder Agents.
2026-07-28 10:05:18 +00:00
Susana Ferreira c3895ff9c0 feat: add CSV export for AI spend data (#27491)
## Description

Adds `GET /api/v2/organizations/{organization}/ai/spend/export`,
returning `text/csv` with per-user, per-group, per-model, per-provider
aggregated AI spend. The data is built from the raw AI Gateway token
usage tables rather than the `ai_user_daily_spend` rollup, but stays
consistent with it: spend is attributed through the token usage's
effective group and bucketed by the token usage `created_at`, the same
values the daily rollup derives from.

The period defaults to the current UTC month, narrowed to the configured
AI Gateway retention window when the month begins before retained data
does. Explicit `period_start`/`period_end` params must be provided
together, are interpreted as UTC, and may span at most 31 days. Unlike
the default period, an explicit period that begins before the retention
window is rejected rather than narrowed. Every row echoes the applied
bounds, so a narrowed window is visible in the export.

The endpoint requires organization-level admin permissions.

## Changes

- Add the `ExportOrganizationAISpend` query aggregating
`aibridge_token_usages` joined to `aibridge_interceptions`, scoped to
the organization via the effective group, resolving the username, group
name, and organization name alongside their IDs.
- Add the `exportOrganizationAISpend` handler and route, gated by the
`aigateway-cost-control` experiment and the `AIBridge` feature,
returning the CSV in a single response.
- Add the `ExportOrganizationAISpend` codersdk client method.
- Require organization-wide `ResourceGroupMember` read, since the export
aggregates every user in the organization. The per-row filter stays in
`dbauthz` as defence in depth.
- Escape leading formula characters in the free-text columns, so a model
or provider name recorded from an intercepted request cannot be
evaluated when the CSV is opened in a spreadsheet.
- Add an index on `aibridge_token_usages (effective_group_id,
created_at)`, which the period and group predicates otherwise cannot
use.

Closes
https://linear.app/codercom/issue/AIGOV-293/add-csv-export-for-ai-spend-data

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira
2026-07-28 10:58:38 +01:00
Susana Ferreira 16cadcf2c8 chore: raise Biome max file size so swagger.json stays formatted (#27569)
Raises Biome's max file size so `coderd/apidoc/swagger.json` keeps
getting formatted.

The raw swaggo output sits just under Biome's 1 MiB default, so adding a
new endpoint tips it over. Biome then skips the file with an info rather
than an error, which means `scripts/biome_format.sh` and `make gen` both
exit 0 while silently leaving it unformatted. Any PR that introduces a
new endpoint ends up with a large spurious diff in `swagger.json` and a
failing `gen` check.

This is what `make gen` prints when it happens:

```
/home/coder/coder/_gen/tmp.NVD90urqoA/swagger.json format ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  i The size of the file is 1.0 MiB, which exceeds the configured maximum of 1.0 MiB for this project.
    Use the `files.maxSize` configuration to change the maximum size of files processed, or `files.includes` to ignore the file.


Formatted 0 files in 3ms. No fixes applied.
Found 1 info.
format ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  × No files were processed in the specified paths.

  i Check your biome.json or biome.jsonc to ensure the paths are not ignored by the configuration.

  i These paths were provided but ignored:

  - /home/coder/coder/_gen/tmp.NVD90urqoA/swagger.json
```

Generated output is unchanged on main, so this is config only.
2026-07-28 10:35:32 +01:00
Jake Howell ea2ad4d6c6 chore(site): premium paywall for <WorkspaceProxyPage /> (#27567) 2026-07-28 18:58:18 +10:00
Susana Ferreira c351280a37 feat: add Prometheus metrics for AI Governance cost control (#27490)
## Description

Adds Prometheus metrics for AI budget cost control, emitted by the
aibridged server under the `cost_control` subsystem (full names are
prefixed `coder_ai_gateway_`).

- `blocked_requests_total` (counter) — labels: `group_id`
- `blocked_users` (gauge) — labels: `group_id`
- `unpriced_requests_total` (counter) — labels: `provider`, `model`
- `enforcement_duration_seconds` (histogram) — labels: `outcome`

## Changes

- Add `GetOverBudgetUsersPerGroup` query (plus dbauthz/dbmetrics/dbmock
wiring) to count over-budget users per effective group.
- Add a background collector that refreshes the `blocked_users` gauge on
an interval, started only when Prometheus is enabled.
- Wire `Metrics` through the aibridged server, coderd API,
`cli/server.go`, and the enterprise AI gateway handler; recording is
nil-safe when metrics are unset.

Closes
https://linear.app/codercom/issue/AIGOV-296/add-prometheus-metrics-for-cost-control

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-28 09:22:58 +01:00
TJ bfcfb71860 fix: show 'Unset' for missing providers in AI models list (#27400)
## Summary

Frontend-only fixes for the `/ai/settings/models` page:

1. **Provider column displays "Unset"** with an info tooltip when a
model's provider has been deleted, instead of "N/A".
2. **Models without a usable provider display as "Disabled"** in the
list, regardless of the stored `enabled` flag. Covers both missing
(soft-deleted) and disabled providers.
3. **Save button re-enabled when only the provider changes** on the edit
page (previously the button stayed disabled because provider changes
lived outside the formik state).

## Scope

Frontend only. The DB constraint
`chat_model_configs_ai_provider_required_when_active` already prevents a
non-deleted model from having a NULL `ai_provider_id`; CODAGT-709
addresses the server-side cascade when a provider is deleted.

## Changes

- `ModelsPageView.tsx`: two `useMemo` maps (`hasProviderByModelId`,
`providerEnabledByModelId`) passed to `ModelRow`.
- `ModelRow.tsx`: `isEffectivelyEnabled = model.enabled && hasProvider
&& providerEnabled`. When `hasProvider` is false, renders "Unset" with a
standard `InfoIcon` tooltip.
- `ModelForm.tsx`: `canSubmit` OR's in `hasProviderChange` so the save
button enables when only the provider dropdown changes.
- `ModelRow.stories.tsx`: four stories covering baseline,
missing-provider (with tooltip assertion), disabled-provider, and
disabled-model paths.
- `ModelsPageView.stories.tsx`: `OrphanedModelShowsUnset` feeds an
orphaned model through the real derivation (map-miss + `?? false`),
matching the production shape produced by `deriveProviderStates`.
`DisabledProviderModelsStillListed` now asserts the "Disabled" badge.
- `ModelForm.stories.tsx`: `EditUpdateEnabledOnProviderChange` asserts
the save button is enabled when the selected provider differs from the
model's stored provider.
- `testFixtures.ts`: `mockOrphanedModel` fixture representing the
deleted-provider case.

Diff: 7 files, 240 insertions, 9 deletions.

> 🤖 This PR was updated with Coder Agents.
2026-07-28 00:17:45 -07:00