Commit Graph
2720 Commits
Author SHA1 Message Date
043bebb7bc docs: add Coder Desktop stale-tunnel recovery and improve macOS log capture (#26735)
## What

Adds a **Recovering from a stale tunnel** section to the Coder Desktop
user guide, with separate macOS and Windows procedures, and tightens the
existing macOS log-collection instructions.

## Why

Users in the field have hit a state where Coder Desktop's menu bar /
tray shows **Coder Connect** as enabled but the embedded tunnel is no
longer working:

* `workspace.coder` fails to resolve (`No such host`), or
* DNS returns stale `fd60:627a:a42b::/48` addresses that no longer
route, causing `coder ssh`, file sync, and the directory picker to hang.

Related issues:

* coder/coder#26669 — `ExistsViaCoderConnect` false positives when Coder
Desktop has stale DNS
* coder/coder-desktop-windows#171 — Tray reports Coder Connect as
healthy while tunnel/DNS is broken

Until the underlying state-management gap is fixed in the apps, the docs
should give users (and support) a safe, repeatable way to recover
without rebooting.

## Changes

`docs/user-guides/desktop/index.md`:

1. **New "Recovering from a stale tunnel" section** under
Troubleshooting:
* **macOS:** stop the VPN configuration with `scutil --nc stop`, quit
the app via `osascript`, restart the helper daemon in place with
`launchctl kickstart -k system/com.coder.Coder-Desktop.Helper`, flush
DNS caches, then relaunch.
* Includes a warning to **not** use `launchctl bootout`, which removes
the daemon from launchd's system domain entirely and is not
re-bootstrapped on app relaunch.
* Includes a verification step using the built-in sentinel hostname
`is.coder--connect--enabled--right--now.coder` (defined in
`tailnet/conn.go` as `IsCoderConnectEnabledFmtString`) so users don't
need a workspace name to confirm the tunnel is healthy.
* Uses `dig @fd60:627a:a42b::53` (explicit server) and `dscacheutil -q
host -a name` because plain `dig` does not respect the macOS system
resolver.
* **Windows:** stop the app and `Coder Desktop` service, flush DNS,
restart, then verify the NRPT rule and Wintun adapter. Notes that
`ipconfig /flushdns` does not reset the embedded resolver and that
filtering agents (e.g., Zscaler) may still shadow `.coder` lookups.
2. **macOS log-collection improvements:**
* Switch the predicate from `subsystem == "com.coder.Coder-Desktop"` to
`subsystem BEGINSWITH "com.coder.Coder-Desktop"` so the export captures
the app, helper daemon, and network extension (which all log under
prefixed subsystems).
* Add a `log stream` example for live tailing while reproducing an
issue.

## Verification

* `npx markdownlint-cli2 docs/user-guides/desktop/index.md` — 0 errors.
* macOS recovery steps were validated end-to-end on a real install (the
`kickstart -k` form, in particular, was confirmed to restart the helper
without breaking the install, unlike `bootout`).

---

Created on behalf of @mdanter

---------

Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
Co-authored-by: Atif Ali <atif@coder.com>
Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
Co-authored-by: Matyas Danter <mdanter@gmail.com>
2026-08-14 12:31:04 -04:00
McKayla はな e1fa247e59 feat: redirect to the template builder after first time setup (#27670) 2026-08-13 11:57:29 -06:00
Michael Suchacz 8d4d0b35dd feat: add Coder Agents chat tools to the MCP toolsdk (#28025)
Exposes the experimental Coder Agents chats API through the MCP tool
registry, so MCP clients (the hosted `/api/experimental/mcp/http` server
and `coder exp mcp server`) can start and drive server-side coding
agents.

New tools in `codersdk/toolsdk`, all thin wrappers over existing
`codersdk.ExperimentalClient` methods:

| Tool | Wraps |
|---|---|
| `coder_create_chat` | `CreateChat` (prompt, optional org, model
config, labels) |
| `coder_get_chat` | `GetChat` (status, last error, last turn summary,
workspace, files) |
| `coder_get_chat_messages` | `GetChatMessages` (user-facing parts,
chronological, cursor pagination, queued prompts) |
| `coder_send_chat_message` | `CreateChatMessage` (queue or interrupt
busy behavior) |
| `coder_interrupt_chat` | `InterruptChat` |
| `coder_archive_chat` | `UpdateChat` with `archived: true` |
| `coder_list_chat_model_configs` | `ListChatModelConfigs` (enabled
configs with default flag) |

Both MCP servers register tools from `toolsdk.All`, so no additional
wiring is needed. Responses are trimmed to what an MCP caller needs (IDs
as strings, user-facing transcripts) rather than full SDK payloads. No
new endpoints and no database changes.

Also adds MCP
[prompts](https://modelcontextprotocol.io/specification/2026-07-28/server/prompts)
for the chat workflows, defined once in `codersdk/toolsdk` and
registered by both servers:

| Prompt | Purpose |
|---|---|
| `coder_agents_delegate` | delegate a task to a Coder Agents chat and
monitor it to completion |
| `coder_agents_check` | check the status and recent activity of an
existing chat |

Each prompt declares the tools its workflow needs; the stdio server
skips prompts whose tools are excluded by `--allowed-tools`.

Tests run the tools against a chat-enabled coderdtest instance (fake
OpenAI-compatible provider plus in-process AI bridge), covering the full
lifecycle, an interrupt against a blocked turn, pagination cursors,
permission-dependent model config filtering, and argument validation.
Prompt coverage spans SDK rendering, the hosted
`prompts/list`/`prompts/get` round trip, and the stdio server including
allowlist gating.

> Mux created this PR on Mike's behalf.
2026-08-13 18:32:47 +02:00
Susana FerreiraandNick Vigilante 3426f83a27 docs: use approximate spend and add Everyone group tip for AI Gateway cost controls (#28012)
## Summary

Updates the AI Governance Cost Control docs in two ways:

- **Terminology:** aligns the docs with the UI, which now labels spend
as **approximate** rather than **estimated**. Renames the `Estimated
spend` term, the "How spend is calculated" section (and its anchor and
references), and updates the surrounding prose.
- **Everyone group tip:** adds a note that, because the organization's
`Everyone` group includes every member, its **Members** tab is a quick
way for an admin to look up any user's effective group. This complements
the existing Get user AI spend API endpoint, since there is no dedicated
cost control page today.

Related: https://github.com/coder/coder/pull/27977

---

_This PR was created by Coder Agents on behalf of @ssncferreira._

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-08-13 16:20:17 +00:00
Susana Ferreira 2d9b6eda8f feat: add experimental CLI to price unpriced AI models (#27926)
## Description

AI Gateway computes the cost of an interception from `ai_model_prices`,
which is seeded on every server start from a price book embedded in the
binary. A model the price book does not cover records a NULL cost, so
its spend is invisible to cost reporting and is not enforced against
budgets. The only fix was to wait for a Coder release that added the
model.

This adds an experimental CLI, backed by an experimental HTTP endpoint,
for pricing those models. Models the price book already covers are
rejected, because the seeder re-applies the book on every start and
would overwrite an operator price. Support for custom pricing will be
handled in
https://linear.app/codercom/issue/AIGOV-589/extend-experimental-cli-command-to-set-custom-ai-model-prices.

## Commands

```
coder exp ai-model-prices list [--provider] [--model]
coder exp ai-model-prices update [file|-] [--provider] [--model] [--input-price] [--output-price] [--cache-read-price] [--cache-write-price] [--yes]
```

## Changes

- Add `GET` and `POST /api/experimental/ai/model-prices`, gated behind
the AI Bridge entitlement and the existing `ai_model_price` RBAC
resource.
- Add a `GetAIModelPrices` query with optional `provider` and `model`
filters applied in SQL.
- Validate the whole request before writing anything, so one bad entry
cannot leave the table half updated, and report every problem at once.
- Reject prices for models the embedded price book already covers,
through a new `prices.IsDefaultPriced`.
- Add the `coder exp ai-model-prices` command with `list` and `update`.
`update` accepts a JSON document or the single-model flags and prints a
plan, asking to confirm unless the document is piped in or `--yes` is
passed.
- Consolidate the supported provider list into
`coderd/aibridge/prices/providers` so the price generator and the server
share one definition.
- Add `codersdk` types and client methods for both endpoints, and bound
the request body at 1 MiB.
- Document the command in the AI Gateway cost controls page.

Closes
https://linear.app/codercom/issue/AIGOV-567/experimental-cli-command-to-set-prices-for-unpriced-ai-models

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by
@ssncferreira
2026-08-13 15:00:36 +01:00
Michael Suchacz e92fd8e96f chore: retire mark3labs/mcp-go dependency (#28061)
## Stack Context

PR 6 of 6 in a stack that migrates every Coder MCP surface from the
archived `github.com/mark3labs/mcp-go` library to the official
`github.com/modelcontextprotocol/go-sdk` v1.7.0.

Stack: #28056 -> #28057 -> #28058 -> #28059 -> #28060 -> #28061

## Why

With every production surface migrated, this PR removes the mark3labs
dependency entirely and converts the remaining test fixtures.

- Migrates the remaining mark3labs test fixtures (coderd MCP e2e tests,
chatd fixtures, mcpclient fixtures, and the Force On MCP policy tests)
to official stateless SDK servers.
- Removes `github.com/mark3labs/mcp-go` from `go.mod` and drops the
corresponding dependabot ignore entry. Zero references remain repo-wide.
- Updates the MCP docs for the 2026-07-28 protocol: stateless Streamable
HTTP behavior, the supported 2024-11-05 through 2026-07-28 protocol
range, and explicit non-features (resources, prompts, structured output,
elicitation, MCP Tasks).
- The e2e ping assertion is removed because MCP 2026-07-28 removed the
ping method.

> Mux created this PR on Mike's behalf.
2026-08-13 10:47:14 +00:00
Steven Masley f0c17291b3 feat: unhide --oidc-redirect-url server option (#28072)
Unhides the `--oidc-redirect-url` / `CODER_OIDC_REDIRECT_URL` server
option so it appears in `coder server --help` and the deployment
configuration docs.

- Removed `Hidden: true` from the option in `codersdk/deployment.go`
- Regenerated CLI golden files and docs via `make gen`

---

> Generated with Coder Agents on behalf of @Emyrk
2026-08-12 16:02:15 -05:00
Bobby Ho 209d1ca498 fix: reject PKCE code_verifier below RFC 7636 length floor (#28003)
The token endpoint accepted any non-empty `code_verifier`, so a
one-character verifier was enough to authenticate. RFC 7636 §4.1
requires 43 to 128 characters from the unreserved set.

That fix plus the related gaps review surfaced in the same path:

- Enforce the length and charset floor on the verifier before the S256
comparison runs.
- Validate the challenge at the authorize endpoint too. It was only
checked for non-emptiness, so a malformed challenge was stored and then
failed late at token exchange, blaming the wrong parameter.
- A malformed verifier now returns `invalid_request` (RFC 6749 §5.2); a
well-formed but wrong one still returns `invalid_grant` (RFC 7636 §4.6).
Both looked identical before, so a client had no way to tell a syntax
error from a hash mismatch and would retry the same bad verifier
forever.
- Revoke the authorization code when a PKCE check fails. Without that, a
leaked code could be replayed with unlimited verifier guesses for its
remaining lifetime, and RFC 6749 §10.5 requires codes to be single use.
- Fix verifier generation in `scripts/oauth2/*.sh` and the docs example.
They deleted reserved base64 characters instead of translating them to
the URL-safe alphabet, so most runs produced verifiers under the new
floor.

Also carries #28041, which merged into this branch: public clients may
register bare custom schemes such as `vscode://` again, with `mailto`,
`tel`, and `sms` rejected.

Split out of #27873 (public OAuth2 client support). PKCE is already
mandatory for every client, so this stands on its own.

<details>
<summary>Manual verification</summary>

Ran against a local dev server on this branch, using a session token and
a throwaway app from `scripts/oauth2/setup-test-app.sh`.

1. Happy path unchanged: HTTP 200, verifier length 43.
2. `code_verifier=short`, and a 43-character verifier ending in `!`:
both HTTP 400 `invalid_request`, so charset is enforced and not just
length.
3. `code_challenge=tooshort` at authorize: HTTP 400 `invalid_request`,
no code issued. An empty challenge still hits the older "required and
cannot be empty" message.
4. Well-formed but wrong verifier: HTTP 400 `invalid_grant`, distinct
from the cases above.
5. Retrying that same code with the correct verifier: HTTP 400, code
already revoked by the failed check.
6. `generate-pkce.sh` produces a 43-character verifier (20 out of 20
runs); the docs example produces 128.
7. `scripts/oauth2/test-mcp-oauth2.sh` passes end to end. The two
bearer-token failures in its output are a pre-existing script bug
(`09c50559f3`, July 2025) that reuses a resource-scoped token against
the real API, not a regression here.

</details>
2026-08-12 13:36:52 -07:00
Michael Suchacz 1458d27d78 fix: allow manual chat compaction from the error state (#28022)
A chat that fails generation with a context overflow (for example `Input
length 262625 exceeds the maximum allowed input length of 262112
tokens`) is stuck in a catch-22: `POST /chats/{id}/compact` returns 409
because the `RequestCompaction` transition is only allowed from the
waiting state, and the only other way out of the error state is sending
or editing a message, which re-runs generation with the same oversized
prompt and fails again. Compaction is exactly the recovery a
context-overflowed chat needs, and it is unreachable exactly when it is
needed.

Three semantic changes:

- Allow `RequestCompaction` from the error states: `E0 -> R0` and `E1 ->
R1` (queued messages are preserved and processed after the compaction
turn).
- Clear `last_error` in `Tx.RequestCompaction`, matching the
architecture rule that transitions leaving `E0`/`E1` clear the stored
error. Without this a successful compaction would land in waiting with a
stale persisted error.
- Grant the compaction turn a fresh history epoch: a
`grant_history_epoch` flag on `UpdateChatExecutionState` sets
`history_version = snapshot_version`, resets `generation_attempt`, and
clears `retry_state` in the same atomic update that clears `last_error`
(mirroring the `chat_messages` trigger postcondition). The transition
inserts no history, so without this the turn inherits the failed turn's
spent retry budget, and resetting the counter alone could collide with
message part episode keys still retained on the erroring replica.

No frontend change is required: the chat input is already enabled in the
error state and `/compact` submission already handles both the success
and 409 paths. Also updates ARCHITECTURE.md (transition matrix,
endpoint, and manual compaction sections), the endpoint's swagger
description, and SDK comments.

> Mux created this PR on Mike's behalf.

<!-- mux-attribution: model=claude-sonnet-4-6 thinking=high -->
2026-08-12 20:38:57 +02:00
Matt Vollmer 52bd05adb4 docs: remove AI Governance Add-On references (#28073)
## Summary

Replaces all remaining "AI Governance Add-On" references with language
consistent with AI Governance being included with a Premium license.

**`docs/ai-coder/ai-gateway/standalone.md`**

- Admonition: "AI Gateway requires the AI Governance Add-On...
deployments without the add-on will not be able to access" → "AI Gateway
requires a Premium license. Community deployments cannot access AI
Gateway."
- Requirements list: "A Coder license with the AI Governance Add-On" →
"A Premium license with AI Governance"

**`docs/install/airgap.md`**

- Table row: "deployments with the AI Governance Add On" → "deployments
with AI Governance"

**`docs/reference/glossary.md`**

- Agent Firewall, AI Gateway, AI Gateway Proxy entries: "This feature
requires the AI Governance Add-On" → "This feature requires a Premium
license"
- Agent Workspace Build entry: "the AI Governance Add-On expands the
allowance" → "a Premium license expands the allowance"
- Heading: "### AI Governance Add-On" → "### AI Governance"
- Definition: "A separate per-user license for Premium customers,
purchased on top of a Premium subscription..." → "Included with a
Premium license, AI Governance unlocks..."

**`docs/ai-coder/ai-governance.md`**

- Removed the "Identifying AI seat consumers" section (heading through
end of file), which described an "AI add-on column" in the UI

## Note

References to Agent Workspace Builds will be eliminated in a separate PR
that removes Coder Tasks from the docs.

---

PR generated with Coder Agents.
2026-08-12 11:35:36 -04:00
Danielle Maywood c424a76a12 feat: wire chat search box to full-text search (#27973) 2026-08-12 15:04:01 +01:00
Cian Johnston e5629126b7 docs: document prebuilds quota group behavior (#28015)
Documents the behavior of the prebuilds quota group so admins can find
it and understand why the `prebuilds` user doesn't appear in its member
list.

Clarifies that prebuilt workspaces are attributed to a group named
`coderprebuiltworkspaces` (often referred to as the **Prebuilt
Workspaces** group), which defaults to a quota allowance of 0 and should
be adjusted to match the desired prebuild pool size. Adds a note that
the `prebuilds` user is a system user and is hidden from group member
listings in the dashboard and API.

> 🤖 This change was generated by Coder Agents (https://coder.com).
2026-08-11 17:01:34 +01:00
Nick Vigilante 0a7bb80a1e feat: make CLI/API doc generators emit front-matter metadata (Phase 2) (#27246)
## Summary

Phase 2 of the H1 → front-matter migration (`DOCS-483`; parent
`DOCS-477`). Makes the two reference-doc generators emit per-page
metadata as YAML front matter instead of a leading `# H1`, so generated
pages are self-describing and `make gen` stops reverting migrated pages
(Phase 3).

Phase 1 (`DOCS-482`) made the coder.com renderers prefer a front-matter
`title` (manifest fallback).

> [!NOTE]
> Rebased onto `main` and fully regenerated, and updated across two
rounds of Coder Agents Review — see **Review follow-ups** below.

## Changes

- **`scripts/clidocgen/command.tpl` + `gen.go` + `main.go`** — front
matter now carries `title` (from `fullName`) and `description` (from the
command's `Short`), and the leading `# H1` is dropped. The CLI index
page's front matter is taken from the manifest `Command Line` route
(title/description/icon_path).
- **`scripts/apidocgen/postprocess/main.go`** — reads the manifest and,
at write time, injects front matter carrying each section's `title` plus
any curated `description`, `state`, and `icon_path`. The API index
page's front matter is taken from the manifest `REST API` route.
- **`scripts/docgenenv`** (new shared code) — one `YAMLScalar`
front-matter escaper, one `Route`/`Manifest` schema +
`LoadManifest`/`FindRoute`, and one `FrontMatter(Route)` emitter, all
imported by both generators (no duplicated helpers, types, or emitters).
- Regenerated all **166 CLI + 31 API** reference pages.

### Metadata → front matter, and what stays in the manifest

Every *per-page* manifest field is mirrored into the page's front
matter: `title`, `description`, `state`, `icon_path`. The **structural**
fields stay in `manifest.json`:

- `children` — the nav tree (explicitly out of scope).
- `path` — the manifest's pointer to the file; a page carrying its own
path is redundant/error-prone, so it's treated like `children`.

The fields are **duplicated** into front matter and **`manifest.json` is
left unchanged**, so this is a **no-op for rendering today** (coder.com
strips front matter for `llms`, and Algolia + the renderer read only
`title`). Removing the fields from the manifest is the natural
follow-up, gated on the renderer reading them from front matter first.

### Why the API side changes the postprocessor, not the `.dot` templates

The issue text suggested editing
`scripts/apidocgen/markdown-template/*`. I deliberately did **not**,
because the postprocessor derives each page's **filename, section title,
and manifest route** from the leading `# {name}` line
(`extractSectionName`). Emitting front matter from the template would
break that extraction. Instead the widdershins templates still emit `#
{name}`, the postprocessor reads it (and now verifies it), and then
swaps the heading for a front-matter block as each section is written.

## Review follow-ups (Coder Agents Review)

### Round 1 — addressed in `e53d5e03` (all threads resolved)

- **CRF-1 / CRF-4** — de-duplicated the escaper and the
`route`/`manifest` schema + traversal into `scripts/docgenenv` (shared
by both generators).
- **CRF-2** — `YAMLScalar` now quotes YAML-reserved scalars
(`true/false/null/…`, numbers); no current value is affected.
- **CRF-3** — added unit tests: a `YAMLScalar` round-trip, `FindRoute`,
and `prependFrontMatter`.
- **CRF-5** — the CLI and API **index** pages now mirror their manifest
route's title/description/icon_path instead of a hardcoded
`coder`/`API`, fixing a rendered-heading regression (`REST API`/`Command
Line` were being overwritten).
- **CRF-6** — dropped the dead `#login` anchor in
`docs/support/support-bundle.md` (the migrated `login.md` no longer
mints that heading anchor).
- **CRF-7 / CRF-8 / CRF-11** — renamed to `prependFrontMatter`, switched
to `bytes.Cut`, and it now strips the first line only when it is the `#
{name}` heading (`extractSectionName` errors otherwise).
- **CRF-9** — removed the orphan `docs/reference/api/chat.md` (not in
the manifest, not linked; the real page is `chats.md`).
- **CRF-10** — the metadata read and the manifest rewrite now share one
`FindRoute` traversal.
- **CRF-13** — moot under squash-merge; this branch is a single
scopeless commit.
- **CRF-15** — the pre-existing `sort.Slice`/`slices.IsSorted`
comparator is left as-is per the review (out of scope; safe today
because section names are unique).

### Round 2 — addressed in `ee796e7107` (all threads resolved)

- **CRF-16** (P1) — removed three em-dashes from new doc comments (the
only `make lint` failure on the prior head); the emdash gate is green.
- **CRF-17 / CRF-18** — unified front-matter emission into one shared
`docgenenv.FrontMatter(Route)`, used by the API postprocessor directly
and by `command.tpl` via a `frontMatter` template func. This retires the
hand-written template YAML and the
`indexTitle`/`indexDescription`/`indexIconPath` closures, so a new
front-matter field is wired in one place, and it gives the CLI index the
`state` arm it previously lacked. Verified byte-identical: a full CLI +
API regen produces zero page changes.
- **CRF-19** — CLI child sort switched to `slices.SortFunc` +
`cmp.Compare` (typed comparator).
- **CRF-20** — reworded the `prependFrontMatter` comment:
`extractSectionName`'s fail-fast is the load-bearing guard; the prefix
check is a defensive backstop.
- **CRF-21** — added `icon_path`/`state` coverage in `docgenenv`'s
`TestFrontMatter/AllFields` (the branch the index page relies on,
previously at 0%).
- **CRF-22** — `YAMLScalar` no longer emits a trailing-space value as a
bare scalar (YAML strips it on read, so it would not round-trip); added
test coverage.
- **CRF-24** — the shared emitter removed the duplicated `cliIndexRoute`
doc comment; the rationale now lives in one place.
- **CRF-23** (Phase 3, out of scope here) — noted: the API generator
wipes and regenerates `reference/api/` from the manifest, so removing
curated metadata from the manifest in Phase 3 needs another source first
(a generator that preserves existing front matter, or metadata carried
alongside the swagger annotations).
- **Process (Mafu-san)** — the verification set below now leads with
`make lint`, the mandatory CI gate that the earlier list omitted.

## Cross-repo dependency

**Resolved — this PR no longer has a hard merge-ordering gate** (CRF-14
was right; the earlier "must merge after #968" note was stale).

The coder.com surfaces that would otherwise leak raw front matter from
`coder/coder` `main` are already front-matter-aware on merged PRs:

- **coder.com#964** (`DOCS-554`, llms-full.txt corpus + Algolia) —
**merged**.
- **coder.com#974** (`DOCS-574`, the `.md` proxy twin + `llms.txt` index
titles) — **merged**.

coder.com#968 (`DOCS-577`) was re-scoped to only the renderer
route-metadata generalization; it's a no-op on today's corpus and its
own description confirms the "deploy before the generators" constraint
no longer applies (that was driven by the llms corpus, now in #964).
Worth a final confirmation that #964/#974 are **deployed** before merge,
but there's no branch/PR ordering blocker left.

## Verification & evidence

AI was the primary author of this PR (see disclosure below); per the [AI
Contribution
Guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING)
here is manual verification.

- `make lint` (golangci-lint + the emdash gate) passes; `go build` / `go
vet` / `go test` are clean for the generators + `scripts/docgenenv`;
`pnpm check-docs` passes.
- `swagger.json`, `docs.go`, and `manifest.json` are **unchanged** —
metadata is duplicated into front matter; command/section names and
routes did not move.
- The diff is purely additive front matter
(`title`/`description`/`state`/`icon_path`) + the leading H1 removal; no
body reflow. A full CLI + API regen produces **zero** page changes
beyond the two index pages.

<details>
<summary>Terminal evidence</summary>

CLI `description` from the command's `Short` (`YAMLScalar` quotes when
needed, e.g. a `Short` with a colon):

```md
---
title: server
description: Start a Coder server
---
```

API pages inherit curated manifest metadata (only Agents/Chats have any
today):

```md
---
title: Chats
description: "REST endpoints for Coder Agents Chats API (programmatic agent sessions)."
state:
  - early access
---
```

Diff scope + "no body changes" proof (uses an explicit `base..HEAD`
range, so it actually tests the claim):

```
$ git diff --shortstat origin/main
 210 files changed, 1447 insertions(+), 344 deletions(-)
# = 166 CLI + 31 API reference pages + generators + scripts/docgenenv
# swagger.json / docs.go / manifest.json: NOT modified

# Every removed line under docs/reference is a leading "# H1"; nothing else:
$ git diff origin/main..HEAD -- docs/reference/ | grep '^-' | grep -v '^---' | grep -v '^-# '
(empty)

$ pnpm check-docs
Summary: 0 error(s)
```

</details>

Linear: DOCS-483

> This PR was created with AI assistance (Coder Agents).
2026-08-11 15:22:55 +00:00
Atif Ali d7953bd046 fix(coderd): use service account wording in account notifications (#27536) 2026-08-11 13:16:25 +00:00
Matt VollmerandNick Vigilante 75e0790cd7 docs: remove beta references from Coder Agents docs and manifest (#27939)
Removes all references to "beta" from the Coder Agents documentation
under `docs/ai-coder/agents/` and the corresponding `"state": ["beta"]`
entries in `docs/manifest.json`. Also updates screenshots, video, and
hero image, and regenerates the auto-generated feature-stages table.

**Beta reference removal:**
- `getting-started.md`: Removed "Coder Agents is in Beta" from the top
note, "is in beta" from the Chats API note, and "during Beta" from the
feedback section. Removed the version/stability note pinning 2.33.1.
- `index.md`: Removed the "Product status" section that stated Coder
Agents is in Beta.
- `manifest.json`: Removed `"state": ["beta"]` from 17 entries for pages
under `docs/ai-coder/agents/`. Preserved all `premium` and `early
access` states.
- `feature-stages.md`: Regenerated the auto-generated beta features
table, which no longer lists Coder Agents.

**Asset updates:**
- `coder-agents-ui.mp4`: Updated demo video on the agents landing page.
- `llm-providers.png`: Updated LLM provider support screenshot.
- `models-list.png`: Updated models list screenshot.
- `models-add-model.png`: Updated add model form screenshot.
- `agents-hero-image.png`: Updated hero image on the `docs/ai-coder`
landing page.

Two references in `models.md` (`v1beta` in the Google Gemini API URL and
`anthropic-beta` in the Anthropic header name) were left unchanged as
they are provider API identifiers, not product status labels.

PR generated with Coder Agents

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-08-11 08:57:57 -04:00
Michael Suchacz 57f38b5c24 fix: keep chat attachments while a linking chat exists
Fixes https://linear.app/codercom/issue/CODAGT-616/keep-chat-attachments-while-chats-remain-unarchived

Chat attachments could disappear even though the chat was still available. This happened when a message was saved without recording which attachments it used, or when cleanup deleted attachments before an archived chat itself was removed.

Creating a chat, sending or queuing a message, and editing a message now record both the message and which attachments it uses as one operation. If the chat is already at the 50-attachment limit, the chat change fails without being partially saved.

Concurrent attachment writes serialize the 50-file cap per chat. Cleanup locks candidates and checks again for new links before deleting. If a file becomes unavailable after input validation, create, send, and edit return a clear client error and roll back the chat change.

An attachment stays available while any chat that uses it still exists. After an archived chat reaches the end of its retention period and is deleted, an old attachment that no remaining chat uses can be cleaned up. The retention guide and unavailable-attachment UI text document this lifecycle. This change cannot restore attachments that were already deleted.

The database migration adds two indexes so attachment cleanup stays fast as attachments accumulate.

> This PR was authored by Mux (AI) on Mike's behalf.
2026-08-11 13:53:15 +02:00
Atif Ali b781be0fa2 docs: refresh JFrog Artifactory integration guide for SaaS (#28005)
## Summary

Refreshes the JFrog Artifactory integration guide to cover JFrog SaaS.
The JFrog-OAuth section previously implied the module was self-hosted
only and mixed the SaaS and self-hosted setup into one ambiguous step.

## Changes

- **JFrog-OAuth**: State the module works with both JFrog SaaS and
self-hosted (on-premises) Artifactory.
- **JFrog-OAuth**: Split setup into a SaaS UI flow (**External
Applications** > **Custom Integration**) and a self-hosted Helm
integration-template flow.
- **JFrog-OAuth**: Update the module example to
`registry.coder.com/coder/jfrog-oauth/coder`, `1.2.4`.
- **JFrog-Token**: Update the stale example to
`registry.coder.com/coder/jfrog-token/coder`, `1.2.2`.

## Validation

- `markdownlint-cli2` passes on the file.
- No emdash/endash.

Preview:
https://coder.com/docs/@matifali/jfrog-oauth-docs-saas/admin/integrations/jfrog-artifactory#jfrog-oauth

Related to the registry README refresh in coder/registry#1040.

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

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑‍💻
2026-08-11 02:18:39 +05:00
Andrew Aquino 6e07e2610f feat: add paginated API endpoint for groups (#27603)
backend-only changes from #27271; see that PR for summary of changes +
implementation details
2026-08-10 13:23:14 -07:00
J. Scott Miller 66b065323b feat: log rate-limited external auth token validation (#26754)
When `ValidateToken` keeps a token because the external auth validation
endpoint was rate-limited (a `403` with rate-limit headers or a `429`),
it returns `valid=true` without provider confirmation. Previously this
happened silently, so operators couldn't tell a provider-confirmed token
from one kept optimistically during a rate limit.

This adds a `Logger` to `externalauth.Config` and emits a `Warn` (with
`provider_id`, `provider_type`, `status_code`, and `reason`) on those
rate-limit branches. It also adds a
`coderd_oauth2_external_requests_rate_limited_total{name, source,
status_code}` counter, incremented in the instrumented round tripper
whenever a provider returns a rate-limited response. The rate-limit
detection is the shared `xhttp.IsRateLimited` (in `coderd/util/xhttp`),
used by both the tripper and `ValidateToken` so the metric and the
validation decision share one definition; no extra wiring is needed
since `ValidateToken` already routes through the instrumented client
with `source="ValidateToken"`.

One deliberate behavioral change rides along: rate-limit detection now
also recognizes the unprefixed `RateLimit-Remaining` header (GitLab, and
the IETF draft rate-limit headers), so a `403` with
`RateLimit-Remaining: 0` is treated as optimistically valid where it was
previously treated as revoked. All other valid/invalid decisions are
unchanged. `TestValidateToken` asserts the warning's fields on the
rate-limited cases and no warning for revocations, `401`, and confirmed
responses; `promoauth` and `xhttp` tests cover the detector and the new
counter.

<details>
<summary>Manual testing</summary>

The signals fire on the external-auth status check (`GET
/api/v2/external-auth/{id}`), which calls `ValidateToken`. To force a
rate-limited response, point a provider's `validate_url` at a mock that
returns the rate-limit shape:

1. Run a mock returning `429` on one path and `403` +
`X-RateLimit-Remaining: 0` on another.
2. Start `coder server` with `--prometheus-enable` and external auth
providers whose `validate_url` point at those mock paths (e.g.
`CODER_EXTERNAL_AUTH_0_VALIDATE_URL=http://127.0.0.1:5599/429`).
3. Create a stored link, either complete the OAuth flow, or insert a row
into `external_auth_links` with a future `oauth_expiry` (token contents
are irrelevant; the mock rejects regardless).
4. `curl` the status endpoint with a session token, then check:
- coderd logs for the `Warn` (`reason=status_code` for `429`,
`reason=rate_limit_headers` for `403`),
- the metrics endpoint for
`coderd_oauth2_external_requests_rate_limited_total{...,status_code="429"|"403"}`.

Notes: `scripts/testidp -429` only rate-limits `/oauth2/userinfo`, not
the `/external-auth-validate/...` path, so it does not exercise this;
use a mock `validate_url`. The default Prometheus port `2112` may
already be taken on dogfood workspaces, set `CODER_PROMETHEUS_ADDRESS`
to a free port.

</details>

🤖 Generated with the help of Coder Agents on behalf of @jscottmiller.
2026-08-10 14:43:16 -05:00
Steven Masley 9a57dfa642 feat: include agent metadata in workspace list responses (#27934)
Closes #27933. Related: #27897 (single-agent GET).

Agent metadata is only readable via a per-agent watch stream, so reading
it across N workspaces costs N+1 requests. This adds a batch read to the
list endpoint:

```text
GET /api/v2/workspaces?q=param:"pool=demo" include_agent_metadata:task_status
```

- New `include_agent_metadata` search key, repeatable and key-scoped. It
expands the response, it does not filter workspaces.
- `GetWorkspaces` aggregates the requested keys as JSON behind a `CASE`:
without opt-in the response is unchanged and the subquery never runs.
Runs only for the returned page, inside the same authorized query.
- Agents in the response gain `metadata`
(`[]codersdk.WorkspaceAgentMetadata`, `omitempty`), mapped by the
`workspace_agent_id` each element carries. The collection script is
omitted; it can be long.
- `codersdk.WorkspaceFilter` gains `IncludeAgentMetadata []string`.
- No wildcard, no schema change, no migration.

---

Authored by Coder Agents on behalf of @Emyrk.
2026-08-10 08:13:32 -05:00
Marcin Tojek cfeae56bed chore(docs): update release docs for v2.35.4 (#27972)
Automated docs update for v2.35.4 release.

Created by `releasetui`.
2026-08-10 11:53:47 +02:00
Marcin Tojek 0414948454 chore(docs): update release docs for v2.34.8 (#27970)
Automated docs update for v2.34.8 release.

Created by `releasetui`.
2026-08-10 09:52:49 +02:00
Ethan ee49107ea9 docs: document per-template agents_allowed (#27518)
Relates to CODAGT-713

Depends on #27517

This updates the Coder Agents platform controls documentation for the
per-template `agents_allowed` model. It replaces the deployment-wide
allowlist instructions with the **Agents allowed** controls in AI
Settings and template settings, documents that templates allow agents by
default, and explains that disabled templates are excluded from
`list_templates`, `read_template`, and `create_workspace`.

This is the final PR in the stack and aligns the template routing and
optimization guidance with the database, API, frontend, cleanup, and CLI
changes in the preceding PRs.
2026-08-07 17:23:28 +10:00
Samuel Volin 50640063a2 feat: DEVEX-732 premium badging (#27847)
Premium badging and gating consistency

as a OSS user, I want to be upsold to premium, and tastefully

Summary

Standardize all base-Premium full-page gates and the two named inline
notices. Admins see an in-app “Learn about Premium” path; non-admins are
told to contact their deployment administrator.
* DEVEX-732
* updates for premium docs pages for consistency
* updates for premium badging and paywall components
* updates implemented uses of premium badge and premiumpaywall


| Before | After |
| --- | ----------- |
| <img width="1271" height="564" alt="Screenshot 2026-08-04 at 3 02
32 PM"
src="https://github.com/user-attachments/assets/027d4bca-3e34-40b2-ad69-28dbaa4a004b"
/> | <img width="1273" height="600" alt="Screenshot 2026-08-04 at 3 26
37 PM"
src="https://github.com/user-attachments/assets/321083c0-7a4c-4c7e-a19c-059807018d3b"
/> |

| Before | After |
| --- | ----------- |
| <img width="1084" height="672" alt="image"
src="https://github.com/user-attachments/assets/741e6bd9-93b0-4ae0-97df-027e8aba5716"
/> | <img width="1289" height="622" alt="Screenshot 2026-08-04 at 3 20
07 PM"
src="https://github.com/user-attachments/assets/b3a8c169-ca6e-439b-8752-9209131fc097"
/> |

| Before | After |
| --- | ----------- |
| <img width="1091" height="865" alt="image (1)"
src="https://github.com/user-attachments/assets/f7cd92dd-a975-4db0-bc2a-af092ba783ce"
/> | <img width="1268" height="680" alt="Screenshot 2026-08-04 at 3 37
06 PM"
src="https://github.com/user-attachments/assets/8af8081a-0ec9-4fd3-921c-470127f2328b"
/> |
2026-08-06 12:13:12 -06:00
Nick Vigilante 2d320de71e docs(docs/.style/style-guide): adopt STE-derived prose rules (#27852)
Stacked on #27849.

Incorporates the transferable rules from [ASD-STE100 Simplified
Technical English](https://www.asd-ste100.org/) (Issue 9, 2025) into the
prose style guide, with per-rule attribution to the source rule numbers.
STE is the controlled-language standard for aerospace maintenance
documentation; this PR adopts its procedure-level discipline and clarity
rules, not its controlled dictionary or grammar restrictions, which
target a different audience.

- New **Procedural writing** page: one instruction per step, condition
before instruction, 20-word step budget, "callouts inform, steps
instruct" (with the delete-the-callouts test), and warnings must state
the consequence.
- **Voice and tone**: sentence and paragraph budgets, verbs over noun
forms, one clear referent per pronoun, and an explicit acknowledgment of
the contractions trade-off for international readers.
- **Word choice**: one term per concept, anchored on the glossary.
- **Accessibility and inclusion**: the idioms rule now covers developer
figurative verbs (spin up, tear down, stand up).
- **README**: registers the new page and adds ASD-STE100 to the
third-party references.

All new rules are documentation-only (no Vale rule) because they need
editorial judgment rather than pattern matching.

---

🤖 Built with AI assistance.
2026-08-06 10:17:41 -04:00
Nick Vigilante aa039479ed docs: add style-guide rule against "whose" for non-person antecedents (#27866)
## What

Adds a Word choice entry to the docs style guide, **"Whose for people,
not things"**. It restricts "whose" to people and points writers to
"with", "where", or "that has" for inanimate objects and abstract
concepts, since "whose" implies personhood.

## Where

`docs/.style/style-guide/word-choice.md`, inserted right after **Phrasal
verbs and their noun forms**, the closest existing grammar/usage rule.
Formatting matches the surrounding entries: sentence-case H2, a
two-sentence rationale (one sentence per line), `**Do**` / `**Don't**`
blockquotes, and a documentation-only enforcement note.

## Rule

> "Whose" is the possessive of "who", so it implies the antecedent is a
person.
> When the antecedent is an inanimate object or an abstract concept,
prefer "with", "where", or "that has".

Example:

- Don't: A chat whose gateway records have been pruned reports no cost.
- Do: A chat with pruned gateway records reports no cost.

## Notes

- Docs-only change (Markdown under `docs/`, no CI or build config), so
it's out of scope for `/coder-agents-review`; the doc-check agent covers
docs-only PRs.
- The style-guide subpages are Vale-exempt, so no Vale rule ships with
this. The enforcement note reads "Documentation-only. No Vale rule.",
matching the other documentation-only entries.

Linear:
[DOCS-612](https://linear.app/codercom/issue/DOCS-612/style-guide-avoid-whose-for-non-person-antecedents)

> This PR was created with AI assistance (Coder Agents).
2026-08-06 10:00:44 -04:00
4b7494be72 feat: harden chat generation runtime instrumentation for billing (#27451)
Closes CODAGT-835

## Summary

`chat_messages.runtime_ms` becomes the billing source of truth for Coder
Agents runtime (summed hourly by #27312), but it was built for
debugging: the June refactor (#26270) silently stopped recording
tool-step runtime, compaction was never measured, and interrupted turns
lost their partial runtime entirely. This PR defines the billable
metric, closes the paths that dropped it, and documents the definition
where the data lives.

## The billable definition

**`runtime_ms` is the wall-clock duration of the model invocation that
produced the persisted message content**, measured from just before the
provider stream opens until it is fully consumed.

What counts:

- Assistant generation steps, in top-level and sub-agent chats
(sub-agents are ordinary chats on the same generation path).
- Compaction summarization calls, persisted on the compaction assistant
message (**new**).
- Interrupted attempts: the message-part episode's lifetime is persisted
on the partial assistant message committed by `FinishInterruption`, so
partial generation time survives interruption (**new**; measured via a
new `Buffer.EpisodeDuration`, which works even though the generation
goroutine and the interrupt task are different tasks).

What deliberately does not count (each is documented in code and docs):

- **Local tool execution.** Tool wall time includes idle waits, most
importantly `wait_agent` polling a sub-agent chat that already bills its
own model invocations; billing the batch would double count, and
excluding one tool from a concurrent batch's wall time is ill-defined.
Pre-refactor instrumentation did include tool time; this makes the
exclusion an explicit product definition instead of a silent regression.
- **Failed model calls whose output is discarded** (retried attempts,
terminal errors, content-filter refusals). They persist no content, so
they bill nothing; billing errs toward undercounting. Notably a
stream-silence timeout can burn 10 idle minutes before a retry, which
should not be billable "active generation". If product later wants
failed attempts billed, that needs a place to persist runtime on error
turns (`FinishError` inserts no rows today) and is a deliberate
follow-up, not instrumentation drift.
- **Ancillary calls that produce no chat messages** (title generation,
advisor, turn summaries) and all idle/parked time (`requires_action`,
queueing).

The definition is documented as `COMMENT ON COLUMN
chat_messages.runtime_ms` (migration 000551, surfacing as a Go doc
comment on `ChatMessage.RuntimeMs`), on
`chatloop.PersistedStep.Runtime`, in the chatd architecture doc, and in
the Spend Management docs page.

## Index for the hourly scan

None needed: `GetTotalChatMessageRuntimeMsInRange` (#27312) filters an
hour-wide `created_at` range, which the existing
`idx_chat_messages_created_at` b-tree already serves; the residual
`runtime_ms IS NOT NULL` filter applies to one hour of rows. A partial
index would add permanent write amplification for a query that runs once
an hour.

> [!NOTE]
> Migration 000551 is also claimed by #27312; whichever merges second
renumbers via `fix_migration_numbers.sh`.

## Tests

- End-to-end: the existing full-server generation test now asserts
`RuntimeMs.Valid` on the committed assistant row (it previously read
`.Int64` without checking `.Valid`, so it passed on NULL).
- Interrupted turn: full task-level test (real DB, mock clock) asserting
the partial assistant message persists the attempt's runtime.
- Errored stream: asserts a failed invocation yields no step and no
runtime.
- Tool-using turn: asserts runtime lands on the assistant row only and
tool rows stay NULL.
- Compaction: asserts the summarization call duration is recorded and
lands on the compaction assistant message only.
- `messagepartbuffer.EpisodeDuration` unit coverage.

Blocks: CODAGT-843 (B3), CODAGT-838 (D8).

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Hugo Dutka <hugo@coder.com>
2026-08-06 16:09:38 +07:00
Jake Howell 3e0b943333 docs: note bulk stop confirmation (#27908)
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell.

## What

Restores the docs change that was reverted out of #27631. The bulk
**Stop** action now shows a confirmation dialog (shipped in #27631), so
the workspace management docs should reflect that stop, alongside update
and delete, prompts for confirmation.

## How

Updates the Bulk operations section of
`docs/user-guides/workspace-management.md` to note that stop is now
included in the actions that prompt for confirmation before running.

<details>
<summary>Reverted change being restored</summary>

Before:

> For update and delete, the user will be prompted for confirmation
before any action is taken.

After:

> For update, delete, and stop, the user is prompted for confirmation
before any action is taken.

This content was originally added in #27631 (commit `e6a0aff`) and
reverted in commit `2378960` before merge.

</details>
2026-08-06 16:40:18 +10:00
Ethan 78b5a0f5a2 feat(cli): add --agents-allowed to template commands (#27517)
Relates to CODAGT-713

Depends on #27515

This adds `--agents-allowed` to `coder templates create` and `coder templates edit`. Template creation defaults the option to true, matching the per-template API and database default, while template editing only changes the value when the flag is explicitly supplied so unrelated edits preserve the existing setting.

The generated CLI help and reference documentation include the new option. #27518 updates the Coder Agents platform controls documentation to describe the completed per-template model.
2026-08-06 14:45:38 +10:00
Ethan 0ac23e3ee1 feat: add per-template Coder Agents access control (#27285)
Relates to CODAGT-713

Depends on #27284

This makes the per-template `agents_allowed` field authoritative in the API and chatd. It adds optional create and metadata update fields with the intended default and omission semantics, supports `agents-allowed:` template search, includes the value in telemetry, and makes `list_templates`, `read_template`, and `create_workspace` read the template row directly. Existing-workspace retries remain idempotent, and blocked same-organisation templates return an actionable message.

The experimental `/template-allowlist` routes remain temporarily because the shipped AI Settings page still calls them, but they no longer control chatd enforcement. #27514 moves that page to per-template metadata, #27515 removes the legacy storage, routes, SDK types, and utility, #27517 adds the CLI flags, and #27518 updates the platform controls documentation for the per-template model, directly addressing CRF-5 and CRF-6. The stack is intended to merge as a unit.
2026-08-06 14:14:37 +10:00
Ethan b3485d9b3a chore: add agents_allowed to templates (#27284)
Relates to CODAGT-713

This adds `templates.agents_allowed` as a default-true, auditable template attribute, along with nullable database filtering. Migration `000562` translates the effective legacy `agents_template_allowlist` state for existing templates: a valid nonempty list allows matching templates and blocks the rest, missing or empty values leave templates allowed, whilst corrupt values fail closed by blocking all existing templates. As per the linear issue, new templates deliberately default to allowed under the per-template model.

This is the database-only first PR in the stack. #27285 makes the field authoritative in the API and chatd whilst temporarily retaining the compatibility routes needed by the shipped frontend. Later PRs migrate the UI, remove the legacy storage, routes, SDK types, and utility, then add CLI flags.
2026-08-06 14:04:23 +10:00
david-fraley 0d0c6e53ba fix(coderd): document HTTP 201 for workspace and build creation (#27903) 2026-08-05 22:17:59 +00:00
Michael Suchacz 4b9880afa6 feat: add --chat-hook-allow-insecure to allow plain HTTP chat hook URLs (#27896)
Adds a hidden `--chat-hook-allow-insecure` /
`CODER_CHAT_HOOK_ALLOW_INSECURE` deployment option (default `false`)
that allows the chat lifecycle hook URL to use plain HTTP for any host.

The HTTPS requirement is enforced at two points, and the flag relaxes
both: `DeploymentValues.Validate()` rejects `http` hook URLs at startup,
and the hook dispatcher's `validateHookURL` allows `http` only for
loopback hosts. With the flag set, any-host `http` is accepted; the
host, fragment/userinfo, secret, and timeout checks are unchanged, and
non-http(s) schemes still fail. This removes the need for an HTTPS
reverse proxy when testing a hook consumer on a trusted network.

Following security review feedback, the flag description and docs state
that plain HTTP lets an on-path attacker forge hook responses (which
control agent execution), and `coder server` logs a startup warning
(with a redacted hook URL) when hooks run over plain HTTP.

Docs, generated API types, and the server config golden are updated
accordingly.

> Mux acted on Mike's behalf to create this PR.
2026-08-05 22:41:17 +02:00
Bobby Ho 97c4031526 feat!: resolve agent external auth by template, not config order (#27854)
## TL;DR

**Problem.** A template can declare which external auth provider it
wants via `data "coder_external_auth" { id = "..." }`, and that
declaration is honored at every stage of the build. It was ignored at
runtime. Any git operation going through `GIT_ASKPASS` supplies only a
hostname, never a provider ID, and the handler scanned *every* provider
configured on the deployment and returned whichever matched the hostname
**last in config order**, with no reference to what the requesting
workspace's own template declared. Reordering
`CODER_EXTERNAL_AUTH_<N>_*` silently redirected a plain `git clone` from
one OAuth client's token to a completely different one.

**Fix.** For hostname-only requests, resolve the calling agent's
workspace and build *before* selecting a provider, then narrow
candidates to the providers declared by that build's template version.
Exactly one match wins regardless of config order. No matching declared
provider falls back to today's deployment-wide scan, so a template that
declares only a GitHub provider can still clone an unrelated host. Two
or more matching declared providers return `409` naming them, rather
than picking one arbitrarily: `external_auth_providers` is stored sorted
by ID, so HCL declaration order is already unavailable and no principled
tie-break exists.

Requests supplying an explicit provider ID are untouched. Server-side
only: no wire protocol, proto, manifest, or database schema change, so
already-running agents get the corrected behavior on their next askpass
call with no restart.

Refs #23718

<details>
<summary><b>Call flow</b></summary>

```mermaid
flowchart TD
    subgraph Push["1. Template import: coder templates push"]
        A1["Terraform extracts coder_external_auth id/optional attrs"]
        A2["CompleteJob(TemplateImport) validates each id<br/>against deployment config"]
        A4["template_versions.external_auth_providers persisted"]
        A1 --> A2 --> A4
    end

    subgraph PreBuild["2. Pre-build and workspace build (unaffected)"]
        B1["User authenticates declared provider(s), exact-ID lookup"]
        B2["Build resolves token by exact ID<br/>(provisionerdserver.go)"]
        A4 --> B1 --> B2
    end

    subgraph Runtime["3. Workspace running: a credential is needed"]
        B2 --> C0{"Caller supplies id or match?"}
        C0 -->|"id (explicit)"| D1["Exact-ID match<br/>UNCHANGED, already deterministic<br/>(coder external-auth access-token)"]
        C0 -->|"match only (GIT_ASKPASS)"| C1["git needs credentials for a hostname<br/>GIT_ASKPASS invoked, unchanged"]
        C1 --> C2["coder gitaskpass sends ExternalAuthRequest{Match: host}<br/>unchanged (cli/gitaskpass.go)"]
        C2 --> C3["workspaceAgentsExternalAuth<br/>(coderd/workspaceagents.go)"]
        C3 --> C4["CHANGED:<br/>1. resolve workspace/build BEFORE matching<br/>2. read that build's declared provider IDs<br/>3. filter: declared AND regex matches host"]
        C4 --> C5{"how many candidates?"}
        C5 -->|"exactly 1"| C6["use it, regardless of config order"]
        C5 -->|"0"| C7["fall back to deployment-wide scan<br/>(unchanged legacy behavior)"]
        C5 -->|"2 or more"| C8["409 naming every matching ID"]
    end

    D1 --> E1["Token returned"]
    C6 --> E1
    C7 --> E1

    style C4 fill:#1f4d2e,stroke:#4caf50,color:#fff
    style C6 fill:#1f4d2e,stroke:#4caf50,color:#fff
    style C8 fill:#1f4d2e,stroke:#4caf50,color:#fff
    style D1 fill:#333,stroke:#888,color:#fff
```

</details>

## Verification

Two test functions were added in `coderd/workspaceagents_test.go`, and
the behavior no unit test can reach was verified against a local dev
cluster with two real GitHub OAuth Apps whose regexes both match
`github.com`.

| Behavior | Unit | Manual |
|---|---|---|
| Declared provider wins over a colliding one | yes | yes |
| Outcome independent of deployment config order | yes | yes |
| No declared match falls back to the full scan | yes | yes |
| Host the template never declared still resolves | yes | via fallback |
| Two declared providers matching one host return `409` | yes | not run
|
| Declared but unauthenticated provider returns its auth URL | yes | not
run |
| Two templates resolve independently and concurrently | yes | no |
| Explicit-ID path unaffected | no | yes |
| Running agent corrected with no restart | **no** | **yes** |
| Declared ID since removed from config falls back | **no** | **yes** |
| Recomputed per build after a template update | **no** | **yes** |

The last three are properties a unit test cannot express: they involve
swapping the server binary underneath a live agent, removing deployment
configuration, and rebuilding a workspace against a new template
version.

<details>
<summary><b>Unit test detail</b></summary>

`TestWorkspaceAgentsExternalAuthTemplateScoped` builds a deployment with
two providers sharing a regex, a template declaring one of them, and a
seeded token for **every** provider, so a mis-selection returns a valid
token with the wrong identity rather than an error. Subtests:

- `DeclaredProviderLast` / `DeclaredProviderFirst`: the declared
provider wins in both config orders. Only the `First` arm is
discriminating, since the pre-change loop had no `break` and returned
the last regex match, which the `Last` arm happens to agree with.
- `NoDeclaredProvidersFallsBackToFullScan`: a template declaring nothing
keeps today's behavior exactly, pinning the legacy last-match rule.
- `UnrelatedHostStillResolvesViaFallback`: a template declaring only a
GitHub provider still resolves a GitLab host.
- `AmbiguousDeclaredSetReturnsError`: `409` whose message names both
colliding provider IDs.
- `OptionalUnauthenticatedDeclaredProviderReturnsAuthURL`: returns the
auth URL for the *declared* provider, not for an unrelated one the user
happens to hold a token for.

`TestWorkspaceAgentsExternalAuthMultipleTemplates` runs two workspaces
from two templates, each declaring a different provider, issuing
requests concurrently. Each resolves to its own template's provider.

</details>

<details>
<summary><b>Manual verification detail</b></summary>

Local dev cluster, two GitHub OAuth Apps both defaulting to
`^(https?://)?github\.com(/.*)?$`, both authorized by the workspace
owner so a wrong selection yields a usable token rather than an error.
Workspace built from a template declaring only `github-dotfiles`. Tokens
redacted.

**Order independence.** Same workspace, never rebuilt, config order
reversed between runs:

| Deployment config order | Token returned |
|---|---|
| `[github-broad, github-dotfiles]` | `gho_<dotfiles>` |
| `[github-dotfiles, github-broad]` | `gho_<dotfiles>` |

**A/B against the pre-fix binary.** Everything held constant except the
coderd build, with `/api/v2/buildinfo` checked on both sides so the
comparison rests on verified binary identity. The workspace was never
stopped, rebuilt, or re-authorized:

| coderd | buildinfo | Token | Honors declaration |
|---|---|---|---|
| pre-fix | `v2.35.3-devel+11e03cfb3a` | `gho_<broad>` | no |
| this branch | `v2.35.3-devel+e8b87d0333` | `gho_<dotfiles>` | yes |

This doubles as the demonstration that a coderd-only upgrade corrects
behavior on a live agent's next askpass call.

**Declared provider removed from config.** `github-dotfiles` deleted
from deployment configuration while the workspace's template still
declared it. Result: `HTTP/2 200` with `gho_<broad>` via the fallback.
No `500`, no fail-closed `404`. The orphaned `external_auth_link` row
remained in the database throughout and correctly had no effect.

**Recomputation after a template update.**

| Workspace state | Build's declared provider | Token returned |
|---|---|---|
| new version pushed, workspace not updated | `github-dotfiles` |
`gho_<dotfiles>` |
| after `coder update` | `github-broad` | `gho_<broad>` |

The pair is what makes it conclusive: the first rules out following the
template's newest version, the second rules out a cached value.

**Explicit-ID path.** `coder external-auth access-token github-broad`
returned that provider's result even though the template declared only
`github-dotfiles`, and did not substitute the declared provider's
already-valid token.

Raw traces were captured with `GIT_CURL_VERBOSE=1 git -c
credential.helper="" ls-remote <private repo>`, reading the unredacted
`== Info: Server auth using Basic with user '<token>'` line. A private
repo is required, since a public one never triggers a `401` and
therefore never invokes `GIT_ASKPASS`.

</details>
2026-08-05 13:08:41 -07:00
blinkagent[bot]andblink-so[bot] 4b6104229c chore: regenerate configuration-reference.md for bedrock placeholder (#27898)
## What

Regenerates `docs/admin/setup/configuration-reference.md` to include the
backtick-wrapped `<region>` placeholder that was introduced at the
source in #27399.

## Why

Commit
[`9dcb75cd`](https://github.com/coder/coder/commit/9dcb75cd567ab910d3fc07f22af4108a435de00e)
(#27399) changed the Bedrock region description in
`codersdk/deployment.go` to wrap the placeholder in backticks and added
the `docshtmlcheck` linter that requires it. The sibling generated file
`docs/reference/cli/server.md` was regenerated correctly in that commit,
but `docs/admin/setup/configuration-reference.md` was missed.

As a result, subsequent CI runs on `main` fail with:

- `gen`: `check_unstaged.sh` reports a one-line diff after `make gen`:
  ```
  -...in the form of 'https://bedrock-runtime.<region>.amazonaws.com'.
  +...in the form of `https://bedrock-runtime.<region>.amazonaws.com`.
  ```
- `lint`: `docshtmlcheck` fails at `configuration-reference.md:358` with
`unknown-element: <region>`.

Example failing run:
https://github.com/coder/coder/actions/runs/31036417075

## Change

Ran `make gen`. Only `docs/admin/setup/configuration-reference.md`
changed (1 insertion, 1 deletion). No source changes.

## Verification

- `make gen` produces no further diff.
- `make lint/docs-html` exits 0.

## Linear

-
https://linear.app/codercom/issue/DOCS-551/backtick-placeholder-syntax-in-generated-reference-docs-cli-help

Created on behalf of @ibetitsmike.

Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
2026-08-05 19:53:46 +00:00
Nick Vigilante 9dcb75cd56 chore: add docs inline-HTML linter and backtick generated placeholders (#27399)
## What

Adds CI enforcement that fails when docs Markdown contains invalid
inline HTML
the docs site silently drops or mangles, and fixes the remaining
generated-doc
placeholders at their source.

This is the tooling half of the docs-HTML audit. The hand-written fixes
it
guards landed in #27298 (kept small and separate so it reviewed fast);
this PR
carries everything that touches code, CI, or generated output.

## Changes

**Linter (`scripts/docshtmlcheck`), wired into `make lint` via
`lint/docs-html`.**
Markdown-aware: parses each file with goldmark and inspects only
raw-HTML nodes,
so angle brackets in fenced code blocks, inline code, HTML comments, and
`<https://…>` / `<user@host>` autolinks are ignored. Flags swallowed
placeholders (`<region>`), void-element end tags (`</br>`), unregistered
or
incorrectly capitalized component tags (`<Image>`), and unclosed
container tags (a
`<div class="tabs">` that leaks its wrapper). The one intentional
renderer
component, `<children>`, is allowed but still balance-checked.

**Generator-source placeholder fixes (regenerated via `make gen`).**
- `codersdk/chats.go`: backtick `<server>__` in the
`ChatContextTool.Name` doc
  comment (it becomes the Swagger description, so it was swallowed in
  `reference/api/{chats,schemas}.md`).
- `codersdk/deployment.go`: backtick `<region>` in the AWS Bedrock
region flag
help (swallowed in `reference/cli/server.md`); also updates `coder
server
  --help` output and the golden files.

**Temporary allowlist.** `docs/reference/cli/agent-firewall.md`'s
`<host>` /
`<glob>` come from the external `github.com/coder/boundary` CLI help
(still
`v0.10.0` on `main`), so they are suppressed on that one file. The
suppression
is self-clearing: if an allowlisted tag stops appearing on a scanned
file, the
linter reports `stale-allowlist-entry` and fails until the dead entry is
removed, so a dead entry cannot silently mask a later regression of that
tag on
that page. (An entry whose file is deleted outright is never rescanned,
but a
missing file yields no findings, so nothing hides behind it either.)

## Review feedback addressed

This tool + generator work was reviewed by Coder Agents Review while it
was
bundled into #27298. Addressed here:

- **P1:** tokenize each raw-HTML node as a whole instead of per source
line, so
a tag whose attributes wrap across lines is no longer torn in half. This
fixes
both the missed multi-line unclosed `<div>` (a leaked wrapper that
passed with
exit 0) and the spurious `stray-end-tag` on valid multi-line tags. Each
token
  maps back to its own source line.
- Normalize allowlist lookup/report paths to a canonical repo-relative
form, so
the escape hatch no longer silently misses under absolute / `./` paths.
- Route generated-page findings to the generator source.
- Add `<search>` to the allowed set; reword the unknown-element message
to note
  that a real element can be added to `allowedElements`.
- Self-clearing allowlist guard (above); rename `optionalEndTag(s)` and
`kindUnclosed(Tag)`; adopt `slices`/`maps` idioms; move the lint banner
to the
  Makefile recipe; stop aliasing the input slice in `filterAllowed`.
- New tests: multi-line tokenization (both classes), interleaved
nesting, a
  pinned line number, `collectMarkdown`, and the stale-allowlist guard.

### Round 2 (Coder Agents Review on this PR)

A second `/coder-agents-review` pass on this PR raised 16 findings;
addressed in
`fix(docshtmlcheck): catch self-closing containers and capitalized
tags`:

- **P2:** self-closing container tags (`<div class="tabs"/>`) were
ignored by
the HTML5 parser and leaked their wrapper like the open spelling; the
balance
  check now tracks self-closing tokens too (CRF-1).
- **P2:** a capitalized component tag whose lowercase name is a real
element
(`<Table>`, `<Section>`) slipped through on the `allowedElements`
lookup. The
tokenizer lowercases tag names, so the check now reads the raw token and
  reports any capitalized name as a component reference (CRF-2).
- Narrowed the `:` / `@` autolink skip to a real URI scheme or a dotted
`local@domain`, so `<region:id>` and `<user@host>` stay checked (CRF-3).
- Stale-allowlist findings now report against the linter source with no
line,
and count separately from invalid-HTML issues in the footer (CRF-7,
CRF-11).
- Comment / README / Makefile wording synced to the honest
capitalized-tag
  behavior; added the deleted-file allowlist caveat and a note that
`allowedElements` is hand-maintained against the renderer (CRF-14,
CRF-17,
  CRF-9).
- Internal cleanups (`pop` -> `matchEndTag`, extracted
`unclosedFinding`) and
new tests: self-closing, capitalized open/close, colon/at placeholders,
a
non-first-token line assertion, `isGeneratedDoc`, and the stale message
  (CRF-12, CRF-13, CRF-1/2/3/4/5/16).

Two findings resolved without a code change:

- **CRF-8** (also wire `lint/docs-html` into `lint-light`): declined.
  `lint-light` is the Go-free fast path; `lint/docs-html` needs the Go
toolchain, so it stays in the full `make lint`, which CI runs. Adding it
would
  pull Go into the light path for no coverage gain.
- **CRF-9** (`allowedElements` <-> renderer coupling): documented with a
maintenance note in the `allowedElements` comment and tracked in
DOCS-597 for
  a cross-repo sync/check decision.

Deferred (note, no current trigger): raw-text element interiors
(`<script>` / `<style>`) are not scanned for nested tags. No docs page
relies
on this today; noted for follow-up.

## Merge order

#27298 (the hand-written fixes this PR guards) has merged, and this
branch is
rebased on `main`, so `make lint/docs-html` now reports 0 findings and
the
`lint` check passes. The two PRs are independent (disjoint files, no
stacking).

## Verification

- `go test ./scripts/docshtmlcheck/`, `go vet`, `gofmt -l`,
`golangci-lint run`: clean.
- `make lint/docs-html` (branch rebased on `main`): 0 findings.

## Linear

- DOCS-584:
https://linear.app/codercom/issue/DOCS-584/add-ci-check-that-fails-on-invalid-inline-html-in-docs
- DOCS-551:
https://linear.app/codercom/issue/DOCS-551/backtick-placeholder-syntax-in-generated-reference-docs-cli-help
- DOCS-597 (follow-up, from CRF-9):
https://linear.app/codercom/issue/DOCS-597/track-docshtmlcheck-allowedelements-drift-vs-docs-renderer-component

> This PR was created with AI assistance (Coder Agents).
2026-08-05 14:45:45 -04:00
Ben Potter 79723db2d2 docs: replace enterprise-base image references with example-base (#27025)
Follow-up to #27018, sweeping the remaining
`codercom/enterprise-base:ubuntu` references to
`codercom/example-base:ubuntu` and `coder/enterprise-images` links to
[coder/images](https://github.com/coder/images). The `example-` prefix
is the recommended one for new deployments per the coder/images README.

Covers the 11 docs pages flagged by doc-check on #27018 plus the
embedded `examples/templates/docker` and `examples/templates/kubernetes`
starter templates (image string only; the `image` variable lives in the
coder/registry templates, see coder/registry#943).

OpenShift imagestream names in `docs/install/openshift.md` keep the
`enterprise-base` local name; only the upstream image reference changed.

Part of DEVREL-201.

🤖 Generated with Coder Agents using Claude, on behalf of @bpmct
2026-08-04 13:47:55 -07:00
Nick Vigilante 10b366cb7c docs(docs/.style/style-guide): fix self-violating examples (#27849)
Two internal-consistency fixes in the prose style guide, found while
auditing it against ASD-STE100 (Simplified Technical English).

The directional-language section in `accessibility-and-inclusion.md`
used "See the [Latin abbreviations rule]" as a **Do** example and
recommended "see the following section" in its replacements table. Both
violate the navigational-"see" ban that `word-choice.md` applies to all
docs, so the examples now use "refer to".

The one-sentence-per-line **Do** and **Don't** examples in
`formatting.md` were byte-identical single source lines, so the
**Don't** examples demonstrated no violation. Blockquotes re-join lines
when rendered, which is why the broken examples went unnoticed. The
examples are now fenced `md` blocks that show the actual source line
breaks (clause breaks and fixed-column wrap).

---

🤖 Built with AI assistance.
2026-08-04 15:07:05 -04:00
Susana Ferreira db88ec3f6a fix: price AI usage by configured provider type (#27836)
## Problem

AI Gateway records the aibridge provider on each interception, which is
the upstream wire format and only ever `anthropic`, `openai`, or
`copilot`. Prices are matched on exact provider and model equality, so a
provider configured as Azure, Bedrock, Google, OpenRouter, or Vercel is
priced as if it were native OpenAI or Anthropic, matching either the
wrong price or no price at all.

## Changes

- Resolve the configured provider type from `ai_providers` by provider
name, which is unique among live providers, and key the price lookup on
it instead of the aibridge provider. No schema change is needed.
- Label `unpriced_token_usage_records_total` with the same provider
value used for the lookup, so it names a provider an operator actually
configured.
- Treat a provider that cannot be resolved as unpriced, consistent with
how a missing price is handled today.

Closes
https://linear.app/codercom/issue/AIGOV-570/resolve-ai-model-prices-using-the-configured-provider-type
Depends on the follow-up that extends the shipped price book to the
remaining provider types:
https://linear.app/codercom/issue/AIGOV-571/ship-prices-for-all-ai-governance-provider-types

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by
@ssncferreira
2026-08-04 14:44:27 +01:00
Marcin Tojek 866eb970a4 docs: correct 2.35 stable version to v2.35.3 (#27842)
## Summary

Follow-up to #27828, addressing review feedback from @matifali.

The automated `releasetui` update in #27828 promoted `2.36.0` to
Mainline but
left two stale references to the 2.35 stable channel:

- `docs/install/rancher.md`: **Stable** was left at `2.34.6` instead of
being
  promoted to the current 2.35 stable patch.
- `docs/install/releases/index.md`: the 2.35 row was marked **Stable**
but its
  latest release still pointed at `v2.35.2`.

The latest 2.35 patch is `v2.35.3` (see the `v2.35.3` release tag), so
both are
now updated accordingly.

## Changes

- `docs/install/rancher.md`: Stable `2.34.6` -> `2.35.3`
- `docs/install/releases/index.md`: 2.35 latest release `v2.35.2` ->
`v2.35.3`

<details>
<summary>Review comments addressed</summary>

- `docs/install/rancher.md` (matifali): "A bit late, but shouldn't the
stable be now 2.35.3?"
- `docs/install/releases/index.md` (matifali): "The latest stable is
2.35.3 and not 2.35.2"

</details>

> [!NOTE]
> This PR was generated by Coder Agents on behalf of @mtojek.
2026-08-04 15:09:05 +02:00
Marcin Tojek 11b38272f6 chore(docs): update release docs for v2.36.0 (#27828)
Automated docs update for v2.36.0 release.

Created by `releasetui`.
2026-08-04 12:54:59 +02:00
Michael Suchacz 6b8f820493 feat: remove native chat cost tracking in favor of AI Gateway cost data (#27330)
## Stack Context

This stack makes AI Gateway data and budgets the source of truth for AI
spend controls.

1. Re-back the per-chat cost endpoint with AI Gateway data (#27328,
merged).
2. Remove native chat usage limits (#27329, merged).
3. **This PR, now based on `main`:** remove native chat cost tracking
and its dedicated admin UI.

## Summary

Removes native per-message price calculation, model pricing fields, cost
persistence, aggregate cost queries, and admin cost API types. It also
deletes the Analytics and Spend pages plus their legacy redirects. The
AI Gateway-backed per-chat cost row and compact budget indicators
remain.

The spend documentation is renamed to `spend-management.md` and updated
for the remaining surfaces, group budget APIs, CSV export, upgrade
handling for native pricing and cost history, and the absence of a
deployment-wide spend dashboard. The per-chat cost API documents that
data follows AI Gateway retention and reports zero after all matching
requests are purged.

No schema is dropped in this release. `chat_messages.total_cost_micros`
remains nullable and unwritten so replicas from the previous release can
continue inserting messages during rolling upgrades. #27600 tracks
removal after the compatibility window.

> Mux prepared this PR on Mike's behalf.
2026-08-04 12:27:38 +02:00
Michael Suchacz f0e6ac64b3 feat: remove native chat usage limits in favor of AI Gateway budgets (#27329)
## Stack Context

This stack makes AI Gateway data and budgets the source of truth for AI
spend controls.

1. Re-back the per-chat cost endpoint with AI Gateway data (#27328,
merged).
2. **This PR:** remove native chat usage limits.
3. Remove native chat cost tracking and its dedicated admin UI (#27330).

## Summary

Removes the native usage-limit API, SDK types, SQL, and chat enforcement
for deployment, user, and group chat limits. Compact AI Gateway budget
indicators remain in the Agents sidebar, user menu, and group settings.
Gateway budget rejections and provider quota failures continue to
classify as usage-limit errors, including a 409 response for synchronous
title generation.

Budget-period labels now use the API's UTC boundaries, so users see the
same dates in every browser timezone. The documentation explains the AI
Gateway replacement, its licensing requirements, and the differences
from native limits.

No schema is dropped in this release. The usage-limit table, index, user
and group columns, constraints, audit mappings, and generated scan
fields remain for mixed-version rolling upgrades. #27600 tracks their
removal after the compatibility window.

## Breaking change

Native day, week, and month chat spend limits are removed and are not
migrated. AI Gateway budgets are month-based, group-scoped with per-user
overrides, and require the AI Gateway entitlement. Deployments without
that entitlement no longer have chat spend enforcement.

> Mux prepared this PR on Mike's behalf.
2026-08-04 11:36:49 +02:00
blinkagent[bot]andblink-so[bot] 84cdc17602 docs: bump AI Gateway client modules to latest and remove Coder Tasks refs (#27810)
Updates the AI Gateway client docs under
`docs/ai-coder/ai-gateway/clients/` to reference the latest module
versions on registry.coder.com and removes mentions of Coder Tasks from
those pages.

Uses pessimistic (`~>`) version constraints so users automatically pick
up compatible non-breaking updates within the same major.

### Version bumps

| Module | Old | New |
|---|---|---|
|
[`coder/claude-code`](https://registry.coder.com/modules/coder/claude-code)
| `4.7.3` | `~> 5.2` (latest `5.2.0`) |
|
[`coder-labs/codex`](https://registry.coder.com/modules/coder-labs/codex)
| `~> 5.0` | `~> 5.3` (latest `5.3.0`) |
| [`coder/mux`](https://registry.coder.com/modules/coder/mux) | `~> 1.0`
| `~> 1.5` (latest `1.5.0`) |

### Coder Tasks removal

- `claude-code.md`: removed the *Coder Tasks* example block (v5 of the
module is a major refactor that dropped the `ai_prompt` input and
`task_app_id` output).
- Remaining inputs in the example (`agent_id`, `workdir`,
`enable_ai_gateway`) still match the latest module.
- `codex.md` and `mux.md` did not reference Tasks, so only version bumps
were needed there.

cc @matifali

---------

Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
2026-08-04 12:09:23 +05:00
Steven Masley 52423eb87b feat: promote MinimumImplicitMember experiment to GA (#27472)
Promotes the `minimum-implicit-member` experiment to GA and removes it.

## What changes

- The `minimum-implicit-member` experiment constant, its
`RoleOptions.MinimumImplicitMember` toggle, and the global
`rbac.MinimumImplicitMember()` accessor are deleted. The minimal-member
behavior is now the only behavior: `organization-member` and
`organization-service-account` carry only the floor (read-self records,
notifications, and similar) and grant **no workspace permissions**.
Workspace access lives exclusively on the
`organization-workspace-access` role.
- The experiment gate on customizing `default_org_member_roles` (`PATCH
/organizations/{org}`) is removed; the built-in-roles-only validation
remains.
- The dashboard's Default Roles section and the implied-roles display on
the members page are no longer experiment-gated.
- Admin docs: new "Default member roles" section in
`docs/admin/users/organizations.md`, cross-linked from
`groups-roles.md`.

## Why this is safe for existing deployments

Migration `000516` (shipped earlier) backfilled
`default_org_member_roles` with `['organization-workspace-access']` on
every organization. Members therefore keep exactly the effective
permissions they had with the experiment off; the workspace elevation
flows through the default role instead of being baked into
`organization-member`.

**Rollback caveat:** rolling back past this release restores the bundled
elevation, silently re-granting workspace access to members of
organizations that cleared their default roles.

## Review

Deep-review R1 findings are addressed in `chore: address deep-review
findings` (copy fixes, read-only Default Roles for viewers, removable
overlapping explicit grants, RBAC prose restoration, test
de-tautologizing, docs). Point-by-point disposition is in the PR
comments.

---

Generated by Coder Agents on behalf of @Emyrk.
2026-08-03 15:56:56 -05:00
dylanhuff-at-coderandNick Vigilante fe4a73f8ab docs: note user secret target uniqueness and delivery boundary (#27532)
Two gaps in the user secrets guide, both independent of any pending
secrets work.

## Changes

**Target uniqueness (`Update a secret`, `File secrets`).** The guide
teaches `coder secret update api-key --file ""` but never states that
env names and file paths are unique per user, so the conflict you get
when setting a target back has no explanation in the docs. The `File
secrets` paragraph also read as though duplicate file paths are
tolerated with a warning; an identical path is rejected outright, while
two *different* paths resolving to the same location are both accepted
and produce the agent warning. Both indexes are partial (`WHERE env_name
!= ''` / `WHERE file_path != ''`), so a cleared target really is
released for another secret to claim — now stated.

**Delivery boundary (`How your secrets reach a workspace`).** Coder
controls where a secret is delivered, not whether it is still valid.
Nothing done in Coder revokes a credential a workspace already received,
so an exposed credential is rotated at its source. This applies to
deletion as much as to clearing a target.

No new headings, no changes to the existing tables or callouts.

> This PR was generated by Coder Agents on behalf of
@dylanhuff-at-coder.

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-08-03 13:06:30 -07:00
ba4779fc87 docs: lead with env vars in admin docs and add configuration reference (#26824)
## What & why

Admin/setup docs lead with `coder server --flag` examples, but most
operators configure Coder through `CODER_*` environment variables
(system service, container, or Helm chart). There is no single page
mapping a setting to its env var, CLI flag, YAML key, and default, so
searching the docs for an env var name such as `CODER_PG_CONNECTION_URL`
returns nothing.

This adds a generated configuration reference and begins shifting admin
docs to lead with the environment-variable form.

## Changes

- **Generated configuration reference**
(`docs/admin/setup/configuration-reference.md`): a searchable,
per-setting list of every visible deployment option. Each option is a
heading (grouped and nested by serpent group) followed by its
description and the environment variable, CLI flag, YAML key, and
default that apply to it. Generated from `codersdk.DeploymentValues` so
it stays in sync.
- **Generator + `make gen` wiring** (`scripts/configdocgen/`): new
binary plus a Makefile target and `GEN_FILES` entry, mirroring the
existing `clidocgen` / `auditdocgen` pattern. Output is host-independent
(same env normalization as `clidocgen`).
- **Demo conversion** (`docs/admin/users/github-auth.md`): inverted to
lead with the `/etc/coder.d/coder.env` env-var form; the CLI-flag form
becomes a closing note that links to the reference. H2 slugs preserved.
- **Style guide** (`.claude/docs/DOCS_STYLE_GUIDE.md`): documents the
env-var-first convention for admin/setup docs.
- **Navigation**: manifest entry under Administration → Setup, plus a
TIP callout on the setup index.

## Risk

Docs + gen pipeline only; no runtime change. The page is regenerated by
`make gen`; the `gen` and `check-docs` CI checks pass.

## Follow-up

Several other admin pages still lead with flag walls. Recommend sweeping
them incrementally in separate PRs rather than expanding scope here.

<details>
<summary>Implementation notes (provenance, conflict resolution,
verification)</summary>

- Continues prior work by @aslilac and @bpmct from the
`kayla/docs-env-vars-first` branch. Both original commits are
cherry-picked here with authorship preserved.
- Rebased onto current `main`. Resolved two `Makefile` conflicts where
`main` had since added the `feature-stages.md` gen target at the same
locations; kept both targets (union) in `GEN_FILES`, `gen/mark-fresh`,
and the recipe block.
- The original branch's checked-in page predated recent
`codersdk.DeploymentValues` changes, so it was **regenerated** against
current `main` (adds `CODER_SCIM_USE_LEGACY`, the `Networking / Cluster`
section with `CODER_CLUSTER_HOST`, `CODER_BOUNDARY_LOG_RETENTION`, and
the AI Gateway description rename). The `gen` CI check enforces this
stays current.
- Fixed flag-link anchors for short-form flags (`--config`,
`--log-filter`): the generator derives the anchor from `FlagShorthand`
to match `clidocgen`'s heading (e.g. `#-l---log-filter`).
- `linkspector` ignores the AWS Bedrock base URL that appears as an
illustrative `<region>` placeholder in an option description, consistent
with the existing `openai.com` ignore patterns.

</details>

<details>
<summary>Configuration reference layout (2026-07-08 update)</summary>

Reworked the reference from a wide table into a nested, per-setting list
so it fits without horizontal scrolling and stops repeating the group
name in every heading:

- **List, not table.** Each option renders as a heading, its
description, and a bullet list of only the configuration methods that
apply to it (non-applicable methods are omitted instead of shown as
`-`).
- **Nested sections.** Sections nest by the serpent group hierarchy, so
`Email / Email Authentication` becomes `Email` (h2) with an `Email
authentication` (h3) subsection instead of a redundant flat title.
- **Shorter, sentence-case headings.** The redundant group prefix is
stripped from each option name and the remainder is lowercased to
sentence case, preserving acronyms and mixed-case tokens (`URL`, `TLS`,
`OAuth2`, `GitHub`) plus a small proper-noun allowlist (`Coder`,
`Terraform`, `Honeycomb`, `Anthropic`, `Bedrock`, ...). Example: `AI
Gateway Send Actor Headers` becomes `Send actor headers`.
- **Deprecated options** sort to the end of each section and lead with
an emphasized **Deprecated** marker. Headings stay clean (no
`(deprecated)` suffix) so their anchors remain stable.
- **Section intros** render from a group's `Description` when the source
defines one (e.g. DERP); no hand-maintained prose or links are
introduced.

All transformations run in pure Go at `make gen` time (no AI at
generation time). Generation is idempotent, and `markdownlint` and
`golangci-lint` both pass.

</details>

---

🤖 Opened by Coder Agents on behalf of @nickvigilante. Continues work by
@aslilac and @bpmct.

---------

Co-authored-by: Kayla (via Coder Agents) <kayla@coder.com>
Co-authored-by: Coder Agents <noreply@coder.com>
Co-authored-by: Ben Potter <me@bpmct.net>
2026-08-03 14:33:01 -04:00
Nick Vigilante ee7e7ecb74 docs: add a glossary to the reference section (#27165)
Adds a reference glossary at `docs/reference/glossary.md` that defines
the Coder-specific terms and product names readers encounter across the
docs, and registers it in `docs/manifest.json` under **Reference**.

The page prioritizes the term collisions around "agent": it
disambiguates Coder Agents (the AI product), the workspace agent (the
in-workspace daemon), and the `coder_agent` Terraform resource with an
`[!IMPORTANT]` callout and cross-referenced entries. Every definition
was checked against the current docs, and every internal link is a
relative path that resolves in-repo.

Decision log and verification notes

**Scope of this PR**

- Creates the glossary page (`docs/reference/glossary.md`) and its
manifest entry.
- Adds glossary drift-prevention guidance in response to review feedback
(see **Follow-up from review** below).
- Out of scope (tracked separately): `Glossary: ` cross-link callouts
across the docs IA, the search-ranking boost, the workspace-daemon
rename decision, and the automated glossary lint guard
([DOCS-604](https://linear.app/codercom/issue/DOCS-604)).

**Follow-up from review (@bpmct)**

Ben flagged the risk that terms get introduced, renamed, or deprecated
without the glossary keeping up. Addressed in commit c12dea4 by pointing
both humans and tooling at the glossary:

- `docs/.style/content-guidelines.md`: a canonical Structural rule to
update the glossary in the same change that introduces, renames, or
deprecates a product or feature name.
- `.claude/skills/doc-check/SKILL.md`: doc-check flags terminology
changes that need a glossary update.
- `.claude/skills/write-docs/SKILL.md`: authoring updates the glossary
in the same change, plus a pre-handoff checklist item.
- `docs/.style/style-guide/word-choice.md`: cross-links the glossary as
the fuller product-name registry.

The single source of truth is the content-guidelines rule; the skills
reference it rather than restate it. The automated lint guard is
deliberately split into
[DOCS-604](https://linear.app/codercom/issue/DOCS-604): it touches
CI/build config and depends on the planned `Coder.ProductTerms` Vale
rule, so keeping it out holds this PR to a doc-only footprint. The four
files above are Markdown-only additions, validated in CI (markdownlint,
emdash, Vale advisory) rather than re-run locally.

**Source**

- Migrated and expanded from a generated glossary draft, then reconciled
against the live docs.

**Corrections made vs. the draft**

- AI Gateway and Agent Firewall are gated by the **AI Governance
Add-On** (Coder v2.32+), not plain Premium. Confirmed in
`docs/ai-coder/ai-governance.md`.
- Coder Tasks is framed as deprecated (12-month ESR, removed from new
releases starting v2.37; Coder Agents is the long-term replacement), per
`docs/ai-coder/tasks.md`.
- "Formerly AI Bridge" and "formerly Agent Boundaries" confirmed via the
rebranding-migration and agent-firewall pages; Agent Firewall backends
are `nsjail` (default) and `landjail`.
- OpenTofu is described as a custom Terraform binary that works but is
not officially supported, per `docs/admin/integrations/opentofu.md`.
- Premium markers were taken from `docs/manifest.json` (`"state":
["premium"]`).

**Local validation** (glossary page)

- `markdownlint-cli2`: 0 errors.
- `scripts/check_emdash.sh`: clean.
- Vale (`Coder` package): 0 errors, 0 warnings, 0 suggestions.
- All 120 links checked; every relative link resolves in-repo.
- 103 terms; no duplicate sibling headings (MD024 `siblings_only`).

**Reviewer note**

- This is a first-pass migration. Per the docs authoring skill, each
entry deserves a final accuracy pass before the page leaves draft. Flag
any term you want reworded, split, merged, or dropped.

> This PR was created with AI assistance (Coder Agents).
2026-08-03 14:32:13 -04:00
Michael Suchacz fc24c27dfd fix: reserve chat hook dispatch capacity for running turns (#27656)
## Context

Follow-up fix from live UAT of the merged chat lifecycle hooks stack
(#27430). Its companion UAT fix (#27655) has merged, so this targets
`main` directly.

## Why?

UAT measured a burst of 1,500 concurrent chat creations against a
consumer with 1.2s latency. 255 were admitted and 1,245 got `502
hook_dispatch_failed (over_capacity)`, which is correct fail-closed
behavior. The collateral wasn't: the same burst failed 24 `stop`
dispatches, parking chats that had already been admitted and had already
executed tools. One 256-slot semaphore served every event, so new-work
admission could take every slot and kill turns in flight.

Callers now classify each dispatch as admission or generation, and
admission draws from a 192-slot gate held *before* the shared pool. At
least 64 shared slots stay reachable only by dispatches for work a chat
already admitted. The dispatcher is per `coderd` replica, so these
limits are per replica, not deployment-wide, and the docs say so.

**The caller classifies, not the event type.** Event type isn't a
reliable proxy in either direction: a subagent spawn dispatches
`user_prompt_submit` from inside a running turn, and the edit path
dispatches `session_start` at admission time. `CapacityClassUnset` is
rejected in `Dispatch`, so a new call site fails closed rather than
silently inheriting a share.

**Acquisition order is load-bearing.** Admission takes its own gate
first. Taking a shared slot first would let admissions queued on the
gate occupy the very capacity the reserve protects. `acquireCapacity` is
the only path that takes either pool, so the order can't be bypassed.

## What this does not guarantee

Nothing bounds how many turns generate concurrently, so the 192/64 split
is a judgement call, not a derived ceiling. This stops an *admission*
burst from consuming every slot; it does not make the remainder
sufficient. A large enough generation load can still exhaust the reserve
and error a running chat. The docs say so explicitly rather than
promising a guarantee the code doesn't deliver.

Generation can now take all 256 slots, so generation traffic starves
admission harder than before. That's the intended priority: rejecting a
new prompt is recoverable, ending a turn that already ran tools is not.

## Testing

Red-green proved both new tests. Removing the release-on-failure path
fails `RefusedSharedAcquireReleasesAdmission` deterministically;
removing the expired-deadline check fails
`ExpiredDeadlineRefusesFreeSlot` in 18/30 runs.

That deadline check fixes a real race found in review. `acquire`
previously shared one `time.Timer` across both acquires. Because
`select` picks a ready case at random, an admission dispatch could take
a slot after its capacity deadline had passed. Measured over 300 trials:
135 late acquisitions, worst overshoot 2.1ms. `acquire` now takes an
absolute deadline and refuses an expired one before selecting, which
measures 0/300.

Go: `coderd/x/agenthooks/...` and `coderd/x/chatd/...`, plus `-race
-count=3` on the dispatcher.

> Mux opened this PR on Mike's behalf.
2026-08-03 19:04:54 +02:00
Fabien Penso 7bd9f5ec93 fix: correct authorization header spelling in api docs (#27721)
Corrects the misspelled `Authorizaiton` Swagger header name to
`Authorization` in the source annotation and checked-in generated API
documentation.

This prevents generated API specs and SCIM examples from documenting the
wrong HTTP header name.
2026-08-03 16:31:26 +00:00