Commit Graph
555 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
Bobby Ho a115896a58 feat: add script resource address and dependencies to Script (#30451)
feat(provisionersdk): add script dependency proto fields

Add optional `resource_address` and `dependencies` fields to `Script`
for transporting resolved script ordering. Dependencies identify a
prerequisite by Terraform address and require `SUCCESS` (successful
exit) or `COMPLETION` (finish regardless of outcome).

- Bump provisionerd API from v1.19 to v1.20, regenerate Go/TypeScript
  bindings, and update the CLI golden output.
- Reuse the existing resource tree for workspace-agent and devcontainer
  scripts; no changes to `GraphComplete` or the provisionerd runner.
- Add round-trip tests for both script types and verify unset fields
  preserve existing wire encoding.

The fields remain unused in this PR. Follow-up provisioner changes
populate them; PLAT-548 reads and persists them in coderd.

**Release requirement:** Ship with the PLAT-545 integration stack,
targeting 2.39, so no daemon advertises v1.20 without sending ordering.
Hold or revert this PR before the release cut if that stack misses it.

Refs PLAT-547.
2026-10-07 22:48:21 +00: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 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
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
Andrew Aquino 6487425885 feat: buffer agent debug logs and flush on connection failure (#29671)
## What

Runs the workspace agent logger at `Info` with a slog flight recorder
(`v3.2.0`) instead of unconditionally at `Debug`. Entries below the
current log level are kept in a rolling in-memory ring and flushed to
the sinks when the agent loses its connection to coderd (and before any
`Error`+ log), so the detail leading up to a failure is available
without writing debug logs during normal operation.

Implements CLIENT-672 (connection-log RFC req 13) for the workspace
agent. Depends on the `cdr.dev/slog/v3` `v3.2.0` bump (already on
`main`).

## How

- `cli/agent.go`:
- The main agent logger is
`AppendSinks(...).Leveled(level).FlightRecorder(flightRecorderSize)`,
where `level` is `Info` by default and `Debug` under the global `-v` /
`CODER_VERBOSE`. The recorder is always attached; at `Debug` it is
inert, which keeps the setup correct if the configured level changes in
the future. The reaper logger is unchanged.
- New `--agent-flight-recorder-size` /
`CODER_AGENT_FLIGHT_RECORDER_SIZE` (default `1000`, `0` disables the
flight recorder), so the ring size is configurable per RFC req 13. The
agent flag is distinct from CLI-4's global `--flight-recorder-size`
(#29752) so the two don't collide when `coder agent` inherits the root
global.
- `workspaceAgent` is a `RootCmd` method so it reuses the root command's
global verbose flag instead of defining an agent-specific one.
- `agent/agent.go` (`runLoop`): on a lost coderd connection (the
`io.EOF` disconnect and the generic run error) the agent calls
`logger.Flush(ctx)` to emit the recorded history and then logs at
`Warn`. These are `Warn` rather than `Error` because reconnectable
disconnects are expected and `slogtest` fails tests on any `Error` log;
the manual flush is what surfaces the recorded detail. Graceful shutdown
paths (`ctx` canceled, agent closed) are not flushed.
- Tests: `agent.TestAgent_FlushFlightRecorderOnDisconnect` covers the
flush-on-disconnect path; `cli.TestWorkspaceAgent/DisabledServers` runs
with verbose since its debug messages are otherwise recorded. Golden
`--help` output regenerated.

## Default log verbosity change

This changes the default agent-log verbosity. Today `coder-agent.log`
receives `Debug` unconditionally; with this change, normal operation
logs `Info`, and recorded below-level entries are emitted only when the
agent loses its coderd connection (via a manual flush) or before any
`Error`+ log, or always under `-v` / `CODER_VERBOSE`. This is the
intended behavior of the feature: a quiet steady state with full detail
retained for diagnosing failures. Operators who want the previous
always-debug output can run with `-v` / `CODER_VERBOSE`.

## Alignment with #29752 (CLI)

This mirrors the CLI-4 (CLI log buffer) design so the two
implementations agree:

- **Level model:** Info by default, debug available on demand via the
global `-v` / `CODER_VERBOSE`.
- **Flight recorder size:** default `1000`, `0` disables. CLI-4 exposes
a global `--flight-recorder-size`; the agent uses a distinct
`--agent-flight-recorder-size` / `CODER_AGENT_FLIGHT_RECORDER_SIZE` (the
`CODER_AGENT_*` env convention) so the inherited global and the agent
flag coexist without collision.
- **Flush trigger:** the recorded history is emitted before any `Error`+
log via slog's auto-flush. The agent additionally flushes manually on a
lost coderd connection, which it logs at `Warn` (reconnectable, and
`Error` would fail `slogtest`-based tests); the CLI's failures are
fatal, so it relies on the auto-flush-on-error.

<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) -> this PR (CLIENT-672,
agent) and CLI-4 (CLI), which are independent consumers and can merge in
any order.
</details>

---
<sub>Opened by Coder Agents on behalf of @aqandrew.</sub>
2026-09-29 14:24:00 -07: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 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
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
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
Steven Masley a90ad83af3 feat!: add a hidden flag to disable dynamic parameter closure evaluation (#29356)
**What changed**
Dynamic parameter rendering now evaluates only the coder parameter blocks and what they reference. Other root-module resources are skipped. Parameter, preset, and tag values are unchanged; optimizing rendering on large templates.

**How to revert**
Set `CODER_DYNAMIC_PARAMETERS_FULL_EVALUATION=true` (or `--dynamic-parameters-full-evaluation`) on `coder server` to restore full evaluation. The flag is hidden and needs no restart of workspaces. If you need it, please [open an issue](https://github.com/coder/coder/issues/new) with the template so we can fix the root cause.

**Troubleshooting**
Symptoms would be a parameter default, option list, preset value, or workspace tag that shows as unknown or empty after upgrading, when it was populated before. Confirm by setting the flag above; if the value comes back, report it. Templates written in `.tf.json` are not affected (they always use full evaluation).

**Why**
Rendering re-ran the entire template graph on every parameter change in the workspace form, which dominated latency on large templates. Resources a workspace would create cannot feed a parameter, so evaluating them is wasted work. The optimization lives in coder/preview#226 (coder/trivy#74); this PR adds the deployment-level escape hatch.

---

- `CODER_DYNAMIC_PARAMETERS_FULL_EVALUATION` / `--dynamic-parameters-full-evaluation` (hidden, default `false`) on `DeploymentValues`.
- `dynamicparameters.PreviewOptions(dv)` maps it to `preview.OptionFullEvaluation()`; `dynamicparameters.WithPreviewOptions` threads it through the loader to `preview.Preview`.
- Wired at the three render paths that hold deployment values: the template version tags extractor, the dynamic parameters websocket, and `wsbuilder` builds created from `coderd` (which call `.DeploymentValues(...)`).

Not covered: the autobuild lifecycle executor and the enterprise prebuilds reconciler construct `wsbuilder` without deployment values, so builds started from those paths use preview's default regardless of the flag. Those only re-render for builds, not the keystroke websocket path the optimization targets.

Prepared with Coder Agents assistance.
2026-09-17 14:33:37 -05:00
Bobby Ho 4ee70c66c3 feat: gate the OAuth2 provider on CODER_OAUTH2_PROVIDER_ENABLE (#29251)
Second of five for PLAT-492. Gates all OAuth2 provider routes and dashboard navigation on CODER_OAUTH2_PROVIDER_ENABLE instead of the oauth2 experiment. The flag is off by default, so deployments using CODER_EXPERIMENTS=oauth2 must set it before upgrading or OAuth2 clients will receive 404s. Existing apps, tokens, secrets, and DCR settings are unchanged. Stacked on #29248 and labeled release/breaking; the next PR makes the old experiment a no-op with a migration warning.
2026-09-14 13:47:48 -07: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
Michael Suchacz df1a910815 chore: remove AI task support from the provisioner protocol (#28790)
Removes AI task support from the provisioner protocol: the task-related
proto fields, terraform scanning for `coder_ai_task` resources, echo
provisioner support, the regenerated `.pb.go` and
`provisionerGenerated.ts`, and the terraform testdata that exercised
them. The provisioner API version change lives in
`provisionerd/proto/version.go`.

**Stack context:** Coder Tasks removal stack (CODAGT-642): #28743
frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084
notifications and usage → #29085 build reasons → #29086 tables → #28750
permissions. The last four PRs replace the single data-drop migration
that used to live in #28750; each carries one concern and a focused
migration test.

**Why:** the proto fields lost their last consumer in #28789; this
deletes the producer side and the wire format.

**What to scrutinize:** the proto/version handling, and that
`coder_ai_task` resources in existing templates are now ignored rather
than errors (template imports simply no longer scan for them).

**Validation:** `go build ./...`, `go test ./provisionersdk/...
./provisionerd/...`, `go test ./provisioner/terraform -run
TestConvertResources`, provisioner list golden regenerated, site tsc,
pre-commit hooks.

**Size:** +580/-1,286 over 76 files; most files are mechanical testdata
and generated-code updates.

> Created by Xum (AI agent) on behalf of @ibetitsmike.
2026-09-11 02:06:11 +00:00
Michael Suchacz 9cd38b5373 feat!: remove the Tasks API from coderd and codersdk (#28789)
Removes the Tasks API and task orchestration from coderd and codersdk:
the `/api/v2/tasks` handlers, task middleware and search filters, task
name generation, autobuild pause/resume logic, task notification
enqueues, telemetry, and the codersdk task types. Regenerates apidoc,
the API reference docs, and `typesGenerated.ts`.

**Breaking change:** the Tasks API is removed; requests to
`/api/v2/tasks` fail. Tasks was deprecated in v2.34.

**Stack context:** Coder Tasks removal stack (CODAGT-642): #28743
frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084
notifications → #29085 build reasons → #29086 tables → #28750
permissions. The last four PRs replace the single data-drop migration
that used to live in #28750; each carries one concern and its own
migration number.

**Why:** with the UI (#28743) and CLI (#28788) gone, this deletes the
server surface. Database tables, RBAC, and notification templates stay
until the top of the stack so every layer builds and migrates
independently.

**What to scrutinize:**
- The `enable-ai-tasks` option is removed outright (review feedback):
configs still carrying `enableAITasks` fail to parse until the key is
deleted.
- provisionerdserver now writes `HasAITask: false` on template/build
flags; the column and these lines are dropped in #29085.
- `codersdk.ResourceTypeTask` stays so audit logs recorded before the
removal keep rendering.

**Validation:** `go build ./...`, `go vet ./...`, `go test
./codersdk/...`, site biome and tsc, CLI goldens regenerated, pre-commit
hooks.

**Size:** +242/-10,792 over 76 files; additions are regenerated
docs/goldens and test fixture updates.

> Created by Xum (AI agent) on behalf of @ibetitsmike.
2026-09-11 01:48:56 +00:00
Michael Suchacz d0de33cdf1 chore: remove the Coder Tasks CLI and task automation (#28788)
Removes every in-repo Tasks client: the `coder exp tasks` CLI command
family, the tasks scaletest runner, and the task-driven triage
automation (`traiage.yaml`, `code-review.yaml`,
`classify-issue-severity.yml`, `scripts/traiage.sh`). Triage runs
through `triage-via-chat-api.yaml` and coder/create-agent-chat-action
instead.

**Stack context:** Coder Tasks removal stack (CODAGT-642): #28743
frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084
notifications and usage → #29085 build reasons → #29086 tables → #28750
permissions. The last four PRs replace the single data-drop migration
that used to live in #28750; each carries one concern and a focused
migration test.

**Why:** clients come off before the API they call. After this layer
nothing in the repo invokes the Tasks API outside coderd itself.

**What to scrutinize:** all but three files are whole-file deletions.
`triage-via-chat-api.yaml` gets a comment fix. `NavbarView.tsx` and its
stories carry two small repairs to the frontend layer below (unused
`user` prop, stale `TasksFilter` story wiring) so the stack lints clean
from this layer up; they rebase away if folded into #28743.

**Validation:** `go build ./...`, `go test ./cli -run TestCommandHelp`,
site tsc, pre-commit hooks (gen, fmt, lint).

**Size:** +4/-6,938 over 42 files; effectively pure deletion, so it
reads much faster than the line count suggests.

> Created by Xum (AI agent) on behalf of @ibetitsmike.
2026-09-11 00:51:04 +02: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
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