Commit Graph
3089 Commits
Author SHA1 Message Date
Michael Suchacz 50ecadf953 fix: scope the MCP OAuth2 resource help text to auto-discovery
An empty resource sends none unless auto-discovery fills it while
registering the client, so say that instead of promising none. Shorten the
create request doc to match, drop a class that has no effect on the
single-field row, and use an example.com resource in the form test.
2026-10-12 13:53:42 +00:00
Michael Suchacz 45ff791c61 docs: note MCP OAuth2 reconnects and the resource fallback form
Say which OAuth2 settings delete stored user tokens, and describe the
normalized server URL that discovery stores when no Protected Resource
Metadata entry matches.
2026-10-12 13:47:36 +00:00
Michael Suchacz b1bf4afd74 fix: align and clarify the MCP OAuth2 resource field
Label the form input "Resource URL" like its sibling endpoint fields, say
that an empty value sends no resource parameter, and match the sibling row
grid so the field lines up with the column above. Describe the API field's
discovery and clear semantics precisely, and cover clearing a stored
resource from the edit form.
2026-10-12 13:43:13 +00:00
Michael Suchacz 2b875068e0 feat: send RFC 8707 resource parameter on MCP server OAuth2 flows
Store an oauth2_resource indicator on MCP server configs. Auto-discovery
fills it from the Protected Resource Metadata entry that covers the
server URL (else the canonical server URL); admins can set or clear it.
When set, Coder sends it as the resource parameter on authorization,
code exchange, and refresh requests. Manual configs without it send no
resource parameter, so providers that reject it keep working.
2026-10-12 11:23:57 +00:00
Thomas Kosiewski f923f4a525 chore!: remove the chat automations experiment (#30412)
Removes the experimental Chat Automations feature (`chat-automations` experiment) from main. This reverts the 16-PR stack that added it and adds two forward migrations that undo its schema and credential changes.

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

## What is removed

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

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

## What stays, and why

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

## Notes for reviewers

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

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

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

![Agents sidebar after the upgrade, with no Automations entry](https://github.com/user-attachments/assets/bd446035-7fc8-4ca4-a735-3a4f36380738)
2026-10-11 19:57:49 +02:00
dfa72df9aa docs: remove references to unsupported SAML authentication (#30507)
## Summary

Coder doesn't support SAML, but a few docs pages implied it did.
This PR removes those mentions.

Resolves
[DOCS-1194](https://linear.app/codercom/issue/DOCS-1194/remove-saml-mentions-from-docs-coder-doesnt-support-saml).

## Changes

- `docs/install/index.md` and `docs/install/prepare/index.md`: "OIDC or
SAML application" is now "OIDC application".
- `docs/.style/style-guide/audience-and-scope.md`: the example snippets
no longer mention SAML or link to a `./saml.md` page that doesn't exist.
The hub-page example now lists headless authentication instead, and the
persona "Coder surface" lines say "OIDC" in place of "OIDC/SAML".

<details>
<summary>Evidence that Coder doesn't support SAML</summary>

Checked against `main`:

- No SAML library in `go.mod`, `go.sum`, or `site/package.json`.
- The `login_type` enum in `coderd/database/dump.sql` and
`codersdk.LoginType` only cover `password`, `github`, `oidc`, `token`,
`none`, and `oauth2_provider_app`.
- No SAML handlers, endpoints, or deployment options in `coderd/` or
`enterprise/`.
- The only code mention is a comment in `coderd/userauth.go` about
SAML-to-OIDC bridges sending `email_verified` as a string.

</details>

## Testing

- `pnpm run lint-docs`: 0 errors.
- The pre-commit hook passed.
- `git grep -i saml -- docs` returns nothing.

---

*Generated by Coder Agents on behalf of @nickvigilante.*

---------

Co-authored-by: Ben Potter <me@bpmct.net>
Co-authored-by: Ben Potter <ben@coder.com>
2026-10-11 08:36:17 -07:00
McKayla はな 86ebc72236 chore: remove unused autofill-parameters endpoint and experiment (#30525) 2026-10-09 16:42:41 -06:00
coder[bot] f8e053e385 docs: document VS Code SSH keepalive and reconnection settings (#30501) 2026-10-09 18:43:18 +05:00
Michael Suchacz 782fb30f09 feat: load whole chat turns per history page (#30524)
Closes
[CODAGT-1372](https://linear.app/codercom/issue/CODAGT-1372/load-whole-turns-per-history-page-so-collapsed-working-blocks-fill-in).

With collapsed working blocks, a long agent turn renders as one row, but
chat history pages hold a fixed 50 messages. A 400-step turn took about
eight sequential page loads to fill, and its block showed partial labels
("at least", "or more") until then.

`GET /api/v2/chats/{chat}/messages` now returns `turn_start_id` on
newest-first pages: the ID of the user prompt that starts the turn
containing the page's oldest message. It comes from a new
`GetChatTurnStartID` query on the existing
`idx_chat_messages_user_prompts` index, so there is no migration.
Soft-deleted prompts and model-only user rows never start a turn.

The history query then fills each page back to that prompt with requests
of up to 200 messages, capped at 1000 messages per page, so a page holds
whole turns and a complete block renders without partial labels. Past
the cap, or when a fill request fails or returns no messages, the page
keeps what loaded and ends mid-turn, and the next page continues it, as
before. Because the fill runs inside the page fetch, a chat now waits
for its fill requests (one to five) before it first renders: with an
injected 500 ms per-request delay, a chat whose newest turn hits the cap
appeared after 3.8 s instead of 1.1 s.

## Screenshots

From the dogfood UAT, the same 200-step turn with its next history
request held, so each label shows only what loaded before it:

**Before**, on the base commit `29e876df4da`, after two 50-message
pages: "Worked for at least 1m 35s (48 steps or more)", partly hidden by
the loading indicator.

![Before: partial label for a 200-step
turn](https://github.com/user-attachments/assets/6b4e4abf-4bc6-4476-8ed5-52c39c8eebe6)

**After**, on `186a9b053a0`, after the first page: "Worked for 6m 39s
(200 steps)".

![After: exact label for the same 200-step
turn](https://github.com/user-attachments/assets/22ec1900-1e7b-4c98-87a9-0463e1d852c2)

A 750-step turn, larger than one 1000-message page, is exact once the
next page loads:

![After: 750-step turn,
expanded](https://github.com/user-attachments/assets/f927a848-62b1-4eb7-a548-fbdff61fc9c4)

A malformed fill response keeps the loaded messages and the partial
label instead of showing "Failed to load chat", as `ecdfb27ec29` did:

![Malformed fill response: partial label, no error
screen](https://github.com/user-attachments/assets/6d393df9-15a2-471e-9bb6-71e919aca570)

## Testing

- Go: `TestGetChatMessages_TurnStartID` (pages spanning turns, deleted
prompts, model-only user rows, polling and empty pages) and the dbauthz
suite entry.
- Vitest: fill request parameters, the 1000-message cap, failed,
malformed, and empty fill responses, and servers without
`turn_start_id`.
- Dogfood UAT through Coder Agents: PASS on `186a9b053a0` (round 4):
whole-turn first pages, the 1000-message cap and its continuation, fill
failures, a live turn, and API checks for deleted prompts and model-only
user rows. Round 3 on `ecdfb27ec29` failed: a malformed fill failed the
chat load, and an empty fill reporting `has_more` repeated forever.
`7266f468290` fixes both, with regression tests.

## Review record

- Test audit with mutation checks: the Go test now covers a page
spanning two turns, which catches a lookup keyed on the newest message.
A re-audit of later test changes changed nothing; the one surviving
mutation drops the `!older.has_more` stop, costing one extra request
when the prompt is deleted mid-fill.
- Frontend review (8 roles, 5 rounds): fixed doc, naming, loose-type,
and test findings. Its suggestions to catch only the fill request (DF5)
and drop the empty-page stop (SD4) caused the round 3 failures and are
reverted. Kept: SD1 (`MAX_MESSAGES_PER_REQUEST` is used once, named like
`MESSAGES_PAGE_SIZE`) and round 5 SD4 (`!older.has_more` is the
endpoint's pagination signal). Declined DF6: the `queued_messages`
refetch race predates this change, and a failed refetch fill only
unloads older history that reloads on scroll.
- Codex: no findings on `186a9b053a0`.
- Known: a hung fill delays the first render (no client timeout); fills
are not cancelled when the user leaves; the top of history costs one
extra empty request; injected malformed fill rows break the page as they
do on the first page.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-09 13:32:39 +02:00
Michael Suchacz 6bae268487 fix: move organization instructions to the Instructions page (#30428)
Moves organization instructions (#30272) from the Coder Agents page to
**AI Settings** > **Coder Agents** > **Instructions**, so every Coder
Agents instruction is managed on one page. The API and stored data are
unchanged.

- **Deployment admins** see a "Deployment instructions" section with the
existing system prompt and plan mode form, then an "Organization
instructions" section. The organization section has an organization
picker when there is more than one organization.
- **Organization admins and auditors** who can read an organization's
chat model configuration get an Instructions entry in the AI settings
sidebar and see only the organization section. Auditors get it
read-only.
- The selected organization is kept in `?org=`, and the sidebar link
carries it over from the other AI settings pages.
- The Coder Agents page goes back to its layout from before #30272. Its
sections and the new page's sections share new `SettingsSection` and
`OrganizationSettingsSection` components.
- Three docs pages point to the new location.

Other behavior changes:

- The deployment section shows a loader while loading and an error alert
when loading or refreshing fails. Before, the page rendered nothing
until both settings loaded.
- The deployment forms no longer have their own accessible names,
because each section is named by its heading.

## Testing

- Vitest for the Instructions page and sidebar link, and stories for the
new states. Breaking each of the 9 main code paths, or removing the
instructions field's accessible name, fails its test.
- The branch merges `main` for #30402, which made the organization
picker a combobox.
- CI passes on `a0cc6a98660`.
- Remote dogfood UAT, [evidence
chat](https://dogfood.cdr.dev/agents/1cbf9da4-9671-4890-ade1-c151a1a69cd7):
**PASS** on `a0d9c3fca46`, 14 scenarios across every role, `?org=`
handling, injected load failures, keyboard use, and a 390 px layout. The
remote agent's FAIL (a double-click on Save sends 2 PUTs) also happens
on the merge base, so it predates this PR. Delta round on `a0cc6a98660`:
**PASS**. When the permission re-check fails, the owner and an
organization admin see the alert above the organization section, and the
unsaved draft stays and saves.
- UAT notes left as is: the fallback for an unreadable `?org=` is
read-only, as on the Coder Agents page; `?org=` matching is
case-sensitive, as on the Models and Spend pages; the old
`/agents/settings/instructions` redirect drops `?org=`; the permission
alert shows the server's error message without saying which check
failed, as on the Models pages.

## Screenshots

From UAT on a test deployment.

| Organization admin | Owner, after a failed refresh (unsaved edit kept)
|
|---|---|
| ![Organization admin sees only the organization
section](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/8c6baf5a5b4784cdfecd066fae54af7f4f3c4881/r3-org-admin-instructions.png)
| ![Error alert above the deployment
form](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/8c6baf5a5b4784cdfecd066fae54af7f4f3c4881/r3-owner-refresh-error-draft-kept.png)
|
| **Coder Agents page, no instructions card** | **Unavailable `?org=`:
warning and read-only fallback** |
| ![Coder Agents
page](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/8c6baf5a5b4784cdfecd066fae54af7f4f3c4881/r3-coder-agents-page.png)
| ![Unavailable organization
warning](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/8c6baf5a5b4784cdfecd066fae54af7f4f3c4881/r3-unavailable-org-fallback.png)
|

## Review record

1. `coder-frontend-review` (8 reviewer agents) on `3dd65e828f9`: fixed
in `a0d9c3fca46` (deployment refetch errors were dropped, plus naming,
prop types, test waits, and a single-organization story). Declined:
`SettingsHeader` in `SettingsSection` and merging the sidebar groups
(both change existing layout), and restructuring the moved card (git
would stop detecting the move).
2. `frontend-review` (FE1 to FE10) on `a0d9c3fca46`: every rule passes,
no changes.
3. Codex,
[review](https://github.com/coder/coder/pull/30428#pullrequestreview-5431118231)
on `a0d9c3fca46`: 1 P2, a docs sentence wrote "more than 1" where the
numbers guide spells out "one". Fixed in `0e71b8f16b9`.
4. Codex,
[review](https://github.com/coder/coder/pull/30428#pullrequestreview-5431285875)
on `0e71b8f16b9`: 2 findings, each confirmed by a failing test and fixed
in `a0cc6a98660`. A failed background re-check of organization
permissions showed no alert, unlike the old Coder Agents page and the
Models pages (P2). The page tests found the instructions field by its
value, so removing its accessible name went unnoticed (P1).
5. `coder-frontend-review` (8 reviewer agents) and `frontend-review`
(FE1 to FE10) on `a0cc6a98660`: everything passes, no changes. The round
1 `findByDisplayValue` suggestion is reversed, because FE10 asks for
role and name queries.
6. Codex on `a0cc6a98660`: [no major
issues](https://github.com/coder/coder/pull/30428#issuecomment-6020794170).

> Xum, an AI coding agent, implemented, tested, and opened this PR on
behalf of @ibetitsmike.
2026-10-09 11:14:59 +02:00
Mathias Fredriksson befda9b29f docs: mention chat reasoning_tokens is part of output_tokens (#30500)
Document that reasoning_tokens is included in the output_tokens on
ChatMssageUsage, which is the case for all known providers.

Refs CODAGT-1350
2026-10-09 12:12:08 +03:00
Atif Ali 261269aff0 fix: support path-aware OAuth discovery for remote MCP (#30168)
## Problem

VS Code discovers Coder's MCP endpoint as a path-qualified OAuth
resource, but Coder advertises the deployment root. Accepting MCP-bound
tokens also requires keeping REST-backed tool calls within the
originating MCP resource rather than granting those tokens direct REST
access.

## Fix

- Publish path-aware protected resource metadata and authentication
challenges; keep authorization-server metadata at the root.
- Validate the MCP audience and delegate tool requests through a private
in-process transport that retains identity, scopes, expiry, revocation,
and streaming cancellation.
- Reject unsupported MCP path aliases and validate SDK path components
before URL resolution.
- Add discovery, audience, authorization, endpoint-isolation, and
transport lifecycle regression tests and update integration docs.

## Validation

VS Code completed OAuth and returned the authenticated user through a
real MCP tool. Official MCP SDK 1.30.1 completed discovery,
registration, PKCE, tool execution, and refresh. These live checks
preceded the final path hardening; the hardened paths are covered by
automated regressions.

Affected Go package tests, targeted race tests, backend/SDK lint, and
targeted documentation checks passed during self-review. The exact PR
commit was also checked separately from the uncommitted consent-scope
fix.

> [!NOTE]
> Tokens are MCP-audience-bound, but grants still include `coder:all`;
least-privilege scopes remain a separate requirement
([PLAT-639](https://linear.app/codercom/issue/PLAT-639)).

Preview:
https://coder.com/docs/@fix/mcp-internal-delegation/ai-coder/mcp-server

<details>
<summary>Implementation decisions and review context</summary>

1. Treat `/api/experimental/mcp/http` and its single-trailing-slash form
as supported MCP resource paths; reject other aliases and descendants
before route authentication.
2. Preserve deployment-root discovery and authorization-server metadata
for existing REST integrations.
3. Bind private delegation to the authenticated API-key ID. Revalidate
the original credential and enforce normal RBAC/scopes on every internal
REST request; do not derive delegation from HTTP headers.
4. Keep internal HTTP, streaming, and WebSocket traffic in-process with
no network fallback. Close the transport on outer-request cancellation
and normal completion.
5. Validate workspace owner/name path segments before SDK URL
construction, including tool-level tests that malformed arguments cannot
select a different REST endpoint.
6. Keep compatibility and delegated tool execution together:
discovery-only changes would allow authentication while leaving real MCP
tool calls broken.

</details>

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑💻
2026-10-09 00:58:39 +05: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
Andrew G. Dunn c11d60ad8d docs: note the pubsub cluster port between HA replicas (#30290)
HA replicas connect to each other's embedded NATS pubsub on TCP 6222.
The port is hardcoded
([`coderd/x/nats/pubsub.go`](https://github.com/coder/coder/blob/7f3d35353eddcd8a9e573094e5e2531bd2d73659/coderd/x/nats/pubsub.go#L62))
with no flag or environment variable, and since #29283 NATS pubsub is on
by default. The HA page explains `CODER_CLUSTER_HOST` but doesn't name
the port, so a firewall or default-deny NetworkPolicy between `coderd`
nodes blocks it. This adds the port, and what happens without it, next
to `CODER_CLUSTER_HOST`.

Measured on v2.37.3 (`CODER_EXPERIMENTS=nats_pubsub`, the default on
main) with two replicas on GKE under a default-deny NetworkPolicy, port
8080 open between the replicas in both runs. Through a port-forward to
replica B, `PUT /api/v2/workspaces/{id}/extend` publishes a workspace
update in the request path. A watcher on `/api/v2/workspaces/{id}/watch`
through replica A counts the events. The control sends the same request
through A.

6222 blocked:

```text
label=blocked A=coder-699ccb59f8-695bj B=coder-699ccb59f8-w8glp baseline_data_events=1
control: extend via A -> HTTP 409; data events on A: 1 (expect 1)
test: 5x extend via B -> HTTP 409 409 409 409 409; data events on A: 0
coder-699ccb59f8-695bj :6222 established: 0
coder-699ccb59f8-w8glp :6222 established: 0
```

6222 allowed between the replicas (same pods, no restart):

```text
label=allowed A=coder-699ccb59f8-695bj B=coder-699ccb59f8-w8glp baseline_data_events=1
control: extend via A -> HTTP 409; data events on A: 1 (expect 1)
test: 5x extend via B -> HTTP 409 409 409 409 409; data events on A: 5
coder-699ccb59f8-695bj :6222 established: 4
coder-699ccb59f8-w8glp :6222 established: 4
```

The 409s are expected because the workspace is stopped; the handler
publishes the update before it returns
([`coderd/workspaces.go`](https://github.com/coder/coder/blob/3a248167f6e58462a8a8cddba3b49a8ff72a9f80/coderd/workspaces.go#L1711)
at v2.37.3).

Would it also make sense for the chart to declare 6222 as a container
port, or for the port to be configurable? I left both out of this
change.

AI involvement: I used an AI assistant to draft this change, and
verified it with the runs above against a two-replica deployment.
2026-10-07 19:21:29 -04:00
Andrew G. Dunn 020b437ec9 docs: document dropping capabilities for restricted Pod Security (#30271)
Following the suggestion in #22543 to have
`coder.securityContext.capabilities` in `values.yaml` without a default,
this adds it as a commented example, the same way `values.yaml` shows
`env` and `initContainers`, and adds one line to the Kubernetes Security
Reference. Existing deployments don't change on upgrade.

The chart's default security context passes every Pod Security Standards
`restricted` check except capabilities, so a namespace that enforces
`restricted` rejects the pod. Because the example is commented out, the
rendered chart is unchanged:

```console
$ diff main.yaml branch.yaml && echo "renders identical ($(wc -l < branch.yaml) lines)"
renders identical (208 lines)
```

Server-side dry runs of this branch's chart into a namespace labeled
`pod-security.kubernetes.io/enforce=restricted` (GKE, Kubernetes 1.35),
using the pod spec from the rendered Deployment, as is and with the
example uncommented:

```console
$ kubectl create --dry-run=server -n coder -f pod-branch.json
Error from server (Forbidden): error when creating "pod-branch.json": pods "pss-main-branch" is forbidden: violates PodSecurity "restricted:latest": unrestricted capabilities (container "coder" must set securityContext.capabilities.drop=["ALL"])
$ kubectl create --dry-run=server -n coder -f pod-branch-drop.json
pod/pss-main-branch-drop created (server dry run)
```

A v2.37.3 deployment with the value set runs in a `restricted`
namespace, ready with no restarts.

AI involvement: I used an AI assistant to draft this change, and
verified it with the commands above against a running cluster.
2026-10-07 23:18:04 +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
blinkagent[bot]andblink-so[bot] c9680e4f36 docs: correct the CODER_AGENT_BLOCK_FILE_TRANSFER block list (#29705)
## Problem

The FAQ entry _"How can I restrict inbound/outbound file transfers from
Coder workspaces?"_ documents the wrong block list for
`CODER_AGENT_BLOCK_FILE_TRANSFER`.

It currently says the list includes `scp`, `rsync`, `ftp`, and `nc`.

The actual list in
[`agent/agentssh/agentssh.go`](https://github.com/coder/coder/blob/main/agent/agentssh/agentssh.go)
is:

```go
// BlockedFileTransferCommands contains a list of restricted file transfer commands.
var BlockedFileTransferCommands = []string{"nc", "rsync", "scp", "sftp"}
```

So the docs have two errors:

- **`ftp` is documented but is not blocked.** An admin reading this page
could reasonably believe `ftp` is covered when it is not.
- **`sftp` is blocked but is not documented.** This matters
operationally, because SFTP is blanket-blocked at the subsystem level
(`if session.Subsystem() == "sftp"`), which disables anything built on
it.

## Changes

1. Correct the block list to match the source, in the same order as the
slice so the two are easy to diff by eye in future:

```diff
-block list, which includes `scp`, `rsync`, `ftp`, and `nc`.
+block list, which includes `nc`, `rsync`, `scp`, and `sftp`.
```

2. Per review feedback, add a note to **Important Notice** covering what
enabling this actually breaks: SFTP-based tooling, and [Coder Desktop
file
sync](https://coder.com/docs/user-guides/desktop/desktop-connect-sync).

Desktop file sync breaks via `scp` rather than `sftp`. It runs Mutagen
over SSH, and Mutagen's SSH transport installs its remote agent binary
by shelling out to `scp`
([`pkg/agent/transport/ssh/transport.go`](https://github.com/coder/mutagen/blob/v0.18.3/pkg/agent/transport/ssh/transport.go)),
which is on the block list. The note keeps that distinction because an
admin debugging it will see an `scp` failure, not an SFTP one.

## Correction

An earlier revision of this description claimed `coder cp` is also
blocked. **That was wrong — there is no `coder cp` command.** No
`cli/cp.go`, no `docs/reference/cli/cp.md`, no `cp` entry in the CLI
index. I've removed the claim rather than document a command that
doesn't exist. Discussed in the thread below.

## Not included

Linking the FAQ to [Agent
Firewall](https://coder.com/docs/ai-coder/agent-firewall) from the "For
more advanced security needs" line, which currently only says "consider
adopting an endpoint security solution." Happy to add if wanted, but it
felt out of scope for a correctness fix.

Also note I only verified the macOS Desktop client.
`coder-desktop-windows` and `coder-desktop-linux` are very likely the
same Mutagen setup, but I didn't read them, so the note makes no
per-platform claim.

Created on behalf of @bartekgatzcoder.

---------

Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
2026-10-07 15:02:55 +00:00
Ehab Younes d56cc3a6c3 docs(docs/support): clarify VS Code support bundle requirements and limits (#30430)
Refs VSC-25, #30118
2026-10-07 11:48:47 +03:00
Ehab Younes fc01bee831 fix: keep new API keys within the caller's scopes and allow list (#30256)
A scoped key holding api_key:create could mint a broader key, e.g. a token scoped to [api_key:create user:read] could mint coder:all.

- New keys must be covered by the caller's scopes and allow list, and inherit them when none are requested
- Requests beyond the caller return 403
- New key expiry is capped at the caller's
- Covers POST /users/{user}/keys/tokens, POST /users/{user}/keys, app auth-redirect, and /oauth2/authorize (invalid_scope on excess grants or a restricted session allow list)
- coder:all sessions, including browser logins, behave as before
- Not addressed: workspace start still mints a coder:all key for the owner
2026-10-07 11:43:19 +03:00
Michael Suchacz e4682343e6 feat: match PR number prefixes in chat search (#30404)
Chat search now matches PR numbers by prefix, so typing `3028` already
finds the chat for PR `30281` instead of showing zero results
mid-typing.

The free-text `search:` branch in `GetChats` switches from `pr_number =
@search::bigint` to `pr_number::text LIKE @search || '%'`, still guarded
by a digits-only regex so the value can never carry LIKE wildcards. The
lookup stays a correlated per-chat EXISTS on the `chat_diff_statuses`
primary key, which leads with `chat_id`, so the cost is the same as
before and no new index is needed. The explicit `pr:` filter stays
exact, and ordering is unchanged (no exact-match ranking) so cursor
pagination is unaffected.

Behavior note: values with leading zeros (`030281`) no longer match PR
`30281`, since the old bigint cast normalized them. PR numbers never
have leading zeros, so this seemed fine.

Closes CODAGT-1342

## Testing

- `TestGetChatsSearch` gains prefix (`4` -> PR 42), no-infix (`2` ->
none), and LIKE-wildcard (`4%` -> none) cases; the prefix case fails on
the old predicate.
- Dogfood UAT through Coder Agents on the branch: searching `3`, `302`,
`3028`, `30281` all surface the PR-linked chat; `0281` and `302810` do
not; `pr:3028` stays exact.

> [!NOTE]
> This PR was created by Xum acting on behalf of @ibetitsmike.
2026-10-06 22:42:56 +02:00
Ian Evans 21c1abe9ad docs(docs/install): reformat to one sentence per line (#30438)
Reformats every Markdown page under `docs/install` to the
[one-sentence-per-line
convention](https://github.com/coder/coder/blob/main/docs/.style/style-guide/formatting.md#one-sentence-per-line).
Addresses DOCS-668.

This is a source-layout change only: 28 of the 36 pages change, and
rendered HTML is identical for all of them except three wording fixes.
Three pre-existing em dashes sat on reflowed lines, which `lint/emdash`
flags as new, so they're rewritten with commas or a sentence break
(`operate/upgrade/esr-2.24-2.29-upgrade.md`,
`operate/upgrade/best-practices.md`).

Front matter, fenced code, tables, HTML blocks, and headings are
untouched.

`Coder.OneSentencePerLine` is not enabled for `docs/install` in
`.vale.ini`: the 39 remaining findings are all table rows or code, which
the guide puts out of scope, and enabling the rule would break the
zero-baseline doctrine.

<details>
<summary>Implementation and verification notes</summary>

**Approach.** A throwaway script reflowed each paragraph. Bullet items,
numbered entries, and blockquote lines (including `> [!NOTE]` callouts)
are each their own paragraph; extra sentences in a list item continue on
indented lines, matching `docs/.style/content-guidelines.md`. Sentence
breaks are never inserted inside inline code, link text, URLs, or HTML
tags, and abbreviations such as `e.g.` and `etc.` don't count as
sentence ends. Images that started their own source line stay on their
own line. The script is idempotent: a second pass produces no changes.

**Merge with main.** `main` restructured `docs/install` into plan,
prepare, server, validate, and operate sections after this branch was
cut. The merge takes `main`'s tree and re-runs the reflow over every
page now under `docs/install`, so the branch diff against `main` is
reflow only. `releases/index.md` and `releases/feature-stages.md` moved
out of `docs/install` on `main` and are no longer in scope.

**Verification.**

- Rendered every page with `marked` from `main` and from this branch and
compared normalized HTML: identical except the three em-dash rewrites.
- Vale with `Coder.OneSentencePerLine` forced on for `docs/install`: 277
findings on `main`, 39 on this branch, all in table rows or fenced code.
- A broader sweep for mid-line sentence boundaries and for false splits
(lines starting lowercase, lines ending in an abbreviation) found no
prose hits.
- `markdownlint-cli2`, `markdown-table-formatter --check`, `make
lint/emdash`, and `make pre-commit-light` pass.

</details>

---

*Generated by Coder Agents on behalf of @ianjevans.*
2026-10-06 13:31:35 -07:00
Nick Vigilante 44af8a1b56 docs: shorten the add-a-language install script copy and note apt reinstalls (#30376)
The "Add a programming language" guide embedded a full copy of the
install script that had drifted from the shipped Template Builder base
(it used `grep -q` partial matching, not `has_language`). The Final code
tab now shows an abbreviated excerpt (helpers plus the new Ruby branch)
so it can't drift again, and Step 4 and the "How does Coder install the
language you pick?" section use `has_language ruby`.

Also adds a short note in Step 4 that `apt-get` installs Ruby into the
ephemeral container, so it reinstalls on every start, while
home-directory installs persist. The persistent `~/.local` approach from
the ticket is not taught because it never landed on `main` (#28485 was
closed unmerged).

The `has_language` helper is present in the Template Builder base on
`main`. The older example template gets it in #30373. Refs DOCS-713.

Generated by Coder Agents on behalf of @nickvigilante.
2026-10-06 10:12:51 -04: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
Mathias Fredriksson cc76b62009 refactor!: drop edit_files search/replace wire compat (#29221)
Remove the deprecated `search`/`replace` keys from the `edit_files`
wire type. `FileEdit` now encodes and decodes `old_text`/`new_text`
only; the shims that carried the old keys through the rename (#28467)
are gone.

**Breaking change:** chat lifecycle hook consumers must use `old_text`
and `new_text` for `edit_files`. A `pre_tool_use` `input_override`
that still sends `search`/`replace` fails with `old_text must not be
empty`.

Fixes CODAGT-483
2026-10-06 10:42:44 +00:00
Mathias Fredriksson 02a12fefa8 chore: remove the Coder Agents chat board prototype (#30394)
Prototypes shouldn't be on main, so this removes the Coder Agents chat
board.

It removes the board added in #29425 and extended in #29472, #30094,
#30103, #30231 and #30332, plus the hidden `chat-board` experiment from
#30084. With them go the route, the sidebar entry and grouping, the
settings toggle, the sidebar row trailing slot, and the `chatId` prop on
`AgentChatPage`. The abort signal on `getChats` stays, because #30079
uses it outside the board.

The board continues in the experimental PR #30395, which is not for
merging.
2026-10-06 13:11:21 +03:00
Ehab Younes f0e2fce326 fix: let scoped tokens list and mark inbox notifications read (#30176)
`inbox_notification:read` and `inbox_notification:update` existed but weren't
in the public scope catalog, so only `coder:all` tokens could use the inbox.
The inbox endpoints also returned 500s or a clean socket close when a scope
was missing, instead of a 403.

- Add `inbox_notification:read` and `inbox_notification:update` to the public
  scope catalog. `create` stays internal, so there is no
  `inbox_notification:*`. No migration is needed.
- Every inbox endpoint checks scopes up front and returns 403 naming the
  missing scope. The watch endpoint checks before the websocket upgrade.
- `read-status` requires both `read` and `update`. It returns 404 unless the
  notification belongs to the caller, so an owner can no longer mark another
  user's notification read.
2026-10-06 13:01:11 +03:00
Michael Suchacz 7993c73c87 feat: add organization-scoped Coder Agents instructions (#30272)
Adds organization-scoped Coder Agents instructions. Organization admins
set them in **Admin settings** > **AI** > **Coder Agents** >
**Organization settings**, or with `GET`/`PUT
/api/v2/organizations/{organization}/chats/config/system-prompt`.
Implements [CODAGT-984](https://linear.app/codercom/issue/CODAGT-984).

The instructions add to the deployment system prompt and never replace
it. When a chat is created, chatd stores the organization prompt as its
own system row right after the deployment row, only for chats in that
organization. Subagents resolve their parent organization's current
prompt when they spawn, and existing chats keep their stored rows.
Access reuses the organization `chat_model_config` permission: owners
and organization admins edit, auditors read, members get 404 on read and
403 on write. Writes reuse the deployment prompt's sanitization, size
limit (128 KiB by default), and audit behavior, with a new
`chat_organization_system_prompt` audit resource type. Migration
`000613` (the next number after `000612` on `main`) adds the
`chat_organization_system_prompts` table.

## Testing

- Go: enterprise authorization (including an update-only custom role),
validation, and audit tests; chatd row order and subagent tests.
- Frontend: Vitest interaction tests and stories for the card (loading,
load error, refetch error over the cached value, save error, read-only).
- Remote dogfood UAT, [evidence
chat](https://dogfood.cdr.dev/agents/b595a709-0709-44e6-9535-96a922974d61):
round 1 **PASS** on `b027cb5ca67` (permission matrix, validation, UI,
row order, cross-organization isolation, audit, subagents, regression).
Round 2 **PASS** on `618bff67c75` (loading and load-error states,
refetch error over the cached value with unsaved edits kept, update-only
custom role saves over the API, row order, the documented size limit,
rapid organization switching, double-click save).
- CI: rebased onto `main` (`98332c739b0`) as `3850fbaa922`; other commit
SHAs in this description are from before the rebase. Every check passed
on `3850fbaa922`, with `test-go-pg` green on the first attempt. After
the review fixes in item 7, `main` was merged in as `006c4951749` to
resolve new conflicts in generated files and renumber the migration to
`000613`. Every check passes on `006c4951749`. Before the rebase, every
check passed on `b4e76543df2`. `test-go-pg (ubuntu-latest)` passed on
its fourth attempt; the first three failed only the `cli` package
goroutine leak check, with every test passing. Two of those leaked a
coderd instance, which also happens intermittently on `main`:
`TestServer/Logging` cancels `coder server` during startup, and an early
return in `cli/server.go` skips closing coderd. That fix is in #30280.
The first attempt leaked an idle HTTP connection instead (not
investigated).

## Screenshots

From remote UAT on a test deployment (test data only).

| Organization admin saves instructions (`b027cb5ca67`) | Auditor sees
read-only instructions, no save actions (`b027cb5ca67`) |
|---|---|
| ![Organization admin saves organization instructions and sees a
success
toast](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r1-admin-saved.png)
| ![Organization auditor sees the instructions
read-only](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r1-auditor-readonly.png)
|
| **Loading state while the first fetch is pending (`618bff67c75`)** |
**Refetch error shown above the field; the unsaved edit is kept and Save
stays enabled (`618bff67c75`)** |
| ![Loading spinner with no textarea or
buttons](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r2-loading.png)
| ![Error alert above the instructions field with the unsaved edit
preserved](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r2-refetch-error-edit-kept.png)
|

## Review record

1. Codex,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5387245297)
on `c42b5f9e05c`: 6 findings. Fixed the missing loading state, refetch
failures hiding cached instructions, and two docs style issues
(`58eab5603a4`, `cc73b714630`). Two were first declined in error, then
corrected: the read-only test now checks that typing leaves the value
unchanged (`cc73b714630`), and update-only custom roles no longer get a
500 on save (`618bff67c75`).
2. Independent security review by a clean-context agent,
[comment](https://github.com/coder/coder/pull/30272#issuecomment-5943505041)
on `c42b5f9e05c`: no P0 to P2 findings. A stale P3 comment was fixed in
`34c17aadb7f`; returning `err.Error()` in 500 details was kept to match
the deployment prompt handlers.
3. Codex,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5387323380)
on `58eab5603a4`: 2 findings (refetch errors not surfaced, docs line
breaks), both fixed in `cc73b714630`.
4. Codex, blockers only,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5387462070)
on `618bff67c75`: 1 P2 (a failed refresh right after a successful save
shows the previous value). Not a blocker, deferred.
5. Final fresh advisory by a clean-context agent,
[comment](https://github.com/coder/coder/pull/30272#issuecomment-5944285083)
on `618bff67c75`: **READY**, no blockers and nothing to cut. It
independently checked authorization, audit, the migration, chatd row
insertion and subagent inheritance, the tests, and soft-deleted
organization handling, and agreed with every deferral. No code changes
followed: the snapshot behavior it suggested documenting is already
documented, and its docs wording note joins the deferred docs item.
6. Codex,
[comment](https://github.com/coder/coder/pull/30272#issuecomment-5952100918)
on `b4e76543df2` (the docs-only follow-up below): no major issues. Mike
asked for a passing Codex review loop after item 5, so this review goes
past the planned stop at the final advisory. No code changes followed.
7. ethanndickson,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5409332502)
on `3850fbaa922`: approved with 4 comments. Fixed 3: the audit target is
now empty (`91e77d3fa8c`), the docs no longer re-explain audit logs
(`a0fb6891af5`), and the organization instructions stories went from 9
to 5 (`e836097f93f`). Not fixed: the organization prompt read fails open
on a database error, like the deployment prompt, and ethanndickson is
changing both after merge
([thread](https://github.com/coder/coder/pull/30272#discussion_r4180191267)).
UAT did not rerun for these changes.

Not counted as reviews: the pre-PR frontend self-review, simplify pass,
and test audit (`de8377e94e1`), and a second test audit of
`de8377e94e1..cc73b714630` (pass with nits; the update-only test case
was added after it).

Docs-only follow-up after the advisory, requested by Mike: `b4e76543df2`
adds audit log guidance for prompt changes to the platform controls page
and an update-only custom role note to the organizations page. Codex
reviewed it (item 6). No UAT covers it, and the code is unchanged since
`618bff67c75`. The deferred claim that the Instructions page path is
outdated was wrong, so it's dropped. Item 7 removed the audit log
guidance again; the custom role note stays.

## Soft-deleted organizations

UAT found that a soft-deleted organization's prompt stays readable and
writable by UUID. This is inherited behavior, not new exposure:
`ExtractOrganizationParam` resolves UUIDs without a deleted filter, so
the sibling organization chat routes (MCP servers, model overrides,
models) behave the same. The same `chat_model_config` RBAC still
applies, nobody gains access to another organization, and writes are
audited.

## Deferred (owner: Mike)

- A failed refresh right after a successful save shows the previous
value with an error alert, so a further edit from that view starts from
the old text (Codex round 4, UAT round 2). Trigger: reports of stale
values after saving on unreliable networks.
- Update-only custom roles can save over the API, but the card stays
hidden without read access. Trigger: a customer uses such a role.
- Soft-deleted organization access by UUID, above. Trigger: the platform
starts rejecting deleted organizations in `ExtractOrganizationParam` or
purging their configuration.
- A contrived "code word" instruction was refused as possible prompt
injection; neutral instructions work. Trigger: reports of ignored
organization instructions.
- UX polish: there is no retry action after a failed first load, the
save toast can cover Cancel, there is no unsaved-changes guard, the
oversize error omits the limit, and whitespace-only text clears the
prompt without notice. Trigger: the next settings UX pass.
- Docs: the 413 response and organization name paths are undocumented.
Trigger: the next Coder Agents docs pass.
- Test audit nits: a redundant `waitFor` and an optional read-only plus
refetch story. Trigger: the next change to these tests.

> Xum, an AI coding agent, implemented, tested, and opened this PR on
behalf of @ibetitsmike.
2026-10-06 10:48:07 +02:00
Danielle Maywood 49b1a2cf5d feat: expose per-ref diff statuses (#29082)
Part 2 of 6. Depends on #29081.

The API now exposes every ref a chat tracks. All API changes are
additive.

- `Chat.diff_statuses` lists every ref on the chat GET and in chat lists
(including child chats). The order is stable: refs are listed by first
report, so the list does not change order when a ref gets a new git
report.
- `Chat.diff_status` is the primary: the ref with the most recent git
report. It is the same rule as before. Use it to find the primary, not
the list position.
- `ChatDiffStatus` gains `remote_origin` and `git_branch`.
- `diff_status_change` watch events carry `changed_diff_status` (`{ref,
status}`) naming the ref that changed. If that ref's row is gone,
`status` contains only `chat_id`.
- `GET /chats/{chat}/diff` accepts optional `origin` and `branch` query
parameters. Set both or omit both (otherwise 400). A selector that
matches no stored ref returns 404. Without a selector the endpoint
returns the primary, as before. The Go SDK adds `WithChatDiffStatusRef`
for this.
- A git report without a chat ID (for example, from a terminal or an
agent older than v2.32) now refreshes only the chats that already track
that ref. It does not add the ref to other chats. Such a report can no
longer give a chat its first ref.

Generated by Coder Agents.
2026-10-06 09:32:46 +01:00
Nick Vigilante 28cf704f27 chore: update references to the relocated install docs paths (#30380)
The Install docs moved into the five-phase spine in #29304, but several
references outside `docs/` still point at the pre-move URLs.
`docs/redirects.json` is empty, so those URLs 404 rather than
forwarding.
The release note generators are the user-visible ones: every generated
release note links `coder.com/docs/install/releases` and
`coder.com/docs/install/upgrade`.

| Reference | Was | Now |
|---|---|---|
| Release schedule links in release notes | `/docs/install/releases` |
`/docs/reference/releases` |
| Upgrade link in release notes | `/docs/install/upgrade` |
`/docs/install/operate/upgrade` |
| README sizing link |
`/docs/admin/infrastructure/validated-architectures` |
`/docs/install/plan/sizing` |
| Provisioner tag table comments | `docs/admin/provisioners/index.md` |
`docs/install/operate/provisioners/index.md` |
| FAQ provenance comment | `docs/admin/licensing/index.md` |
`docs/install/prepare/licensing.md` |
| ESR 2.24-2.29 upgrade table | `/docs/admin/provisioners` |
`/docs/install/operate/provisioners` |
| Helm provisioner README, `NOTES.txt`, and `values.yaml` |
`/docs/admin/provisioners` | `/docs/install/operate/provisioners` |
| Helm Coder chart README | `/docs/install/kubernetes` |
`/docs/install/server/kubernetes` |
| `workspace-tags` example README |
`/docs/admin/provisioners#external-provisioners` |
`/docs/install/operate/provisioners#types-of-provisioners` |
| `kubernetes-envbox` example README |
`/docs/admin/infrastructure/architecture#agents` |
`/docs/install/plan/architecture#agents` |

`scripts/releaser/docs.go` was already updated in #29304; this covers
what that pass missed.

Two notes on anchors:

- The `#external-provisioners` anchor was already dead before #29304, so
it now points at `#types-of-provisioners`, the section covering
external, organization-scoped, and user-scoped provisioners.
- Every other anchor was verified to still exist on its new page.

One link left alone: `provisionerd/provisionerd.go` references
`docs/admin/provisioners.md` through a pinned-commit GitHub permalink,
which still resolves and shouldn't be rewritten.

## Verification

- `go test ./scripts/release/...` passes, including the release note
golden strings.
- `go build ./scripts/releaser/` succeeds.
- `make pre-commit` passes.
- Markdown table padding reflowed with `markdown-table-formatter`;
`markdownlint` reports no new findings.

<sub>Opened by Coder Agents on behalf of @nickvigilante.</sub>
2026-10-05 22:28:54 +00:00
Garrett DelfosseandClaude Opus 5.5 a08ba6a70c feat: add shared project memory API for chats in a project (#29301)
- Experiment, stacked on #29242. UI is in #29583.
- Adds **project memory**: `chat_project_memories` rows with a name
(lowercase slug, unique per project), a one-line description (150
characters) and a body (8KB). Up to 200 per project, shared by every
root chat in the project. Chats outside a project and subagents have no
memory.
- Memories are immutable: they are created and deleted, never edited.
Agent tools are `read_memory`, `save_memory`, `delete_memory` and
`consolidate_memory`. Saving an existing name fails and points the agent
at `consolidate_memory` to replace it.
- **Consolidation is agent-driven, in the turn**, modeled on how Claude
Code compacts its memory index when warned it is near its limit. From
160 memories (80%), save results ask the agent to get under 140 (70%)
with `consolidate_memory`, choosing what to merge and drop. That tool
deletes and saves memories in one transaction under the per-project
advisory lock, and rolls back entirely if a delete is missing, a name is
taken, or the result exceeds 200. There is no background extraction or
consolidation.
- **The memory index reaches the model as model-only conversation
messages**, not in a tool description or the system prompt. At turn
start the chat gets a full `<project-memory-index>` snapshot when its
prompt has none (first turn, or after compaction), otherwise a
`<project-memory-index-update>` listing only what changed. Tool
definitions and the system prompt carry no memory state, so memory
writes never invalidate the provider's cached prompt prefix. Writes by
other chats, or by this chat mid-turn, reach the model at its next turn.
- REST API (create, list, get, delete) under
`/api/experimental/organizations/{organization}/chats/projects/{project}/memories`.
Memory permissions follow projects onto the `agents-access` role.
- **Every memory change is audited** as `ChatProjectMemory` create or
delete. REST changes are attributed to the caller. Tool changes
(`save_memory`, `delete_memory`, `consolidate_memory`) are attributed to
the chat owner, carry the `chat_id`, and record one entry per memory
after the change commits, so a rolled-back consolidation records
nothing.

### Examples

**What the model sees.** The system prompt gets a fixed guidance block
with no memory state:

```text
<memory>
Memory is durable context shared by every chat in the project "platform".
Save facts that will matter in future chats: … The memory index is in the conversation: a <project-memory-index> message lists every saved memory, and <project-memory-index-update> messages at the start of later turns list what changed. Changes made during a turn, including your own, appear in the next turn's update. … Memories cannot be edited: replace one that no longer holds with consolidate_memory, or delete it.
</memory>
```

On the first turn, after the user's message, the chat gets a model-only
row with the full index (hidden in the UI):

```text
<project-memory-index>
- deploy-day: Deploys happen on Tuesdays
- release-owner: Alice owns releases; ping her before tagging
</project-memory-index>
```

On a later turn where memories changed, it gets only the difference:

```text
<project-memory-index-update>
Added or changed:
- deploy-day: Deploys happen on Wednesdays (changed 2026-09-30)
- staging-url: Staging lives at staging.example.com
Removed:
- old-ci-notes
</project-memory-index-update>
```

Resulting request layout, with the provider's cached prefix unchanged by
memory writes:

```text
[tools: fixed]  [system: fixed <memory> guidance]  [turn 1 user] [index snapshot] [assistant/tools …]  [turn 2 user] [index update] [assistant …]
```

**Tool calls and results** (produced by the tools in this PR):

```text
save_memory {"name":"staging-url","description":"Staging lives at staging.example.com","body":"Staging is https://staging.example.com; deploys from main."}
→ {"count":3,"saved":"staging-url"}

save_memory {"name":"deploy-day", …}   // name already exists
→ error: a memory named "deploy-day" already exists; read it, then replace it with consolidate_memory by deleting "deploy-day" and saving the new version in one call

consolidate_memory {"delete":["deploy-day"],"save":[{"name":"deploy-day","description":"Deploys happen on Wednesdays (changed 2026-09-30)","body":"The team deploys every Wednesday since 2026-09-30."}]}
→ {"count":3,"deleted":["deploy-day"],"saved":["deploy-day"]}

read_memory {"name":"deploy-day"}
→ {"name":"deploy-day","description":"…","body":"…","created_at":"2026-09-30T15:04:05Z","created_by":"alice"}
```

Near and at the cap:

```text
save_memory … → {"count":160,"saved":"one-more","warning":"memory is 160/200, approaching the limit. Consolidate it to under 140 memories now with consolidate_memory: merge overlapping memories into one, and drop stale, wrong, or superseded ones."}

save_memory … → error: memory is full (200/200); use consolidate_memory to merge overlapping memories and drop stale ones, and include this memory in its save list
```

**REST memory object** (`GET .../chats/projects/{project}/memories`):

```json
{
  "id": "59500000-0000-4000-8000-000000000001",
  "project_id": "7c0e4a3e-5b1f-4f7d-9a51-2f3c8f6d2b10",
  "organization_id": "bb640d07-ca8a-4869-b6bc-ae61ebb2fda1",
  "name": "deploy-day",
  "description": "Deploys happen on Wednesdays (changed 2026-09-30)",
  "body": "The team deploys every Wednesday since 2026-09-30.",
  "created_by": "0ed9befc-4911-4ccf-a8e2-559bf72daa94",
  "created_by_username": "alice",
  "created_at": "2026-09-30T15:04:05Z"
}
```

Create takes `{"name", "description", "body"}` and answers 409 on a
duplicate name or at the cap.

<details>
<summary>Screenshots (predate the immutable-memory rework; tool output
shape has since changed)</summary>


![save_memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-01-chat-saves-memory-raw.png)

![read_memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-02-chat-reads-memory-raw.png)
![Agent reads every
memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-agent-lists-memories-raw.png)

</details>

---
Generated with Coder Agents on behalf of @f0ssel.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 12:52:10 -04:00
Jake Howell 3f444d9528 fix: accept 128-character template descriptions on creation (#30348)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Template creation rejected descriptions of exactly 128 characters even
though the forms allow them and the database supports them. Change both
the standard and template-builder creation request validators to accept
up to 128 Unicode code points, and regenerate the API schema and
reference.

<details>
<summary>Investigation and scope</summary>

The validator counts Unicode code points, not bytes; the SDK comment is
corrected accordingly. The existing forms remain unchanged: their UTF-16
length checks are conservative for supplementary characters such as
emoji. This fixes the creation off-by-one without broadening frontend
character-count behavior.

</details>
2026-10-06 02:34:46 +11:00
Nick Vigilante 3f408825b5 docs: add playback controls and descriptions to autoplaying videos (#30263)
## Summary

Four docs pages embed autoplaying, looping screencasts with no controls,
so readers cannot pause them (WCAG 2.2.2, Level A). This adds `controls`
and `muted` to each `<video>` and a one-sentence text description after
each video. The renderer-side companion for the beta docs is
coder/docs-engine#203.

## Changes

- Add `controls` and `muted` to the `<video autoplay playsinline loop>`
tag in `external-auth.md`, `open-in-coder.md`,
`ai-coder/agents/index.md`, and `compute-engine.md`. `autoplay`,
`playsinline`, and `loop` stay.
- Add a one-sentence description of each screencast directly below it.
- `extending-templates/external-auth.md` is not in `docs/manifest.json`,
so it is unpublished. It is fixed for consistency.

## Testing

- `pnpm lint-docs` (markdownlint-cli2): 0 errors across 519 files.
- `make lint/emdash`, `go run ./scripts/docshtmlcheck`, `go run
./scripts/styleclaims`: pass.
- The repo pre-commit hook passed.
- Not run: rendering the pages in a browser. The descriptions are
inferred from the surrounding prose and file names, not from watching
the videos.

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

_Generated by Coder Agents on behalf of @nickvigilante._
2026-10-05 09:35:36 -04:00
Michael Suchacz bb9f31d94b fix: apply Anthropic prompt caching through OpenRouter and OpenAI-compatible gateways (#29563)
Anthropic models configured through an `openrouter` provider (and, by
the same code path, `vercel` and generic `openai-compat` providers)
never got prompt caching. Two independent gaps: chatd only emitted
`cache_control` breakpoints when the fantasy client was `anthropic`, and
even when a client sent them, the AI Gateway chat-completions
interceptor rebuilt the upstream body from typed
`openai.ChatCompletionNewParams` and silently dropped the unknown key.
Dogfood UAT on main @ 77479408b4 measured 0 cached tokens on 27/27 turns
for `anthropic/claude-haiku-4.5` via OpenRouter while the direct
Anthropic provider cached 7k to 11k tokens per turn.

## Fix

**AI Gateway** (`aibridge/intercept/chatcompletions`):
`ChatCompletionNewParamsWrapper` records every message-level and
content-part-level `cache_control` from the raw request and re-applies
it at the same JSON path when the upstream body is rebuilt, before the
Google-specific patching. The blocking path now sends the raw body
whenever preserved fields exist; the streaming path already sent the
rebuilt body. Nothing is added unless the client sent it, and at most
four markers are recorded per request (Anthropic's breakpoint limit) so
the per-marker body rewrites stay bounded.

**chatd** (`coderd/x/chatd`): the caching gate becomes a small strategy
resolver keyed on the fantasy client and the model ID. `anthropic` keeps
the existing message-level breakpoints; `openrouter` and `vercel` reuse
them for Anthropic-family IDs since both clients translate them;
`openai-compat` gets content-part-level `ContentExtraFields` markers
(last text part of the last system message plus the final two
text-bearing user or assistant messages, tool messages skipped, at most
3 markers). `chatprovider.IsAnthropicFamilyModelID` recognizes
`anthropic/...`, Bedrock-style `anthropic.`/`.anthropic.` IDs, and bare
`claude` IDs. The `claude` substring match is deliberately broad; a
non-Anthropic model whose ID contains it would receive markers that
OpenAI-compatible upstreams ignore.

Docs: a short "Prompt caching" note in `docs/ai-coder/agents/models.md`.
`coderd/x/chatd/ARCHITECTURE.md` has no caching text to update.

## Dogfood UAT

Remote Coder Agents UAT on dogfood (chat:
https://dogfood.cdr.dev/agents/9f81cc40-add0-4b6f-b76c-f348b04762e4),
OpenRouter provider with real keys:

- Baseline (main @ `77479408b4`): 0 cached tokens on every OpenRouter
Haiku turn; direct Anthropic control cached normally; a hand-added
`cache_control` on the same key cached fine.
- Fix (`1d685f7e3e`, the first three commits):
`anthropic/claude-haiku-4.5` via OpenRouter now sends 2 markers on turn
1 and 3 afterwards (system last part plus the last two text-bearing
messages, never on tool messages). OpenRouter's `/generation` ground
truth reported `native_tokens_cached` 7137 to 7255 on turns 2+, equal to
Coder's `cache_read_tokens` and the AI Gateway's
`cache_read_input_tokens` on all 43 measured rows. Turn-2 prompt cost
dropped about 8x versus baseline. Agentic S3 cache reads grew from 7156
to 13993 as a 2500-line file entered the prompt. `openai/gpt-5-mini`,
`google/gemini-2.5-flash`, `deepseek/deepseek-chat-v3.1`, and
`moonshotai/kimi-k2.5` received 0 markers with unchanged request shapes;
the direct Anthropic control was unchanged. 76 upstream attempts, 0
non-200. The remote agent reported FAIL only because one acceptance
criterion I wrote asked the chat usage indicator to display cached
tokens, which the UI has never done for any provider; the runner
endorsed PASS for the fix itsel... [truncated]
- Smoke re-tests on `20ad259999b` (marker-code simplification) and on
`e31f1806748` (docs reflow plus the four-marker cap; the later head
`92b8f8ad0b8` only renames `google_openai_compat.go` to
`request_body.go` with no content change): S1 cache reads 0 / 7139 /
7161 / 7184 / 7207 equal to OpenRouter ground truth on every row,
markers 2 then 3 and never on tool messages, tool-heavy turn all 200, a
12 KB file read grew cache reads to 13548 with every request body
inspected for marker placement, `openai/gpt-5-mini` still 0 markers.

Known follow-ups surfaced by the UAT and out of scope here:
`provider_options.openrouter.*` never reach the wire on the gateway
path; OpenRouter cache writes are folded into `input_tokens` in chat
message usage (`cache_creation_tokens` stays 0) although the gateway
records them; the AI Gateway sessions UI has no cache columns and labels
every OpenAI-compatible provider "OpenAI"; attachment-only messages (no
text) fail upstream with HTTP 400 on OpenRouter (pre-existing,
reproduced without markers).

> Xum acted on behalf of @ibetitsmike for this pull request.
2026-10-04 22:55:37 +02:00
Kyle Carberry 98332c739b feat: align MCP workspace tools with Coder Agents and add execute tools (#30275)
The control-plane MCP server's workspace tools now share their
arguments, behavior, and result formats with the Coder Agents tools. The
MCP server also exposes the Coder Agents execute and process tools.

The shared logic lives in a new `codersdk/toolsdk/workspacetools`
package that both `coderd/x/chatd/chattool` and `codersdk/toolsdk` call.
The Coder Agents tool schemas, descriptions, and JSON responses are
unchanged and the existing chattool tests pass unmodified. The one
exception is the missing-shell guidance, which now reads "Workspace
commands run with `sh -c`" instead of naming Coder Agents. Golden files
in `coderd/mcp/testdata/workspace_tools` hold the shared contract for
each tool, and a test checks both the Coder Agents and MCP tools against
them, so contract changes show up in review. The test also fails if MCP
text names a tool that only exists in Coder Agents.

The MCP versions differ from Coder Agents in four ways:
- Each tool takes a `workspace` argument.
- Invalid arguments and agent API errors come back as MCP tool errors.
- A single call waits at most 5 minutes, matching the agent's maximum
blocking wait. Longer timeouts are rejected with a pointer to
`run_in_background`.
- There is no `model_intent` argument.

**Breaking changes to `/api/experimental/mcp/http` and `coder exp
mcp`:**

| Before | After |
|---|---|
| `coder_workspace_read_file`: byte offset/limit, base64 `content` +
`mimeType`, binary-safe | Line-based `offset`/`limit`, text only,
returns `{content, file_size, lines_read, total_lines}` |
| `coder_workspace_write_file`: base64 `content`, binary-safe |
Plain-text `content`, returns `{ok: true}` |
| `coder_workspace_edit_file` + `coder_workspace_edit_files` |
`coder_workspace_edit_files` only, returns `{files: [{path, diff}], ok}`
|
| `coder_workspace_bash` over SSH: `timeout_ms` (default 60s, 5m cap),
kills the command on timeout (exit 124), trims output |
`coder_workspace_execute`: `timeout` (default 10s, 5m cap), `workdir`,
`run_in_background`. On timeout the command keeps running and the result
has `background_process_id`. Output is untrimmed and capped at 32KB. |
| None | `coder_workspace_process_output`,
`coder_workspace_process_list`, `coder_workspace_process_signal` |

`--allowed-tools` lists and templates that name the removed tools will
need updating. A code search found `coder_workspace_bash` in a couple of
demo templates (`coder/demo-env-templates`, partner demos).

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

- **Shared core vs. duplication.** The execute lifecycle has the most
logic that could drift: waiting in the foreground, handing off to the
background on timeout, recovering a snapshot after transport errors, and
truncating output. It's extracted rather than copied, along with
edit-file validation, read-file handling, and result types. Each surface
keeps its own protocol handling: fantasy and MCP response envelopes,
plan-turn restrictions, `model_intent`, and workspace resolution and
authorization. Struct-tag descriptions must be literals, so the
golden-file test is what keeps them in sync with the shared constants.
Shared result structs keep their fields in alphabetical order so the
JSON matches what Coder Agents produced from maps before.
- **Replace instead of add alongside.** Keeping `coder_workspace_bash`
next to `coder_workspace_execute` would give models two overlapping ways
to run commands. The read and write contracts change anyway, so keeping
the old names wouldn't preserve compatibility. The endpoint and CLI
command are both experimental.
- **5-minute cap on MCP calls.** Each stateless MCP request has to
return before the client gives up. Otherwise the `background_process_id`
needed to follow up is lost and the command keeps running with no ID the
model knows about. Coder Agents has no cap, so its behavior is
unchanged.
- **No SSH fallback.** `execute` doesn't fall back to SSH on older
agents, because SSH can't support the process management contract. The
agent process API and line-based reads shipped in February 2026.
- **Process scoping.** The agent scopes processes by chat ID, which
coderd sets only for Coder Agents connections. MCP calls carry no chat
ID, so they can't see or signal Coder Agents chat processes. All MCP
callers share one process namespace per workspace, which means anyone
with SSH access can list and signal processes another MCP user started.
That matches what SSH access already allows. The existing `ActionSSH`
check in `coderd/mcp_http.go` still runs before every agent connection.
Nothing reaps MCP processes; they run until they exit, are signaled, or
the agent stops.
- **Errors.** As in Coder Agents, command failures and timeouts come
back as result JSON (`success: false`, `background_process_id`). Agent
API errors have transport metadata removed, the same way Coder Agents
formats them.

</details>

---

🤖 Generated by Coder Agents on behalf of @kylecarbs.
2026-10-04 11:36:48 -05:00
Nick Vigilante fcbf45c571 docs: render audit log resources as one table per resource (#29797)
## Summary

The audit logs page now lists each tracked resource in its own section
with a simple two-column table, replacing the nested HTML tables that
rendered poorly and overflowed on phones.

## Before and after

Before, the generated block was a single Markdown table with a malformed
`|<b>Resource</b>||` header.
Each row held the resource name and its actions in one cell, then split
a raw HTML `<table>` of fields across the remaining cells.
The result rendered unevenly across renderers, was far wider than the
page on mobile, and was hard to navigate with a screen reader.

After, each resource gets an `###` heading under **Tracked Events**,
which also gives it a linkable anchor.
Below the heading, an `Actions:` line lists the audited actions as
inline code, followed by a two-column Field and Tracked table with `Yes`
or `No` values.
Every table uses the same fixed column widths (Field 75%, Tracked 25%),
so the Tracked column lines up across all resources.
Two narrow columns fit at phone width without horizontal scrolling.
Resources with no mapped actions skip the `Actions:` line instead of
rendering an empty one.
Resource ordering is unchanged.

## Changes

- `scripts/auditdocgen/main.go` writes one section per resource.
Each fields table is a small HTML table with `width` attributes, because
Markdown tables size columns to their content and cannot align across
tables.
GitHub and the docs site sanitizer both keep `width` but strip inline
`style` and `<colgroup>`.
- The generator no longer panics when its start marker is the last thing
in the file.
- New `scripts/auditdocgen/main_test.go` covers section output, marker
handling, and idempotent regeneration.
- `docs/admin/security/audit-logs.md` is regenerated, and the intro
sentence above the block now explains the actions line and the Tracked
column.

## How it was regenerated

`make docs/admin/security/audit-logs.md`, which builds the generator and
runs `markdownlint-cli2 --fix` and `markdown-table-formatter` over the
output.
Running it a second time produces no diff.

## Testing

- `go test ./scripts/auditdocgen/...` passes.
- `pnpm exec markdownlint-cli2 docs/admin/security/audit-logs.md`
reports 0 errors.

Linear: https://linear.app/codercom/issue/DOCS-894

---
🤖 Built with AI assistance.
2026-10-02 15:05:10 -04:00
Nick VigilanteandIan Evans c30b44ad14 docs: turn the Quickstart's next steps into goal-based paths (#29800)
## Summary

The Quickstart ends with one "customize your template" sentence and a
flat "Learn more" list, so a reader who has just launched a workspace
has no clear goal for what to do next.
This rewrites "What's next?" into three goal-based paths, puts Coder
Agents first, and gives readers without a project a small first task.

## Changes

- **Hand a task to a coding agent**: what Coder Agents is, that
Community deployments can run up to five agents at no cost, the
LLM-provider-key prerequisite, and a link to the Coder Agents
getting-started guide.
Includes a concrete starter prompt idea for readers with no project in
mind.
- **Make the workspace fit how you work**: the existing Customize your
template series, plus dotfiles.
- **Bring in your team**: install on a separate machine, create users,
and have teammates launch workspaces from the same template.
- **Learn more** keeps monitoring and adds the Coder Registry; the
workspace-management link moves into the team path.

## Testing

- `pnpm exec markdownlint-cli2 docs/get-started/index.md`: 0 errors.
- Checked that every relative link target exists on `main`, including
the `#create-a-user` anchor.

## Notes

- #29304 touches this page (terminology only, in other hunks); the only
shared line, `A control plane running locally.`, is already on `main`,
so the two should not conflict.
- Not a Fumadocs upstream candidate (content only).

Linear: https://linear.app/codercom/issue/DOCS-342

---
🤖 Built with AI assistance.

<details>
<summary>CI flakes unrelated to this change (rerun)</summary>

- `Storybook`: the Pixel upload returned HTTP 500 for many snapshots and
the browser context closed mid-run. This PR changes only
`docs/get-started/index.md`, so no stories are affected. Failed job
rerun.
- `Analyze PR for Documentation Updates Needed`: the AI docs check
failed before analysis because the bot's Coder account was suspended
(`401 User is not active`). Later runs on other PRs pass. Failed job
rerun.

_Generated by Coder Agents on behalf of @nickvigilante._

</details>

---------

Co-authored-by: Ian Evans <5760366+ianjevans@users.noreply.github.com>
2026-10-02 18:32:25 +00:00
Thomas Kosiewski 7f3d35353e docs: add chat automations documentation (#30220)
Closes CODAGT-1216
Part of CODAGT-1135

Adds an early-access page for chat automations in Coder Agents:
`docs/ai-coder/agents/automations.md`. It covers enabling the
`chat-automations` experiment and the `off` experiment rule as the
operator kill switch, webhooks (endpoint, bearer secret, 256 KiB JSON
body, responses, single and multi use, rotation), schedules (cron and
time zone, server previews, no catch-up, Run now), **When busy**, the
`manage_automations` tool and heartbeats, the per-owner cap and the
queue share, and the accepted risks (spend, silent failures, prompt
injection).

It also adds the manifest entry (early access, after Chat Sharing), a
glossary entry, a `manage_automations` row in the built-in tools table,
and a link from the experiment-gated features list in Platform Controls.

The page documents the code as built on this stack, not the RFC, where
they differ. Notable differences: reasoning effort is only offered for
new chat targets; schedules accept an occurrence up to 60 seconds late
and never replay older ones; the dashboard has no delete control, so
delete is documented through the API; `manage_automations` never returns
webhook secrets.

Dogfood UAT followed the page step by step on a `develop.sh` instance
built from this branch (experiment rule on and off, webhook creation and
curl deliveries with the documented status codes we could trigger,
schedule previews and Run now, the Manage automations switch), and
passed.

<details>
<summary>Where the page's claims come from</summary>

| Claim | Source |
|---|---|
| Experiment name, user-scoped | `codersdk/deployment.go`
(`ExperimentChatAutomations`, `ExperimentsUserScoped`) |
| Behavior when the experiment is off | `coderd/exp_chat_automations.go`
(`requireChatAutomations`, events handler),
`coderd/x/chatd/automation_schedules.go` (scan skips owners, keeps
cursors) |
| Management routes and fields | `coderd/coderd.go`,
`codersdk/chatautomations.go`, `coderd/x/chatd/automations.go`
(validation) |
| Owner-only update, enable, rotate, run |
`coderd/x/chatd/automations.go` (`ErrAutomationOwnerOnly`) |
| Webhook endpoint, 256 KiB limit, responses |
`coderd/exp_chat_automations.go` (events handler,
`writeChatAutomationError`), `coderd/exp_chats.go`
(`maxChatRequestBodyBytes`) |
| Event data wrapping | `coderd/x/chatd/automations_publish.go`
(`automationEventText`) |
| Rotating a used single-use webhook returns 409 |
`coderd/x/chatd/automations.go` (`RotateAutomationSecret`),
`AutomationWebhookFields.tsx` (button hidden) |
| Events rate limit | `coderd/httpmw/ratelimit.go`
(`RateLimitByEndpointKey`), `--api-rate-limit` default 512 |
| Cron, time zone, previews | `coderd/schedule/cron/cron.go`,
`coderd/exp_chat_automations.go` (`chatAutomationNextRunCount = 5`,
schedule preview) |
| 30 s scan, 60 s grace, no catch-up |
`coderd/x/chatd/automation_schedules.go` (`automationScheduleInterval`,
`automationScheduleGrace`) |
| When busy, queue share | `coderd/x/chatd/automations_publish.go` (busy
check, `max(1, MaxQueuedMessagesPerChat/2)`), `codersdk/chats.go`
(default 20) |
| manage_automations gating and containment |
`coderd/x/chatd/automations_tool.go`, `coderd/exp_chats.go`
(`manage_automations_enabled` checks), `AgentChatInput.tsx` |
| Per-owner cap | `codersdk/deployment.go`
(`--chat-max-automations-per-owner`), `codersdk/chats.go` (default 50) |
| Skipped and missed log messages |
`coderd/x/chatd/automation_schedules.go` |
| Audit fields | `enterprise/audit/table.go` (`prompt` and
`webhook_secret_hash` are secret) |

Identifiers kept off the page because the reader never types or receives
them: `queue_generation`, `schedule_revision`, `schedule_next_run_at`,
and the internal error names above.
</details>

---
_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:56 +00:00
Thomas Kosiewski fb0951b850 feat: add the manage_automations chat tool switch and read actions (#30214)
Adds the `manage_automations` chat tool with its read and stop actions
(`list`, `get`, `disable`, `delete`), gated by an interim per-chat
switch. Tool sets have not landed, so this ships
`chats.manage_automations_enabled` as the RFC describes for that case;
tool sets later replace it and migrate its values.

Part of CODAGT-1212 (slice 12a of 3). Part of CODAGT-1135.

## What changes

- **Switch.** Migration `000611` adds `chats.manage_automations_enabled`
(default off). It is set through `POST /api/v2/chats` and `PATCH
/api/v2/chats/{chat}`. After creation only the chat owner may send the
field (403 otherwise). Turning it on returns 400 when the
`chat-automations` experiment is off for the chat owner (POST checks the
resolved `owner_id`, not the caller) or when the chat is a sub-agent
chat. Turning it off is always accepted. The audit table tracks it.
- **Offering.** The tool is offered only in root chats, outside plan
mode and explore mode, with the switch on, and with the experiment on
for the chat owner (decided once per turn, like `mcp-tool-search`). It
is not on the plan-mode or explore allowlists, and sub-agent chats are
created with the switch off.
- **Per-call recheck.** Every call reloads the chat and checks all rules
again, with a fresh experiment evaluation, before doing anything.
- **Scoping.** Owner and organization come from the chat, never from
arguments. Reads run as the owner through a new query that filters on
organization and owner. Other members' automations are "not found", even
when the chat owner is an organization admin.
- **Automation-reached turns.** Detected at call time from the full
history (compaction replays user rows without `automation_id`, so the
prompt window is not enough). In such turns only automations that target
the chat or created it (`chats.automation_id`) are visible.
- **Visibility of prompts and deletes.** `list` leaves out prompts (tool
results stay in the chat, which may be shared); `get` returns the prompt
of the automation it names. In a turn an automation reached, `delete`
only removes the triggering automation; the others can still be
disabled.
- **Audit.** `disable` and `delete` go through the management service
and write a background audit entry with `chat_id`, plus the triggering
`automation_id` and `input_id` in reached turns. Results use the API
shape and never contain a secret or secret hash.

`create`, `update`, `enable`, and `run_now` come in the next PR and
return "not available in this version" here.

Follow-up: CODAGT-1270 (bound the history read that reached-turn
detection does on each call).

## Size

About 1,380 hand-written lines: about 460 production, 680 tests, and 240
SQL that has to be there (the `chats_expanded` view rebuilt in both
migrations and the 17 inline column lists). Generated: +649/-280 (sqlc,
dbmock, dbmetrics, dump.sql, apidoc, API and audit docs,
`typesGenerated.ts`).

## Validation

- Unit and DB tests for every rule above (switch 403/400 cases, offering
rules, per-call recheck, owner/org scoping with an org-admin owner,
reached-turn detection including compaction replay, audit fields, secret
scan), plus a separate test audit. Full `make pre-push` passed before
push.
- Remote dogfood UAT passed on this slice: switch API cases, tool absent
with the switch off, in plan mode, in sub-agents and with the experiment
off for the owner (checked in the server's per-step tool lists),
list/get/disable/delete, and a secret scan of all tool output. Audit
entries are verified in Go tests only.

> [!NOTE]
> ARCHITECTURE.md prose was drafted by an agent at the user's request;
the user will review it.

## Stack

Stacked on the Automations for Coder Agents stack (30085 ... 1214b).
Next: slice 12b (write actions), then 12c (composer toggle).

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-10-02 15:54:55 +00:00
Thomas Kosiewski a3fbd2384d feat: add the Agents automations list page and chat-list automation filter (#30171)
Closes CODAGT-1213. Part of CODAGT-1135 (Automations for Coder Agents,
RFC step 7).

Adds an Automations list to the Agents UI and an `automation_id` filter
on the chat list, so users can see their automations and find the chats
an automation created or wrote to.

## Changes

- **Chat-list filter:** `GET /api/v2/chats?automation_id=<uuid>` returns
root chats whose `chats.automation_id` matches (chats the automation
created) and chats with a non-deleted message whose
`chat_messages.automation_id` matches (chats it wrote to). The nil UUID
is rejected, because the query uses it as "no filter". It is honored
only when the `chat-automations` experiment is on for the caller;
otherwise it is ignored, as the RFC says, and the evaluator runs only
when the parameter is present. Chat authorization is unchanged. Swagger
documents the parameter, and `codersdk.ListChatsOptions` gains
`AutomationID`. The existing partial indexes back the filter.
- **List page:** `/agents/automations`, with an **Automations** sidebar
entry. Both are hidden when the experiment is off for the viewer
(per-user experiment list). The page lists the automations of the
organization selected in the Agents organization picker; it shares the
stored selection with the new-chat form and has its own picker. Columns:
name (with the creating chat for agent-created automations), trigger
(cron and time zone, or webhook single or multi use), target (chat link,
"New chat each run", or a **Missing target** badge for a deleted or
archived target), next run from the server's `next_run_times`, an
enabled switch (PATCH; a non-owner cannot re-enable), **Run now** (owner
only, schedules only, disabled for a missing target and while another
run is pending), and **View chats** (owner only; a paged dialog backed
by the new filter). Chat titles are looked up only for the viewer's own
automations. The list refetches every minute so the next run stays
current. On mobile, the chats header links to the page, which opens full
width with a back link. A Run now failure, such as `409` for a busy chat
with skip or `429` for a full queue or share, shows the server message
in an alert above the table.
- Out of scope, per the ticket: the **Last skipped run** column, and the
editor (CODAGT-1214). The empty state points to the API because the
`manage_automations` tool is not in this stack yet.

## Validation

- Go: `TestListChats/AutomationFilter` covers:
- created and written-to chats, deleted messages, and another user's
chat;
  - an unknown id, a malformed id (`400`), and the nil UUID (`400`);
- the experiment turned off by a per-user rule, where the parameter is
ignored, including a malformed id.
- Vitest (`AgentAutomationsPage.test.tsx`), all asserting requests:
- the selected organization's list is requested, and switching the
picker refetches and stores the choice;
  - the switch sends `PATCH {enabled:false}`;
  - Run now sends its POST when the server answers `409` or `429`;
- View chats requests `?automation_id=`, and Load more requests the next
page;
  - nothing is requested with the experiment off.
- Storybook (Pixel): `WithAutomations`, `OtherOwner`, `Empty`,
`MissingTarget`, `RunNowError`, `ChatsDialog`,
`ChatsDialogLoadMoreError`, `Loading`, `RefetchError`, `ListError`, and
`ChatsSidebar/MobileWithAutomations`.
- Remote dogfood UAT: PASS in round 1 (`fa60a15767`) and round 2 on the
current head `b37e9d99d0`. Round 2 repeated every criterion and verified
the review fixes. Screenshots are in the comments below.
- `coder-frontend-review` self-review: every role passes after fixes on
each update, except two items:
- the experiment-off test waits for the not-found page only as a sync
point before asserting that no request was sent;
- there is no story for a chat-title lookup error, because the Storybook
query helper cannot inject errors.
- Codex review: 4 rounds (8, 4, 4 and 6 P2 findings, no P0 or P1).
- Rounds 1 to 3 were fixed, except the model-availability item
(CODAGT-1244).
- Round 4 found no blocker and is tracked in CODAGT-1246, together with
the minor UAT round 2 findings.
- All threads are resolved. There is no clean Codex verdict on the
current head. Further rounds were not requested because findings were
not converging and none was a blocker; the stack orchestrator accepted
stopping at round 4.
- CI: `ci` run 36703512580, started with workflow_dispatch, is green on
the current head `b37e9d99d0`. Pushes to existing stacked PRs did not
start the pull_request `ci` run (noted in the comments). The earlier
head `8f2ee30d8f` was green through a normal pull_request run.

Size: about 1,370 hand-written lines (about 560 of them tests and
stories), plus generated code. This is over the 1,000-line guideline,
mostly from review fixes.

## Stack

Stacked on #30085, #30096, #30112, #30117, #30127, #30134, #30160,
#30166 and #30167 (CODAGT-1215). Base:
`tk/codagt-1215-automations-chat-labels`, merged in (not rebased).
Follow-ups: CODAGT-1244, CODAGT-1246.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-10-02 15:54:53 +00:00
Thomas Kosiewski b96f1b970c feat: label automation messages in agent chats (#30167)
Closes CODAGT-1215. Part of CODAGT-1135 (Automations for Coder Agents,
RFC step 9).

Chat messages and queued inputs delivered by a chat automation (webhook,
schedule, Run now) now show a label: `Automation run · <automation name>
· input <first 8 chars of input ID>`. A tooltip holds the full
automation and input IDs. While names load, the label omits the name
part. When the name cannot be resolved (deleted automation, a
shared-chat viewer who cannot read it, or experiment off), the label
shows the automation ID instead. Ordinary messages have no label.

## Changes

- **Backend (minimal, SDK exposure only):** `codersdk.ChatMessage` and
`codersdk.ChatQueuedMessage` gain `automation_id` and `input_id`
(omitted when unset). `db2sdk` fills them from the existing columns, so
REST messages and the stream `message` and `queue_update` events carry
them. No behavior change in the lower layers.
- **Frontend:** `API.experimental.getChatAutomations`, a
`chatAutomations` query, and `useChatAutomationNames`. The hook fetches
`GET /api/experimental/organizations/{org}/chat-automations` only when
the user-scoped `chat-automations` experiment is on and the chat holds
automation input. The `AutomationLabel` component uses the shared
`Badge` and `Tooltip`, and is wired into `ConversationTimeline`
(history) and `QueuedMessagesList` (queue). The chat store refetches
names when new automation input arrives, so automations created or
renamed after page load show their current name.
- Out of scope, per the ticket: the occurrence label and the
requested-versus-resolved effort display.

## Validation

- Vitest: the automations list is requested for the chat's organization
only when the chat holds automation input and the experiment is on;
`useChatAutomationNames` reports loading until the list resolves and
then maps IDs to names; the chat store refetches names on new live
automation input. Go: `TestChatMessageAutomationProvenance` for both
converters.
- Storybook (Pixel): `ConversationTimeline/AutomationUserMessages` and
`QueuedMessagesList/AutomationMessages` (named, deleted by ID, long name
at phone width, no label on ordinary items) and
`QueuedMessagesList/AutomationMessagesLoading` (name still loading: no
UUID flash).
- Remote dogfood UAT on a develop.sh instance with the experiment on:
PASS in round 2. It covered webhook input in an existing chat (history
and queue), a schedule, a new_chat first message, the ID fallback after
deletion, and no label on ordinary messages. Screenshots are in a
comment below. Run now was not on the base branch during UAT; it uses
the same fields and path.
- coder-frontend-review self-review: all roles PASS, after fixes on each
update.

## Known limitations (follow-ups under CODAGT-1135)

- A shared-chat viewer who does not own the automation sees its ID,
because automation RBAC has no chat ACL (CODAGT-1239).
- Copying the label text yields three lines, because the name span
truncates separately (CODAGT-1238).

## Stack

Stacked on #30085, #30096, #30112, #30117, #30127, #30134, #30160 (1211
7a) and #30166 (1211 7b). Base: `tk/codagt-1211b-automations-run-now`.

---
_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:53 +00:00
Thomas Kosiewski b25f8859f2 feat: add Run now for schedule chat automations (#30166)
Closes CODAGT-1211. Part of CODAGT-1135.

> Stack: PR 7b of "Automations for Coder Agents", on top of 7a (#30160,
the schedule scanner), which sits on 1210 5b (#30134).

Adds Run now for schedule automations: `POST
/api/experimental/organizations/{organization}/chat-automations/{automation}/runs`
publishes the saved prompt at once through the existing `Publish` path,
with no occurrence. It never writes the automation row, so the schedule
cursor and revision stay unchanged.

- **Owner-only.** `chatd.RunAutomation(ctx, actorID, id)` compares the
caller with the automation owner before anything else, so org admins and
site owners get 403 even though dbauthz lets them read and write the row
(CODAGT-1226). A user who cannot read the automation gets 404, and the
route sits behind the experiment gate, so a caller with
`chat-automations` off gets 404. `Publish` also checks the owner's
experiment again.
- **Statuses.** 202 with `input_id` and `chat_id`; 400 for a
non-schedule automation; 409 for a disabled schedule, a busy chat with
When busy `skip`, or an unavailable target or model; 429 when the chat
queue or the automations' share of it is full; hook denials use the same
response as chat messages.
- **new_chat.** A Run now of a new_chat schedule creates a chat titled
with the run time in the schedule's time zone and records the same audit
entry as webhook-created chats.

## Tests

`coderd/exp_chat_automation_runs_test.go` runs against a real coderdtest
server: the owner's run saves one message with the returned input id and
leaves the whole automation row byte-equal; org admin and site owner get
403 (also on a webhook automation, proving the owner check comes first)
and a non-reader gets 404, with nothing saved; webhook 400, disabled
409, busy `skip` 409, queue share 429; new_chat title, owner, and audit
entry. The experiment gate test covers the new route.

Dogfood UAT ran on a real dev instance through Coder Agents and passed:
immediate publish with the cursor and revision unchanged, 409/429
refusals, 403 for an org admin and the site owner, 404 with the
experiment off, and a one-minute schedule that kept one message per
minute around a Run now.

## Size

About 325 hand-written lines (about 190 of them tests). Generated:
`coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
`docs/reference/api/schemas.md`, `site/src/api/typesGenerated.ts` (213
lines).

ARCHITECTURE.md prose was drafted by an agent at the user's request; the
user will review it.

Also replaces the CODAGT-1209 ARCHITECTURE.md TODO from #30117; the
prose was drafted by an agent at the user's request, and the user will
review it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-10-02 15:54:52 +00:00
Thomas Kosiewski b517db4beb feat: deliver webhook events to existing chats through chat automations (#30127)
Part of CODAGT-1210 (1 of 2). Part of CODAGT-1135.

> Stack: PR 5 of "Automations for Coder Agents", on top of #30117. The
ticket is split in two by operation: this PR delivers webhook events to
`existing_chat` targets; the stacked follow-up delivers them to
`new_chat` targets and closes CODAGT-1210. Until then a `new_chat`
automation's events endpoint answers `501`.

## What this adds

- `POST /api/experimental/chat-automations/{automation}/events`.
External systems send the automation's webhook secret as `Authorization:
Bearer <secret>` and a JSON body of at most 256 KiB. The route has no
API key middleware and sits outside the `/api/experimental` group,
behind its own rate limiter keyed by caller and a fixed endpoint key (IP
address for unauthenticated callers), so varying the automation id does
not reset the budget.
- Secret check: SHA-256 of the bearer value, compared in constant time.
Unknown ids, other kinds, and wrong secrets all get the same `401`. The
`chat-automations` experiment is checked for the automation owner only
after the secret matches (`404` when off). The body is then read: over
the limit `413`, not JSON `400`.
- `chatd.PublishAutomationWebhook` sends as the owner (`dbauthz.As` with
the owner's subject) through `SendMessage` with the `queue` busy
behavior set explicitly, so automations never interrupt or steer.
`user_prompt_submit` hooks run first: a denial is `403`, an unreachable
hook service `502`.
- One admission check runs before the send (so refused events never
reach hooks) and again in the `AdmitInTx` callback, which locks the
automation together with the chat's queued automations in one
ascending-order call. Under the lock it rechecks: enabled, secret
version (a request verified before a rotation but committed after it
gets `401`), single-use state, target chat (root chat of the owner, same
org, not archived), owner status, and the owner's `chat:update`
permission. It then applies **When busy**: `skip` refuses a busy chat
(`409`), `queue` refuses input beyond the automations' share, half the
chat queue cap rounded down and at least 1 (`429`); busy and the share
count only queued rows that promotion would still deliver. It marks a
single-use webhook consumed and returns the provenance.
- The message has two parts: the saved prompt, and a labeled part with
the body as untrusted event data inside `<automation_event_data>` tags.
`json.HTMLEscape` escapes `<`, `>`, and `&` in the body, which keeps the
JSON value and makes the closing tag impossible to forge.
- `chatd.Config.Authorizer` (wired from `options.Authorizer`) for the
explicit owner checks; publishing fails closed without one.
- New query `ConsumeChatAutomationWebhookByID` with a dbauthz wrapper.

Status codes follow the RFC's failure outcomes table; the
chat-without-a-model case returns the same `400` as a person's message.

## Notes for reviewers

- Single-use consumption runs from the chatd publish code as the owner,
because the chatd role only reads `chat_automation`. No lower-layer RBAC
change.
- ARCHITECTURE.md prose was drafted by an agent at the user's request;
the user will review it.
- Size: about 1,460 hand-written lines after review fixes (about 770 of
them tests), over the ~1,000 budget because of the review hardening.
Generated: about 360 lines (`coderd/apidoc`, `dbmock`, `dbmetrics`,
`querier.go`, `queries.sql.go`, `docs/reference/api/schemas.md`,
`typesGenerated.ts`).
- Dogfood UAT ran through Coder Agents on a real dev deployment with
curl deliveries. Round 1 found error-mapping defects, fixed here; rounds
2 and 3 passed, the last on the final code (the head after it changes
only ARCHITECTURE.md).
- Deferred: CODAGT-1233 (stale automation rows filling the physical
queue cap; lower-layer `SendMessage` path).

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-10-02 15:54:51 +00:00
Thomas Kosiewski 5c1662ea4c feat: disable, re-enable, and rotate chat automations with schedule preview (#30117)
Completes the chat automations management API from RFC step 3: disable
and re-enable, delete that disables first, webhook secret rotation, and
a server-side schedule preview. Stacked on #30112.

- **Disable** (`PATCH` with `{"enabled": false}`) runs in two steps. A
short transaction that touches only the automation row sets `enabled =
false` and increments `queue_generation`, the cutoff. After it commits,
the automation's queued rows below the cutoff are deleted one chat at a
time through chatd's existing `DeleteQueued` transition, run as chatd,
so queue versions and stream updates match a manual delete. If a row is
missed, for example after a crash between the steps, the queue promotion
guard from #30096 discards it, because its generation is stale. Running
turns are not interrupted.
- **Delete** deletes the row and then removes all of the automation's
queued rows the same way. Deleting the row is itself the cutoff, because
the promotion guard discards rows whose automation no longer exists. So
delete needs only delete permission, not update. This differs from the
RFC's "disable, then delete" order, with the same outcome.
- **Re-enable** (`{"enabled": true}`) moves a schedule's cursor to the
next future cron time, so the disabled period is not replayed. The
generation never resets.
- **Permissions:** only the owner can enable, edit, or rotate.
Organization admins and site owners can send exactly `{"enabled":
false}` (anything combined with it is 403), and can still list, read,
and delete.
- **Rotation:** `POST .../chat-automations/{automation}/secret/rotate`
(owner only, webhooks only) returns the new secret once and increments
`webhook_secret_version`. Only the SHA-256 hash is stored, and the
rotation is audited with the hash redacted.
- **Preview:** `POST .../chat-automations/schedule-preview` evaluates an
unsaved cron expression and time zone with create's rules and returns
the next five run times, or 400.
- `coderd/x/chatd/ARCHITECTURE.md` gets a `TODO (CODAGT-1209)` note
about disable using the delete-queued transition. **Author action before
merge:** replace that TODO with the architecture prose (agents do not
write that document).

Known gap, tracked in CODAGT-1227: when the target chat is archived,
disable and delete cannot remove its queued automation rows, because
`DeleteQueuedMessage` is not allowed from archived states. The rows
never run, since the promotion guard discards them, but they stay
visible after the chat is unarchived. The fix needs a chatstate
transition from the lower layer.

Dogfood UAT ran on a real dev instance and passed. It covered disable
removing only that automation's queued rows (the chat API agreed),
delete, re-enable without replay, the permission matrix for an
organization admin and the site owner, rotation (the stored hash matches
the new secret, and neither secret appears in get or list), preview, and
a runtime experiment rule. It also checked that a leftover row is
discarded on promotion.

Closes CODAGT-1209
Part of CODAGT-1135
Refs CODAGT-1217

Stack: PR 3b of the Automations for Coder Agents stack, on top of #30112
(PR 3a), #30096, and #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:50 +00: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
Thomas Kosiewski f55aa6c50d feat: add chat automations schema, RBAC resource, and audit entries (#30085)
Adds the storage and authorization pieces for Automations for Coder
Agents. No route, SDK request type, or chatd code uses them yet, so
nothing is exposed.

This is the bottom PR of the Automations stack (RFC step 1). Later PRs
add the chatd acceptance seam, management routes, webhooks, and
schedules on top of these names and constraints.

**Schema** (migrations 000609, 000610)

- `chat_automations` table with enums `chat_automation_kind`,
`chat_automation_target_mode`, `chat_automation_webhook_use`, and
`chat_automation_when_busy`. It includes `created_by_chat_id`, the
webhook secret hash and version, the single-use `webhook_consumed_at`
marker, the schedule cursor and revision, and `queue_generation`. Named
CHECKs enforce the target and kind shapes from the RFC. A composite
foreign key keeps `new_chat_model_config_id` in the automation's
organization, the same pattern the model override tables use. A trigger
(`chat_automations_chat_organization`) keeps `target_chat_id` and
`created_by_chat_id` in that organization too. A composite foreign key
cannot do that while keeping `ON DELETE SET NULL` on PostgreSQL 13. The
trigger validates a reference only on insert or when it changes, so chat
deletion can still clear both references. Indexes cover the owner and
both chat references for cascades and `SET NULL`.
- Provenance columns with partial indexes and no foreign key to
`chat_automations`: `automation_id`, `input_id`, `queue_generation` on
`chat_queued_messages` (all set or all null), `automation_id` and
`input_id` on `chat_messages`, and `chats.automation_id`.
`chats_expanded` is recreated to include `automation_id`.
- `chat_automation` values for `api_key_scope` and `resource_type`. The
down migration is a no-op because enum values cannot be dropped.

**Authorization**

- New organization-scoped RBAC resource `chat_automation` (create, read,
update, delete). The `agents-access` role grants it for the member's own
automations. It is excluded from the member role's user-level
permissions, so a member without `agents-access` gets nothing. Site
owners and organization admins get it through their existing
all-permissions lists. The owner-only update, enable, and run rule from
the RFC belongs to the management service in a later PR.
- The generated scopes stay out of `externalLowLevel`, so API keys gain
no user-requestable scopes.
- `dbauthz` wrappers for the three queries this PR adds:
`InsertChatAutomation`, `GetChatAutomationByID`, and
`DeleteChatAutomationByID`. `InsertChatAutomation` also requires update
on the target chat, read on the creating chat, and read on the new-chat
model config (its user and group ACL). There is also a
`dbgen.ChatAutomation` helper.

**Audit**

- `enterprise/audit/table.go` entries for `ChatAutomation`, with
`webhook_secret_hash` and `prompt` marked `ActionSecret`. The prompt is
treated as chat content, like chat titles. The schedule cursor,
revision, and queue generation are ignored as internal bookkeeping.
`Chat.automation_id` is tracked.

**Required checks from the ticket**

- Migrations apply and roll back: `TestMigrate` and
`TestMigrateUpWithFixtures` (new fixture for 000609). Dogfood UAT also
applied the migrations on a dev instance, rolled them back, re-applied
them, and compared schema dumps. After rollback, the only differences
from main were the enum values that cannot be dropped and develop.sh's
own `_develop` schema. After re-applying, the only difference from this
branch's `dump.sql` was the `_develop` schema.
- Secret hash marked secret: `Test_chatAutomationSecretFieldsRedacted`
checks the table entries and that an audit diff contains neither the raw
hash, its base64 form, nor the prompt text.

Also covered: `TestRolePermissions` cases for own, other owner, other
organization, and a member without `agents-access`.
`TestChatAutomationShapeConstraints` covers the named CHECKs, the
cross-organization foreign key and trigger, a cross-organization
retarget, and deleting referenced chats. Under `site/`, only generated
files changed (`typesGenerated.ts`, `rbacresourcesGenerated.ts`).

Closes CODAGT-1207
Part of CODAGT-1135

---
_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:48 +00:00
Nick Vigilante 1ad46e48ac feat: report port-forward sessions as app usage (#30156)
`coder port-forward` reported usage with the deprecated
`UpdateWorkspaceUsageContext`.
It now reports a `port_forwarding` session, like `coder ssh` and the VS
Code SSH path, but only while a forwarded TCP connection is open.

**Behavior change:** CLI output is unchanged.
Port-forward sessions previously only bumped the workspace's last-used
time.
With the hidden `workspace-usage` experiment enabled, the server now
also records `port_forwarding` session counts under a new
`port_forwarding` family, which the deployment banner totals under
**Other**.
Without the experiment, `postWorkspaceUsage` returns 204 before reading
the body, so nothing changes.

<details>
<summary>Decisions</summary>

- Added `codersdk.UsageAppNamePortForwarding` (`port_forwarding`) rather
than reusing `ssh`, so port-forwarding isn't counted as interactive SSH.
The name matches the arbitrary app names RFC's connection-method name.
- Registered a `port_forwarding` family in `codersdk/appname.go`.
Families resolve at read time, so no data migration is needed. Template
insights list apps individually; telemetry, metricscache, and agentstats
gauges are legacy fixed fields and stay as they are. The Prometheus
insights family is left to #29906.
- Only TCP connections count. UDP forwards never see EOF, so one
datagram would keep the session active until exit.
- Reports once at startup, like the old call, then every minute and once
on shutdown. An idle tick sends an empty body, which still bumps
last-used.

</details>

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

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


<details>
<summary>CI note: unrelated test-go-race-pg flake</summary>

The `test-go-race-pg` job failed on a data race between
`tailnet.(*configMaps).updatePeerLocked` and slog formatting of the same
peer value, which does not touch port-forward code. The job was rerun.

</details>
2026-10-02 11:05:48 -04:00
Nick Vigilante 14bb1f27d3 docs: add redirects.json and rebuild the docs site when it changes (#30208) 2026-10-02 10:30:25 -04:00
Mathias Fredriksson ff158c0589 feat: preserve user-supplied chat titles (#29486)
Chats created through the API or MCP couldn't be given a title, and
automatic title generation could overwrite a title the user had set,
at creation or by renaming during generation. #30254 tried to keep
renames by comparing title text, but text can't tell a user title
from a generated one that has the same text.

Chat creation over the API and MCP now accepts a title. Each chat
records where its title came from: fallback (derived from the
prompt), generated, or user. A title can only be replaced by a title
from the same source or a higher one, so automatic generation never
overwrites a user's title. Title changes no longer reorder the chat
list, and clients apply them in the order they were written. Chats
created before this change are treated as having fallback titles.

Closes CODAGT-1047
Reverts #30254
2026-10-02 12:58:53 +00:00