Commit Graph
260 Commits
Author SHA1 Message Date
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
Ethan c1af0793e5 feat: add caller-supplied tools kill switch for chats (#29466)
This is the first PR in a stack that adds experimental support for
attaching MCP servers to a chat when it's created, and then deprecates
`unsafe_dynamic_tools` in favour of them. Both are "caller-supplied
tools", i.e. tools the client hands to coderd at chat creation rather
than tools an admin has configured, so we want a single switch admins
can use to turn all of them off.

This PR adds that switch: `--disable-chat-caller-supplied-tools`
(`CODER_DISABLE_CHAT_CALLER_SUPPLIED_TOOLS`). It follows the existing
`disable-*` deployment flag pattern (`--disable-chat-sharing` etc.), so
there's no new API route and it's independent of any experiment. When
set, `POST /api/v2/chats` returns a `403` if the request includes
`unsafe_dynamic_tools`, and chats that already have dynamic tools run
without them; a call to one gets a tool error result and the model just
continues. Later in the stack, chat-attached MCP servers are gated
behind the same flag.

It's unset by default, so nothing changes unless you opt in.


Part of CODAGT-1131
2026-09-25 18:51:53 +10:00
Nick Vigilante 99a3425333 fix: advertise install.sh with curl -fsSL everywhere (#29801)
## Summary

The install one-liner is advertised as `curl -L` in most docs pages, the
README, and the CLI's default version-mismatch hint, while `install.sh`
itself and the deployment-local hint use `curl -fsSL`.
Without `-f`, curl writes an HTTP error body to stdout, and the
one-liner pipes that error page into `sh`.
This PR standardizes every `install.sh` invocation on `-fsSL` so a
failed download fails closed.

## Changes

- Docs: `install/cli.md`, `install/operate/upgrade.md` (twice),
`get-started/index.md`, `start/local-deploy.md`,
`install/operate/provisioners/index.md`,
`admin/templates/managing-templates/change-management.md` (twice),
`user-guides/workspace-access/zed.md`, and `README.md`.
- CLI: `defaultUpgradeMessage` in `cli/root.go` now prints `curl -fsSL`,
matching the deployment-local branch in the same function.
- `codersdk/deployment.go`: the `--cli-upgrade-message` description now
says `curl -fsSL`; the server help goldens, `server-config.yaml.golden`,
`docs/reference/cli/server.md`, and
`docs/admin/setup/configuration-reference.md` are regenerated to match.
- `install.sh`: the "To run" header comment now matches the script's own
usage text.
- Style guide: a new "Commands that pipe a download into a shell" rule
in `docs/.style/style-guide/formatting.md`, and the tabs example uses
`-fsSL`.

The coder.com download page already builds its command from `-fsSL` in
coder/coder.com#1093, and coder.com `main` has no other `install.sh`
one-liners outside test fixtures, so no coder.com change is needed.
DatoCMS content and a release verification page are not in this PR.

`main` since moved the upgrade and provisioner pages under
`docs/install/operate/` and removed the install one-liner from
`docs/install/index.md` in #29304, so that page no longer appears in
this diff.

## Testing

- `TZ=UTC go test ./cli
-run='Test(CommandHelp|ServerYAML|ErrorExamples|.*Golden)' -update` and
`go test ./enterprise/cli -run=TestEnterpriseCommandHelp -update` pass
and produce the committed golden diffs.
- `go test ./cli -run 'Test.*Version|TestWrapTransport'` passes,
including `Test_wrapTransportWithVersionCheck`.
- `go run ./scripts/configdocgen` output contains the new `curl -fsSL`
description.
- `markdownlint-cli2` on the edited style guide page reports 0 errors.
- `git grep` finds no remaining `curl -L …install.sh` outside the style
guide's **Don't** example.
- After merging `main`: `make pre-commit` passes, and `make test`, `make
test-js`, and `make site/out/index.html` pass.

Linear:
https://linear.app/codercom/issue/DOCS-964/standardize-installsh-curl-flags-on-fssl-across-docs-codercom-and-the

---
🤖 Built with AI assistance.
2026-09-24 18:23:54 +00:00
McKayla はな 0c98308ca9 feat: default the CLI workspace search to the user filter (#29753) 2026-09-23 19:42:10 -06:00
Paweł Banaszewski c47eb47393 feat: add stateless AI Gateway proxy mode (#29349)
Adds proxy mode to the AI Gateway. No AI provider is supported in this
mode yet.
2026-09-18 16:47:16 +02:00
Ethan 77479408b4 feat: make the Coder Agents stream silence timeout configurable (#29394)
The `chatloop` stream silence guard cancels and retries a model attempt
after `10m` of silence, and it was hard-coded. It's armed before the
request opens, so it also bounds time to first token, and slow local
models (e.g. `llama-server` on a large prompt) can spend longer than
that on prompt processing alone, meaning every attempt just gets
cancelled and retried.

This PR adds `--chat-stream-silence-timeout` /
`CODER_CHAT_STREAM_SILENCE_TIMEOUT` (default `10m`) and passes it to
both the main loop and the advisor. Setting it to `0` disables the guard
entirely, and anything above `24h` is rejected, which also keeps the
watchdog arithmetic below from overflowing.

Whilst doing this I ran into the runner's `15m` task watchdog, which
kept counting during an open stream. That silently cancelled any healthy
stream longer than `15m`, and would've stopped a silence timeout above
`15m` from ever firing. To fix, the silence guard now kicks the watchdog
out to `max(15m, silence + 5m)` whenever it arms or sees a part. Silent
streams still fail through the guard, healthy streams can run for as
long as they like, and hang detection is unchanged everywhere else. With
the guard disabled there's nothing to kick against, so arming it just
stops the watchdog for the rest of the attempt. That does mean the DB
write after the stream isn't bounded either when `0` is set; I think
that's fine for an opt-in setting, and a user can still stop the chat
from the UI if it wedges there.

I did consider removing the guard entirely, but the provider HTTP
clients have no timeout, so a provider that holds the connection open
would only ever be caught as a generic task hang, which is what #25782
was fixing.
2026-09-18 15:24:15 +10:00
Bobby Ho 1cc73bc43f feat: add the CODER_OAUTH2_PROVIDER_ENABLE deployment flag (#29248)
First of five PRs for PLAT-492, adding the opt-in CODER_OAUTH2_PROVIDER_ENABLE flag for the OAuth 2.1 provider. It defaults to false and is not enforced yet, so there is no behavior change.

Adds the CLI/env/YAML flag and exposes oauth2_provider in build info.
Enables it by default in tests to prepare for route gating.
Updates tests, golden files, and frontend fixtures.
Follow-ups will gate routes/UI, retire the experiment, add startup logging, and update docs.
2026-09-14 08:31:26 -07:00
Steven Masley 940f988cfb feat: add deployment-level option to disable Terraform module caching (#29187)
<!-- Generated by Coder Agents on behalf of @Emyrk. -->

<img width="762" height="239" alt="Screenshot From 2026-09-11 17-09-41"
src="https://github.com/user-attachments/assets/9f31fd1e-4cb2-47ab-8d37-4073df9f0a7c"
/>


Closes #22834.

Adds `CODER_PROVISIONER_DISABLE_MODULE_CACHE` so an admin can disable
Terraform module caching for every template at once instead of toggling
~100 templates by hand.

- The deployment setting wins. Templates cannot opt back in, and the
per-template toggle becomes read-only while the deployment setting is
on.
- Modules stay cached at template import, so dynamic parameter rendering
still resolves module-defined parameters. Only the workspace build is
denied the cached files.
- Templates report `module_cache_disabled_by_deployment`, and template
settings shows why the checkbox is locked.

<details><summary>Agent context</summary>

Decisions taken with @Emyrk before implementing:

1. **Precedence.** `deployment || template`, no per-template override,
so no migration and no nullable column. The rule lives in one place,
`codersdk.ModuleCacheDisabled`.
2. **Import-time caching untouched.** `dynamicparameters/render.go`
overlays `cached_module_files` at `.terraform/modules` to render
module-defined parameters. Skipping the cache there would reproduce the
`Module not loaded. Did you run terraform init?` failure reported by a
customer, so the deployment setting only affects what `AcquireJob` hands
the provisioner.
3. **Write path.** A PATCH carrying `disable_module_cache` is discarded
while the deployment setting is on, rather than persisted. Persisting it
would silently keep templates opted out after the deployment setting is
removed.
4. **API shape.** `disable_module_cache` keeps its meaning (this
template's stored value) and the new read-only
`module_cache_disabled_by_deployment` reports the deployment state.
Reading the effective value from `/deployment/config` was rejected
because template admins may lack deployment-config read permission.
5. **Naming.** `CODER_PROVISIONER_DISABLE_MODULE_CACHE` over the issue's
`CODER_DISABLE_TERRAFORM_MODULE_CACHE`, to match the provisioning option
group.

Note: `InsertTemplateParams` has no `disable_module_cache` binding, so
new templates always store `false`. With deployment precedence they
still behave as opted out, so the create path needed no change.

Out of scope and tracked elsewhere: the `coderd_template` Terraform
provider attribute (separate repo) and backporting the per-template
toggle to `release/2.30`.

</details>

---

<sub>Coder Agents on behalf of @Emyrk.</sub>
2026-09-11 18:13:16 -05:00
Garrett Delfosse 65d01ef9b7 fix: error on CLI HTTP redirects instead of following them (#29104) 2026-09-09 07:34:51 -04:00
Paweł Banaszewski 8472a6884f chore!: remove env-based AI provider configuration (#29053)
> AI tools were used to create this PR

Removes deprecated AI provider configuration through environment
variables, CLI flags, and YAML.
Deletion includes indexed providers and legacy OpenAI, Anthropic, and
Bedrock options under both AI Gateway and AI Bridge branding, eg.
`CODER_AI_GATEWAY_PROVIDER_<N>_*` or `CODER_AI_GATEWAY_ANTHROPIC_KEY`.
Removes the associated startup-seeding code.
Updates tests and documentation.

**Breaking change:** Remove [obsolete AI provider CLI flags and YAML
keys](https://coder.com/docs/ai-coder/ai-gateway/providers#database-management-of-providers)
before upgrading, otherwise Coder will fail to start with an `unknown
flag` or `unknown option` error. Provider environment variables are
ignored and no longer seed the database. Existing database-stored
provider configuration is preserved.
2026-09-09 10:16:24 +02:00
Harsh Singh Panwar df4a7644fd feat: import template metadata from README frontmatter on push (#28465) 2026-09-08 21:45:43 -06:00
dylanhuff-at-coder 4875ae218a feat: enforce user secret file policy (#28518)
Adds the deployment option `--user-secrets-disable-file-path` /
`CODER_USER_SECRETS_DISABLE_FILE_PATH` / `userSecretsDisableFilePath`
(default `false`). When it is set, the create and batch-create
user-secret endpoints reject requests with a non-empty file path, and
PATCH validates the post-update state under a `SELECT ... FOR UPDATE`
row lock, rejecting a new or changed file path as well as enabled states
that would have no effective delivery target. Legacy stored paths are
preserved, so users can still edit, disable, clear the path, or migrate
the secret to env delivery.

This is PR 1 of a 4-PR stack; follow-ups cover manifest filtering, the
dashboard, and CLI/docs.

Refs #27488

Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder.
2026-09-02 09:21:36 -07:00
Stefan Naglee 1fa6ebe5c3 fix: support first-user-trial in non-interactive login (#28321)
## Summary

`coder login --first-user-trial=true` was unusable in non-interactive
environments: the trial info fields could only be collected via
interactive prompts, so scripted setup failed with a bare `EOF`.

This adds flags and env vars for every trial info field, extracts the
functions into a helper, turns the EOF into an actionable error, and
fixes a related quirk where enabling the trial via env didn't reliably
suppress the trial prompt.

Fixes coder/coder#23264

## Changes

* Add a flag + env var for each trial field (matching the existing
`first-user-*` convention):
`--first-user-trial-{first-name,last-name,phone-number,job-title,company-name,country,developers}`
and their `CODER_FIRST_USER_TRIAL_*` env vars.
* When a trial field is missing with no input available, return an error
naming the exact flag/env instead of a raw EOF.
* Read `CODER_FIRST_USER_TRIAL` from `inv.Environ` instead of
`os.Getenv` so the flag binding and the "Start a trial?" prompt gate
agree (previously the env toggle could hit an EOF prompt that silently
reset `trial` to `false`).
* Regenerate `coder_login_--help.golden` and
`docs/reference/cli/login.md`.

## Testing

* Non-interactive login via flags and via env vars (env test asserts the
trial is actually provisioned via a recording `TrialGenerator`).
* Missing trial info returns the clear flag-naming error instead of
hanging.
* Existing interactive `TestLogin` subtests pass; `golangci-lint` clean.

## Notes

No strict CLI validation of `country`/`developers` against the UI option
lists: the server doesn't enforce them, and the existing fixture uses
`developers=10-50` which isn't in the CLI bucket list. Can add if
preferred.

---

*Created by Coder Agents on behalf of* @snagles\*.\*
2026-08-31 11:35:59 -04:00
Jeremy Ruppel c73f34c35d feat: honor the deployment registry mirror in template builder bases (#28727)
## Summary

Threads the deployment's configured module registry
(`CODER_TEMPLATE_BUILDER_REGISTRY_URL`) into template-builder **base**
rendering, so a base that embeds a catalog module (e.g. the quickstart
base's `git-clone`) resolves its `source` through a registry mirror the
same way wizard-composed modules already do. Previously base-embedded
module sources hardcoded `registry.coder.com`, so on a
mirror/private-registry deployment a base-embedded module reached the
public registry while wizard modules used the mirror.

Implements [DOCS-610](https://linear.app/codercom/issue/DOCS-610).

## What changed

* `BaseRenderContext.RegistryBase` (new field), mirroring
`ModuleRenderContext.RegistryBase`. `Compose` threads the deployment
registry through `renderBase` into the base render context, and the four
hardcoded base module sources (`quickstart` git-clone,
`azure-linux`/`gcp-linux`/`gcp-windows` region modules) now use `{{
.RegistryBase }}`. Because the value defaults back to
`registry.coder.com`, rendered sources stay byte-identical; the only
golden change is the removal of the now-stale quickstart "follow-up"
note.
* **Boot-time validation.**
`codersdk.ValidateTemplateBuilderRegistryURL` runs in
`DeploymentValues.Validate()`, gated on the builder being enabled,
matching the chat-hook precedent. A malformed value fails at server
start naming the option, instead of surfacing as a per-request error to
a template author who cannot fix it. It uses `net/url` in authority form
to reject a scheme, path, query, fragment, trailing slash, or
credentials and accept a bare `host[:port]`; it does not canonicalize
the host.
* `Compose` **trusts the validated value**, defaulting an unset one and
defensively rejecting a malformed one for direct callers that bypass
boot.

## Tests

* `codersdk`: validator accept/reject matrix (incl.
credentials-without-echo) and a `DeploymentValues.Validate` boundary
test with a disabled-skips-validation case.
* `templatebuilder`: a base honors the mirror and falls back to the
default when unset, plus a defensive-reject case; existing compose tests
updated to bare-host registry values.

<details><summary>Design decision log</summary>

This PR is a deliberately minimal reimplementation of the
[DOCS-610](https://linear.app/codercom/issue/DOCS-610/template-builder-base-embedded-modules-should-honor-the-deployment)
scope, started fresh from `main` rather than carrying forward an
earlier, larger draft (coder/coder#28480). Key decisions:

* **Scope kept to the ticket.** The ticket's fix is three bullets: add a
registry field to `BaseRenderContext`, thread the deployment
`RegistryURL` through `Compose` -> `renderBase`, and use it in base
module sources. Independent hardening explored in the earlier draft was
dropped as out of scope: `terraform-svchost`-based IDN/punycode/port
canonicalization, a rendered-HCL backstop with a 500 mapping, and HCL
module-source extraction helpers. Telemetry misclassification of mirror
modules is tracked separately
([DOCS-712](https://linear.app/codercom/issue/DOCS-712/telemetry-misclassifies-registry-mirror-modules-as-non-coder))
and is not addressed here.
* **Default lives in the render layer.**
`templatebuilder.DefaultRegistryBase` holds the fallback host;
`codersdk` keeps its own option-default literal. An earlier version
exported the constant from `codersdk`, which only emitted a dead
`typesGenerated.ts` entry that nothing in the frontend consumed, so it
was moved out. The `codersdk` validator is a function, so it generates
no TS type.
* **Validate at the config boundary, fail fast.** The repo convention is
to hard-fail structurally invalid config in
`DeploymentValues.Validate()` (access URL, OAuth lifetimes, chat hook
URL) and to warn only for functional-but-risky settings. A malformed
registry host is structurally invalid, so it fails at boot. This also
puts the error in front of the admin who set it, rather than a template
author hitting a per-request error they cannot fix.
* `net/url`**, not a regex.** The codebase validates identifiers/names
with regexes but host/URL-shaped config with `url.Parse` (chat hook URL,
OAuth redirect URIs, AI provider base URL). This value is host-shaped,
so it follows that convention. `url.Parse("//" + v)` with `u.Host == v`
rejects a scheme/path/query/fragment/trailing-slash in one check.

</details>

> This PR was created with AI assistance (Coder Agents).
2026-08-31 09:32:24 -04:00
Michael Suchacz d6b67e8e31 feat: enforce SSRF protection for MCP config-directed traffic (#28242)
Routes all MCP config-directed traffic from coderd and chatd through a
shared SSRF-protected HTTP client, now that organization admins, not
only deployment admins, control MCP server URLs (#27942 and its stack
below).

## Summary

- Uses the [`coder/safedial`](https://github.com/coder/safedial)
library: it blocks private and special-purpose destinations at dial time
(validating resolved addresses at connection time so DNS rebinding
cannot bypass the check) and rejects cross-origin redirects.
- Covers the complete traffic surface: OAuth2 discovery, dynamic client
registration, code exchange, token refresh, revocation, and runtime MCP
connections from chatd.
- Deployments that intentionally host internal MCP servers opt in via
the new `--mcp-allowed-private-cidrs`
(`CODER_MCP_ALLOWED_PRIVATE_CIDRS`) option.
- Includes the deployment configuration surface, generated docs, CLI
goldens, TypeScript types, and regression coverage for each traffic
path.

## Merge window

This protection originally lived inside #27942 and was split out to keep
that diff reviewable. Until this PR lands, the stack below ships with
only main's existing discovery IP-range guard
(`CODER_MCP_OAUTH2_DISCOVERY_ALLOWED_IP_RANGES`), while org admins can
already point MCP configs at arbitrary URLs. This PR should merge
promptly after the stack below it.

Top of the MCP org-separation stack (CODAGT-711 -> CODAGT-717 audit ->
CODAGT-712 ACLs -> CODAGT-806 token RBAC -> CODAGT-714 org picker ->
this PR).

> Mux (AI agent) authored this PR on Mike's behalf.

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-30 13:09:17 +02:00
McKayla はな 29995c9ef8 feat: add a per-template workspace rename setting (#27558) 2026-08-25 11:05:42 -06:00
Jon Ayers 26de6140fb feat: add flag to disable workspace agent context sync (#28522) 2026-08-24 19:58:30 -05:00
J. Scott Miller 76962273d8 feat: add coder organizations edit for default member roles (#28227)
`default_org_member_roles` was only settable through Terraform or a raw
`PATCH /api/v2/organizations/{organization}`. This adds a CLI
equivalent.

```console
coder organizations edit --org acme --default-org-member-roles organization-workspace-access,organization-template-admin
coder organizations edit --org acme --default-org-member-roles ""   # grant no roles
```

- The flag replaces the organization's current list rather than adding
to it. It accepts a comma-separated list, may be repeated, and
de-duplicates. An empty value removes every role.
- Removing a role prompts for confirmation, listing the roles being
removed, unless `-y` is passed. Adding roles applies without a prompt.
- The resulting set is printed, so no follow-up command is needed to
confirm what was applied.
- The organization is chosen with `-O/--org` or `$CODER_ORGANIZATION`,
and is implicit when the caller belongs to exactly one organization.

The org update endpoint is behind `FeatureMultipleOrganizations`, so the
command is enterprise/premium only. Non-built-in roles are rejected by
the server, and `dbauthz` already prevents a caller from setting a
default they could not assign to a member individually.

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

## Shape

`codersdk.UpdateOrganizationRequest.DefaultOrgMemberRoles *[]string` and
the enterprise `patchOrganization` handler already existed; only the CLI
was missing, and nothing in `cli/` called `UpdateOrganization` at all.
No server or SDK changes are needed.

`organizations edit` follows the partial-update pattern of `coder groups
edit`: check `ParsedFlags().Changed(...)`, populate only the fields the
user set, and leave the rest nil so the handler preserves them. Passing
no flags is an error.

Two earlier shapes were tried and dropped:

- **A `default-org-member-roles` entry in the `organizations settings`
registry.** Every sibling entry unmarshals an SDK type that maps 1:1 to
a dedicated endpoint; this field has no such endpoint. Reusing
`UpdateOrganizationRequest` for the piped JSON meant a stray `name`
field could rename the org, and the documented `show > file`, edit, `set
< file` workflow failed on the default organization, whose name is
reserved.
- **A `--default-org-member-roles` flag on `organizations create`.**
`create` cannot set display name, description, or icon either, so a
roles-only flag there is asymmetric. It would also require
`CreateOrganizationRequest` to grow the field plus server-side
validation.

## Known sharp edge

`serpent.StringArray` resets its slice when any flag value is empty, so
`--default-org-member-roles a --default-org-member-roles ""` clears the
list rather than keeping `a`. This is pinned by a test and called out in
a code comment. The confirmation prompt catches it interactively; a
script passing `-y` would not. A custom flag value that ignores empty
occurrences was prototyped and reverted as more machinery than the
behavior warranted.

## Validation

Manually verified against a local dev deployment with a premium license:
setting, adding, clearing, prompt accepted and declined, duplicate and
whitespace handling, invalid role rejection, and a plain member being
denied. Confirmed with `/authcheck` that a member loses workspace-create
access when the roles are cleared and regains it when restored, and that
the change is recorded in the audit log.

## Follow-ups worth considering

- `--name`, `--display-name`, `--description`, and `--icon` on
`organizations edit`; all already exist on `UpdateOrganizationRequest`.
Rename deserves its own discussion.
- Setting the defaults to `organization-admin` makes every member an org
admin, including the ability to edit the org further, and those users
still render as plain members in member listings. Reachable today via
the API, UI, and Terraform; a warning on privileged roles would help.
- `dbauthz.InsertOrganization` has no `canAssignRoles` check, unlike
`UpdateOrganization`. Harmless while the only caller passes the
deployment default constant.
- `docs/admin/users/organizations.md` still points users at the
dashboard or a raw `PATCH`.
</details>

---

Created by Coder Agents on behalf of @jscottmiller.
2026-08-24 09:41:21 -05:00
david-fraley 8203b2ebaf feat!: hide Coder Tasks behind the enable-ai-tasks flag (#28008) 2026-08-19 14:46:10 -05:00
Paweł Banaszewski a441b03d70 feat: add yaml config option to standalone AI gateway (#28258)
`coder ai-gateway start` now accepts a `--config` / `-c` flag (and
`CODER_CONFIG_PATH`) to load configuration from a YAML file.
2026-08-19 10:07:22 +00:00
Steven Masley f0c17291b3 feat: unhide --oidc-redirect-url server option (#28072)
Unhides the `--oidc-redirect-url` / `CODER_OIDC_REDIRECT_URL` server
option so it appears in `coder server --help` and the deployment
configuration docs.

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

---

> Generated with Coder Agents on behalf of @Emyrk
2026-08-12 16:02:15 -05:00
Nick Vigilante 0a7bb80a1e feat: make CLI/API doc generators emit front-matter metadata (Phase 2) (#27246)
## Summary

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

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

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

## Changes

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

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

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

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

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

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

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

## Review follow-ups (Coder Agents Review)

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

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

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

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

## Cross-repo dependency

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

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

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

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

## Verification & evidence

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

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

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

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

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

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

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

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

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

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

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

</details>

Linear: DOCS-483

> This PR was created with AI assistance (Coder Agents).
2026-08-11 15:22:55 +00:00