Commit Graph
271 Commits
Author SHA1 Message Date
Atif Ali 062c0fdd3b docs: rebrand Windsurf doc page to Devin Desktop (#28205)
## Summary

Cognition (maker of Devin) rebranded the Windsurf Editor as Devin
Desktop on June 2, 2026, after acquiring it from Codeium in July 2025.
Our docs still referred to the editor as Windsurf and linked to a dead
`codeium.com` domain.

## Changes

- Renamed `docs/user-guides/workspace-access/windsurf.md` to
`devin-desktop.md`, rewritten to lead with Devin Desktop branding, note
the Codeium -> Windsurf -> Devin Desktop history, and use current links
(`windsurf.com`, `docs.windsurf.com`) instead of dead `codeium.com`
ones.
- Updated `docs/manifest.json` and
`docs/user-guides/workspace-access/index.md` to reference the new page.
- Updated remaining Windsurf mentions to Devin Desktop in
`docs/ai-coder/ide-agents.md`, `docs/ai-coder/index.md`,
`docs/reference/glossary.md`, and
`docs/ai-coder/ai-gateway/clients/index.md`.
- Added `windsurf.com`/`devin.ai` to `.github/.linkspector.yml` ignore
patterns; both rate-limit repeated automated requests with 429s (same
class of issue as the `codeium.com`/`marketplace.visualstudio.com` fix
in #28203).
- Switched every module reference from `windsurf` to the new
`devin-desktop` registry module (`docs/about/contributing/modules.md`,
the three `get-started/customize-your-template/*.md` Terraform
tutorials, and the main doc page's module link), since the new module
actually renders `display_name = "Devin Desktop"` / `slug =
"devin-desktop"` in the UI (the old `windsurf` module hardcodes
"Windsurf Editor").

<details>
<summary>Scope notes / sequencing</summary>

The `devin-desktop` module referenced here is being added in
[coder/registry#1050](https://github.com/coder/registry/pull/1050) (not
yet merged/released). That PR is itself gated on
[coder/coder#28214](https://github.com/coder/coder/pull/28214)
(whitelisting the `devin:` URI scheme) shipping in a released Coder
version first. This docs PR can merge independently, the module link
will 404 until #1050 is released, same as any
docs-ahead-of-registry-release sequencing.

The Terraform code samples now show `module "devin-desktop"` because
that module's `display_name`/`slug` are properly parameterized (unlike
`windsurf`, which hardcodes "Windsurf Editor"/`windsurf` regardless of
what's passed in), so the docs stay accurate to the rendered UI.

</details>

## Validation

- `make lint` (docs lint, markdownlint, repo checks) passes.
- Manually verified the new outbound links (`docs.windsurf.com`) return
200; `windsurf.com`/`devin.ai` are rate-limited (429) from this
environment too, hence the added ignore patterns.

Stacked on #28203 (targets that branch so the diff here stays scoped to
the rebrand; will retarget to `main` once #28203 merges).

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑💻
2026-08-18 15:17:02 +05:00
Susana Ferreira db3566c1a3 chore: correct AI Gateway metric provider label and cardinality notes (#28220)
The cardinality notes in `aibridge/metrics/metrics.go` assume the
`provider` label takes one of three values, and two for the key pool
metrics. That was accurate when the notes were written: `provider` is
the provider instance name, and the name defaulted to one of the three
provider types aibridge supports. Instances can now be given their own
names, so the label takes any configured name and the series counts
scale with the number of configured providers rather than being capped
at a fixed number.

The monitoring docs are also updated to make clear that `provider` is
the provider instance name.

Comments and documentation only, no behaviour change.

Follow-up to #28210.
2026-08-18 09:47:00 +00:00
Susana Ferreira 95328f1ead fix: label unpriced token usage metric by provider name and type (#28210)
## Problem

The `provider` label was inconsistent between AI Gateway metrics. Every
metric emitted by the gateway labels `provider` with the provider
instance name, for example `anthropic-eu`, while
`coder_ai_gateway_cost_control_unpriced_token_usage_records_total` used
the provider type, for example `anthropic`. The two could not be
correlated on `provider`.

The metric was also inconsistent with itself: the path where a provider
fails to resolve labelled by instance name, and the path where a model
has no price labelled by type. The type is still worth exposing, since
prices are keyed on `(provider_type, model)` and that is what an
operator needs to add a price.

## Changes

- Label the metric with `provider` (the instance name, consistent with
the other gateway metrics) and add `provider_type` (the configured type
the price is keyed on).
- Use `unknown` for `provider_type` when the provider does not resolve
to a configured type.
- Log the unresolved-provider case at `warn` instead of `info`. A
missing price is an expected steady state, but a provider that cannot be
resolved is not.
- Update the metrics docs and the `metricsdocgen` fixture.

Closes [AIGOV-574](https://linear.app/codercom/issue/AIGOV-574)

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by
@ssncferreira
2026-08-17 14:08:28 +01:00
Nick Vigilante 58de9ab8f8 docs: correct broken CLI commands and flags from drift sweep (#28098)
## Summary

Corrects broken CLI commands and flags surfaced by the DOCS-637
full-corpus runtime drift sweep. Each fix was verified against the
generated CLI reference (`docs/reference/cli/*`) and, where relevant,
`codersdk` source.

## Changes

| Page | Fix |
|------|-----|
| `docs/user-guides/workspace-access/index.md` | `coder port forward` →
`coder port-forward` (the space form is unrecognized; the command is
hyphenated). |
| `docs/ai-coder/github-to-tasks.md` | Remove `coder templates list
--org your-org-name` in two spots — `templates list` has no `--org` flag
(`unknown flag: --org`). |
| `docs/admin/infrastructure/scale-utility.md` | `--cleanup-timeout
15min` → `15m` — Go durations reject the `min` unit (`invalid duration:
unknown unit "min"`). |
| `docs/admin/integrations/dx-data-cloud.md` | `coder users list >
users.csv` emitted a whitespace table, not CSV. Emit JSON and convert to
real CSV with `jq`, mirroring the API tab on the same page and using the
same columns as the default table view
(`username,email,created_at,status`). |

## Notes / judgment calls

- **dx-data-cloud (CSV):** the page genuinely needs CSV (the DX CSM
imports a CSV, and the API tab already produces one via `jq ... @csv`).
`coder users list` only supports `--output table|json`, so the CLI tab
now produces real CSV via `jq` rather than switching the page to JSON.
- **scale-utility `:109` left as-is:** `--target-users 0:100` is
prefixed with "For dashboard traffic:", which correctly scopes it to the
`scaletest dashboard` subcommand, so it is not drift.
- **Excluded — sessions-tokens `--lifetime=720h`:** the sweep flagged
this because the throwaway SUT capped token lifetime at 168h, but
`--max-token-lifetime` defaults to `876600h` (~100 years), so the
example is valid on a default deployment. The `CODER_MAX_TOKEN_LIFETIME`
dependency is also already documented in the page's "Set max token
length" section. No change needed.

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

> This PR was created with AI assistance (Coder Agents).
2026-08-14 12:49:11 -04:00
Nick Vigilante 1d189cc204 docs: fix P2/P3 typos and syntax errors from drift sweep (#28101)
## Summary

High-confidence textual subset of the DOCS-637 **P2/P3** drift batch (31
findings total). These 8 fixes are pure typo / grammar / syntax
corrections verified directly against the doc source, so they carry no
risk of misreconstructed command output.

## Changes (6 files)

| Page | Fix |
|------|-----|
| `docs/admin/templates/extending-templates/variables.md` | Remove
doubled word: "file in in the template directory" → "file in the
template directory". |
| `docs/admin/networking/port-forwarding.md` | Grammar: heading "From an
coder_app resource" → "From a coder_app resource". |
| `docs/user-guides/workspace-access/index.md` | Malformed heading
"Through with the CLI" → "Through the CLI". |
| `docs/about/contributing/modules.md` | Conventional-commit example
missing the required space: `feat(git-clone):add` → `feat(git-clone):
add`. |
| `docs/ai-coder/tasks-migration.md` | Add missing closing double-quotes
on Terraform `source`/`version` in two snippets that would fail
`terraform` parsing. |
| `docs/admin/users/idp-sync.md` | Role Sync section said "group sync
settings" (copy-paste from the Group Sync section); remove an invalid
trailing comma from a JSON output example. |

## Deferred (remaining ~23 P2/P3 items, not in this PR)

The rest of the batch is stale **command-output** samples (column/schema
changes, sample values) and items that need a content decision (e.g.
`--psk` now deprecated in favor of `--key`; `--address` deprecated; an
undocumented retention flag). Those need live-output reconstruction or a
call on direction, so they're left for follow-up work, consistent with
the issue's "handle after the P0/P1 fixes land" guidance. One catalog
row (`reverse-proxy-nginx.md:57`, certbot `ws=apache`) is already
handled by #28086 and is excluded here.

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

> This PR was created with AI assistance (Coder Agents).
2026-08-14 12:44:55 -04:00
Michael Suchacz 8d4d0b35dd feat: add Coder Agents chat tools to the MCP toolsdk (#28025)
Exposes the experimental Coder Agents chats API through the MCP tool
registry, so MCP clients (the hosted `/api/experimental/mcp/http` server
and `coder exp mcp server`) can start and drive server-side coding
agents.

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

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

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

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

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

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

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

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

Updates the AI Governance Cost Control docs in two ways:

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

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

---

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

---------

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

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

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

## Commands

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

## Changes

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

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

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

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

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

## Why

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

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

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

Three semantic changes:

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

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

> Mux created this PR on Mike's behalf.

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

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

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

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

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

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

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

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

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

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

## Note

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

---

PR generated with Coder Agents.
2026-08-12 11:35:36 -04:00
Matt VollmerandNick Vigilante 75e0790cd7 docs: remove beta references from Coder Agents docs and manifest (#27939)
Removes all references to "beta" from the Coder Agents documentation
under `docs/ai-coder/agents/` and the corresponding `"state": ["beta"]`
entries in `docs/manifest.json`. Also updates screenshots, video, and
hero image, and regenerates the auto-generated feature-stages table.

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

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

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

PR generated with Coder Agents

---------

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

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

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

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

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

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

> This PR was authored by Mux (AI) on Mike's behalf.
2026-08-11 13:53:15 +02:00
Ethan ee49107ea9 docs: document per-template agents_allowed (#27518)
Relates to CODAGT-713

Depends on #27517

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

This is the final PR in the stack and aligns the template routing and
optimization guidance with the database, API, frontend, cleanup, and CLI
changes in the preceding PRs.
2026-08-07 17:23:28 +10:00
4b7494be72 feat: harden chat generation runtime instrumentation for billing (#27451)
Closes CODAGT-835

## Summary

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

## The billable definition

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

What counts:

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

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

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

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

## Index for the hourly scan

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

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

## Tests

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

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Hugo Dutka <hugo@coder.com>
2026-08-06 16:09:38 +07:00
Michael Suchacz 6b8f820493 feat: remove native chat cost tracking in favor of AI Gateway cost data (#27330)
## Stack Context

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

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

## Summary

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

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

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

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

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

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

## Summary

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

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

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

## Breaking change

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

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

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

### Version bumps

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

### Coder Tasks removal

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

cc @matifali

---------

Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
2026-08-04 12:09:23 +05:00
Susana Ferreira 3f1973f45c docs: document AI Gateway cost controls (#27643)
### Description

Adds documentation for AI Governance Cost Control, including how
administrators configure budgets, how effective groups are resolved, how
enforcement works, and where spend reporting is available.

### Changes

- Replace the placeholder cost control page with a full admin guide
- Document deployment settings, group budgets, user overrides, and
effective group resolution
- Explain estimated spend, unpriced models, notifications, enforcement,
and spend reporting
- Add migration guidance for Coder Agents Cost Control
- Add screenshots for group budgets and user overrides

Closes
[AIGOV-476](https://linear.app/codercom/issue/AIGOV-476/add-documentation-for-ai-bridge-cost-controls).

> [!NOTE]
> Initially generated by Coder Agents, modified and reviewed by
@ssncferreira
2026-07-30 15:04:39 +00:00
3f3fd1c4d7 feat: show network request summary on AI session detail card (#27418)
Frontend for the AI session network summary. Adds Network calls, Blocked
network requests, and Top domains rows to the Session summary card on
the individual AI session detail page, driven by the network fields on
the session threads response.

Renders "Disabled" when network monitoring was not active and "No
activity" when there were no calls. Covered by Storybook stories for
each state.

### PR map (merge strictly bottom-up)

This change is a 4-PR stack. Each PR depends on all the ones below it,
so merge in this exact order:

1. #27417 — backend network summary
2. #27418 — frontend summary rows
3. #27425 — backend per-call list `network_call_logs`
4. #27426 — frontend network-calls panel

Refs AIGOV-463

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Cian Johnston <cian@coder.com>
2026-07-30 13:23:51 +02:00
Jaayden Halko 54d5eb7ec2 feat: add hourly hb_agent_runtime_v1 usage events for Coder Agent runtime (#27312)
closes CODAGT-839
closes CODAGT-843
closes CODAGT-773

## Summary

Adds a new heartbeat usage event type, `hb_agent_runtime_v1`, measuring
the total agent-loop runtime of Coder Agents (chats) per UTC hour, plus
a reconciler that generates one event per hour with self-healing
backfill over a trailing 7-day window. Events flow to Tallyman through
the existing publisher unchanged. This measures the new Coder Agents
(the `chats` tables), not the deprecated Tasks counted by
`dc_managed_agents_v1`.

Independent of #27508, which fixes the dead ai-seats cron registration.
Both PRs carry the identical `usage_event` create permission hunk for
the usage-publisher subject (this feature's generator and the ai-seats
cron each need it for heartbeat inserts), so they can land in either
order and the overlap merges cleanly.

> [!WARNING]
> **Do not include this in a release until Tallyman accepts
`hb_agent_runtime_v1`.** The publisher marks permanently rejected events
as done-forever, and the generator then sees those buckets as complete
locally, so their usage would be silently and permanently lost.

## Details

Each event's payload is `{"runtime_ms": N}`: the sum of
`chat_messages.runtime_ms` for messages created in the hour bucket `[H,
H+1)`, across all chats (sub-agents, API-created, archived, and
soft-deleted messages included). Events use deterministic IDs
(`hb_agent_runtime_v1:<bucket start>`) with `created_at` set to the
bucket start, so concurrent replicas race safely via `ON CONFLICT (id)
DO NOTHING` without locking, and daily rollups attribute backfilled
hours to the correct day. Idle hours produce zero-valued events. A
bucket becomes eligible 5 minutes after it closes; hours missing for
longer than the 7-day window are forfeited, which can only undercount.

Note that this makes `usage_events.created_at` explicitly the *event
occurrence time* rather than the row insertion time; the two only
diverge for backfilled events. It already behaved as the occurrence
timestamp (it drives the daily rollup day and is shipped to
Tallyman/Metronome as the event timestamp), and the migration now
documents this with a `COMMENT ON COLUMN`, which also surfaces as a Go
doc comment on `UsageEvent.CreatedAt`.

The new `usage.Generator` runs unconditionally in enterprise builds; the
`publish_usage_data` license flag continues to gate egress only, so
air-gapped deployments still fill their local ledger. The
`aggregate_usage_event()` trigger sums `runtime_ms` per day into
`usage_events_daily` (unlike `hb_ai_seats_v1`, which takes the daily
max).

`InsertHeartbeatUsageEvent` now takes an explicit `createdAt` so
generators can backfill historical buckets; the cron passes
`clock.Now()` to preserve its existing behavior.

## Tallyman follow-up

<details>
<summary>Prompt for the Tallyman-repo agent</summary>

> **Task**: Add support for the new Coder usage event type
`hb_agent_runtime_v1` so Tallyman accepts, validates, and forwards it to
Metronome.
>
> **Background**: coder/coder PR (this PR) adds hourly heartbeat events
measuring Coder Agent runtime. Events arrive via the existing
`/api/v1/events/ingest` endpoint with: `event_type:
"hb_agent_runtime_v1"`, `event_data: {"runtime_ms": <int64 >= 0>}`,
deterministic `id` of the form `hb_agent_runtime_v1:2026-07-15_14:00:00`
(UTC hour bucket start), and `created_at` set to the bucket start (may
be up to ~8 days in the past due to backfill; within Metronome's 34-day
dedup window). Zero-value events are normal (idle hours).
>
> **Work**:
> 1. Update Tallyman's vendored/imported `coderd/usage/usagetypes` (or
equivalent) to the coder/coder commit that adds
`UsageEventTypeHBAgentRuntimeV1` and `HBAgentRuntime`.
> 2. Ensure ingestion validation accepts the type (`Valid()` switches)
and rejects negative `runtime_ms`.
> 3. Ensure Metronome forwarding maps the event with transaction ID
derived from the event `id` as for existing types, passing `runtime_ms`
through as the property for a SUM-aggregated billable metric ("Coder
Agent Hours" = `SUM(runtime_ms) / 3,600,000`).
> 4. Do NOT permanently reject unknown-but-well-formed future `hb_*`
types if avoidable; at minimum confirm current behavior for unknown
types (temporary vs permanent rejection) and report it.
> 5. Tests: ingest accept/validate, dedup by ID, Metronome payload
mapping.
>
> **Constraint**: this must be deployed to tallyman-prod **before** any
coder/coder release containing the event generator; coderd treats
permanent rejections as terminal per event.

</details>
2026-07-30 08:37:45 +01:00
Paweł BanaszewskiandCian Johnston 18128b7b52 docs: add standalone AI Gateway docs (#27592)
Documents standalone AI Gateway deployment, Gateway key authentication,
monitoring, and the updated embedded vs standalone topology in the AI
Gateway docs.

---------

Co-authored-by: Cian Johnston <cian@coder.com>
2026-07-29 19:38:22 +02:00
Matt Vollmer 4987afada7 docs: present AI Governance as included with Premium (#27545)
## Summary

AI Governance is now included with Premium licenses instead of being
sold as a separate per-user add-on. This updates `docs/` to describe the
new packaging, removes "Add-On" from AI Governance references, and
refreshes the editions architecture diagram.

## Changes

- **`docs/ai-coder/ai-governance.md`**: title is now "AI Governance";
rewrote the licensing statements (previously "a separate, per-user
license... not included with a Premium subscription and must be
purchased separately") to state it is included with Premium. The
usage-pool section now attributes the shared Agent Workspace Build pool
to Premium deployments.
- **Repeated admonition (28 files under `ai-coder/agent-firewall/` and
`ai-coder/ai-gateway/`)**: replaced "requires the AI Governance Add-On /
as of Coder v2.32, deployments without the add-on..." with "is part of
AI Governance, which is included with a Premium license." The v2.32
add-on gate no longer applies; the gate is now Premium vs. Community.
- **`docs/ai-coder/index.md`, `security.md`, `tasks.md`,
`usage-data-reporting.md`, `admin/licensing/index.md`,
`install/releases/esr-2.29-2.34-upgrade.md`,
`ai-gateway/ai-gateway-proxy/setup.md`,
`ai-gateway/clients/claude-code.md`**: reworded add-on references to
Premium inclusion.
- **`docs/manifest.json`**: nav title "AI Governance Add-On" → "AI
Governance", updated two descriptions, and swapped the 25 `"state": ["ai
governance add-on"]` badges to `["premium"]` so the sidebar badge reads
"Premium" instead of "AI Governance Add-On".
- **`docs/images/single-region-architecture.png`**: refreshed the
diagram in the **Community and Premium editions** tab on
[Architecture](https://coder.com/docs/admin/infrastructure/architecture).
Also deleted the unreferenced `single-region-architecture.svg` copy.

## Follow-ups outside this PR

- The `"ai governance add-on"` doc-state badge is defined in
`coder/coder.com` (`src/utils/docs/state.ts`). After this merges, no
manifest entry uses that key, so it becomes dead config and can be
removed there.
- `enterprise/coderd/license/license.go:564-572` still warns admins that
"The AI Governance add-on is required to use AI Gateway." That backend
string will contradict these docs once shipped.

## Verification

- `pnpm run lint-docs`: 0 errors across 504 files
- `make lint/emdash`: clean
- Vale on the changed Markdown files: 0 errors; remaining warnings are
pre-existing gerund headings on untouched lines
- `docs/manifest.json` validated as JSON
- Confirmed the deleted SVG had no references anywhere in the repo

---

PR generated with Coder Agents on behalf of @mattvollmer.
2026-07-29 08:45:20 -04:00
Susana Ferreira e96e7cfec2 docs(docs): add AI Gateway cost controls placeholder page (#27570)
## Summary

Adds a placeholder "Cost Controls" page under AI Gateway in the docs,
plus its `manifest.json` navigation entry. This is a stub with a title
only; the full content will be written in a follow-up.

Relates to
[AIGOV-476](https://linear.app/codercom/issue/AIGOV-476/add-documentation-for-ai-bridge-cost-controls).

Related to [internal slack
thread](https://codercom.slack.com/archives/C096PFVBZKN/p1785150528587409).

## Changes

- Add `docs/ai-coder/ai-gateway/cost-controls.md` placeholder page
- Register the page in `docs/manifest.json` under AI Gateway (after
Monitoring)

---
> [!NOTE]
> This PR was generated with Coder Agents.
2026-07-28 10:05:18 +00:00
TJ bfcfb71860 fix: show 'Unset' for missing providers in AI models list (#27400)
## Summary

Frontend-only fixes for the `/ai/settings/models` page:

1. **Provider column displays "Unset"** with an info tooltip when a
model's provider has been deleted, instead of "N/A".
2. **Models without a usable provider display as "Disabled"** in the
list, regardless of the stored `enabled` flag. Covers both missing
(soft-deleted) and disabled providers.
3. **Save button re-enabled when only the provider changes** on the edit
page (previously the button stayed disabled because provider changes
lived outside the formik state).

## Scope

Frontend only. The DB constraint
`chat_model_configs_ai_provider_required_when_active` already prevents a
non-deleted model from having a NULL `ai_provider_id`; CODAGT-709
addresses the server-side cascade when a provider is deleted.

## Changes

- `ModelsPageView.tsx`: two `useMemo` maps (`hasProviderByModelId`,
`providerEnabledByModelId`) passed to `ModelRow`.
- `ModelRow.tsx`: `isEffectivelyEnabled = model.enabled && hasProvider
&& providerEnabled`. When `hasProvider` is false, renders "Unset" with a
standard `InfoIcon` tooltip.
- `ModelForm.tsx`: `canSubmit` OR's in `hasProviderChange` so the save
button enables when only the provider dropdown changes.
- `ModelRow.stories.tsx`: four stories covering baseline,
missing-provider (with tooltip assertion), disabled-provider, and
disabled-model paths.
- `ModelsPageView.stories.tsx`: `OrphanedModelShowsUnset` feeds an
orphaned model through the real derivation (map-miss + `?? false`),
matching the production shape produced by `deriveProviderStates`.
`DisabledProviderModelsStillListed` now asserts the "Disabled" badge.
- `ModelForm.stories.tsx`: `EditUpdateEnabledOnProviderChange` asserts
the save button is enabled when the selected provider differs from the
model's stored provider.
- `testFixtures.ts`: `mockOrphanedModel` fixture representing the
deleted-provider case.

Diff: 7 files, 240 insertions, 9 deletions.

> 🤖 This PR was updated with Coder Agents.
2026-07-28 00:17:45 -07:00
Susana Ferreira dba45cede7 fix: remove 403 from key failover and cooldown on 401 (#27419)
## Problem

When a key returned 401 or 403, the pool marked it permanently
unavailable for the lifetime of that in-memory pool. This is bad UX: a
transient auth failure or a briefly-misconfigured key could take a key
out of rotation until the operator either restarted Coder or
reconfigured the key (even re-saving the same working value).

## Changes

- **403 removed from key failover**: it's a per-request authorization
failure, not a key-level problem, so it's surfaced to the caller as-is
without marking the key or failing over.
- **401 now applies a temporary cooldown** (like 429) so the key
recovers on its own instead of staying blocked.
- When every key is in an auth-failure cooldown, the pool reports a
`502` with no `Retry-After`, but the keys still recover automatically
once the cooldown elapses.

Closes
https://linear.app/codercom/issue/AIGOV-421/ai-gateway-a-quarantined-centralized-key-never-recovers-without-a
Closes
https://linear.app/codercom/issue/AIGOV-533/403s-misclassifying-keys-as-permanently-down-in-ai-gateway

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-27 12:06:01 +01:00
Michael Suchacz 02fd1cc691 feat: allow spawn_agent model and reasoning effort override (#27385) 2026-07-22 18:43:22 +02:00
Sas SwartandClaude Opus 4.8 f17d488479 feat: add network call badges to AI sessions table (#27341)
Surface the total and blocked Agent Firewall network calls on the AI
sessions list. Sessions that did not pass through Agent Firewall show as
"Disabled".

<img width="2842" height="1366" alt="image"
src="https://github.com/user-attachments/assets/2a68b4a9-4d93-454d-a06e-5f0d0b734a33"
/>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 14:16:31 +02:00
Nick Vigilante f55be09bfc docs(docs/ai-coder/ai-gateway): fix bmcp_ described as suffix instead of prefix (#27392)
The Tool Injection section of the AI Gateway MCP doc called `bmcp_` a
suffix, directly contradicting the correct description one section
earlier on the same page and the `aibridge` implementation, where
`injectedToolPrefix` is prepended to every bridged MCP tool name
(`aibridge/mcp/tool.go`).

Reported by a customer who read the suffix wording and assumed `bmcp` in
a tool name like `bmcp_github_list_gists` was a typo.

---
🤖 Built with AI assistance.
2026-07-21 11:59:30 -05:00
Michael Suchacz 3227cac217 feat: add manual chat compaction via /compact (#27081)
Adds a user-triggered `/compact` action for Coder Agents chats: typing
`/compact` in the composer (or picking it from the `/` trigger menu)
summarizes the conversation so far to free up context window space.

## How it works

- New `POST /api/experimental/chats/{chat}/compact` endpoint
(owner-only, RBAC `ActionUpdate`, excluded from the public API reference
via `x-apidocgen skip`). It marks the chat with a durable one-shot
`chats.compaction_requested_at` signal and moves it `waiting -> running`
via a new `RequestCompaction` state transition; no message row is
inserted. AI Gateway attribution needs no per-request key: generation
preparation resolves the owner's synthetic API key (#27170) like any
other turn.
- `RequestCompaction` hands off chat ownership (clears
`worker_id`/`runner_id`) so a worker acquisition hint is published;
since the transition changes no history, the previous runner could
otherwise miss the request under reordered pubsub delivery.
- The background chat worker picks the chat up like any other turn. A
pending manual request takes precedence over turn completion in the
generation decision, and forces compaction even below the automatic
threshold (and when compaction is disabled via threshold=100). The
commit step consumes the request marker in the same transaction; any
transition that ends the turn clears stale markers.
- The summary triplet reuses the automatic-compaction path, now tagged
with a `source` (`automatic` | `manual`) that is plumbed through
streamed progress parts, persisted tool JSON, and the UI label
("Summarized (manual)").
- Validation order: busy chats reject with 409 (state-machine conflict),
empty/already-compacted chats with 409 "nothing to compact", archived
chats with 400; the owner usage-limit check runs last so no-op requests
surface the specific conflict instead of a limit error.
- Web UI: the `/` trigger menu now has a built-in "Commands" group
listing `/compact`; submit intercepts exactly `/compact` and calls the
endpoint instead of sending a message. A personal or workspace skill
named `compact` takes precedence over the built-in command; while skill
collisions are still resolving, an exact `/compact` submission is
blocked with a retryable hint instead of leaking as message text.
History and queued-message edits are never intercepted. After
compaction, the context usage indicator resets to its unknown state
until the next assistant response reports fresh usage, instead of
showing the stale pre-compaction number.
- codersdk: `ExperimentalClient.CompactChat`.

Worker-path execution (rather than compacting synchronously in the
handler) reuses the existing lock fencing, live "Summarizing..."
streaming, retry accounting, restart resilience, and debug-run
observability. Rationale documented in `coderd/x/chatd/ARCHITECTURE.md`.

## Testing

- State machine: transition-matrix coverage for `RequestCompaction`,
marker lifecycle tests (carried by lease renewals/queue appends, cleared
by terminal transitions, consumed by commit), ownership handoff +
acquisition hint assertions.
- Worker: decision-ordering and forced-compaction unit tests;
active-server end-to-end test (manual compact below threshold produces a
`source=manual` summary, returns to `waiting`, no assistant follow-up;
busy chat rejected).
- API: success, archived, non-owner, RBAC-denied, empty-chat, no-daemon
cases; usage-limit ordering (at-limit owners still get
state/nothing-to-compact conflicts for no-op requests, with marker
rollback).
- Frontend: Storybook play tests for the Commands menu group, submit
intercept, skill-name collision, queued-edit passthrough, and
manual/automatic tool rendering; unit tests for command availability
resolution and the post-compaction context usage reset.

> This PR was created by Mux, an AI coding agent, working on Mike's
behalf.
2026-07-21 10:58:08 +02:00
Michael Suchacz 9f4ddea571 feat: revoke MCP server OAuth grants at the provider on disconnect (#27300)
Closes
[CODAGT-805](https://linear.app/codercom/issue/CODAGT-805/revoke-oauth-grants-at-the-source-for-mcp-servers).

The experimental MCP server OAuth2 disconnect endpoint previously
deleted only the stored token row, leaving the grant active at the OAuth
provider. This PR adds provider-side token revocation while keeping
local disconnect independent of provider availability.

## Changes

- Add `mcp_server_configs.oauth2_revocation_url` in migration `000547`.
The value can be configured manually, discovered from RFC 8414 metadata,
and managed through the MCP server settings UI. Non-admin responses
redact it with the other OAuth2 fields.
- Revoke the refresh token first through the RFC 7009 endpoint, then
fall back to the access token only for `unsupported_token_type`. Public
clients send `client_id`; confidential clients use
`client_secret_basic`.
- Delete the local token transactionally before best-effort provider
revocation. Callers without a token receive the same response for hidden
and nonexistent config IDs, and provider failures return a generic
warning without exposing provider response bodies.
- Require HTTPS revocation endpoints except for HTTP loopback URLs.
Redirects must preserve the POST and remain on the configured origin.
Redirect errors omit provider-controlled paths and query strings so
reflected token material cannot enter logs.
- Treat `200 OK` and `204 No Content` as completed revocations. `202
Accepted` remains a failure because it does not confirm completion.
- Prevent an in-flight refresh from recreating a token deleted by
disconnect. Refresh persistence now uses an optimistic update keyed by
token ID and `updated_at`; only the OAuth callback can create a token
row. Refresh conflicts reload the current row or clear in-memory auth
when disconnect deleted it.
- Return `{token_revoked, token_revocation_error}` from disconnect,
while retaining SDK compatibility with the legacy `204` response. The UI
surfaces provider revocation failures as warning toasts.
- Document revocation endpoint discovery, HTTPS requirements, and
best-effort disconnect behavior.

No token or no configured revocation URL returns `token_revoked: false`
without an error, so disconnect remains idempotent.

> Updated by Mux, an AI coding agent, on Mike's behalf.
2026-07-20 00:14:03 +02:00
Michael Suchacz 1ac106255b feat: add Anthropic 1M context window toggle for Agents model configs (#27257) 2026-07-17 13:04:13 +02:00
Yevhenii Shcherbina 1453b4b1fc docs: document Bedrock mantle protocol (#27296)
Implements:
https://linear.app/codercom/issue/AIGOV-518/add-docs-for-bedrock-mantle
Follow-up to: https://github.com/coder/coder/pull/26745
2026-07-16 14:58:09 -04:00
Nick Vigilante c84aa564ba docs: normalize code-fence languages for Shiki compatibility (#27161)
Normalizes non-standard code-fence language tags across `docs/**` so a
strict highlighter (Shiki, used by Fumadocs) won't fail the build on an
unrecognized language, and unifies redundant synonym tags onto one
canonical form per language. The current renderer (Speed-Highlight)
detects the language from the code content, not the fence label, so this
drift wasn't visible until now.

## Changes

- `hcl` -> `tf` (199 fences, including indented ones nested in
numbered/bulleted lists). Shiki ships `hcl` and `terraform` as two
distinct grammars (not aliases); every `hcl`-tagged fence in `docs/**`
is actually Terraform resource/data/provider syntax, so the more
specific `terraform` grammar is correct for all of them. `tf` is Shiki's
own alias for that grammar, and it's also what GitHub's own markdown
renderer resolves to the same HCL/Terraform highlighting.
- `pwsh`/`powershell` -> `ps1`. Both `ps` and `ps1` are registered
PowerShell aliases in Shiki, but on GitHub's renderer only `.ps1` is a
registered file extension (`.ps` isn't), so `ps1` renders identically to
`powershell` there today while bare `ps` would silently lose
highlighting.
- `env` -> `dotenv` (a dedicated Shiki grammar for `KEY=VALUE` files)
- `text`/`output`/`none`/`url` -> `txt`. Same built-in plain-text
fallback either way, just shorter.
- `Dockerfile` -> `dockerfile` (lowercase)
- `bash`/`shell` -> `sh` (732 fences). Shiki and GitHub both alias all
three to a single shell grammar; this was already the style guide's
stated preference, just not enforced across the existing corpus until
now.
- `markdown` -> `md` (4 fences). Alias of the same grammar in both Shiki
and GitHub.
- `jsonc` -> `json` (1 fence). The block has no comments or trailing
commas, so it doesn't need the comments-capable grammar.
- `ts` -> `tsx` (2 fences, `docs/about/contributing/frontend.md`).
Verified the actual content tokenizes identically under both grammars,
and a sibling block in the same file already needs `tsx` for real JSX,
so unifying to one tag is safe for this file. Documented a caveat: `tsx`
mis-tokenizes the legacy angle-bracket type-assertion syntax
(`<Type>value`), which is invalid in real `.tsx` files anyway, so use
`value as Type` instead.
- `yml` -> `yaml` (1 fence)
- Updated `docs/.style/style-guide/formatting.md` to document all
canonical tags

`promql` (2 fences) and `caddyfile` (2 fences) are left as-is. Shiki
doesn't bundle a grammar for either, so they need a custom grammar
registration when the site adopts Shiki, rather than degrading to `txt`.
Tracked as follow-up work under DOCS-118 and
[DOCS-544](https://linear.app/codercom/issue/DOCS-544/vendor-a-local-promql-grammar-for-shiki-syntax-highlighting)
(promql).

Does not touch `offlinedocs/`.

Linear:
[DOCS-476](https://linear.app/codercom/issue/DOCS-476/normalize-docs-code-fence-languages-de-risk-shikifumadocs)

<details>
<summary>How the fence tags were verified</summary>

Each tag was tested against a real `shiki@latest` highlighter instance
(`codeToHtml`/`codeToTokens`) and cross-checked against GitHub's
`@wooorm/starry-night` grammar sources (the renderer that actually
displays these `.md` files today, in repo browsing and PR diffs), since
that's what determines whether brevity is safe before Shiki adoption:

```text
FAIL  env        -- Language `env` is not included in this bundle.
FAIL  Dockerfile -- Language `Dockerfile` is not included in this bundle.
FAIL  promql     -- Language `promql` is not included in this bundle.
FAIL  caddyfile  -- Language `caddyfile` is not included in this bundle.
FAIL  pwsh       -- Language `pwsh` is not included in this bundle.
FAIL  output     -- Language `output` is not included in this bundle.
```

`hcl` doesn't error in Shiki, since it's a real grammar, but that's
exactly the trap: it was silently rendering every fence with the generic
HCL grammar instead of the Terraform-specific one. Every `hcl`-tagged
fence in `docs/**` was manually checked against `origin/main` and is
genuinely Terraform content.

For `ts`/`tsx`, tokenizing the actual doc content confirmed identical
output under both grammars; a synthetic test with the legacy
angle-bracket cast syntax confirmed `tsx` degrades on that specific
construct, which the style guide now calls out.

The first normalization pass only matched fence tags at column 0
(`^```tag$`), missing tags indented inside numbered/bulleted lists. A
follow-up pass caught the remaining occurrences at any indentation
level.

</details>


---

*This PR description and the underlying changes were prepared with Coder
Agents assistance.*
2026-07-15 14:07:09 -04:00
Paweł Banaszewski 3126306598 feat: add --aigateway-proxy-target flag (#27122)
Adds `--aigateway-proxy-target` option to
`deploymentGroupAIGatewayProxy` that defines URL to which intercepted
requests should be forwarded to.
Forward URL used to be hardcoded to `coderAPI.AccessURL` pointing to
embedded Gateway. With addition of standalone AI Gateway this needs to
be configurable.

Renamed `aibridgeproxyd.Server.coderAccessURL` and `coderAccessPort` ->
`gatewayURL` and `gatewayPort` + option to better reflect reality.
2026-07-14 16:40:22 +00:00
Michael Suchacz 55b06f14a3 feat: allow overriding advisor reasoning effort (#27196) 2026-07-14 11:01:51 +02:00
Michael Suchacz 6f6d7539c8 feat: remove unused chat statuses pending, paused, and completed (#27064)
The chatd state machine only recognizes `waiting`, `running`, `error`,
`requires_action`, and `interrupting`. Remove the unused `pending`,
`paused`, and `completed` values from the database enum, backend, SDK,
frontend, generated queries, and API docs.

Migration `000543_chat_status_remove_unused` remaps existing `pending`
rows to `running`, remaps `paused` and `completed` rows to `waiting`,
drops the obsolete `idx_chats_pending` index, and recreates
`chats_expanded` around the enum swap. It also removes the dead
`AcquireChats` query and all remaining query literals for the deleted
statuses.

**NOTE**: The enum swap can break chat queries from older replicas
during a mixed-version rollout because they still reference
`'pending'::chat_status`. Chats are experimental, so this PR accepts
that limited rollout window instead of adding a two-release expand and
contract sequence.

> This PR was authored by Mux (AI agent) on Mike's behalf.
2026-07-13 20:28:28 +02:00
Nick Vigilante 199b5936c1 fix(docs): replace invalid </br> tags and format swallowed placeholder URL (#27174)
## Summary

Fixes two classes of invalid/broken HTML in hand-written docs. Both are
visible problems in today's rendered docs, independent of any
docs-engine work.

1. **`</br>` is not a real HTML tag.** `br` is a void element with no
closing form; browsers error-correct `</br>`, but it is invalid HTML.
Replaced all 15 usages with `<br />` across:
   - `docs/admin/templates/extending-templates/dynamic-parameters.md`
   - `docs/admin/users/idp-sync.md`
   - `docs/tutorials/best-practices/organizations.md`
2. **Browser-swallowed placeholder URL.** In
`docs/ai-coder/github-to-tasks.md`,
`https://<your-coder-url>/settings/external-auth` was unformatted, so
HTML renderers parse `<your-coder-url>` as an unknown tag and drop it.
The live docs currently render the broken text `re-authenticate at
https:///settings/external-auth`. Wrapped in backticks, matching every
other instance in the same file.

Table realignment noise in the diff is from `fmt/markdown` (`<br />` is
one character wider than `</br>`).

A repo-wide grep confirms no remaining `</br>` and no other unformatted
`https://<placeholder>` URLs in prose (other hits are inside code fences
or already backticked). The equivalent placeholder issues in
**generated** reference docs (CLI help strings, swagger annotations) are
intentionally out of scope and tracked separately in
[DOCS-551](https://linear.app/codercom/issue/DOCS-551/backtick-placeholder-syntax-in-generated-reference-docs-cli-help).

Tracking issue:
[DOCS-550](https://linear.app/codercom/issue/DOCS-550/fix-invalid-br-tags-and-browser-swallowed-placeholder-url-in-hand)

---

Created by Coder Agents on behalf of @nickvigilante.
2026-07-13 10:41:38 -04:00
Thomas Kosiewski 9af3d31036 fix: relabel advisor max uses setting from per run to per turn (#27046) 2026-07-10 09:36:12 +02:00
Cian Johnston 14767dfa8e feat: explain missing POSIX sh on Windows workspaces (#27048)
When a workspace has no POSIX sh on PATH (typical for fresh Windows workspaces), the execute tool fails with a raw `exec: "sh": executable file not found in %PATH%` error the model cannot act on. 

This change:
- Enriches the above error in chattool with remediation steps and a docs link.
- Documents the requirement in the Coder Agents architecture page.

> This PR was generated by Coder Agents on behalf of @johnstcn
2026-07-07 21:32:27 +00:00
Danielle Maywood 7c78698a6d feat: notify users when chats are shared (#26914) 2026-07-06 13:15:58 +01:00
Yevhenii Shcherbina 121107f151 docs: document the Bedrock external ID for role assumption (#26973)
Document the Bedrock external ID for role assumption.
2026-07-02 19:06:16 +00:00
Danny Kopping e3ac65aa5f docs: add AI Gateway rebranding migration guide (#26854)
## Summary

Adds an operator-facing migration guide for the AI Bridge to AI Gateway
rebrand, as a new docs page under **AI Coder > AI Gateway** (last child
in the section).

The guide documents:

- **Config aliases** (env vars, CLI flags, YAML group keys): old
`aibridge` names still work as hidden, deprecated aliases; new
`ai_gateway` names are canonical. Includes full env-var mapping tables
and the mechanical substitution rules.
- **HTTP API**: canonical path is now `/api/v2/ai-gateway`; legacy
`/api/v2/aibridge` routes retained.
- **Metrics**: prefixes renamed `coder_aibridged_*` ->
`coder_ai_gateway_*` and `coder_aibridgeproxyd_*` ->
`coder_ai_gateway_proxy_*`. Both old and new names are emitted today, so
dashboards keep working; guidance to migrate before the old names are
removed, plus an optional `metric_relabel_configs` drop snippet.
- **No database changes** and no required config changes to upgrade.

Implements the docs/release-notes portion of
[AIGOV-240](https://linear.app/codercom/issue/AIGOV-240) (parent:
[AIGOV-207](https://linear.app/codercom/issue/AIGOV-207)).

## Notes

- Content reflects what actually shipped in the codebase (metrics are
*aliased*, not hard-renamed), which differs from the original RFC that
assumed a hard rename.
- Registered in `docs/manifest.json` with `state: ["ai governance
add-on"]` to match sibling pages.


---

*This PR was produced by opencode (agent) using the
`anthropic/claude-opus-4-8` model, under human direction and review.*

---------

Signed-off-by: Danny Kopping <danny@coder.com>
2026-07-01 10:54:19 +02:00
Danielle Maywood 6b8c38b5a4 fix: gate chat advisor and virtual desktop behind experiments, delete experiments page (#26809) 2026-06-30 21:57:40 +01:00
Mathias Fredriksson 2fd5ae4323 fix: stop Agents dead-ending on unsupported providers (#26841)
Configuring only a GitHub Copilot provider left the Agents page stuck on
"set up a provider then add a model", even with a provider and models
configured. The catalog dropped any provider type that NormalizeProvider
did not recognize, so a Copilot-only deployment looked identical to an
empty one and never unlocked the page.

The Agents harness cannot use Copilot: it needs a per-request token only
an official Copilot client can mint, and the harness is not one. Instead
of dropping such providers, the catalog now reports them as unsupported
so the UI can explain the dead end and point elsewhere, rather than ask
for setup that already happened. The providers stay usable through the
AI Gateway proxy.

Support is derived from the provider type, not stored, so there is no
migration. codersdk.IsAgentsUnsupportedProviderType is the single source
of truth, consulted by the chatd catalog and, through the generated
AgentsUnsupportedProviderTypes list, the frontend.

The diff also carries unrelated modernization of nearby db2sdk and
chatprovider helpers (slices.SortFunc, strings.Cut, range-over-int).

Closes CODAGT-627
Refs CODAGT-256
Refs CODAGT-682
2026-06-30 18:49:50 +03:00
Nick Vigilante 89b0a66079 docs: add top-level Get started section and move the Quickstart (#26821)
Add a top-level "Get started" docs section to the nav and move the Quickstart to /docs/get-started, with inbound link updates and the install page TIP pointing to the Quickstart.

Filed via Coder Agents on Nick's behalf.
2026-06-29 16:07:10 -04:00
TJ 5f42bbcdbf feat(site/src): nest agent pages under a Coder Agents subsection in AI nav (#26667)
Groups the agent-related AI settings pages under a new **Coder Agents**
parent in the sidebar, with a continuous left rule connecting the
children and an active-segment indicator that lights up the rule where
the current sub-item sits.

The new nav order:

- AI Governance
- AI Gateway keys
- Providers
- Coder Agents
  - Models
  - MCP servers
  - Templates
  - Spend
  - Instructions
  - Lifecycle

All target pages already exist on main (Danielle's recent migrations of
Models, MCP servers, Templates, Instructions, Lifecycle, Spend, and
Coder Agents into AI Settings). This PR only changes the sidebar visual
structure: the children move into an indented group with a `border-l
border-l-border` rule, and the active child paints a
`border-l-content-primary` segment over that rule via `-ml-px` so the
rule and indicator share a column instead of stacking.

<details>
<summary>Design notes</summary>

Concept 1 from the earlier exploration: always-expanded with indents,
the parent is its own page. Chosen because it adds no expand/collapse
state, no "which child is the default" question, and no animation work;
the parent reuses the existing nav-item, and the children sit in a
wrapper `div` with a left rule. The site bundle ships without Tailwind's
preflight, so the wrapper and sub-item borders are paired with
`border-solid` to actually paint, matching the pattern already in
`Sidebar.tsx`.

</details>

---

_This PR was prepared by Coder Agents on behalf of @tracyjohnsonux._
2026-06-29 13:46:09 +00:00
Ben Potter 73cd34cc5f fix: correct MCP registry remote URL in server.json (#26755)
The MCP Registry rejects our `server.json` remote because the URL uses
`{coder_url}` as the entire base. Registry validation requires remote
URLs to literally begin with `https://`, and template variables are only
allowed after the scheme/host. The previous value
(`{coder_url}/api/experimental/mcp/http`) fails both the JSON schema
`^https?://[^\s]+$` pattern and the semantic remote-URL check.

## Changes

- Use `https://{coder_hostname}/api/experimental/mcp/http` with a
`coder_hostname` variable (users now enter a hostname like
`coder.example.com` instead of a full URL).
- Update the VS Code registry instructions in
`docs/ai-coder/mcp-server.md` to ask for the deployment hostname.

Verified with `mcp-publisher validate` against
`registry.modelcontextprotocol.io`:

```
Validating against https://registry.modelcontextprotocol.io...
 server.json is valid
```

This was caught by running the `Publish to MCP Registry` workflow in
validate-only mode (`publish: false`) before any real publish, so
nothing broken reached the public registry.

<details>
<summary>Root cause detail</summary>

The registry validator (`internal/validators`) substitutes known
template variables, then parses the URL. Because `{coder_url}` replaces
the whole scheme+host, the parsed URL has no scheme and is rejected as
an invalid remote URL. Hard-coding `https://` and scoping the variable
to the host satisfies both the schema pattern and `IsValidRemoteURL`
(which also requires `https`). The registry mandates `https` for remotes
regardless, so there is no loss of functionality.

</details>

---
_Generated with Coder Agents._
2026-06-26 16:32:32 +00:00
Atif AliandBen Potter 18efcb6c41 feat: publish Coder MCP server to official MCP Registry (#21673)
## Summary

This adds the necessary configuration to publish Coder's remote MCP
server to the official MCP Registry at registry.modelcontextprotocol.io.

## Changes

- **`server.json`**: MCP server metadata for registry discovery
- **`.github/workflows/publish-mcp-registry.yaml`**: GitHub Actions
workflow to automatically publish on release

## How it works

1. When a new Coder release is published, the workflow automatically
publishes to the MCP Registry
2. MCP clients (Claude, ChatGPT, VS Code, etc.) can discover Coder via
the registry
3. Users just need to provide their Coder deployment URL - OAuth handles
authentication automatically via RFC 7591 Dynamic Client Registration

## MCP Registry Entry

The server will be listed as `io.github.coder/coder` with:
- **Transport**: `streamable-http` 
- **Endpoint**: `{coder_url}/api/experimental/mcp/http`
- **Auth**: OAuth2 (automatic via
`/.well-known/oauth-authorization-server`)

## Testing

After merge and next release, verify at:
```bash
curl "https://registry.modelcontextprotocol.io/v0.1/servers?q=io.github.coder"
```

Closes #21275

---
_Generated with `mux` • Model: `anthropic:claude-opus-4-5` • Thinking:
`medium`_

---------

Co-authored-by: Ben Potter <me@bpmct.net>
2026-06-26 11:20:45 -05:00
Mathias Fredriksson 59fcc9c0ad feat: improve sub-agent orchestration tools (#26673)
Tool errors caused orchestrators to abandon spawned agents. Bare error
responses and the close_agent name framed delegation as one-shot: one
transient failure or timeout ended the work, and the orchestrator had no
way to recover or reuse agents.

Renames close_agent to interrupt_agent with a hidden backward-compatible
alias. wait_agent and message_agent return structured payloads instead
of bare errors, so the orchestrator can retry after a timeout, recover
from an error status, or redirect an idle agent. Adds list_agents so
orchestrators can rediscover spawned agents. Adds root-only
orchestration guidance for error recovery.
2026-06-26 13:41:43 +03:00