281 Commits
Author SHA1 Message Date
Ehab Younes d807abc2e3 feat: honor --use-keyring together with --global-config (#32392)
An explicit --use-keyring flag or CODER_USE_KEYRING value now selects the
keyring backend even when --global-config points at a custom directory.
When --use-keyring is left at its default, a custom --global-config still
selects file storage so existing callers keep finding <dir>/session.

Removes the test-only RootCmd.UseKeyringWithGlobalConfig override and the
duplicate clitest.NewWithDefaultKeyringCommand helper.

Closes CLI-1, #29105
2026-11-20 19:02:08 +03:00
Bobby Ho 88d3494b9a feat: require a setup token to create the first user on a tunnel (#32324)
fix(security): require setup token for first user on tunnels

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

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

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

Refs CORE-784
2026-11-19 20:22:21 -07:00
Nick VigilanteandBen Potter 1baff57cb0 fix: resolve docs and code conflicts found in the main docs audit (#32158)
## Summary

Addresses 106 of the 113 conflicts between the docs and the code that
the November audit of `main` found: 102 are fixed and 4 have an interim
docs fix. Every finding was re-checked against the code before it was
fixed. Most fixes are docs-only. Three are small code fixes where the
docs described the intended behavior and the code was wrong, each in its
own commits so it can be split out. No change in this PR alters template
build or agent behavior.

## Changes

Fixes by area (finding counts): templates 28, install 13, integrations
and monitoring 13, auth and security 12, networking 11, Coder Agents 9,
AI governance 7, reference 7, workspaces 6.

Code fixes. Each needs a look from the code owner. If an owner prefers
not to take one, drop its commits and I will change the docs to describe
the current behavior instead.

| Commits | Change | Risk to check |
|---------|--------|---------------|
| `fix: keep built-in listener defaults in packaged coder.env`, and
three follow-up commits | `coder.env` comments out `CODER_HTTP_ADDRESS=`
and the three `CODER_TLS_*` lines, so an untouched package install
listens on `127.0.0.1:3000` as the docs say. Only the
`CODER_HTTP_ADDRESS=` line changed behavior. The TLS options default to
empty, so commenting them out is for consistency. The Lima examples
rewrite the commented line and fail if the line is not found. A test
compares every option that the file sets against the built-in defaults.
| The deb and RPM packages were not built or installed. Every released
package through v2.39.0 ships the empty line, and upgrades keep an
existing file (`config\|noreplace`), so the upgrade pages now say how to
fix it. |
| `fix(cli/clilog): accept log sinks that are all disabled`, and three
follow-up commits | `--log-human=/dev/null` with no other log location
no longer fails with "no loggers provided". It is the documented way to
disable logging. An empty location still fails with that error when no
other sink is set, as before. | Behavior change: with `/dev/null`, the
server and the provisioner daemon can start with no log output. |
| `fix(cli): detect CODER_PROC_PRIO_MGMT by presence`, and a comment
follow-up | Log line only. With the variable set to an empty value, the
agent now logs that process priority management is enabled, which is
what `agentexec` already does. No detection or behavior change. | Low. |

Two option descriptions in `codersdk/deployment.go` are corrected, with
the CLI reference, configuration reference, and golden files
regenerated: the default quiet hours schedule (the max deadline is the
quiet hours window on the next day that the template's autostop
requirement applies) and `--experiments` (`*` opts in to the experiments
marked safe, also in `enterprise/cli/provisionerdaemonstart.go`).

### Code fixes that were reverted after review

Two code fixes from the first version of this PR are reverted in the
branch. The net diff has no change under `agent/` or `coderd/`. The docs
now describe what the code does, and both issues stay open for the
owner.

- **`error` merge strategy for `coder_env` (DOCS-1669).** The fix made
`merge_strategy = "error"` fail whenever a name was set twice, whatever
the resource order. Existing template versions that pair an `error`
entry with a later `replace` or `append` entry would start to fail every
build after `terraform apply`. That is a breaking change that needs its
own PR and release note. The fix and its tests are in `dff8e7c6ce` and
can be cherry-picked. `environment-variables.md` now says the check runs
only when the `error` resource is processed.
- **Nice value before the capability drop (DOCS-1687).** The fix let
`coder agent-exec` apply a negative nice value by calling `setpriority`
before it drops effective capabilities. The current order is deliberate:
with the fix, any local process could run the agent binary with
`--coder-nice=-20` when the binary has the `CAP_SYS_NICE` file
capability. `process-priority.md` now says a nice value below the
agent's own is not applied, and no longer tells admins to grant
`CAP_SYS_NICE`.

## Not included

Seven findings are left out.

- DOCS-1629: covered by #31639.
- DOCS-1703 and DOCS-1724: covered by #31980.
- DOCS-1584, DOCS-1683, DOCS-1685, DOCS-1686: each needs an owner
decision, and no neutral docs wording exists until that decision is
made. The validation comment on each issue names the decision.

Four fixes are interim, so their issues stay open:

- DOCS-1600: the AI Gateway pages now agree that the legacy metric names
are deprecated and "will be removed in a future release". The code still
emits them, and its TODO names v2.37, which has shipped. The owner still
needs to set the removal release.
- DOCS-1689: the page now says **New Template** opens the builder only
for users with the Owner role, because the page gates on read access to
the deployment config. Whether Template Admins should get the builder is
still open.
- DOCS-1669 and DOCS-1687: docs-only for now. Refer to [Code fixes that
were reverted after
review](#code-fixes-that-were-reverted-after-review).

## Review notes

- Claims that describe product intent and need an owner's yes: the
Premium qualifier on per-organization workspace sharing (the API route
has no license check, the dashboard needs multiple organizations),
`organization` port sharing in OSS, the telemetry field list, and the
`1-5` cron range in the prebuilds schedule example.
- Not run end to end: the PostgreSQL TLS procedure on a cluster, the
OpenShift and air-gapped examples, the BSD `date` and `tar` forms on
macOS, the Windows command on the multiple Kubernetes clusters page, and
the keep-alive script in `docs/reference/index.md` (only its comparison
logic was run, against sample values). Nothing was checked on a live
deployment.
- Likely merge conflicts with open PRs: #31990 (`mcp-server.md`,
`feature-stages.md`, `docker-in-workspaces.md`), #31982
(`workspace-management.md`), #31980 (`health-check.md`), #31977
(`manage-provisioner-jobs.md`), #31869 (`airgap.md`), #30486
(`add-envbuilder.md`), and #31326 and #31531 (`codersdk/deployment.go`
and generated files).

## Testing

- `make pre-commit` (gen, fmt, lint, slim build), before the PR opened
and again after the review changes.
- `go test` for `./cli/clilog/...`, `./codersdk/`, `./cli/`
(`TestServer`, `TestAgent`, and golden files), and `./enterprise/cli/`
(provisioner, server, and help golden files). `./agent/agentexec/...`
and `./coderd/provisionerdserver/...` pass after the reverts. Linux
only. CI covers macOS and Windows.
- The `coder.env` test fails against the file on `main` and passes
against the new one. It reads the file with `godotenv`, which accepts
CRLF line endings.
- An empty `CODER_HTTP_ADDRESS=` was confirmed end to end with a full
build of the server (output below).
- The new `sed` and `grep` lines in the Lima examples were run with GNU
tools against the old and the new form of `coder.env`. The Lima VMs were
not started.
- `--log-human=/dev/null` and `CODER_LOGGING_HUMAN=` were confirmed with
the same build (output below).
- `coder agent-exec --coder-nice=-5 -- echo` from a full build, as a
non-root user: `coder-agent: failed to adjust niceness to -5 ...:
permission denied` on stderr, the command output on stdout, exit code 0.
- `postgres-ssl.md` rendered with the GitHub Markdown API: two ordered
lists with three and five items, where `main` has six lists.
- markdownlint, the table formatter, `make lint/emdash`, `make
lint/docs-html`, `make lint/docs-manifest`, `make lint/docs-redirects`,
`make lint/style-claims`, and Vale on the changed lines.
- A doc-check self-review of the docs diff by four independent
reviewers. It found six problems, which are fixed. The accuracy and
coverage lenses ran on every area. The language and structure lenses ran
in full on only part of the diff.

<details>
<summary>Test and terminal output for the code fixes (Linux)</summary>

```console
$ go test ./codersdk/ -run TestPackagedCoderEnvKeepsDefaults -count=1 -v
--- PASS: TestPackagedCoderEnvKeepsDefaults (0.00s)
ok  	github.com/coder/coder/v2/codersdk	0.071s

$ go test ./cli/clilog/ -run TestBuilder -count=1 -v
--- PASS: TestBuilder (0.00s)
    --- PASS: TestBuilder/NoSinks (0.00s)
        --- PASS: TestBuilder/NoSinks/JSONDevNull (0.00s)
        --- PASS: TestBuilder/NoSinks/StackdriverDevNull (0.00s)
        --- PASS: TestBuilder/NoSinks/NoConfiguration (0.00s)
        --- PASS: TestBuilder/NoSinks/HumanDevNull (0.00s)
    --- PASS: TestBuilder/WithHuman (0.00s)
    --- PASS: TestBuilder/WithFilter (0.00s)
    --- PASS: TestBuilder/WithJSON (0.00s)
    --- PASS: TestBuilder/Verbose (0.00s)
    --- PASS: TestBuilder/FromDeploymentValues (0.01s)
        --- PASS: TestBuilder/FromDeploymentValues/Defaults (0.00s)
        --- PASS: TestBuilder/FromDeploymentValues/EmptyHumanEnv (0.00s)
        --- PASS: TestBuilder/FromDeploymentValues/Override (0.00s)
ok  	github.com/coder/coder/v2/cli/clilog	0.171s

$ TMPDIR=$HOME/.cache/agentexec-tmp go test ./agent/agentexec/... ./coderd/provisionerdserver/... -count=1
ok  	github.com/coder/coder/v2/agent/agentexec	4.236s
ok  	github.com/coder/coder/v2/coderd/provisionerdserver	2.404s

# Full build of the server (go build ./cmd/coder). An empty value stops it before it connects to the database.
$ CODER_HTTP_ADDRESS= coder server --postgres-url 'postgres://127.0.0.1:1/x?sslmode=disable'
Encountered an error running "coder server", see "coder server --help" for more information
error: TLS is disabled. Enable with --tls-enable or specify a HTTP address

# With the variable unset, the server passes that check and goes on to the database.
$ coder server --postgres-url 'postgres://127.0.0.1:1/x?sslmode=disable'
2026-11-13 02:19:41.901 [warn]  ping postgres: retrying  error="dial tcp 127.0.0.1:1: connect: connection refused"  try=11
Encountered an error running "coder server", see "coder server --help" for more information
error: connect to postgres: connect to postgres: unable to connect after 11 tries; last error: dial tcp 127.0.0.1:1: connect: connection refused

# An empty log location with no other sink still stops the server.
$ CODER_LOGGING_HUMAN= coder server --postgres-url 'postgres://127.0.0.1:1/x?sslmode=disable'
Encountered an error running "coder server", see "coder server --help" for more information
error: make logger: no loggers provided, use /dev/null to disable logging

# /dev/null passes the logger check. The server prints no log lines and goes on to the database.
$ coder server --log-human=/dev/null --postgres-url 'postgres://127.0.0.1:1/x?sslmode=disable'
Encountered an error running "coder server", see "coder server --help" for more information
error: connect to postgres: connect to postgres: unable to connect after 11 tries; last error: dial tcp 127.0.0.1:1: connect: connection refused
```

</details>

## Linear

Fixes DOCS-1583, DOCS-1585, DOCS-1586, DOCS-1587, DOCS-1588, DOCS-1589,
DOCS-1590, DOCS-1591, DOCS-1592, DOCS-1593, DOCS-1594, DOCS-1595,
DOCS-1596, DOCS-1597, DOCS-1598, DOCS-1599, DOCS-1601, DOCS-1602,
DOCS-1603, DOCS-1604, DOCS-1605, DOCS-1606, DOCS-1607, DOCS-1608,
DOCS-1609, DOCS-1614, DOCS-1618, DOCS-1619, DOCS-1620, DOCS-1624,
DOCS-1635, DOCS-1639, DOCS-1644, DOCS-1651, DOCS-1652, DOCS-1653,
DOCS-1654, DOCS-1655, DOCS-1656, DOCS-1657, DOCS-1658, DOCS-1659,
DOCS-1660, DOCS-1661, DOCS-1662, DOCS-1663, DOCS-1664, DOCS-1665,
DOCS-1666, DOCS-1667, DOCS-1668, DOCS-1670, DOCS-1671, DOCS-1672,
DOCS-1673, DOCS-1674, DOCS-1675, DOCS-1676, DOCS-1677, DOCS-1678,
DOCS-1679, DOCS-1680, DOCS-1681, DOCS-1682, DOCS-1684, DOCS-1688,
DOCS-1690, DOCS-1691, DOCS-1692, DOCS-1693, DOCS-1694, DOCS-1695,
DOCS-1696, DOCS-1697, DOCS-1698, DOCS-1699, DOCS-1700, DOCS-1701,
DOCS-1702, DOCS-1704, DOCS-1705, DOCS-1706, DOCS-1707, DOCS-1708,
DOCS-1709, DOCS-1710, DOCS-1711, DOCS-1712, DOCS-1713, DOCS-1714,
DOCS-1715, DOCS-1716, DOCS-1717, DOCS-1718, DOCS-1719, DOCS-1720,
DOCS-1721, DOCS-1722, DOCS-1723, DOCS-1725, DOCS-1726, DOCS-1727

Part of DOCS-1600, DOCS-1689, DOCS-1669, DOCS-1687

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

### Scope

- One PR for all findings, as agreed with the reviewer. The code fixes
are separate commits so an owner can ask for any of them to move to its
own PR. Nothing in the PR is a breaking change, so the title has no `!`.
- A finding was skipped only when an open PR already covers it, or when
every available wording would assert an undecided product behavior.
- Each validation comment on the Linear issues records the evidence, the
corrections to the original finding, and what was not verified.

### Docs or code

- The default was a docs-only fix that describes what the code does.
- A code fix was chosen when the docs describe a behavior the code
plainly intended and the code change is small and testable: the packaged
env file, the log sink check, and the log line for the environment
variable presence check.
- The `error` merge strategy and the nice value ordering started as code
fixes and went back to docs-only after review. The first breaks existing
template versions. The second weakens a deliberate security ordering.
- The SCIM `userName` finding (DOCS-1609) took the docs path. The
handler is unchanged.

### Wording choices worth a second look

- `feature-stages.md` says `--experiments=*` enables only the
experiments marked safe, and points to the "Get safe experiments" API.
It does not list the other experiments, because the list would drift and
those experiments are hidden on purpose. The `--experiments` flag help
now says the same.
- `agent-metadata.md` replaces the writes-per-second formula with a
description of the batcher (each server replica writes one statement
every 5 seconds, or sooner at 500 entries).
- `extending-templates/index.md` no longer calls `startup_script`
deprecated. The provider documents it as an alias for a `coder_script`.
- `postgres-ssl.md` separates client verification from server
verification, so the server verification steps work alone.
- `rpm.md`, `upgrade.md`, and the 2.29 to 2.34 ESR upgrade page explain
the empty `CODER_HTTP_ADDRESS=` line that older packages shipped,
because upgrades keep the old file. The behavior changed in v2.34.0 with
the serpent upgrade in #24926.
- The keep-alive script in `docs/reference/index.md` reads the current
deadline and skips the request when it is already later. The comparison
is on text, so it applies only when the API returns a UTC timestamp,
which needs the database to use the UTC time zone. Otherwise the script
sets the deadline on every pass, as it did before, and the page says so.
- `external-auth.md` anchors the new GitHub Enterprise regex example.
The older unanchored examples on that page and on `git-providers.md` are
not changed here.

### Self-review findings that were rejected

- "The builder opens for Template Admins": the Templates page needs a
successful deployment config read, which the Template Admin role does
not have.
- "Organization Admins can set AI model prices": the price write
authorizes against a site-level object, which organization-scoped grants
do not match.
- "The provisioner chart sets no default resources":
`helm/libcoder/templates/_coder.yaml` applies 2000m and 4096Mi when
`coder.resources` is empty.

### Automated review, round 1

The `coder-agents-review` app left 45 findings on `8853332`. Fixed: the
two reverts above, the anchored regex, the `coder.env` follow-ups (Lima
examples, upgrade notes, a comment in the file, and a test that covers
every option in the file), the clilog change, the two option
descriptions, and the docs findings (CORS behavior, token lifetime
example, keep-alive script, agent metadata, refresh token errors,
`switch` form type, `dbcrypt` skip list, and a stray line in a YAML
example).

Declined, with the reason on each thread:

- Refactoring the `agentexec` logging and renaming its log field: not
related to a docs conflict.
- Rewording the "process priority management not enabled (linux-only)"
log message: the docs quote the message, and the wording predates this
PR.
- Problems in code and docs that this PR does not change (the
`Capabilities` subtest, the Helm values comment, the AWS provider path
in `airgap.md`, and others in the review's out-of-scope list).

### Automated review, round 2

The app left 14 new findings on `04925bd`, and accepted the three
declined threads on `cli/agent.go`. All 14 are fixed. The main one: the
round 1 change that removed the "no loggers provided" error went too
far, because an empty log location would then start a server with no
logs. The error is back for every case except `/dev/null`.

Reported by the app as out of scope and not changed: the swagger
annotation for `GET /api/v2/experiments/available` declares an array,
but the handler returns an object with a `safe` array. Three Storybook
fixtures keep the old `--experiments` description.

### Automated review, round 3

The app confirmed that all round 2 findings are fixed, and left 10 small
findings on `f55cb6d` (8 P4, 2 Nit). All are fixed: the TLS condition
and the release range in the `coder.env` notes, one place for the
`/dev/null` rule in `clilog`, two test cases, a clearer test failure,
and the CPU example in `agent-metadata.md`.

### Automated review, rounds 4 and 5

Round 4 left one P4 on `8fffb38` (name the `--trace` option in the
logging note), which is fixed. Round 5 on `2ce754e` reports no new
findings and says every earlier finding is fixed or closed. The app did
not post an approval: it leaves its out-of-scope items and the code
fixes to a human reviewer. Two threads on `cli/agent.go` stay open on
purpose for the code owner.

### Doc-check review

The doc-check workflow left 12 comments on `2ce754e` (10 blocking, 2
suggestions). All are fixed in `c888885`: "refer to" or "visit" in place
of "see" for cross-references on the lines this PR added, the **New
template** label as the dashboard shows it, one instruction per step in
the server verification procedure of `postgres-ssl.md`, and two wording
changes in `process-priority.md`. The `CAP_SYS_NICE` sentence keeps a
short reason, which differs from the suggested text.

The `coder-agents-review` app then reviewed that commit (rounds 6 and
7). Round 6 left two P4 findings, fixed in `30b2c79`: the `failed to
adjust niceness` message is described once, in the troubleshooting
entry, with where it appears, and the client verification steps in
`postgres-ssl.md` render as one numbered list. Round 7 reports no new
findings. `2a6035c` then softens one sentence from that fix, because the
agent logs the stderr of devcontainer CLI commands. The app was not run
again on that commit.

### Adjacent gaps found and not fixed here

- `add-envbuilder.md` has the same `zip` command that
`template-from-scratch.md` had.
- `template-from-scratch.md` leaves the reader in `build/` after `cd
$_`, before a step that runs from `template-tour`.

</details>

---

_Generated by Coder Agents on behalf of @nickvigilante._

---------

Co-authored-by: Ben Potter <me@bpmct.net>
2026-11-13 21:34:59 +00:00
Nick Vigilante bd268cb28d feat: add output formats to coder organizations members edit-roles (#30145)
Uses the `cliui` output helpers from #30508.

`coder organizations members edit-roles` printed only `Member roles
updated to [...]`, while `members list` supports `-o table|json` and
`-c`.

It now accepts `-o text|table|json` and `-c`.
Table and JSON show the updated member using the `members list` row type
and columns.

**Behavior change:** Additive.
Default text output is unchanged.
The command now fetches the member after updating roles, on every
invocation; if that read fails, it exits with an error even though the
roles were already updated.

<details>
<summary>Decisions</summary>

- The update endpoint doesn't return user data, so the member is re-read
to build the table and JSON rows.

</details>

Closes [CLI-27](https://linear.app/codercom/issue/CLI-27)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-11-13 14:33:32 -05:00
Nick Vigilante 32e1f2502f feat: add JSON output to coder tokens create (#30135)
Uses the `cliui` output helpers from #30508.

`coder tokens create` printed only the new token's secret, so scripts
had to call `tokens view` afterwards to get the token's ID, expiry, and
scopes.

This adds `-o/--output` with `text` (default) and `json`.
The JSON document contains the token's metadata from `APIKeyByID` plus
the one-time `key`.

**Behavior change:** Additive.
The default output is still just the secret, so `$(coder tokens create
...)` keeps working.
The command now makes one extra API call after creating the token; if it
fails, the command prints a warning to stderr and still outputs the
secret rather than exiting with an error.

<details>
<summary>Decisions</summary>

- The metadata lookup uses the key ID parsed from the `<id>-<secret>`
token, the same convention `tokens view` and `tokens remove` use.
- A failed metadata lookup never fails the command, because the token
already exists and the secret can't be shown again.

</details>

Closes [CLI-14](https://linear.app/codercom/issue/CLI-14)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-11-13 12:45:32 -05:00
Nick VigilanteandJeremy Ruppel 3def3bf5a3 feat: add JSON output to coder provisioner keys create (#30152)
Uses the `cliui` output helpers from #30508.

`coder provisioner keys create` printed the new key's secret as prose,
so scripts provisioning external provisioners had to scrape it and look
up the key's ID and tags separately.

It now accepts `-o text|json`.
JSON is the key as `provisioner keys list` shows it (ID, name,
organization, tags, created at) plus the one-time `key`.

**Behavior change:** Additive.
Default text output is unchanged.
The command now fetches the new key's metadata with the returned secret
(`GET /api/v2/provisionerkeys/{key}`). If that fails, it prints a
warning to stderr, falls back to the name, organization and tags it sent
(leaving `id` and `created_at` unset), and still outputs the secret.

<details>
<summary>Decisions</summary>

- `CreateProvisionerKey` only returns the secret, so the key's metadata
comes from `GetProvisionerKey(secret)`, the same lookup `coder
provisioner start` uses. This replaced an earlier list-and-match-by-name
approach, per review.
- A failed lookup never fails the command, because the key already
exists and the secret can't be shown again.

</details>

Closes [CLI-36](https://linear.app/codercom/issue/CLI-36)

_This PR was generated by Coder Agents on behalf of @nickvigilante._

---------

Co-authored-by: Jeremy Ruppel <jeremyruppel@users.noreply.github.com>
2026-11-12 08:58:37 -05:00
Ehab Younes 1126533c31 feat: export workspace last used time to Prometheus (#31346)
Add an opt-in coderd_workspace_last_used_timestamp_seconds gauge that
reports workspaces.last_used_at, the value the dormancy threshold
measures inactivity from. To enable it, set
--prometheus-collect-workspace-stats or
CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS.

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

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

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

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

Refs AIGOV-514

## Open questions for reviewers

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

## Verification

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

`TestServer_AIGatewayEmbedded` fails when the new check is removed.

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

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

</details>

---

Generated with Coder Agents; reviewed, revised, and verified by
@mollymaefraser.
2026-11-11 11:50:16 +00:00
Ethan a0be9d0e1d feat: make message_agent always steer (#31175)
`message_agent` no longer takes an `interrupt` flag, and always steers.
If the child is busy, it gets the message before its next model call and
keeps working. To correct or redirect a busy child, the parent just
calls `message_agent`, and `interrupt_agent` only stops it, which is the
same split the API has after #31174. The tool result also drops
`interrupted`, as it was just whether the child was running before the
send.

That was the last caller of the interrupt busy behaviour, so chatd and
chatstate drop it too. `SendMessage` never interrupts now. On a busy
chat it only ever adds the message to a lane, so the sends that moved a
running chat to interrupting, or a `requires_action` chat back to
running, are gone, along with the send's inline interruption finish for
chats with no worker. Most of the diff is deleted tests.

A steer send to a paused chat, or to an errored chat whose next message
is being edited, no longer fails with a 429 at the queue limit when it's
delivered straight away, which is whenever the message being edited is a
queue message.

Part of CODAGT-1140
2026-11-09 15:55:17 +11:00
Kyle CarberryandJon Ayers b798061108 perf: reuse import-time lock file and cache terraform version (#29825)
Workspace builds now reuse the lock file that `terraform init` wrote
during template import, which takes a minimal Docker build from about
3.1s to 1.65s, measured from build created to agent connected.

---------

Co-authored-by: Jon Ayers <jon@coder.com>
2026-11-06 19:32:46 -06:00
Atif Ali fb6d287528 fix: write agent host entries with config-ssh --no-wildcard (#31192)
`coder config-ssh --no-wildcard` writes one `Host` entry per workspace
and none per agent. OpenSSH only applies exact `Host` matches, so with
`--no-wildcard` (and without Coder Desktop):

- `ssh <agent>.<workspace>.<owner>.coder`, the hostname the dashboard's
**Connect via SSH** button shows and Coder Connect serves, doesn't
resolve.
- Agents in multi-agent workspaces can't be reached with plain `ssh`;
`ssh <workspace>.coder` hits "multiple agents found".

Before wildcard hosts (#14986), `config-ssh` wrote an entry per agent.
`--no-wildcard` (#26753) brought back per-workspace entries only.

## Change

With `--no-wildcard`, also write an `<agent>.<workspace>.<owner>` entry
for each agent, using the same prefix/suffix as workspace entries:

```
Host dogfood.coder                        # unchanged
Host coder.dogfood.matifali.coder         # new
Host dev.dogfood.matifali.coder           # new
```

`coder ssh --stdio` already parses `agent.workspace.owner`, so no
ProxyCommand changes are needed.

- **Non-breaking**: existing `<workspace>` entries are unchanged; agent
entries are added after them. Without `--no-wildcard` the config is
unchanged.
- **Workspaces without agents on their latest build** (stopped, or a
start that is pending or failed): known agents come from that
workspace’s most recent successful start using the same template
version, not template-import defaults. Lookups are cached per workspace
and bounded to eight concurrent requests. Missing or incompatible
history leaves only the workspace entry; lookup failures also produce a
warning.
- **Devcontainers**: while a workspace runs, its sub-agents get entries
too.
- **Validation**: workspace and owner names retain `codersdk.NameValid`
checks. Agent components permit safe ASCII letters, digits, underscores
and hyphens, preserving Terraform-precreated names such as `dev_box`
while rejecting SSH syntax, leading options and doubled-hyphen
delimiters. Workspace entries are written as before, including legacy
names (related: SEC-378).

The flag description, generated CLI reference/help, and workspace access
and Gateway tips describe known agents. The guide explains when stopped
workspaces have only a workspace entry and how to populate their agent
entries.

## Verification

`TestConfigSSH_NoWildcard` verifies two stopped workspaces sharing a
template version but having different actual agents, import defaults
that differ from both, a precreated `dev_box` agent, and injection
rejection. History tests cover pagination, failed/newer builds, version
changes and request failures. Regression controls failed before the
fixes and passed afterward. Race tests, strict Go lint and docs checks
pass on the refreshed stack.

<details>
<summary>Validation commands</summary>

Latest rebase preserves the implementation and carries the docs edits to
main’s renamed `docs/workspaces/` paths. The SSHButton documentation
links and preview URL use the new routes. Revalidated the full
SSH/ping/config CLI race suite, strict lint, 25 frontend tests, 53
stories, and docs/manifest/redirect checks. The local shell’s Oh My Zsh
update prompt interrupted the first race run; the unchanged suite passed
with `DISABLE_AUTO_UPDATE=true` scoped to the test process.

Review decision: use workspace-specific build history because template
imports cannot represent chosen workspace parameters. Preserve the
last-start template-version boundary rather than inventing agents when
no compatible history exists. Both stack branches are rebased onto
`main` at `63b5c4d64a`.

```sh
go test -race -tags=testsmallbatch ./cli -run 'TestConfigSSH|Test_noWildcardHostNames|Test_previousStartResources|TestCommandHelp' -count=1 -parallel=4
GOMEMLIMIT=6GiB make lint/go/new-code GO_LINT_CONCURRENCY=4
```

Docs validation also passed emdash, HTML-table and manifest checks,
targeted markdownlint, table formatting and Vale.

</details>

Fixes
[CLI-68](https://linear.app/codercom/issue/CLI-68/config-ssh-no-wildcard-does-not-write-host-entries-for-workspace).
#31188 is stacked on this PR.

Preview:
https://coder.com/docs/@fix%2Fconfig-ssh-no-wildcard-agents/workspaces/workspace-access

> 🤖 This PR was created with the help of Coder Agents, and has been
reviewed by my human. 🧑💻
2026-11-05 10:01:33 +05:00
a9643ffcd3 feat: add rootless Podman starter template and EKS Auto Mode guidance (#30804)
## Summary
- EKS Auto Mode supports kernel sysctls via the NodeClass
`advancedCompute` field since 2026-10-01 ([AWS
announcement](https://aws.amazon.com/about-aws/whats-new/2026/10/eks-auto-mode-advanced-compute-config/)),
so rootless Podman no longer requires a separate managed node group;
document the custom NodeClass recipe and the `idsPerPod` requirement for
`hostUsers: false` pods
- Document native overlay storage (real-filesystem graph root + clearing
the image's `mount_program` pin), which removes the `/dev/fuse` device
plugin dependency on kernel 5.13+
- Add a "Nested container engines" section: one level of nesting is
supported; the dev container `docker-in-docker` feature is not, with
`docker-outside-of-docker` as the documented alternative
- Add the `kubernetes-podman-rootless` starter template (`coder
templates init --id kubernetes-podman-rootless`):
- persistent `/home/coder` volume (`fs_group_change_policy =
"OnRootMismatch"`), so repos, images and build cache survive restarts
- startup script fails with the Podman log when the API socket doesn't
start
  - `kubernetes_pod_v1`, pinned to amd64 (the image is amd64-only)

Refs DOCS-1277. Related follow-up: DOG-74.

## Testing
- 2026-10-14, EKS Auto Mode v1.37 sandbox: rootless Podman on pure Auto
Mode nodes with native overlay, including builds with cache mounts,
Testcontainers-style Postgres, and the Docker-compatible API socket
- 2026-11-02, same cluster, starter template at 0227e04 on a 20 GiB gp3
home volume:
- ext4 home, `overlay` driver with native overlay diff, graph root on
the volume
- `podman run`, classic `docker build` via the agent's `DOCKER_HOST`,
Docker API socket
- after stop/start: home files, all images, and subuid-owned layer files
(`101233:101233` on disk, `1234:1234` in the container) intact; built
image runs without a rebuild
- Fail-fast startup path tested with a stub `podman` only (exit 1,
prints the `newuidmap` error)
- `terraform validate` (no deprecation warnings), markdownlint, CI `gen`
and `lint-docs`

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-11-03 22:47:39 +00:00
Nick Vigilante 1893b80805 fix(docs/reference/cli): regenerate ping docs with table headers (#31292)
## Summary

Regenerate `docs/reference/cli/ping.md` so `main` passes
`lint/docs-html` and the `offlinedocs` unstaged-files check again.
#30148 committed the page from a branch that predated #30879, which gave
CLI option tables a `Property | Value` header.

## Changes

- Regenerate `docs/reference/cli/ping.md` with `make -B
docs/reference/cli/index.md`. No hand edits.

Linear: DOCS-1424

## Testing

- `make -B docs/reference/cli/index.md` reports that only `ping.md`
changed, and the diff matches what CI reported.
- `go run ./scripts/docshtmlcheck` passes.

---

> [!NOTE]
> Generated by Coder Agents on behalf of @nickvigilante.
2026-10-26 13:44:04 -04:00
Nick Vigilante d469763bc0 feat: add JSON output to coder ping (#30148)
`coder ping` printed per-pong lines and a summary table with no
structured output, so monitoring scripts had to parse text.

It now accepts `-o table|json` (default `table`, today's output) through
the shared CLI output formatter.
JSON is a single document at the end with each attempt (sequence, time,
latency, direct or DERP region, error) and the summary.

**Behavior change:** Additive.
Default output is unchanged.
`-o json` requires `--num` and fails early without it, because pings
otherwise continue until interrupted.
In JSON mode, the per-pong and diagnostic lines that normally go to
stdout go to stderr, so stdout contains only the JSON document.

<details>
<summary>Decisions</summary>

- One document at the end rather than streaming, because it's simpler to
parse.
- Require `--num` with `-o json`. In the default continuous mode, a
single document would leave stdout empty until Ctrl+C and hold every
pong in memory. Newline-delimited JSON per pong is a possible follow-up
if continuous machine-readable output is needed.
- Durations are reported as `*_ms` floats because `time.Duration`
doesn't marshal to a portable unit.
- Output goes through the shared `cliui.NewOutputFormatter` (table and
JSON), matching `coder speedtest`. This also adds the standard `-c,
--column` flag for the summary table.

</details>

<details>
<summary>CI note</summary>

`Storybook` failed once on 61b39ef70b inside Pixel (`build finished with
status failed`). This PR changes no frontend files; the job passed on
rerun.

`test-go-pg (ubuntu-latest)` failed on 8e6276921e in [run
38948569950](https://github.com/coder/coder/actions/runs/38948569950/job/117134059011)
on `TestChatTurnStopsAtStepLimit/Default` in `coderd/x/chatd`. This PR
doesn't touch `coderd/x/chatd`, so the failed job was re-run.

</details>

Closes [CLI-32](https://linear.app/codercom/issue/CLI-32)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-10-26 13:17:51 -04:00
Nick Vigilante 6e51c66a97 docs: give every table header cell text and fail lint on empty ones (#30879)
## Summary

axe reports `empty-table-header` on 116 generated CLI reference pages
and several hand-written pages: a header cell with no text is announced
by screen readers as an unnamed column. This PR gives every table header
cell in `docs/` text, and adds a lint check so empty header cells can't
come back.

## How to review this PR

- `docs/reference/cli/`: 116 files, these all generate identically, so I
would only spot check 2-3 of them and skip the rest
- `docs/*` outside of `docs/reference/cli/`: 6 files, normal review of
these
- `scripts`: 5 files, code review of the Bash and Go files to make sure
we're properly inserting headers into each table

## What changed

**Generator.** `scripts/clidocgen` wrote an empty header row (`| | |`)
over each option's metadata table (Type, Environment, YAML, Default). It
now writes `| Property | Value |`. Subcommand tables already had `Name |
Purpose` and are unchanged. Regenerated with `make
docs/reference/cli/index.md`: 116 files under `docs/reference/cli/`
change. The header rows change, and the body rows of each option table
are re-padded to the wider first column; the content is otherwise
identical. Every option on those 116 pages now shows a visible `Property
| Value` header row above Type, Environment, YAML, and Default, so this
is a visual change on the docs site as well as a screen reader one. The
CLI's own `--help` output doesn't use this template, so it's unchanged.

**Audit logs.** `docs/admin/security/audit-logs.md` already has `Field |
Tracked` headers on `main` (the generator writes them), so there was
nothing to change there; the live-site finding predates that.

**Hand-written tables.**
- `docs/admin/networking/port-forwarding.md`: the CORS matrix had three
empty spanning corner cells. The corner now reads `From user` and `From
workspace` (spanning the three row-header columns, beside the Alice/Bob
and Workspace rows) and `To user`, `To workspace`, `To app` (over the
three row-header columns). The grid is still 3 header rows by 7 columns.
The From cells have `scope="row"` and the other header-row cells
`scope="col"`, so the From labels don't become column headers for the
body's label columns; the body's user, workspace, and app labels are
`<th scope="row">`; and a `<caption>` says columns are the origin and
rows the destination.
- `groups-roles.md`, `airgap.md`, `scale-testing.md`,
`workspace-tags.md`: these four corner cells are already filled by
#30873. The new check would fail CI without them, so this PR carries the
same four lines, byte-identical to #30873 (`Permission`, `Component`,
`Scenario`, `Input`), so whichever PR merges second rebases without
conflict. If #30873 merges first, these hunks drop out.

**New check.** `scripts/docshtmlcheck` (`make lint/docs-html`, part of
`make lint`) now also reports `empty-table-header`. I put it there
because that checker already parses every Markdown file under `docs/`,
generated pages included, with goldmark and tokenizes raw HTML with
`golang.org/x/net/html`, and it already runs in CI. A markdownlint
custom rule would have needed a new JS rule and HTML parsing there.
- Markdown pipe tables: the header row, via goldmark's GFM table
extension.
- Raw HTML tables: every `<th>`, tracked across HTML blocks, with
entities decoded and whitespace trimmed, so `<th></th>`,
`<th>&nbsp;</th>`, and `<th><br></th>` are all reported. Markdown
between the HTML blocks of an open `<th>` counts as its text. Tables in
code blocks are ignored.
- Output: `docs/x.md:29: empty-table-header: header cell 1 has no text
(table's first header "Auditor")`, plus a summary footer.
- The tokenizer loop moved out of `scanNode` into a shared
`tokenizeSegments` helper so both checks use it; `scanNode`'s behavior
is unchanged.
- The style guide's checks table gets one row; the README for the
checker describes the rule.

## Testing

- Tests first: `TestCheckTables` (now 22 cases) and
`TestRunEmptyTableHeader` failed against a stub, then pass. The existing
`docshtmlcheck` tests pass unchanged.
- `go run ./scripts/docshtmlcheck` on `main` reports 1,561 empty header
cells (116 CLI pages, port-forwarding, and the four #30873 tables); on
this branch it reports none.
- `go test ./scripts/docshtmlcheck/ ./scripts/clidocgen/
./scripts/docgenenv/`, golangci-lint on the changed packages, `make
lint/docs-html lint/docs-manifest lint/docs-gen-filter lint/emdash`,
`pnpm run check-docs`, and Vale on the changed hand-written pages all
pass.
- `make gen` couldn't run to completion locally (no `protoc-gen-go`);
CI's gen check covers it. The CLI pages were regenerated with the repo's
own target.

Review feedback applied in cfd29a2160 (entities decoded in Markdown
text, image alt text and autolinks count as text), 709a58f603 (per-kind
counts, finding order, CLI generator note), 8e61ff3afa (CORS matrix
scopes and caption), and b807bcbbc7 and 2871f89bdf (style guide rule
section, `make lint/docs-html` in the checks table, coverage counts).

Linear: DOCS-1308

---

🤖 Built with AI assistance.
2026-10-21 10:58:04 -07:00
Nick Vigilante d187dea338 docs: end every page description with a period and lint for it (#30863)
## Summary

Page descriptions in the docs were inconsistent about ending with a
period. This makes every page description end with one and adds a lint
so it stays that way.

A page description can come from three places, and the docs site reads
front matter first and falls back to the manifest:

- the hand-written YAML sidebar sources under `docs/manifest/`
(including `children_from` overlays),
- the generated fragments (`docs/manifest/generated/cli.json`,
`rest-api.json`), compiled into `docs/manifest.json`,
- a page's own front matter (today only the generated CLI and API
reference pages carry one).

The check covers all three. For the CLI, the description comes from each
command's `Short`, which stays unpunctuated by CLI-help convention, so
`clidocgen` adds the period when it writes the docs description instead
of changing 120 `Short` strings and the CLI golden files.

## What the lint checks

`make lint/docs-manifest` (`docsmanifestgen check`, already part of
`make lint` in CI) now fails when a non-empty description doesn't end
with `.`. No description in the tree ends with `?` or `!`, so the rule
allows only a period. Errors name the source file, the sidebar
breadcrumb, and the description, for example:

```
install/plan/sizing.yml: Install > Plan your deployment > Coder Validated Architecture > Up to 1,000 users: description must end with a period: "Hardware specifications and architecture guidance for Coder deployments that support up to 1,000 users"
generated/api.json: General: description must end with a period: "General endpoints"
reference/cli/ping.md: Reference > Command Line > `ping`: front matter description must end with a period: "Ping a workspace"
```

The style guide's page-description rule now lists the requirement and
cites the checker, and `styleclaims` recognises
`scripts/docsmanifestgen` so the coverage table counts it as
tool-checked.

## Count of descriptions fixed

147 descriptions in `docs/manifest.json`:

- 27 hand-written descriptions in 15 sidebar source files,
- 120 generated CLI descriptions, which also update the front matter of
120 CLI reference pages.

The REST API descriptions already ended with a period. No description is
otherwise reworded.

## Testing

- New table cases in `scripts/docgenenv` (section route, child route,
overlay, generated fragment, front matter, and a `?` ending) and
`scripts/clidocgen`, written first and failing before the change.
- `docsmanifestgen check` on the unfixed tree reported the 27 source
descriptions; after the fixes and regeneration it passes.
- `go test ./scripts/docgenenv/ ./scripts/clidocgen/
./scripts/docsmanifestgen/ ./scripts/styleclaims/
./scripts/apidocgen/...`
- `golangci-lint run` on the changed packages, `pnpm run check-docs`,
`go run ./scripts/styleclaims`, `scripts/check_emdash.sh`, and
`docsmanifestgen fmt` (no changes).

Linear: [DOCS-1304](https://linear.app/codercom/issue/DOCS-1304)

---

🤖 Built with AI assistance.
2026-10-20 18:51:44 -04:00
Nick Vigilante 93205d98bc feat: add JSON output to coder ai-gateway keys create (#30139) 2026-10-16 16:01:21 -04:00
Steven Masley 03cba25a63 feat: list a workspace build's secrets in coder secret list (#30388)
`coder secret list` now shows the current workspace build's secrets next to your user secrets, and which user secrets they replace. Part of [RELAY-7](https://linear.app/codercom/issue/RELAY-7/agent-relay-deliver-provider-credentials-via-coder-secrets-instead-of).

**Stack** (design decisions in #30248)
1. #30248 Database schema, queries, and RBAC
2. #30249 Encryption at rest
3. #30250 Set secrets on workspace builds
4. #30251 Deliver secrets to the agent
5. #30252 Docs
6. **#30388 List a build's secrets (this PR)**
7. #30459 Audit a build's secrets

- New `GET /workspacebuilds/{workspacebuild}/secrets` lists a build's secrets (metadata only, never values) and which user secret each one replaces.
- Inside a workspace, `coder secret list` includes the current build's secrets. Outside a workspace, use `--workspace` or `--build-id`.
- The agent now exposes `CODER_WORKSPACE_BUILD_ID`, so the CLI knows which build it is running in.
- The agent manifest and the new endpoint use one shared resolver, so they always agree on which secret wins.
- The user secret API is unchanged.

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

- The manifest carries `workspace_build_id`; the agent sets it as `CODER_WORKSPACE_BUILD_ID`.
- `coderd/workspacesecrets.Resolve(user, build, policy)` decides which secret is delivered on each env var and file. The manifest no longer relies on entry order.
- `codersdk.WorkspaceSecret` embeds `UserSecret` and adds `workspace_build_id`, `ephemeral`, `cleared_at`, `env_replaces`, and `file_replaces`. Secrets whose values a later build cleared are still listed, with `cleared_at` set.
- CLI columns: `source` and `replaced by` are shown by default only when a build is included; `ephemeral` is opt-in. The CLI makes two requests: user secrets, then build secrets.
- Agents that predate the build ID fall back to `CODER_WORKSPACE_ID` and its latest build.

</details>

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

(existing decision log, unchanged)

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 17:40:00 -05:00
Nick Vigilante c6a47c4428 docs: replace references to the retired Enterprise license tier (#30853)
## Summary

Coder has only Community and Premium license tiers, but several docs
pages, CLI help strings, and SDK field comments still called features
"Enterprise" or "enterprise-only".
This PR changes them to say Premium and regenerates the reference docs
built from those strings.

Resolves
[DOCS-1298](https://linear.app/codercom/issue/DOCS-1298/remove-references-to-the-retired-enterprise-license-tier).

## Changes

- `docs/admin/users/quotas.md`: Replace "scoped to Groups in Enterprise
and organizations in Premium" with a correct sentence. Quotas are
Premium, allowances are set on groups, and each user's budget is
calculated separately in each organization (per
`GetQuotaAllowanceForUser`).
- `docs/user-guides/workspace-lifecycle.md`: Replace "Enterprise" with
Premium, and correct the quotas sentence to match the quotas page.
- `docs/ai-coder/agents/platform-controls/mcp-servers.md`: Replace
"enterprise entitlement" with Premium license.
- `cli/templatecreate.go`, `cli/templateedit.go`: Update
`--require-active-version`, `--allow-user-autostart`, and
`--allow-user-autostop` help text. Point the `--require-active-version`
help at the renamed `#template-update-policies` section, because the old
`#require-automatic-updates-enterprise` anchor is broken. Make the
errors for these flags tier-neutral.
- `enterprise/cli/features.go`: `coder features` now says "List license
features and entitlements", and its AGPL error no longer names a tier.
- `codersdk/templates.go`, `codersdk/organizations.go`: Update field
comments that feed the API reference and TypeScript types.
- `docs/reference/glossary.md`: The Premium entry now says "paid license
tier" instead of "paid enterprise tier".
- `docs/.style/style-guide/voice-and-tone.md`: The example sentence now
says "Premium licensing".
- Regenerated: CLI golden files, `docs/reference/cli/`,
`docs/manifest.json`, `docs/manifest/generated/cli.json`,
`docs/reference/api/`, `coderd/apidoc/`, and
`site/src/api/typesGenerated.ts`.

## Testing

- `go test ./cli -run 'TestCommandHelp|TestCliTemplateCreate'` and `go
test ./enterprise/cli -run
'TestEnterpriseCommandHelp|TestTemplateCreate|TestTemplateEdit|TestFeaturesList'`
pass.
- The pre-commit hook passed, including `make gen`, `fmt`, `lint/go`,
`lint/ts`, `lint/markdown`, and a slim build.

<details>
<summary>Decisions and out-of-scope items</summary>

### Decisions

- **Premium wording and legacy Enterprise licenses:** Coder still
accepts existing Enterprise licenses, and `FeatureSetEnterprise`
includes the features labeled Premium here. Docs and help text say
"Premium" because that is the tier sold today, and about 25 other docs
pages already use "Premium feature". Error strings are tier-neutral, so
they're accurate for every license holder.
- **Glossary and style guide:** The issue marked these as borderline.
Both were one-word changes, so I made them.

### Not changed

- `docs/reference/api/enterprise.md` keeps the "Enterprise" sidebar
title. It comes from the swagger tag on the `enterprise/` Go package, so
renaming it is a larger change.
- Other "Enterprise" references the review flagged as out of scope: the
`coder server --help` option group, quiet hours SDK comments, internal
`coderd` comments, and the dashboard's "Enterprise" badge on the
require-active-version option.
- No docs page says that legacy Enterprise licenses are still valid.
- Uses that don't refer to the license tier: GitHub Enterprise, Red Hat
Enterprise Linux, "enterprise environments", and `enterprise/` package
paths.

</details>

---

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-10-15 17:46:05 +00:00
dylanhuff-at-coder c856d5fb22 feat: accept template version IDs in --template-version (#30563)
Follow-up to #30199. `--template-version` on `coder create`, `start`,
`stop`, and `update` (plus `--stop-template-version` on `update`) now
takes a template version ID as well as a name. Passing a version UUID
used to 404 with a pretty unhelpful `get template version by name`
error.

`resolveTemplateVersionID` still looks up by name first, so a version
that happens to be named like a UUID resolves the same way it did
before. If that 404s and the input parses as a UUID, it falls back to
fetching the version by ID. Either way the version has to belong to the
selected template. That check matters most for `create`, which only
sends the version ID and lets the server derive the template from it, so
without it `coder create --template foo --template-version <id of a bar
version>` would quietly create a `bar` workspace.

The name is now path-escaped before the lookup. Previously something
like `../../../templateversions/<id>` could reach other API routes
through the name lookup and skip the template check entirely.

Not-found errors now read `template version "x" not found for template
"foo"` instead of the raw SDK error, so anything matching on the old
text will need updating. Flag help and the generated CLI docs say "name
or ID" now.
2026-10-14 08:52:36 -07:00
Garrett Delfosse 2b9fad8bba feat: add chat project sharing database layer (#30479)
Database and authorization layer for chat project sharing (experiment
`chat-projects`), part 1 of 2. #30439 adds the API on top of it. Nothing
here changes behavior: projects start with empty ACLs, no endpoint
writes them yet, and deleting a project still detaches its chats.
Project deletion is in #30683.

- **Schema:** migration `000621` adds `user_acl` and `group_acl` jsonb
columns to `chat_projects`, typed as `ChatACL` like chats, with GIN
indexes. It also adds the `chat_project:share` API key scope.
- **Queries:**
- `GetChatProjectsOwnedOrSharedWithUserID`: owned projects plus projects
with an ACL entry for the user directly, through a group, or through the
Everyone group (whose ID is the organization ID). Entries count only for
members of the project's organization. Keys match regardless of actions,
so dbauthz filters the rows.
- `IsChatProjectAccessibleByUserID`: whether a user owns a project or
holds a `read` or `*` grant on it, for code running under a system
subject. With sharing disabled, dbauthz answers owner-only.
- `GetChatProjectByIDForUpdate`: lets the ACL update read, modify, and
write in one transaction.
  - `UpdateChatProjectACLByID`.
- **RBAC:**
- New `share` action on `chat_project`. dbauthz requires it to update
the ACL.
- `ChatProject.RBACObject` attaches the project ACL. Memory objects get
a derived ACL: project `read` grants memory read, and `read` with
`update` grants memory create and delete. Wildcard grants count. Read
sharees change memories through their chats' agents, which #30439 gates.
Project instructions authorize through the same object, so a `read`
grant reads them and an `update` grant edits them.
- `--disable-chat-sharing` also covers projects: ACLs are ignored, the
ACL update is rejected, and roles deny `chat_project:share`. The help
text and chat sharing docs say so.
- **Audit:** `user_acl` and `group_acl` changes are tracked.
- **Tests:**
- Querier tests run the access queries both raw and through dbauthz
(owner, direct user, group, Everyone, wildcard grants, a member of
another org, grants without read).
- RBAC object and memory ACL tests, with an authorizer check, in both
sharing modes.
- dbauthz cases including the disabled guards, and the
`chat_project:share` negation in the roles test.

The generated TypeScript changes only add the new scope value.

> Generated by Coder Agents.
2026-10-14 10:42:00 -04:00
Thomas Kosiewski f923f4a525 chore!: remove the chat automations experiment (#30412)
Removes the experimental Chat Automations feature (`chat-automations` experiment) from main. This reverts the 16-PR stack that added it and adds two forward migrations that undo its schema and credential changes.

> [!WARNING]
> **Upgrade consequences**
>
> - **Automation data is deleted.** Migration 000615 drops the `chat_automations` table and deletes every queued message an automation delivered. Chats, their messages and ordinary queued messages stay. Messages lose their automation provenance (`automation_id`, `input_id`).
> - **Automation-only credentials are revoked.** Migration 000616 deletes API keys, OAuth2 codes and OAuth2 tokens whose only scopes (or allow-list entries) were `chat_automation:*`. Mixed credentials keep their other scopes. Custom roles lose their `chat_automation` permissions. OAuth2 apps that allowed only `chat_automation` scopes get the whitespace allowlist that grants nothing, as in 000595.
> - **A coordinated restart is required.** Stop all old replicas before the new version runs the migrations. Old replicas read the dropped table and columns, so a rolling deploy is not supported.
> - **Remove `--chat-max-automations-per-owner` before upgrading.** The flag, the YAML key `chat.maxAutomationsPerOwner` and the env var `CODER_CHAT_MAX_AUTOMATIONS_PER_OWNER` are removed. A deployment that still sets the flag or the YAML key will not start (`unknown flag` / `unknown option`). The env var is ignored. This includes dogfood. No release or tag contains the flag.
> - **Down migrations restore the schema only.** 000616 down and 000615 down recreate the 000611 schema with empty tables. They do not restore deleted automations, webhook secrets, provenance, queued deliveries, revoked credentials, stripped permissions or the deleted experiment rule.

## What is removed

- The `chat-automations` experiment and its stored runtime rule (`experiment_rule:chat-automations`).
- The `--chat-max-automations-per-owner` deployment option.
- The `chat_automation` RBAC resource, its member and chatd grants, and the `chat_automation:*` API key scopes.
- The automation sqlc queries, dbauthz wrappers and audit table entries.
- The management routes under `/api/experimental/organizations/{organization}/chat-automations`, and the webhook route `POST /api/experimental/chat-automations/{automation}/events` with its rate limiter.
- The chatd management service, webhook publish, schedule loop, the `manage_automations` tool, and the chatstate admission seam and queue promotion guard that only automations used.
- The Agents Automations page, editor, nav entry, chat labels, the Manage automations toggle and the API client.
- The `archived:any` chat search value that the automations "View chats" dialog added.
- `docs/ai-coder/agents/automations.md`, its manifest entry, the glossary entry and the related rows.

Reverted PRs: #30085, #30096, #30112, #30117, #30127, #30134, #30160, #30166, #30167, #30171, #30187, #30207, #30214, #30217, #30219, #30220.

## What stays, and why

- Migrations 000609, 000610 and 000611, their fixture, and the #30297 lock fix with `migration000609_test.go` stay unchanged. Deployments such as dogfood already ran them.
- New migration **000615** reverses the schema changes of 000609 and 000611 against the current schema. It uses the same short-wait lock-and-retry block as 000609, and it rebuilds `chats_expanded` from main's current definition minus the two automation columns. New migration **000616** follows the 000595 Tasks removal for credentials and recreates `api_key_scope` without the five `chat_automation:*` values. It keeps the `chat_project_memory:*` values from 000612.
- The `chat_automation` value stays in the `resource_type` enum, and `codersdk.ResourceTypeChatAutomation` stays. Old audit log rows stay readable, as with `task` after the Tasks removal.
- The 000615 delete fires the existing queue-version trigger, so `queue_version` moves to `snapshot_version` for each affected chat. `snapshot_version` is not bumped: the coordinated restart restarts every stream loop from an empty state, and the site does not read the version fields.
- `coderd/x/chatd/ARCHITECTURE.md` drops the sections the stack added and gets back its pre-stack wording, merged with the later main edits to the same file.

## Notes for reviewers

- #30379 (chat project page) merged while this PR was in progress. It passed `manageAutomationsEnabled` in `AgentCreatePage.test.tsx` and listed an `automations` route in `AgentsPageLayout.test.tsx`. Later main commits also added automation props in `ConversationTimeline.test.tsx` and `ConversationTimelineWorkingBlocks.stories.tsx`. This PR removes all of them.
- Remaining `automation` matches under `coderd`, `codersdk`, `enterprise`, `site/src` and `docs` are intended:
  - migrations 000609 to 000611, their fixture and `migration000609_test.go`;
  - the new 000615 and 000616 migrations and `migration000615_test.go`;
  - the `chat_automation` resource type in `dump.sql`, `models.go`, `codersdk/audit.go`, the generated API docs, `swagger.json` and `typesGenerated.ts`;
  - unrelated uses of the word "automation" (docs, `chatlabels_test.go`, `ratelimit.go`, `autostop.go`, `subagent_catalog.go`, `WorkspaceSharingSection.tsx`, `AgentChatPage.stories.tsx`).

Remote UAT on an isolated dev deployment passed. It upgraded a populated pre-removal database, then checked chats, queued messages, tokens, the 404 routes, the removed page and nav entry, and the experiments list.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_

![Agents sidebar after the upgrade, with no Automations entry](https://github.com/user-attachments/assets/bd446035-7fc8-4ca4-a735-3a4f36380738)
2026-10-11 19:57:49 +02:00
Nick Vigilante a8303a8f2b feat!: add output formats to coder schedule start, stop, and extend (#30136)
`coder schedule start`, `stop`, and `extend` printed the updated
schedule as a fixed table with no `-o` or `-c`, while `coder schedule
show` has both.

All four commands now share one formatter with the same row type,
default columns, `-o table|json`, and `-c`, so the output of a change
and of `show` is interchangeable.

**Behavior change:** Adds `-o` and `-c` to the three commands.
The default table output changes slightly: the WORKSPACE column no
longer includes the favorite-star prefix, matching `schedule show`.
Other columns are unchanged.

<details>
<summary>Decisions</summary>

- Previously these commands rendered `WorkspaceListRow`, which prefixes
the workspace name with a favorite icon. Using `scheduleListRow` for
consistency with `schedule show` drops that prefix.

</details>

Closes [CLI-15](https://linear.app/codercom/issue/CLI-15)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-10-08 13:07:17 -04:00
Nick Vigilante 98bcc3afb7 fix!: remove the unused --yes flag from coder autoupdate (#30149)
`coder autoupdate` has registered `-y/--yes` since #10438 but never
prompts, so the flag did nothing.
This PR removes it.

**Breaking change:** `coder autoupdate` no longer accepts `-y/--yes`.
Scripts that pass it now fail with `unknown shorthand flag: 'y'`.
To fix them, drop the flag; it never had an effect.

<details>
<summary>Decisions</summary>

- The first version kept `-y` as a hidden no-op so existing scripts
wouldn't break.
- Reviewers preferred removing it outright as a breaking change, since a
deprecation period would end in the same removal and the hidden flag is
cruft.
- The title uses `fix!:` and the PR carries `release/breaking`, so the
release tooling lists it under breaking changes.
- `cliui.HiddenSkipPromptOption()` landed on `main` through the
organizations create PR and stays there for that command; this PR no
longer touches it.
- The test now pins the new behavior: passing `-y` returns an unknown
flag error.

</details>

Closes [CLI-33](https://linear.app/codercom/issue/CLI-33)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-10-08 11:55:29 -04:00
dylanhuff-at-coderandNick Vigilante b4d51012da feat: allow template version selection for workspace builds (#30199)
Add named template version selection to `coder start` and `coder stop`,
and independent stop/start selection to `coder update` with
`--stop-template-version` and `--template-version`. Stop still defaults
to the workspace's current version, and update starts with the active
version by default. Explicit selections use the selected version for
parameter preparation and builds, keep server permissions authoritative,
and never silently fall back to the active version.

Classic stop builds retain previous parameter values omitted by the
selected stop version, so a later start can reuse them across separate
commands or an interrupted update. Declared parameters still follow
normal validation, and start builds still discard removed parameters.
Update now returns an error and retry guidance when a start apply fails
after stopping, including unflagged updates that previously returned
success.

Closes #29100


[PLAT-616](https://linear.app/codercom/issue/PLAT-616/cli-allow-specifying-a-template-version-for-stopstart-builds-and-both)

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-10-07 13:17:12 -07:00
Jakub Domeracki b4fb7901e6 docs: clarify that disable-password-auth also applies to owners (#30362)
The `--disable-password-auth` help text says owners can still sign in
with a password "to avoid potential lock out", and a comment in
`coderd/userauth.go` says the same. Neither is true. #6193 removed the
owner bypass on purpose, so the flag blocks password login for everyone.
The recovery advice was also wrong. It named a command that doesn't
exist (`create-admin`), and any admin that `create-admin-user` creates
while the flag is on still can't sign in.

This PR changes docs and comments only:
- Rewrites the flag description to say it applies to owners too and how
to recover access. Regenerated the CLI and config reference docs and the
golden files.
- Fixes the misleading comment in `coderd/userauth.go`.
- Adds the same warning and recovery steps to
`docs/admin/users/password-auth.md`.

> [!NOTE]
> Generated by Coder Agents on behalf of @jdomeracki-coder.
2026-10-07 19:03:46 +02:00
Nick Vigilante 237616a87d fix!: make --yes skip the rename confirmation prompt (#30151)
`coder rename` registers `-y/--yes`, but its confirmation asks you to
type the workspace name, and `cliui.Prompt` only honors `-y` for yes/no
prompts.
So `coder rename ws new -y` still blocked on input.

With `-y`, the type-the-name prompt is now skipped.
The data-loss warning is still printed.

**Behavior change:** With `-y`, the rename happens without reading
stdin.
Without `-y`, the prompt is unchanged.

Closes [CLI-35](https://linear.app/codercom/issue/CLI-35)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-10-06 10:08:14 -04:00
Thomas Kosiewski 9316d67440 feat: add chat automations management API behind chat-automations (#30112)
Adds the management API for chat automations under
`/api/experimental/organizations/{organization}/chat-automations`,
behind the new user-scoped `chat-automations` experiment. This is the
first of two PRs for RFC step 3; nothing publishes automation messages
yet.

- **Experiment:** `chat-automations` is in `ExperimentsKnown`,
`ExperimentsUserScoped`, and the ruleguard list in `scripts/rules.go`.
Every route asks `chatd.AutomationsEnabled(ctx, api.ExperimentEvaluator,
callerID)`, which fails closed on a missing subject or evaluator; the
routes stay mounted and return 404 when the experiment is off for the
caller, so a runtime rule for one user applies on the next request
without a restart. There is no `/api/v2` alias.
- **Routes:** list, create (201), get, `PATCH`, delete (204), with
Swagger annotations and audit entries. List returns the automations in
the organization the caller can read (members see their own,
organization admins see all).
- **Service** (`coderd/x/chatd/automations.go`): create validates kind
and target shape, a non-empty prompt, a five-field cron and IANA time
zone, model access, and that an `existing_chat` target is a root chat of
the owner in the same organization. It defaults `when_busy` to `skip`
for schedules and `queue` for webhooks and computes the first schedule
cursor. `PATCH` runs the same per-field validation on each changed
field, rejects `kind` and `target_mode`, bumps `schedule_revision` on
prompt, cron, or time zone changes, and recomputes the cursor on cron or
time zone changes.
- **Owner-only:** only the owner can `PATCH` an automation, even with
organization-admin or site-owner roles (403); admins can list, read, and
delete.
- **Secrets:** a webhook's secret (`coder_automation_` prefix) is
returned once in the create response. Only its SHA-256 is stored, and it
appears in no list, get, audit, or log output.
- **Cap:** new option `--chat-max-automations-per-owner` (default 50)
caps automations per owner across all organizations; creating one more
returns 409. Creates serialize on a per-owner advisory lock.
- **Cron:** `cron.Standard(spec, timeZone)` accepts any standard
five-field expression (the existing `Weekly` rejects day-of-month and
month restrictions). Responses include the next five run times of an
enabled schedule.

PR 3b (stacked on this one) adds disable and re-enable with the queue
cutoff, makes delete run disable first, and adds secret rotation and the
schedule preview route. Until then, the queue promotion guard from
#30096 discards queued rows whose automation was deleted.

Dogfood UAT ran on a real dev instance and passed:
create/list/get/patch/delete via curl, owner-only 403s for an
organization admin and the site owner, the cap (including concurrent
creates and cross-organization counting), a runtime rule turning the
experiment off for one user without a restart, and `/api/v2` 404s.

Part of CODAGT-1209 (PR 3b closes it)
Part of CODAGT-1135
Refs CODAGT-1217

Stack: PR 3 of the Automations for Coder Agents stack, on top of #30096
(which is on top of #30085).

> This PR was written by an AI agent (xum) and reviewed by the agent's
own test audit and UAT. A human has not reviewed it yet.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-10-02 15:54:49 +00:00
Nick Vigilante 0d1225694e feat: show coder sharing in CLI help and reference docs (#30141)
`coder sharing` has been hidden since it was added behind an experiment,
although Shared Workspaces is GA and the prose docs already use it.

This removes `Hidden: true`, regenerates `docs/reference/cli/sharing/*`,
and adds the pages to the docs manifest.
The shared workspaces guide and the persistent shared workspaces
tutorial now link to the new reference.

**Behavior change:** `coder sharing` and its subcommands now appear in
`coder --help`.
The commands themselves are unchanged.
The `sharing remove --user/--group` help text previously said "to share
the workspace with"; it now says "to remove from the workspace".

<details>
<summary>Decisions</summary>

- Follow-up not in this PR: `DELETE /workspaces/{workspace}/acl` has no
CLI caller.

</details>

Closes [CLI-22](https://linear.app/codercom/issue/CLI-22)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 21:29:51 +00:00
Nick Vigilante 46265fc361 fix: hide the unused --yes flag on coder organizations create (#30144)
`coder organizations create` registered `-y/--yes` but has had no
confirmation prompt since the org-delete prompt was removed in #16972.

`-y` is now a hidden no-op: it's gone from help and the reference docs
but still accepted, so existing scripts don't break.

**Behavior change:** `-y/--yes` no longer appears in `coder
organizations create --help`.
Passing it still works.

<details>
<summary>Decisions</summary>

- Adds `cliui.HiddenSkipPromptOption()`. The autoupdate PR adds the same
helper, so whichever merges second will need a trivial rebase.

</details>

Closes [CLI-26](https://linear.app/codercom/issue/CLI-26)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 14:57:29 -04:00
Nick Vigilante b6aab35a7b feat!: confirm before coder update restarts a running workspace (#30150)
`coder update` stopped and restarted a running workspace without asking
and had no `-y`, while `coder restart` and the dashboard's update dialog
both confirm first.

It now asks for confirmation before stopping a running workspace, using
the dashboard's wording that updating can delete non-persistent data.
`-y` skips it, and also answers the existing "Enqueue another stop?"
prompt.

**Behavior change:** **New prompt; can break scripts.** `coder update`
on a running workspace without `-y` now blocks on stdin, or fails if
stdin is closed.
Stopped workspaces don't prompt.
Parameter prompts such as `--always-prompt` aren't affected by `-y`.

The [Update
workspaces](https://coder.com/docs/user-guides/workspace-management#update-with-the-cli)
guide now notes the prompt and `-y`.

<details>
<summary>Decisions</summary>

- Mirrors `coder restart`'s prompt pattern.
- Doc-check suggested a row in the 2.29 to 2.34 ESR upgrade guide. This
change ships after 2.34, so it's documented in the user guide instead.

</details>

Closes [CLI-34](https://linear.app/codercom/issue/CLI-34)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 14:31:43 -04:00
Nick Vigilante c9813d97f7 fix: swap description and command in coder organizations show examples (#30154)
The `coder organizations show` help examples had their `Description` and
`Command` fields swapped, so `--help` and
`docs/reference/cli/organizations/show.md` read backwards.

This swaps them back, tidies the descriptions, and regenerates the help
snapshot and reference page.

**Behavior change:** Help text and generated docs only.

Closes [CLI-38](https://linear.app/codercom/issue/CLI-38)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 13:00:38 -04:00
Nick Vigilante 3baeaceb1d feat: show coder workspace-proxy in CLI help and reference docs (#30146)
`coder workspace-proxy` (`wsproxy`) has been hidden since it was added
for manual testing in #7176, although
`docs/admin/networking/workspace-proxies.md` tells admins to run it.

This removes `Hidden: true`, regenerates
`docs/reference/cli/workspace-proxy/*`, adds them to the docs manifest,
and corrects "Display of the proxy" to "Display name of the proxy" in
the `create` and `edit` help.

**Behavior change:** `coder workspace-proxy` and its subcommands now
appear in `coder --help`.
The commands themselves are unchanged.

<details>
<summary>Decisions</summary>

- `server` stays visible. Its reference page is 447 lines, about a fifth
of `coder server`, because it only lists proxy-relevant options.
- Rough edge not fixed here: `create` and `regenerate-token` print the
proxy token in cleartext, including in the default table columns. That's
consistent with other show-once secrets but worth a docs callout.
- Most of this diff is generated reference pages.

</details>

Closes [CLI-28](https://linear.app/codercom/issue/CLI-28)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 12:39:06 -04:00
Nick Vigilante e6774c2602 feat: add --column to coder users show (#30143)
`coder users show` offered `-o table|json` but was the only table
command without `-c/--column`, because it uses a custom key/value
format.

The custom format now registers `-c` and filters its rows.
Column names match `users list` where they overlap: `id`, `username`,
`name`, `email`, `status`, `created at`, `roles`, `organizations`.

**Behavior change:** Additive.
The default output is byte-for-byte unchanged.

<details>
<summary>Decisions</summary>

- Switching to `cliui.TableFormat` would have turned the vertical
key/value layout into a horizontal table, so the existing renderer is
kept and filtered instead.

</details>

Closes [CLI-25](https://linear.app/codercom/issue/CLI-25)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 12:38:45 -04:00
Nick Vigilante dde500a646 feat: add --yes to coder users suspend and activate (#30155)
`coder users suspend` and `coder users activate` always prompt but,
unlike other commands with a confirmation prompt, had no `-y/--yes`.

Both now accept `-y`.
The suspend help also says that suspending stops the user's running
workspaces and that activating doesn't restart them.

**Behavior change:** Additive.
New `-y` flag; without it, both commands prompt as before.

<details>
<summary>Decisions</summary>

- The workspace note is based on the lifecycle executor, which
auto-stops a suspended user's running workspaces; activation doesn't
restart them.

</details>

Closes [CLI-23](https://linear.app/codercom/issue/CLI-23)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 12:38:14 -04:00
Nick Vigilante cf60604a75 feat!: confirm role changes in coder users edit-roles (#30140)
`coder users edit-roles --roles ...` replaces the user's whole set of
site roles, so granting one role could silently remove others, including
owner.
It registered `-y` but never prompted, and `-y` didn't skip the
interactive role picker.

It now prints the roles being added and removed and asks for
confirmation; `-y` skips it.
The `--roles` help says it replaces the full set.

**Behavior change:** **New prompt; can break scripts.** `edit-roles
--roles ...` without `-y` now prompts.
`-y` without `--roles` now fails with an error instead of opening the
picker.
If the requested roles match the current roles, it prints `No role
changes for <user>.` and doesn't prompt.

<details>
<summary>Decisions</summary>

- No-op requests skip the prompt so idempotent scripted calls stay
quiet.

</details>

Closes [CLI-21](https://linear.app/codercom/issue/CLI-21)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 12:36:30 -04:00
Nick Vigilante 302edffd87 feat: add JSON output to coder server create-admin-user (#30138)
`coder server create-admin-user` is mostly used in automation but only
printed text.

It now accepts `-o text|json`.
JSON contains the created user's ID, username, email, roles, and
organization memberships.

**Behavior change:** Additive.
The default text output is unchanged and still goes to stderr.
JSON goes to stdout so it can be piped.
The password is never included in any format.

<details>
<summary>Decisions</summary>

- The command talks to the database directly, so the JSON uses a small
local response type instead of a codersdk type.
- JSON goes to stdout while text stays on stderr, matching how other
commands emit machine-readable output.

</details>

Closes [CLI-17](https://linear.app/codercom/issue/CLI-17)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 12:36:05 -04:00
Nick Vigilante fd41ca682a feat: add JSON output to coder licenses add and delete (#30137)
`coder licenses add` and `coder licenses delete` printed only text,
while `coder licenses list` supports `-o json`.

Both now accept `-o text|json`.
`add` prints the added license in the same shape as `licenses list -o
json`, and `delete` prints `{"id": <id>}`.

**Behavior change:** Additive.
Default text output is unchanged.
The license key itself is never printed.

<details>
<summary>Decisions</summary>

- `add` applies the same `license_expires_human` claim enrichment that
`licenses list` does, so the two JSON shapes match.

</details>

Closes [CLI-16](https://linear.app/codercom/issue/CLI-16)

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-09-30 12:35:41 -04:00
Andrew Aquino 4a67ac3306 feat: buffer CLI session logs and flush on connection failure (#29752)
## What

Adds in-memory log buffering for CLI diagnostics so the debug detail
leading up to a failure is available without logging debug during normal
operation. Below-level entries are kept in a slog flight recorder
(`v3.2.0`) and emitted only when a command returns an error. This
implements CLI-4 (connection-log RFC req 13). Depends on the
`cdr.dev/slog/v3` `v3.2.0` bump (already on `main`).

## How

- **Root command** (`cli/root.go`):
- New global `--log-buffer-size` / `CODER_LOG_BUFFER_SIZE` (default
`10`, `0` disables, clamped to `10000`), shared by all commands instead
of duplicated per command.
- `bufferedLoggerMiddleware` runs the invocation logger at `Info` (or
`Debug` with `-v`) with a flight recorder, and on a returned error calls
`Flush` to replay the buffered history to stderr. `Flush` does not add a
duplicate error line; the returned error is still rendered by the normal
formatter.
- Opt-in via an `annotationBufferedLogger` annotation so it does not
clobber the ~17 commands that build their own logger on `inv.Logger`
(which would otherwise double-log). Future commands opt in with one
line.
- `start` / `stop` / `update`: opt into the middleware and just
`client.SetLogger(inv.Logger)` so codersdk request/response debug is
captured and flushed to stderr on failure. They **no longer write
session log files** and dropped their per-command `--log-dir` /
`--log-buffer-size`.
- `ssh`: keeps its own file logger (writing to stderr would corrupt its
stdio stream), now using the global buffer size and the shared
`bufferedLogger` helper. It retains `--log-dir` / `CODER_SSH_LOG_DIR`,
stdio/PID filename handling, and file pruning (50 most recent).
- `restart` is excluded, matching the `client_session_id` opt-in set
(DEVEX-664).

## Default behavior change

`start` / `stop` / `update` now emit buffered diagnostics (recent
below-level entries, e.g. sdk request/response) to **stderr** when they
fail; on success they stay quiet. `coder ssh` continues to write a
per-connection diagnostic file by default under the XDG state dir
(`~/.local/state/coder/logs`), pruned to the 50 most recent. Opt out of
buffering with `--log-buffer-size 0`.

## Review changes (Asher)

- Shared logger construction: the level is computed once and the flight
recorder is always attached, in a single `bufferedLogger` helper used by
ssh and the workspace commands.
- Workspace commands print to normal output instead of a log file, and
the default buffer is `10` to avoid flooding the terminal on failure.
- The buffer lives on the root command / logger (global option +
middleware) rather than being wired into each command.

## Alignment with #29671 (agent)

Same core model: `Info` default with a flight recorder, `-v` for full
debug, and the shared `--log-buffer-size` semantics (`0` disables).
Differences: the agent writes to a file and defaults the buffer to
`1000`, while the CLI prints to stderr and defaults to `10`; both now
rely on slog's auto-flush-on-error (the CLI additionally flushes via the
middleware on a returned error).

> [!NOTE]
> The agent PR (#29671) adds an agent-scoped `--log-buffer-size` /
`CODER_AGENT_LOG_BUFFER_SIZE` on the hidden `coder agent` command. Once
both land, the global `--log-buffer-size` here and the agent's own flag
will need reconciling on `coder agent`. Flagging for whichever merges
second.

## Testing

`cli.TestClampLogBufferSize`, `TestPruneSessionLogs`,
`TestDefaultSessionLogDir`, and `TestBufferedLogger_*` cover clamping,
ssh log retention, the default state dir, buffer-until-error, the
middleware's flush path, and the verbose escape hatch.
`start`/`stop`/`update`/`ssh` command tests pass. Golden `--help` output
and `docs/reference/cli` regenerated. (`TestSSH/Env` is a pre-existing
interactive-PTY test that does not run in all sandboxes; it fails
identically on `main` here.)

<details>
<summary>Rollout context</summary>

Cross-repo sequence: coder/slog flight recorder (released as v3.2.0) ->
go.mod bump in coder/coder (#29600, merged) -> CLIENT-672 (agent,
#29671) and this PR (CLI-4), which are independent consumers and can
merge in any order.
</details>

---
<sub>Opened by Coder Agents on behalf of @aqandrew.</sub>
2026-09-29 22:27:30 +00:00
Cian Johnston 9fa17a12ef fix: strip client actor headers unconditionally (#30037)
Strip all client-supplied headers matching `IsActorHeader()` in
`PrepareClientHeaders`, regardless of `send_actor_headers`. This
reserves the case-insensitive `X-AI-Bridge-Actor` prefix for identity
injected by the gateway. Remove the redundant deletion of the three
standard actor headers from `BuildUpstreamHeaders`.

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 20:26:17 +01:00
Cian Johnston 8742d2484c feat: add opt-in AI Gateway actor email headers (#29930)
Add opt-in forwarding of the authenticated Coder account email through
`--ai-gateway-actor-header-meta-email`,
`CODER_AI_GATEWAY_ACTOR_HEADER_META_EMAIL`, or
`ai_gateway.actor_header_meta_email`. The option defaults to empty:
enabling `send_actor_headers` alone does not forward email. Set a
destination header explicitly to opt in; accounts without an email omit
it.

Carry authenticated email through the Gateway authorization response and
strip client-supplied standard/configured email headers before applying
trusted identity. The additive protocol field joins unreleased Gateway
API v1.3 alongside workspace attribution. Includes email configuration
precedence, authorization compatibility, captured upstream request
tests, and matching documentation.

Refs https://linear.app/codercom/issue/AIGOV-601

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 20:07:49 +01:00
Cian Johnston 05d1fa8a4c feat: configure AI Gateway actor identity headers (#29929)
Allows configuring AI Gateway actor ID and username headers independently through
`--ai-gateway-actor-header-id` and
`--ai-gateway-actor-header-username` or associated environment
variables and YAML settings. 

- Defaults to existing header name, an empty string disables that attribute. 
- Existing `send_actor_headers` gate remains off by default.
- Validates header names, case-insensitive collisions, and protected
destinations for embedded and standalone gateways.
- Strips standard and configured identity destinations before injecting authenticated values.
- Adds coverage for configuration precedence, captured upstream request, and generated help/API documentation.

Refs https://linear.app/codercom/issue/AIGOV-601

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 18:22:59 +01:00
Sas Swart bcb981b839 chore: bump github.com/coder/boundary to v0.11.0 (#30083)
Bumps `github.com/coder/boundary` from v0.10.0 to
[v0.11.0](https://github.com/coder/boundary/releases/tag/v0.11.0). No
transitive dependency changes.

boundary v0.11.0 wraps the `--session-id-inject-target` format and
example in backticks, so:

- The `coder agent-firewall` help golden and
`docs/reference/cli/agent-firewall.md` are regenerated.
- The temporary `<host>`/`<glob>` entry for that page in
`scripts/docshtmlcheck`'s `allowedUnknownTags` is now stale (the
linter's self-clearing guard fails on it), so it is removed. The
allowlist is now passed into `filterAllowed`/`reportFindings` so the
tests use their own fixture instead of depending on the real, now-empty
map.

> Generated by Coder Agents on behalf of @SasSwart.
2026-09-29 17:00:27 +02:00
Sas Swart 813b8c151f feat: make AI Gateway content recording optional (#30031)
Add `--ai-gateway-disable-content-recording`, which stops user prompts,
tool
calls and model thoughts from being stored. Cost control reads none of
those
tables, so budgets, spend accounting and enforcement are unaffected.

A dropped record is still logged, so pairing the option with
`--ai-gateway-structured-logging-source=gateway` keeps the SIEM export
for
records that are never persisted. The gateway warns at startup when
content is
dropped while coderd is the only emitter, since those records then reach
neither
the database nor a SIEM.

Covered end to end for the embedded and the standalone gateway, and
documented
alongside cost controls.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 11:48:53 +02:00
Sas Swart 23fb35d185 feat: let the AI Gateway emit the structured interception records (#30030)
coderd emitted the structured interception records as they arrived over
DRPC, so
a record the gateway never sends cannot be exported.

- Add `--ai-gateway-structured-logging-source` (`coderd`, `gateway`,
`both`) and
teach the gateway's `LogRecorder` to emit the same format where the
records
originate. Gateway lines omit `thread_parent_id` and `thread_root_id`,
which
  are resolved by a database lookup only coderd can perform.
- Reaching the serving pool required repairing the pool options: they
were
derived at construction sites and discarded, so the server always built
its
pool with the defaults. They are now derived from the deployment
configuration
in one place and passed to the pool that serves requests. The server
reports
those options, and its ownership of the `key_pool_state` collector, so a
second
  registration cannot silently reappear and panic startup.
- The standalone gateway inherits both structured logging options, since
it is
  now one of the processes that can emit.

This is the keystone of the stack: the flag, the mechanism that carries
it and
the behavior it selects land together, so
`TestAIGatewayStart_InheritedOptions`
and the gateway help output stay truthful at every commit.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 11:48:52 +02:00
Nick Vigilante d40e24cf7d docs: nest the CLI reference by subcommand (#29956)
## Summary

Nests the CLI reference by subcommand so the Command Line sidebar
collapses from 156 flat entries to 49 top-level verbs.
Each page's URL follows the invocation, its page title is the full
command as inline code, and its sidebar label is only its own verb as
inline code.

| | Before | After |
| --- | --- | --- |
| File | `docs/reference/cli/oauth2-provider_dcr_disable.md` |
`docs/reference/cli/oauth2-provider/dcr/disable.md` |
| URL | `/reference/cli/oauth2-provider_dcr_disable` |
`/reference/cli/oauth2-provider/dcr/disable` |
| Page title (front matter) | `oauth2-provider dcr disable` | `` `coder
oauth2-provider dcr disable` `` |
| Sidebar label (manifest) | `oauth2-provider dcr disable` | ``
`disable` `` |

Resolves DOCS-140 (coder/coder half). Also fixes the Makefile part of
DOCS-1073 / DOCS-912, which this change depends on.

## Changes

- `scripts/clidocgen`: pages nest by command path. A command with
visible subcommands becomes its directory's `index.md`, so
`oauth2-provider/index.md` and `oauth2-provider/dcr/index.md` sit above
`oauth2-provider/dcr/disable.md`. Subcommand table links are relative to
the parent page.
- `scripts/clidocgen`: the manifest "Command Line" section is built from
the command tree (nested, sorted by name, hidden commands skipped)
instead of a flat list. The redundant `coder` child that pointed back at
`reference/cli/index.md` is gone.
- `Makefile`: the CLI rule now replaces `docs/reference/cli/` wholesale,
so stale pages get removed. The manifest rule now runs `clidocgen
-manifest-only` on top of the API staging manifest, so the CLI nav is
generated instead of edited by hand. As a result, the nine pages that
had no nav entry (`ai-gateway*`, `secret enable/disable`, `server
fix-oidc-links`) now have one.
- `scripts/configdocgen` and 48 prose pages: links point at the new
paths (for example `reference/cli/server.md` is now
`reference/cli/server/index.md`).

## How to review/QA this PR

- `docs/reference/cli/**/*` (approximately 190 pages): Each of these
pages are generated automatically. Some pages appear deleted, and some
pages appear new. Every deleted page corresponds to a new page somewhere
else, so no information is being deleted. The docs in this section
should adhere to the following, so a test in the build preview for each
of these items should be satisfactory:
- [ ] Each subcommand of a command gets nested as a child instead of
being displayed as a flat list.
  - [ ] Each parent command is stored in an `index.md` file.
- [ ] The title of each page inside the page should now feature the full
`coder XYZ` command.
- [ ] The title of each page inside the page should now be formatted as
inline code.
- [ ] The title of each page in the sidebar should be the most granular
subcommand of the whole command string (if the page's title is `coder
ai-gateway keys create`, the sidebar label is `create`).
- [ ] The title of each page in the sidebar should now be formatted as
inline code.
  - [ ] The page slug for each page is now the most granular subcommand.
  - [ ] All links now point to the correct page.
- `docs/manifest.json`: The changes here reflect the updated structure
of the `docs/reference/cli` section.
- `docs/**/*.md` outside of `docs/reference/cli/**/*` (approximately 50
pages): The extent of the changes in these pages are just updating the
paths to point to the new page locations.
- [ ] The links on the page all point to the correct new path in
`docs/reference/cli`.
- `scripts/clidocgen` (4 files): This is the Go code responsible for
generating everything inside of `docs/reference/cli/**/*`. A typical
code review here should be satisfactory.
- `scripts/configdocgen` (2 files): these two files just have updates to
the raw `.md` path used by `docs/admin/setup/configuration-reference.md`
and updates the tests to reflect that.
- `Makefile`: This updates the `make` targets for generating the CLI
docs to fit the new structure.

## Merge ordering

Without the renderer PRs deployed, both docs sites show literal
backticks in titles and sidebar labels. Without the redirects, the old
flat URLs return 404.

1. Deploy before merging this PR: coder/docs-engine#176 (beta-docs
renders these titles as inline code) and coder/coder.com#1111 (classic
docs renders them as inline code). Both are safe to ship first, because
titles without backticks render as before.
2. Merge this PR.
3. Merge coder/coder.com#1112 (redirects from the old flat URLs) only
once this content reaches the mainline release branch that serves
unversioned `/docs`.

## Testing

- `go test ./scripts/clidocgen/ ./scripts/configdocgen/
./scripts/docshtmlcheck/`: pass. New tests cover page paths, subcommand
links, the nested manifest, and front matter quoting.
- `make docs/reference/cli/index.md docs/manifest.json
docs/admin/setup/configuration-reference.md`, then a forced rerun: the
second run produced no diff.
- Checked the manifest: all 164 CLI entries resolve to a file, no page
is missing a nav entry, and everything outside "Command Line" is
byte-identical.
- Relative `.md` links across `docs/`: 0 broken, same as `main`.
- `make pre-commit` and `make pre-push`: pass. On earlier pre-push
attempts, different unrelated vitest files timed out under host load.
Those files pass when run alone, and the final push passed with
`PARALLEL_JOBS=1`.

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

**Goal (from DOCS-140 and the requester):** URLs follow the command
hierarchy. Pages are titled with the full command, and sidebar entries
with the last verb only. Both are formatted as inline code.

**Contract with the renderers:** a title wrapped entirely in one pair of
backticks (``^`[^`]+`$``) renders as inline code. Plain-text consumers
(`<title>`, meta, search, llms corpus) strip the backticks. Page title
comes from front matter `title`, and the sidebar label from the manifest
node `title`.

**Decisions**

- A parent command is `dir/index.md` rather than a sibling `dir.md`. The
root CLI page is already `index.md`, and both docs-engine and the legacy
coder.com renderer map `x/index.md` to `/x`.
- The manifest is built from the command tree, not from the written
files, so ordering is deterministic and the nesting matches the pages
exactly.
- The manifest discard bug (DOCS-1073 item 1) is fixed here, because
without that fix the generated nested manifest would never reach the
tree. DOCS-1073 items 2 through 4 (a prose fix and a hidden-command
policy) are out of scope.
- `-manifest-only` keeps the existing parallel `make gen` layout: the
API rule still owns `_gen/manifest-staging.json`, and CLI regeneration
doesn't retrigger swag.
- The renderer and redirect work lives in the companion PRs in
coder/docs-engine and coder/coder.com. It is linked above and not
duplicated here.

</details>

---

> [!NOTE]
> Generated by Coder Agents on behalf of @nickvigilante.
2026-09-28 15:44:10 -04:00
Jon Ayers 797dc6b2d1 feat: refresh header commands based on JWT expiration (#29760)
Adds opportunistic JWT parsing for values returned from the
`--header-command`. If a JWT is parsed we use the value of its `exp`
field to determine when we should re-run the command to refresh the
values.
2026-09-28 09:42:31 -05:00
Michael Suchacz f5092aaa4a feat: make chat limits configurable deployment options (#28927)
Adds deployment options for the chat limits that shape turn behavior and
API acceptance, replacing hardcoded constants in `coderd/x/chatd` and
the chat API. Defaults are unchanged.

| Option | Default | Limit |
|---|---|---|
| `CODER_CHAT_MAX_STEPS_PER_TURN` | 1200 | steps (model responses) in a
chat turn |
| `CODER_CHAT_MAX_GENERATION_RETRIES` | 25 | consecutive retries after a
model generation fails with a transient error |
| `CODER_CHAT_MAX_QUEUED_MESSAGES_PER_CHAT` | 20 | messages that can be
queued in a chat |
| `CODER_CHAT_MAX_ATTACHMENTS_PER_CHAT` | 50 | files linked to a chat;
linking more deletes the earliest uploads |
| `CODER_CHAT_MAX_PROMPT_BYTES` | 131072 | system prompt, plan mode
instructions, and each user's custom prompt |
| `CODER_CHAT_MAX_CONCURRENT_RECORDING_UPLOADS` | 25 | desktop
recordings each server stores at the same time |

`codersdk.DefaultChat*` constants remain the single source of truth.
Values below 1 fail startup validation, and each option's description
ends with "Must be at least 1." `chatd.New` fills any zero field in
`chatd.Config.Limits` with its default once, `LimitsFromConfig` is a
plain conversion, and the code that receives a limit as a parameter (the
`chatstate` queue and file link checks, the turn step check,
`chatretry.Retry`, and `chatadvisor.NewRuntime`) returns an error for a
limit below 1 instead of choosing a default or disabling the limit. The
options are documented in the generated configuration reference and in
the platform controls docs.

`CODER_CHAT_MAX_GENERATION_RETRIES` counts consecutive retries, and the
count resets after each successful step. The default allows 25 retries
(26 attempts) where the old constants allowed 24. The same limit now
applies to each nested advisor model call and to background title,
summary, and turn status label generation, which previously used fixed
`chatretry` budgets.

Chat creation and tool result bodies keep the fixed 256 KiB limit from
main. The prompt-saving endpoints accept bodies up to twice the prompt
limit, for JSON escaping and characters that sanitization removes, but
never less than 256 KiB, so small prompt limits still return the 400
length error. At the default this equals the 256 KiB limit on main.

Four settings from earlier revisions were removed, and the fixed limits
from main are back:

- `CODER_CHAT_MAX_TOOL_OUTPUT_BYTES`: the agent already keeps a 16 KiB
head and a 16 KiB tail of command output, so raising it had no effect
and lowering it cut the tail.
- `CODER_CHAT_MAX_DYNAMIC_TOOLS_PER_CHAT`: tool definitions share the
256 KiB chat creation body limit, so raising the count did little.
- `CODER_CHAT_DEBUG_MAX_BODY_BYTES`: one setting covered two unrelated
debug caps.
- `CODER_CHAT_DEBUG_MAX_TEXT_RUNES`: the name did not say what it
applied to.

Root and subagent concurrency caps stay fixed because they are licensing
behavior, and `MaxChatFileSizeBytes` stays fixed because the web UI
hardcodes the generated constant for client-side checks.
`codersdk.MaxChatFileIDs` is removed; the web UI's "Attachment expired"
tooltip no longer quotes the number because the cap is now per
deployment, and it says that attaching a file beyond the limit
permanently deletes the chat's earliest-uploaded attachments.

## Review record

| Round | Reviewed head | Result | Disposition |
|---|---|---|---|
| Codex 1 and 2 (Sep 2 to 3) | `7f10a1572f8`, `8ee09f8fa3b`,
`197bb78d5b` | 10 findings, then OK on `197bb78d5b` | all threads
resolved |
| Codex 3 (Sep 17) | `e4efac249a5` (pre-rebase) | 4 findings | advisor
retry limit confirmed and fixed in `9e462b7b3d0` (rebased from
`67341e458e8`); ARCHITECTURE.md TODOs added; JSON-escaping body sizing
and streamed-argument rune cap declined as pre-existing design (evidence
in threads) |
| Codex 4 (Sep 18) | `9e462b7b3d0` | 6 findings | recording evicted at
attachment cap 1 confirmed and fixed in `5b61895decb`; `Limits` field
docs and zero-value fallback documented; prompt retro-enforcement,
generated multi-sentence lines, and tool-output truncation metadata
declined as pre-existing design (evidence in threads) |
| Codex 5 (Sep 18) | `5b61895decb` | 1 finding | over-cap batch of
already-linked files accepted after lowering the cap: confirmed and
fixed in `f44063e74e5` |
| mafredri (Sep 23) | `f44063e74e5` | 24 threads, changes requested |
all fixed in `05e3e3d622a`, `c1f78e09e8b`, `709ddb67977`, `d0587a49829`,
`ca4347b24de`, and `1f6c9e2a46f`, then answered and resolved; the
ARCHITECTURE.md text was written at the author's direction and approved
by the author |
| Sibling sweep (Sep 24) | `1f6c9e2a46f` | author-requested audit of all
24 mafredri threads for sibling issues, plus a test refactor | fixed in
`37eaf07d34d` through `1f14ac041b7`: the advisor retry limit,
`chatretry.Retry`, and the turn step check reject values below 1 instead
of disabling retries or the limit; limit tests run against both the
default and configured values set through `chatd.Config` or
`DeploymentValues`; the expired-attachment tooltip is concrete. A
required coder-frontend-review run (8 roles in one agent, CD re-run
once) found a stale story comment, removed. |
| Codex 6 (Sep 27) | `a71383e3a31` | OK, no findings | requested after
the rebase at the author's direction, past the six-pass review budget |

The branch was rebased onto main `4851c7b60c8` on Sep 27; the previous
head was `91b84000adb`, and the earlier SHAs in the review record
predate the rebase. Conflicts in the `chatstate` transitions and
`CreateChat` keep both main's `InitialStatus` and this PR's
`MaxFileLinks`, and main's rewrite of `advisor_internal_test.go` in
#28754 keeps main's version plus this PR's limit tests. Two tests added
on main needed the new retry arguments:
`TestGenerateStructuredTitleWithUsage_FallsBackToTextWhenToolChoiceRejected`
and `TestAdvisorRunStreamsReasoningDeltasSeparatelyFromAdvice`.
Validation on `a71383e3a31`: the pre-commit hook (generation,
golangci-lint, build), the full `coderd/x/chatd/...` suite (20
packages), the chat tests in `codersdk`, `coderd`, and
`enterprise/coderd`, the CLI help tests, race-detector runs of the
`chatd`, `chatstate`, `chatadvisor`, and `chatretry` packages, and `go
build` plus `go vet` on each of the 27 commits. No remote UAT was run.

> Xum acted on behalf of @ibetitsmike for this pull request.
2026-09-28 09:25:01 +00:00
Michael Suchacz 6826da9397 feat: restore agents-access as a default organization role (#30004)
Restores `agents-access` (**Coder Agents User**) as a built-in
organization role and adds it to every organization's
`default_org_member_roles`. Members keep Coder Agents by default, and
admins can now restrict it per organization by removing the role from
the defaults and granting it through IdP role sync or direct assignment.

Since #28186, chat permissions lived in the organization-member floor,
so the only way to limit Coder Agents was narrowing per-model access
lists, which did not hide the feature.

- Migration 000602 appends `agents-access` to every organization's
defaults, so upgrading keeps every member's access. New organizations
get it from `rbac.DefaultOrgMemberRoles()`.
- Service accounts do not inherit the role from the defaults
(`GetAuthorizationUserRoles`), so they still need an explicit grant for
chat.
- Owners and Organization Admins keep chat access regardless of
defaults. Chats shared with a user stay readable without the role.
- Role sync is unchanged. It does not store default roles, so after the
default is removed a mapped user gets `agents-access` at their next
sign-in.
- The retired-role mechanism (`IsRetiredRoleName`) is removed.
- `PATCH /api/v2/organizations/{organization}` rejects duplicate
`default_org_member_roles` entries (the CLI already de-duplicated them).
- Custom organization role requests treat built-in role names
case-insensitively, since custom role names are stored lowercase and
`Agents-Access` would otherwise become an undeletable shadow of the
built-in role.
- The Agents permission alert tells restricted members their chats are
kept, and the model selector for users without chat permission no longer
claims that no models are configured.

Docs add "Control who can use Coder Agents" to the Agents
getting-started guide.

**NOTE**: Migration 000602 deletes custom roles named `agents-access`,
which the built-in role would shadow. The down migration does not
restore them. Stored member grants of `agents-access` from the earlier
built-in role or a deleted custom role stay and now grant chat access.

## Validation

- Remote dogfood
[UAT](https://dogfood.cdr.dev/agents/e1c18dc6-f6f0-49a1-b6cd-6ce014b51a86)
passed on fb441dfae5, covering case variants of built-in role names on
create, update, delete, default roles, and member grants. The previous
round, on a6fef66b3f, passed the upgrade from main 5dde49dffb on a
fresh database. 6b7f107e0b only changes wording (docs, comments, UI
copy, CLI help) and did not go through UAT.
- Local: rbac, dbauthz, idpsync, migrations (chain including 000602 down
and up), querier, httpmw, provisionerdserver, coderd and enterprise
chat, role, and organization tests, chatd, toolsdk, CLI; frontend
vitest, story tests, biome, oxlint, tsc.

## Known issues (not changed here)

- Sending from a chat page that was already open when access was removed
shows a generic 404 panel until reload.
- The members page role editor is not locked for OIDC users under org
role sync; the API rejects the change with 400.
- Creating a custom role named after a system role
(`organization-member`, `organization-service-account`) returns 400 with
a raw database unique-constraint error.

<details>
<summary>Review record</summary>

- Remote UAT (UAT Critic sub-agent `6636c855ec`): round 1 on 8bec029d35
passed with issues, fixed in d7ba937a10 and e0f16e1a45f; round 2 on
a6fef66b3f passed; round 3 on fb441dfae5 passed.
- Codex: round 1 on a6fef66b3f found one P2 (case variants of built-in
role names), fixed in fb441dfae5 with a red-green test. Rounds 2 and 3
on fb441dfae5 found no major issues.
- mafredri on fb441dfae5 (PR text only): nine wording suggestions
applied in 6b7f107e0b9; NOTE extended for stored grants; description
trimmed.
- Frontend: FE1 to FE10 and coder-frontend-review checkpoints
self-audited.

</details>

> 🤖 This PR was opened by [Xum](https://mux.coder.com) on behalf of
@ibetitsmike.
2026-09-27 23:34:26 +02:00
Ethan f64ccfb836 feat: add experimental inline MCP servers (#29546)
Closes CODAGT-1131

Fifth PR in the inline MCP servers stack, on top of #29520. A chat owner
can now declare MCP servers by URL and headers on their own chat, and
chatd connects to them every turn alongside the org-configured ones.

They go in a new `inline_mcp_servers` field on `POST /api/v2/chats` and
`POST /api/v2/chats/{chat}/messages`, which replaces the whole set (omit
to keep, `[]` to remove). Root chats only. `GET /api/v2/chats/{chat}`
returns them, with the URL blanked for non-owners and header values
never returned. Subagents only get servers marked `allow_in_subagents`,
a root chat in explore mode gets none, and a root chat in plan mode gets
all of them.

URLs must be `https`, or `http` to an IP literal in
`CODER_MCP_ALLOWED_PRIVATE_CIDRS`. Header values have no minimum length,
so anything under the redactor's 8 byte floor from #29518 is accepted
but not redacted, which the docs call out. Every cap is exported from
`codersdk`.

It's behind the `chat-inline-mcp-servers` experiment, and the
`--disable-chat-caller-supplied-tools` kill switch from #29466 covers it
too. With either off, declaring servers gets a 403 and existing chats
stop connecting to theirs, but `[]` still works so a client can detach.

Load failures show up in the chat debug panel as failed connections, as
do org servers with an invalid config. Docs are hand-written in
`mcp-servers.md`.
2026-09-25 18:51:55 +10:00