Commit Graph
330 Commits
Author SHA1 Message Date
Yevhenii ShcherbinaandSusana Ferreira 80c2621f9d docs: document missing AI model price notifications (#28775)
Documents the weekly **Missing AI Model Prices** notification, its
recipients, limits, and delivery defaults.

Follows up on #28419.

---

Created by Coder Agents on behalf of @evgeniy-scherbina.

---------

Co-authored-by: Susana Ferreira <susana@coder.com>
2026-09-10 12:38:15 +00:00
Hugo Dutka 8e3c36ec5a fix: standardize org use in the mcp server tools (#29141)
Addresses
https://linear.app/codercom/issue/CODAGT-970/expose-mcp-tools-for-organization-selection.

Currently our MCP server does not handle organizations consistently.
Some tools, like `create_template`, use a random organization if the
user is in multiple orgs. Others, like `create_chat`, pick the
organization which contains the latest chat the user spawned.

This PR standardizes organization use in the MCP server tools.
Organization ID is now in the argument schema of all tools that depend
on it. It's always optional. If the user is only a member of one
organization, tools default to that organization. If the user is a
member of multiple organizations, tools return an error asking to supply
an organization id.

This PR also adds a new `list_organizations` tool to allow MCP clients
to view the organizations that the user has membership in.
2026-09-10 11:48:08 +02:00
Ethan d8e3f4fcf7 feat: evict the oldest attachments at the chat file cap (#29063)
Closes CODAGT-933

Long agent sessions were hitting the 50 attachment cap, after which
every upload, screenshot and `attach_file` call was rejected, so people
were abandoning otherwise healthy chats.

Rather than raise the cap (which just moves the cliff and multiplies the
worst-case per-chat `bytea` storage), a chat now keeps its 50 most
recent attachments. `LinkChatFilesAfterLock` deletes the oldest
`chat_files` rows in the same statement and the cascade drops their
links. Files in the incoming batch are never evicted, so the only
remaining rejection is a single message with more than 50 files.

Nothing in the product ever linked one file to two chats, so rather than
guard the eviction against it, this adds `UNIQUE (file_id)` on
`chat_file_links`, with the migration dropping any existing duplicates
in favour of the oldest chat.

Evicted attachments render as the existing "Attachment expired" tile. A
`pinned` flag is the obvious follow-up if someone needs to keep a
specific file around.
2026-09-10 13:40:16 +10:00
Paweł Banaszewski 8472a6884f chore!: remove env-based AI provider configuration (#29053)
> AI tools were used to create this PR

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

**Breaking change:** Remove [obsolete AI provider CLI flags and YAML
keys](https://coder.com/docs/ai-coder/ai-gateway/providers#database-management-of-providers)
before upgrading, otherwise Coder will fail to start with an `unknown
flag` or `unknown option` error. Provider environment variables are
ignored and no longer seed the database. Existing database-stored
provider configuration is preserved.
2026-09-09 10:16:24 +02:00
Cian Johnston 760fd15e21 docs: add detail on testing bedrock provider with curl (#29077)
Adds directions on testing a Bedrock provider through AI Gateway via `curl`.
2026-09-08 17:59:05 +01:00
Nick Vigilante 7846490770 docs: reconcile H1/label mismatches into front-matter titles (Phase 3) (#28036)
## Summary

**Batch B of Phase 3** of the H1 → front-matter migration (`DOCS-484`;
parent `DOCS-477`), the editorial follow-up to Batch A (#28030). For the
**124** hand-authored pages whose leading body H1 differed from the
manifest nav label, this promotes the richer body H1 to the front-matter
**page title** and drops the duplicate H1, while keeping the short
manifest **label** as the sidebar entry.

Policy agreed with the docs owner:
- Short sidebar labels win. Duplicate sidebar labels are acceptable.
- Identical **page titles** across two pages are not. On a collision,
rename the non-generated page's title.

## Page-title collisions resolved

Promoting the H1 created 4 page-title collisions; each is disambiguated
by renaming the non-generated / secondary page (sidebar labels left
unchanged):

| page | sidebar label | body H1 | → page title |
|------|---------------|---------|--------------|
| `install/index.md` | Install | Installing Coder | **Install Coder in
your infrastructure** |
| `install/cli.md` | Coder CLI | Installing Coder | **Install the Coder
CLI** |
| `ai-gateway/clients/jetbrains.md` | JetBrains | JetBrains IDEs |
**JetBrains** |
| `workspace-access/web-ides.md` | Web IDEs and Coder Apps | Web IDEs |
Web IDEs *(kept — primary user guide)* |
| `extending-templates/web-ides.md` | Web IDEs and Coder Apps | Web IDEs
| **Web IDEs in templates** |
| `workspace-management.md` | Workspace Management | Workspaces |
**Manage workspaces** *(vs generated `api/workspaces.md`)* |

These titles are the only non-mechanical editorial calls in this PR.

## Deliberately excluded: generated pages

`admin/security/audit-logs.md` and
`admin/setup/configuration-reference.md` are `make gen` outputs
(`auditdocgen` / `configdocgen`) that Phase 2 did **not** update, so a
hand-added title would be reverted on the next generation. They're
excluded here and need their generators taught to emit front matter
first (Phase 2 pattern), tracked as `DOCS-631`. Batch A (#28030) had the
same issue for three other generated pages; it has been corrected there
too.

## Verification

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

- Promote = set front-matter `title` to the body H1 (or the
disambiguated title above) and remove that one duplicate H1. No other
body prose is reflowed.
- Every added front-matter block parses as YAML; all files pass `pnpm
check-docs` (markdownlint-cli2 + table formatter): `Summary: 0
error(s)`.
- Removing the H1 orphaned one in-page fragment (`[MCP](#mcp)` in
`ai-gateway/mcp.md`), now repointed. A cross-file fragment audit into
the retitled pages found no real breakage.


Anchor-change note

Unlike Batch A (title unchanged, a rendered no-op), Batch B changes each
page's effective title from the manifest label to the body H1, so the
rendered H1 **anchor slug changes**. An audit of cross-file
`.md#fragment` links into these pages surfaced no links that break as a
result (the only hits were false positives against a still-present `##
TLS & Reverse Proxy` heading). Same-file fragments are enforced by
markdownlint MD051, which is green.

## Title casing (follow-up, DOCS-742)

A follow-up commit puts the promoted titles into sentence case and
removes leading gerunds (for example, `Managing workspace schedules` →
`Manage workspace schedules`): 57 of the 120 titles changed, the other
63 were already compliant. Proper nouns and branded names (Coder
Validated Architecture, JetBrains, File Browser, Dev Containers,
Island), acronyms (API, CLI, IDE, MCP, OIDC, URL, UI, CI/CD), the
Premium license tier, and maturity labels (Beta, Experimental) are
preserved. The four `Nk-users` pages become `Reference architecture: up
to N users` (lowercase, matching the CVA landing page's own usage); the
CVA landing page keeps its branded title. `pnpm check-docs`: `Summary: 0
error(s)`.

Linear: DOCS-484, DOCS-742

> This PR was created with AI assistance (Coder Agents).
2026-09-08 16:34:00 +00:00
Cian JohnstonandSas Swart e9946e81c5 feat: Add search to AI Gateway SessionTimeline (#28424)
This pull request:
- Wires debounced search into AI Gateway session details
- Filters prompts, tool calls, inputs, and network destinations
- Highlights matches and expands relevant content
- Reports matching events and loaded-data limitations

Stack details:
- #28422
- #28424 (this PR)

> Generated by Coder Agents on behalf of @johnstcn

---------

Co-authored-by: Sas Swart <sas.swart.cdk@gmail.com>
2026-09-08 16:38:29 +02:00
Yevhenii Shcherbina 93089d447f fix: resolve Bedrock application inference profile ARNs (#28877)
AWS recommends [application inference
profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/cost-mgmt-application-inference-profiles.html)
for attributing Bedrock spend to a team or workload, which requires
invoking Bedrock with the profile ARN as the `modelId`. AI Gateway used
the configured Bedrock model for both the invocation target and model
capability detection, and capability detection is substring matching
against model IDs. Application inference profile ARNs are opaque, so
they matched nothing.

Reproduced against a profile wrapping `anthropic.claude-opus-4-8`: the
client sent `thinking.type: "adaptive"`, the gateway rewrote it to
`enabled` + `budget_tokens` because the ARN did not look like an
adaptive-capable model, and Bedrock returned

```text
400 "thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.
```

Models that accept both shapes, such as Sonnet 4.6, did not fail but had
adaptive thinking silently downgraded. The ARN was also recorded as the
interception model, so those requests never matched a price and may
appear in the weekly Missing AI Model Prices report.

The gateway now resolves application inference profile ARNs through
`GetInferenceProfile` and uses the model behind them for capability
detection, usage records, pricing, and metrics, while still invoking the
profile so AWS records the cost attribution. Resolution runs only for
`application-inference-profile` ARNs, so plain model IDs and
system-defined inference profile ARNs, which already carry the model ID,
cost no AWS call and need no new permission. Deployments that do
configure a profile must grant `bedrock:GetInferenceProfile` to the
identity the gateway already uses, including any assumed role.
Resolution failure fails provider construction, matching how other
misconfigured providers behave: the failure is logged and the provider
is reported as errored rather than serving requests it would shape
incorrectly.

## Concerns

**Every provider reload re-resolves every application inference
profile.**

Any provider create/update/delete publishes on
`AIProvidersChangedChannel`, and each subscriber responds by rebuilding
its whole snapshot: `Reload` fetches all providers and
`BuildProvidersFromProto` constructs every one of them from scratch
before `ReplaceProviders` swaps the snapshot in.

That rebuild used to be purely local work. This PR makes it hit the
network: a Bedrock provider configured with an AIP ARN now performs a
synchronous `GetInferenceProfile` call during construction,
sequentially, before the snapshot is published. So editing an unrelated
OpenAI provider re-resolves every AIP in the deployment. Consequences:

- Reload latency grows with the number of AIP-configured providers,
bounded by the 30s resolution timeout per provider.
- A transient AWS failure during an unrelated provider edit drops the
Bedrock provider from the new snapshot until the next reload, surfacing
as a 404 for a provider whose configuration never changed.

An ARN-keyed resolution cache would remove this: the Bedrock API has no
`UpdateInferenceProfile`, so a profile's underlying model is fixed at
creation and repointing requires a new ARN, hence a config change and a
reload. A process-lifetime cache is therefore sound with no invalidation
logic. Left out of this PR to keep it scoped.

## Improvement Options

1. Keep it as is.
2. Add a per-process in-memory cache that maps AIP ARNs to models.
3. Add a database-level cache for AIP-to-model resolution.
4. Move AIP resolution to the per-LLM-request path and cache the result
there.

My choice would be either 3 or 4. See the relevant P1s:
- https://github.com/coder/coder/pull/28877#discussion_r3936255218
- https://github.com/coder/coder/pull/28877#discussion_r3936255211

Closes https://linear.app/codercom/issue/AIGOV-488

Created by Coder Agents on behalf of @evgeniy-scherbina.
2026-09-07 21:01:39 -04:00
Matt Vollmer eb9fe95308 docs(docs/ai-coder/agent-relay): update Cursor BYOM reference to Self-Hosted Machines (#28934) 2026-09-03 02:50:39 -04:00
Matt VollmerandNick Vigilante cb6c98147f docs: add Agent Relay docs (#28786)
## What this adds

Two new docs pages for **Agent Relay**, a feature that connects a
supported cloud-hosted AI agent provider's hosted sessions to
self-hosted Coder workspaces. The provider's orchestration and AI
inference stay cloud-hosted; a worker process inside the workspace
executes the agent's tool calls.

- `docs/ai-coder/agent-relay/index.md` — top-level overview: what it is,
what it does, what it is and isn't, business value, current state, and
supported providers.
- `docs/ai-coder/agent-relay/cursor.md` — the Cursor-specific child
page, naming Cursor Cloud Agents and Cursor's own bring-your-own-machine
(BYOM) terminology.

Both pages are tagged `"state": ["early access"]` in the manifest and
state the feature is in **closed preview with select customers**,
pointing readers to their Coder account team or `sales@coder.com` for
access.

## Also included

- `docs/user-guides/workspace-management.md`: broadened the workspace
definition to include coding agents alongside developers.
- `docs/reference/glossary.md`: added an Agent Relay entry (alphabetized
between Agent Firewall and AI Gateway) and added it to the existing
"agent" term-disambiguation callout, since it's easy to conflate with
Coder Agents.

## Scope note for reviewers

`Agent Relay` itself (the underlying service, config, and worker
implementation) lives in a separate, non-public repository. I don't have
access to that source from this environment, so I deliberately kept both
pages high-level and didn't invent specifics like CLI flags, config file
structure, or exact command syntax. Before this goes further, someone
with access to that repo should verify the mechanics described here
(workspace-per-session lifecycle, provider pool mapping, worker
connection model) against the real implementation, and a follow-up PR
should add a step-by-step "Getting started" section once the feature
moves past closed preview to something self-serve.

## Validation

- `docs/manifest.json` is valid JSON.
- `markdownlint-cli2`: 0 issues across all changed/added Markdown files.
- `vale --no-exit`: 0 errors on every changed/added file (a handful of
pre-existing gerund-heading warnings on `workspace-management.md` and
`glossary.md` predate this branch and aren't touched here).
- `scripts/check_emdash.sh`: passes.
- Confirmed every relative link target in the new pages resolves to a
real file in the repo.

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

- Dropped an "air-gap capable" claim and a "Coder AI Gateway" claim that
would have been present in an earlier draft: the integration requires
the in-workspace worker to hold an outbound connection to the cloud
provider for inference/orchestration, so true air-gapping isn't
possible, and Coder's AI Gateway isn't in the inference path for this
feature.
- Named the specific Cursor product as **Cursor Cloud Agents** and
linked Cursor's own "bring-your-own-machine (BYOM)" terminology
(`cursor.com/docs/cloud-agent/bring-your-own-machine`) rather than
inventing Coder-specific naming for the same concept.
- Kept "workspace" lowercase per the existing style guide (`workspace`
is the documented generic-concept casing, distinct from named features
like "Workspace Proxy"), while still linking the term to the Workspace
Management page.
- Used "closed preview with select customers" rather than "Preview," and
removed a blanket "not feature-complete or stable" disclaimer sentence
per explicit direction.

</details>

---

🤖 This PR was created by Coder Agents on behalf of @mattvollmer.

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-09-02 09:19:49 -04:00
blinkagent[bot]andblink-so[bot] 3d2cf5fcc6 docs: correct Coder Tasks deprecation version to v2.34 (#28764)
Co-authored-by: blink-so[bot] <211532188+blink-so[bot]@users.noreply.github.com>
2026-08-31 22:17:23 +05:00
Nick Vigilante bc77c40296 docs: add front-matter titles to mechanical and no-H1 pages (Phase 3) (#28030)
## Summary

**Batch A of Phase 3** of the H1 → front-matter migration (`DOCS-484`;
parent `DOCS-477`). Adds a front-matter `title` to every navigable docs
page whose title can be migrated **mechanically**, with no editorial
judgment.

This is the content step that Phase 1 (renderers prefer front-matter
title, `DOCS-482`) and Phase 2 (tooling + generators front-matter-aware,
`DOCS-483`) unblocked. Both are merged; coder.com #964/#974 are merged
and live.

**Rendered no-op.** The renderers already resolve the page title from
the manifest and hide the leading body H1 (Phase 1), so no page changes
visually. This just moves the title into front matter where Fumadocs and
the migrated tooling can read it.

## What's in this batch

Dry-run on `main` (464 navigable pages) splits into:

| category | count | this PR |
|----------|-------|---------|
| already has front-matter title (Reference, from Phase 2 generators) |
196 | skipped (idempotent) |
| **mechanical** — leading body H1 equals the manifest label | 138 | ✅
add front-matter `title`, drop the duplicate H1 |
| **no body H1** — renders under the manifest label only | 4 | ✅ add
front-matter `title` only |
| **mismatch** — body H1 differs from the manifest label | 126 | ⏭️
deferred (needs an editorial decision, see below) |

142 files changed, all under `docs/`.

## Deliberately out of scope: the 126 mismatches

Pages where the body H1 is richer than the short sidebar label (e.g.
label **Modules** / H1 *Contributing modules*, label **Install** / H1
*Installing Coder*) need a canonical-title decision, not a script. A few
even look like the body H1 is the redundant one (`install/cli.md` and
`install/index.md` both carry the H1 *Installing Coder*). These will
land in follow-up batches **by nav section** once the policy is set, so
each gets real review.

## Verification

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

- Every added front-matter block parses as YAML and its `title`
round-trips to the manifest label (checked programmatically across all
142 files).
- Every removed line is a leading `# H1` that equalled the manifest
title; no body prose was reflowed. Front matter is correctly hoisted
above pre-existing `<!-- markdownlint-disable -->` comments on the two
pages that had them.
- `pnpm check-docs` (markdownlint-cli2 + table formatter) passes on the
changed set: `Summary: 0 error(s)`. `MD041` stays off (re-enabled in
Phase 4); `MD025` is not tripped because the duplicate body H1s are
removed.

```
$ pnpm exec markdownlint-cli2 $(git diff --name-only origin/main)
Linting: 142 file(s)
Summary: 0 error(s)
```

Linear: DOCS-484

> This PR was created with AI assistance (Coder Agents).
2026-08-27 12:34:13 -04:00
Nick VigilanteandIan Evans 47a77016c4 feat(docs/.style): enable Coder.SelectClick, use "select" over "click" (#28599)
Adds a Vale rule enforcing the existing "select, not click" style
guidance: "click" assumes the reader has a mouse, and touch, keyboard,
and assistive-technology users don't click.

`Coder.SelectClick` (warning severity) flags
`click`/`clicks`/`clicked`/`clicking` in prose, exempting:

- Literal mouse-button phrasing (`left-click`, `right-click`,
`middle-click`, `mouse click`, and combinations) — these name an actual
mouse action with no device-agnostic equivalent.
- `one-click`/`single-click` as a compound feature descriptor
("one-click install").

Reworded every existing instructional "click" in `docs/` to the matching
`select` form (`select`/`selects`/`selections`/`selected`/`selecting`)
so the rule ships with a clean baseline, per this repo's Vale-rule
doctrine.

Left alone, deliberately: two generated API reference pages
(`docs/reference/api/enterprise.md`, `schemas.md`) use "click" as an
analytics-event noun, tied to a Go source doc comment and an operation
ID (`report-a-premium-paywall-click`). Fixing those means editing
generated code and an API operation ID, which is out of scope for a
docs-style PR — see the rule's own comments for the reasoning. That
leaves 2 non-zero-baseline findings for this rule.

---
🤖 Built with AI assistance.

---------

Co-authored-by: Ian Evans <5760366+ianjevans@users.noreply.github.com>
2026-08-27 16:24:06 +00:00
Michael Suchacz 9c42b14857 feat: add /clear chat context command (#24745)
> [!NOTE]
> Xum acted on Mike's behalf in this pull request.
<!-- xum-attribution: model=claude-fable-5 thinking=high -->

Adds a `/clear` slash command to Agents chats that resets the model
context without deleting anything: the transcript stays visible, and the
next prompt runs as if the chat were brand new. It mirrors `/compact`'s
UX (slash menu entry, exact-text interception, dedicated endpoint,
synthetic tool block in the transcript) but generates no summary and
makes no model call.

## How it works

`POST /api/experimental/chats/{chat}/clear` commits synchronously inside
the API transaction through a new `chatstate` transition,
`ClearContext`, allowed from `waiting` and from `error` without queued
messages (`W -> W`, `E0 -> W`). No worker round-trip, no status flicker
to `running`, no migration. Clearing an errored chat clears
`last_error`, and any pending manual compaction request is dropped
rather than left to run against the cleared context.

The endpoint persists the same compressed boundary shape `/compact`
uses: a hidden model-only sentinel row, a visible synthetic
`chat_cleared` tool call, and its result. Prompt assembly already
selects the latest compressed model-only row as the context cutoff, so
the query is unchanged. Boundary detection is generalized to recognize
both `chat_summarized` and `chat_cleared`, so `/compact` after `/clear`
(and the reverse) never reach across the newer boundary, and
auto-compaction does not fire off stale pre-clear usage.

Busy chats, errored chats with queued messages, and clears with no
conversation after the latest boundary return 409. Archived chats are
rejected. The endpoint is owner-only for symmetry with `/compact`.

## Frontend

`/clear` joins the slash command menu, and the previously compact-only
send interception becomes a small built-in command dispatch shared by
both commands, so a personal or workspace skill named `clear` still
takes precedence. Because the clear commits synchronously, the UI keeps
the chat in `waiting`, refetches on success, and surfaces conflicts with
the standard error toast. The transcript renders a "Context cleared"
card via a new `ChatClearedTool` renderer.

## Docs

The user-facing agents architecture page documents `/clear`.
`coderd/x/chatd/ARCHITECTURE.md` carries TODO notes in the affected
sections for the PR author to write.

## Tests

- `chatstate`: transition matrix entries plus dedicated `ClearContext`
coverage (error-state entry, queued-message rejection, boundary row
requirement).
- `chatd`: end-to-end manual clear (fresh next prompt, error recovery,
boundary interplay with compaction, stale-usage auto-compaction
regression, busy rejection) plus boundary and message-builder units.
- `coderd`: HTTP authorization and error mapping for the endpoint.
- Frontend: slash command availability and skill collision units,
stories for the submit path, the conflict toast, and the cleared-card
renderer.
2026-08-27 13:48:08 +02:00
Ethan 0f5c7b3154 refactor!: remove default organization model routes (#28632)
> [!IMPORTANT]
> Most of the added lines in this PR are generated API reference content
for publishing the organization-scoped `GET` and `POST
/api/v2/organizations/{organization}/chats/models` replacements. There
is no matching generated-doc deletion because the three removed
default-organization endpoints are experimental and are not present in
the generated public API reference on the current base. The removed
paths remain only as explicit 404 reservations, with no
default-organization shim or functional handler.

## Summary

Remove the unused default-organization chat model collection routes:

```text
GET  /api/experimental/chats/models
GET  /api/experimental/chats/model-configs
POST /api/experimental/chats/model-configs
```

Use the organization-scoped collection instead:

```text
GET  /api/v2/organizations/{organization}/chats/models
POST /api/v2/organizations/{organization}/chats/models
```

## Context

The intention of PR #28440 was to consolidate model availability into
the organization-scoped models collection for CODAGT-898 and remove the
superseded collection routes. That PR removed
`/organizations/{organization}/chats/models/available`, but it missed
these older default-organization routes and explicitly retained one of
them. This PR completes the intended #28440 cutover. The repository has
no SDK, CLI, or frontend consumer for the removed routes.

This change also prevents PR #28496 from promoting the missed
default-organization `/chats/models` route into the stable `/api/v2`
API.

This change is separate from the one-release `/api/experimental`
compatibility window in CODAGT-921. That window preserves experimental
versions of the intended stable API. It does not require compatibility
routes for unused deployment-scoped endpoints.

Refs CODAGT-898.

## Breaking change

Clients that call the removed routes must use the organization-scoped
model collection and provide an organization.

## Changelog

Remove unused default-organization Coder Agents model API routes. API
clients must use the organization-scoped chat models collection.

> [!NOTE]
> Coder Agents generated this pull request on Ethan Dickson's behalf.
2026-08-27 10:49:14 +01:00
Nick Vigilante 77743afdb8 docs: rewrite extending-agents MCP and skills discovery for pushed context (#28576)
This PR rewrites the MCP and skills discovery sections of
`docs/ai-coder/agents/extending-agents.md` to match the current
pushed-context architecture.

The page documented a removed mechanism: per-chat-turn `.mcp.json` reads
with a 5-second discovery timeout, first-turn scans of `.agents/skills/`
only, and no mention of pinning.

What changed:

- Adds a "How the workspace shares context with chats" section: the
agent scans and pushes a context snapshot, chats pin one snapshot, a
push marks already-pinned chats out of date, and **Refresh context**
re-pins. Explains why an in-flight chat can keep an older snapshot.
- Documents the readiness gate: only an empty snapshot is published
until startup scripts finish.
- Documents the scan roots (working directory, `~/.coder`,
`~/.coder/skills`, `~/.claude/plugins/cache`, user-declared sources) and
that discovery is shallow.
- Documents all four skill container directories (`skills`,
`.agents/skills`, `.claude/skills`, `.codex/skills`) instead of only
`.agents/skills`.
- Adds snapshot limits and failure modes: 64 KiB per resource emitted as
oversize with no content, 2 MiB aggregate and 500 resource caps emitted
as excluded, invalid skill frontmatter.
- Replaces the 5-second discovery claim with the 30-second per-server
connect timeout and the fsnotify watcher with a 250 ms debounce; notes
that tool calls are proxied through the agent, so a pinned chat can list
tools it cannot execute while the workspace is unreachable.
- Keeps the values that are still correct: 60 s per tool call,
`SKILL.md` <= 64 KB, supporting files <= 512 KB truncated, personal
skills single file <= 64 KB and <= 100 per user, `read_skill_file` path
restrictions.

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

<details><summary>Analysis evidence</summary>

Every claim was verified against code on this branch's merge base.

**Push and pin model**

- `agent/agentcontext/push.go`: `RunPush` ships the current snapshot and
every subsequent snapshot on change; it skips version 0 (pre-ready).
- `coderd/agentapi/context.go`: `PushContextState` persists the snapshot
and calls `ContextDirtyMarker.HydrateAndMarkChatsDirty` inside the
transaction; the doc comment states it "hydrates chats for the agent
that have no pinned hash yet ... and flips already-pinned chats whose
hash differs".
- `coderd/x/chatd/context_hydration.go`: `HydrateAndMarkChatsDirty`
stamps NULL-hash chats via `HydrateAgentChatsContext` and dirties
differing chats via `MarkChatsContextDirtyByAgent`; "The pinned hash on
dirtied chats is intentionally left unchanged; the refresh endpoint
re-pins it." `RefreshChatContext` backs `PUT /chats/{chat}/context`
(route registered in `coderd/coderd.go`), and
`site/src/pages/AgentsPage/components/ChatPageContent.tsx` wires the
**Refresh context** button to it. This confirms the pinning semantics
claim: a chat mid-turn keeps its older snapshot until refreshed.
- `coderd/x/chatd/chatd.go` (`resolveWorkspaceMCPTools` /
`pinnedWorkspaceMCPTools`) builds the turn's MCP tools from
`chat_context_resources`, and `coderd/x/chatd/context_prompt.go` builds
the instruction block and skill index from the same pinned rows. No
per-turn live discovery remains.

**Readiness gate**

- `agent/agentcontext/manager.go`: `resolveAndBroadcast` returns early
while `!m.ready`; `agent/agentcontext/doc.go` describes the version-0
empty snapshot. `agent/agent.go` calls `a.contextManager.SetReady()`
after the startup-script lifecycle transition, then reloads MCP servers.
(The gate lives on `agentcontext.Manager`, not `agentmcp.Manager`.)

**Scan roots and shallow discovery**

- `agent/agentcontext/manager.go` `scanRootsLocked`: user sources, then
`defaultBuiltinRoots()`, then the working directory.
- `agent/agentcontext/defaults.go`: built-in roots are `~/.coder`,
`~/.coder/skills`, `~/.claude/plugins/cache`.
- `agent/agentcontext/doc.go` and `resolve.go`: instruction files and
`.mcp.json` are read only at a scan root's top level; the resolver never
descends or climbs.

**Skills**

- `agent/agentcontext/resolve.go` `skillContainerRelPaths`: `skills`,
`.agents/skills`, `.claude/skills`, `.codex/skills`;
`skillContainersFor` also treats a root named `skills` as a container,
which is what makes `~/.coder/skills` work.
- `readSkillMeta`: frontmatter name must match the directory basename
and match `workspacesdk.SkillNamePattern` (`^[a-z0-9]+(-[a-z0-9]+)*$`),
otherwise `StatusInvalid`; oversize files get `StatusOversize` with no
payload.
- `coderd/x/chatd/chattool/skill.go`: `maxSkillMetaBytes =
workspacesdk.MaxSkillMetaBytes` (64 KiB), `maxSkillFileBytes = 512 *
1024` with truncation, `validateSkillFilePath` rejects absolute paths,
`..`, and hidden components. `loadPinnedWorkspaceSkillContent` serves
the body from the pin; `bestEffortSkillFiles` needs a live connection.
- `coderd/x/skills/skills.go`: `MaxPersonalSkillSizeBytes` = 64 KiB,
`MaxPersonalSkillsPerUser` = 100.

**Caps**

- `agent/agentcontext/resolve.go`: `DefaultMaxResourceBytes` 64 KiB
(oversize, empty payload), `DefaultMaxSnapshotBytes` 2 MiB and
`DefaultMaxResources` 500 (excluded, payload cleared).
`coderd/x/chatd/context_prompt.go` `pinnedContextResources` surfaces
non-OK rows with status and error.

**MCP timeouts and watcher**

- `agent/x/agentmcp/manager.go`: `connectTimeout = 30 * time.Second`,
`toolCallTimeout = 60 * time.Second`. No 5-second discovery timeout
exists anywhere in `coderd/x/chatd` or `agent/x/agentmcp`.
- `agent/x/agentmcp/configwatcher.go`: `defaultWatchDebounce = 250 *
time.Millisecond`; the watcher fires on create, write, remove, and
rename. `agent/agentcontext/watcher.go` uses the same 250 ms window.
- `agent/agent.go`: `a.mcpManager.SetOnReload(a.contextManager.Trigger)`
re-resolves and re-pushes when the catalog changes; the shared engine
owns one connection set for discovery and execution.
- `coderd/x/chatd/chattool/mcpworkspace.go`: tool calls proxy back
through the agent connection, so execution requires a reachable
workspace.

**Validation**

- `pnpm install --frozen-lockfile`, `pnpm run format-docs` (no changes),
`pnpm run lint-docs` (0 errors), `vale` on the page (0 errors; 1
pre-existing `Coder.GerundHeading` warning on the untouched H1).

</details>

Generated by Coder Agents on behalf of @nickvigilante.


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

The CI run for commit a60db5adee concluded with `startup_failure`
(workflow never started; runner infrastructure), marking Flake Check,
Storybook, and gen as failed on a markdown-only change. Unrelated to the
changed paths; both runs re-triggered.

</details>
2026-08-26 21:32:42 +00:00
TJandMichael Suchacz 78c65ea556 feat: reposition org pickers in AI settings models and MCP pages (#28564)
Repositions the organization picker on the AI settings models and MCP
servers pages so it lives with the content it scopes instead of floating
above the page header.

**Models** (`/ai/settings/models`)

- The picker moved out of `OrganizationModelsLayout` into a shared
`ModelOrganizationSelect` component that preserves the current path and
auxiliary query params when switching orgs.
- List page: rendered in the filter row to the right of search.
- Add/edit model form: rendered as row 3 of the form grid at 50% width,
labeled "Organization". On the edit page it is informational only (a
static value, not a picker), since switching org there would 404 the
model. Also rendered in the no-provider fallback and "Provider not
found" states so the switcher never disappears on those pages.

**MCP servers** (`/ai/settings/mcp-servers`)

- List page: new client-side search input (matches display name, slug,
and URL) with the org picker beside it, label hidden.
- Add/edit server form: the picker moved into the form as the third cell
of the first row (slug, display name, organization), making it a 3-up.
- `OrganizationPicker` now renders a static read-only value instead of a
disabled button when the org cannot be changed (no handler or single
org). This fixes the muted `content-disabled` text on the update page.
The read-only rendering is shared with the models edit page via a new
`OrganizationValue` component beside `OrganizationAutocomplete`.

**Status columns** (both list tables)

- The visible "Status" header and the Enabled/Disabled badges are
removed; both list tables drop the status column entirely. Models whose
provider is deleted or disabled show a warning "Unavailable" badge (with
an explanatory tooltip) beside the name.
- Disabled models and MCP servers show a "Disabled" badge beside the
name, matching the existing "Default" badge placement, and the row dims
like disabled providers: avatar/icon at half opacity, text in
`content-disabled`.

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

- `ModelOrganizationSelect` reuses `OrganizationAutocomplete` and reads
accessible organizations from the models context
(`accessibleOrganizations` added to `OrganizationModelsContext`), rather
than duplicating the layout's navigation logic per page.
- Navigation semantics are unchanged: switching orgs rewrites the `org`
search param and preserves the path and remaining params, exactly as the
old layout-level picker did.
- The MCP `OrganizationPicker` read-only state uses an `<output>`
element (labelable, keeps the `Label` association) rather than a
disabled button, so non-interactive values do not render with disabled
styling or sit in the tab order.
- The add MCP server page keeps a standalone picker above the "cannot
add servers" alert since the form (and its picker slot) is not rendered
in that state.
- Story review: one interaction story per new behavior. A
`ModelsPageView` story duplicating the shared picker's
select-and-navigate flow was deliberately dropped; list-page placement
is covered by the `OrganizationModelsLayout` stories that mount the real
`ModelsPage`. The `ModelForm` fallback-branch picker has no dedicated
story since its sibling branch and the shared flow are covered.

</details>

Verification: `pnpm lint:types`, `pnpm check`, and all affected
Storybook tests pass (ModelsPage and MCPServersPage: 140), plus the
`organizationModels` and `mcpServerFormLogic` unit tests.

---

🤖 This PR was generated by Coder Agents on behalf of @tracyjohnsonux.

---------

Co-authored-by: Michael Suchacz <203725896+ibetitsmike@users.noreply.github.com>
2026-08-26 12:14:47 -07:00
Michael Suchacz 35cbca080e feat: allow sharing MCP servers with users and groups (#28593)
## Summary

Adds the missing user-facing half of MCP server config ACLs: admins can
now share an MCP server with individual users and groups from the UI,
backed by a new permission-safe candidate-discovery endpoint.

## Problem

The MCP server config ACL backend already existed (share RBAC action,
hydrated `GET .../acl`, sparse `PATCH .../acl`), but there was no
frontend for it. There was also no way to populate a sharing
autocomplete without the generic organization member/group APIs, which
require `organization_member:read` and `group:read` and would wrongly
couple MCP sharing to the workspace-sharing mode (the same bug fixed for
chat models in #28542).

## Changes

Backend:

- New v2-only `GET
/api/v2/organizations/{organization}/mcp-servers/{mcpserverconfig}/acl/available`
returning `codersdk.ACLAvailable`; because this API is new, it is not
mounted under the experimental compatibility prefix. Gated on
`ActionShare` for the specific server config; performs bounded
org-scoped member/group lookups via `dbauthz.AsSystemRestricted`;
excludes system users; supports `q`, `limit`, `offset`, and `after_id`
with template/chat-model autocomplete semantics.
- Tests cover authorization (404 without share), search, pagination,
system-user exclusion, org scoping, and a share-only custom role under
all three workspace-sharing modes (`none`, `service_accounts`,
`everyone`).

Frontend:

- `shareMCPServerConfig` permission plumbing; the MCP servers list,
details page, and AI settings sidebar now admit share-only users (share
does not require update; share-only users cannot edit the server form).
- Share-only access follows the established permission contract: a
bare-share role manages sharing through the list and ACL endpoints (the
detail route still requires read, update, or delete, matching the
existing enterprise permission-matrix tests), and the disabled-config
gate now also admits the share permission so a sharer with read access
can open a disabled server. Top-level navigation (Admin settings menu
and the /ai/settings index redirect) discovers organization-level MCP
sharers and surfaces permission lookup failures instead of silently
falling back.
- "Share server" action on the MCP server edit page opening a sharing
dialog: hydrated ACL grants render from the `GET .../acl` response,
adds/removals are saved as sparse `PATCH` deltas (`"read"` / `""`).
- Principal autocomplete backed exclusively by the new `/acl/available`
endpoint; the sharing flow never calls the generic org member/group APIs
(Storybook enforces this by rejecting those API spies). A discovery
error surfaces under the autocomplete without hiding existing grants.
- Storybook interaction coverage for the dialog (hydrated rendering,
add/remove, sparse deltas, error/cancel/reopen paths, autocomplete
exclusion and failure) and share-only access to the page/form.

Dogfood UAT ran remotely against a dev instance and passed, including
verifying via the network log that candidate discovery only hits
`/acl/available`. The share-only custom role UI flow could not be
exercised there (no premium license on the dev instance); it is covered
by the backend permission-matrix tests.

> 🤖 This PR was authored by Xum (an AI coding agent) acting on Mike's
behalf.
2026-08-26 19:49:43 +02:00
Nick Vigilante 8afd0020ea docs: fix chat status names and auto-archive behavior claims (#28570)
Two Coder Agents pages describe chat statuses that no longer exist and
attribute auto-archive to the wrong subsystem. The valid status set is
`waiting`, `running`, `error`, `requires_action`, `interrupting`.

- `architecture.md`: a submitted prompt marks the chat `running`, not
`pending`; there is no queued state.
- `chat-auto-archive.md`: the excluded status set is `running`,
`interrupting`, `requires_action`.
- `chat-auto-archive.md`: the job runs in the chatd chat worker on an
hourly tick, not in `dbpurge`.
- `chat-auto-archive.md`: documents the dashboard control at **AI
Settings** > **Coder Agents** > **Lifecycle**, and the 25-title cap on
the digest notification.

API paths on the auto-archive page are intentionally untouched; a
separate PR fixes the `/api/v2` to `/api/experimental` drift.

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

<details><summary>Analysis evidence</summary>

- `codersdk/chats.go`: `ChatStatus` constants are `waiting`, `running`,
`error`, `requires_action`, `interrupting`. No `pending`, `paused`, or
`completed`.
- `coderd/x/chatd/chatstate/transitions.go`:
`sendMessageQueueAndSetStatus` and the send paths apply
`database.ChatStatusRunning`, so a submitted prompt is `running`
immediately. `docs/ai-coder/agents/tasks-to-chats-migration.md` already
states that chats have no separate queued state.
- `coderd/database/queries/chats.sql`,
`GetAutoArchiveInactiveChatCandidates`: `status NOT IN ('running',
'interrupting', 'requires_action')`, plus `archived = false`, `pin_order
= 0`, `parent_chat_id IS NULL`.
- `coderd/x/chatd/auto_archive.go`: `archiveLoop` runs from
`coderd/x/chatd/worker.go` on `opts.ArchiveInterval`;
`coderd/x/chatd/options.go` sets `defaultArchiveInterval = time.Hour`.
Nothing in `dbpurge` performs chat auto-archive.
- `coderd/x/chatd/auto_archive.go`: `chatAutoArchiveDigestMaxChats =
25`; `buildAutoArchiveDigestData` truncates to 25 titles and reports the
remainder as `additional_archived_count`.
- `coderd/x/chatd/options.go`: `defaultArchiveBatchSize = int32(1000)`,
so the existing "up to 1,000 root chats" claim stands.
- `site/src/pages/AISettingsPage/LifecyclePage/LifecyclePageView.tsx`
mounts `AutoArchiveSettings`;
`site/src/modules/management/AISettingsSidebarView.tsx` places the
Lifecycle sub-nav item under Coder Agents.

Validation: `pnpm run format-docs` (no changes) and `pnpm run lint-docs`
(0 errors).

</details>

Generated by Coder Agents on behalf of @nickvigilante.
2026-08-26 11:36:36 -04:00
Mathias Fredriksson 6093705476 fix: use old_text/new_text vocabulary across edit_files (#28626)
The schema has advertised old_text/new_text since #25658, but agent
error strings and hints still said "search string", directing the
model toward field names it is not sending.

Fixes CODAGT-523
2026-08-26 18:35:27 +03:00
Michael Suchacz 351bb14032 feat: mount chat API routes under /api/v2 (#28496)
## Stack context

This is the base of a 3-PR stack promoting the chat API from
`/api/experimental` to `/api/v2`: server compatibility mounts (this PR),
codersdk promotion (#28497), and frontend path updates (#28498).

## Summary

Double-mount the stable chat and MCP handlers under `/api/v2` while
retaining the existing experimental routes for the one-release
compatibility window decided in CODAGT-921. CODAGT-922 tracks removing
the compatibility mounts.

The shared route builders preserve existing authentication and
middleware behavior. Experiment-gated, debug, tombstone, and legacy
default-organization model routes remain experimental-only. Signed file
URLs, external OAuth callback URLs, and mixed-version replica relays
also remain on the experimental prefix during the transition.

Update Swagger and the generated API reference for the promoted routes,
including the workspace lookup and a runnable raw-body chat file upload
example. Retain internal endpoints outside the published reference,
share chat-file rate limits across both prefixes, enable CORS for the v2
MCP routes, and cover dual mounts plus exclusions with compatibility
tests. Remote dogfood UAT passed for the promoted chat, model, MCP, and
file flows.

> [!NOTE]
> Xum acted on Mike's behalf in this pull request.
<!-- xum-attribution: model=claude-fable-5 thinking=high -->
2026-08-26 16:17:06 +02:00
Michael Suchacz 845790e652 feat: enable Coder Agents for organization members (#28186)
## Summary

- make Coder Agents available to organization members without a separate
built-in role
- remove the obsolete role from backend and frontend role surfaces
- update authorization, UI, documentation, and regression coverage

## Database note

This PR intentionally ships no migration so it backports cleanly across
diverged migration numbers. Stale `agents-access` grants may remain in
user role arrays and org default member roles; the retired name is
treated as a grant of nothing (role expansion drops it, assignment
validation ignores it, and the name stays reserved). A follow-up PR will
add the data cleanup migration.

## Validation

- `make gen`
- `make lint`
- repository pre-commit checks
- targeted RBAC, migration, chat API, enterprise, site, Storybook, and
race tests
- `git diff --check`

## Rollback note

Rolling back the deployment restores the previous behavior directly: no
data changed, and older binaries still resolve any lingering
`agents-access` grants.

> Mux created this pull request on Mike's behalf.
2026-08-26 13:33:13 +02:00
Susana Ferreira 56c614422e fix: clarify AI provider collision warnings (#28549)
AI provider collision warnings were only partially asserted, and the
update coverage did not exercise a provider changing from a distinct
hostname to a colliding hostname.

Assert the complete warning consistently across create, get, list, and
update responses, cover collisions introduced by base URL and
enabled-state updates, and only return the proxy-specific warning when
AI Gateway Proxy is enabled. Clarify that lifecycle status values are
reported by the provider metrics.

Follow-up to #28208.

> [!NOTE]
> Generated by Coder Agents for @ssncferreira.
2026-08-26 11:12:33 +01:00
Nick Vigilante ce59a86a81 docs: fix Coder Agents tool tables, search filters, attachments, template ranking (#28575)
Corrects four independent factual errors in the Coder Agents
documentation, each verified against the current implementation.

- **Missing tools in the tool tables.** `stop_workspace` was absent from
the built-in tool table in `docs/ai-coder/agents/index.md` and the
platform tool table in `docs/ai-coder/agents/architecture.md`, and from
the root-chat-only tool list. `find_tools` was undocumented entirely;
both docs now list it with its `mcp-tool-search` experiment gating.
- **Missing `source:` search filter.**
`docs/ai-coder/agents/chat-search-syntax.md` documented every chat
filter except `source:`, while also stating that unrecognized keys
return HTTP 400. Adds the filter row and an example.
- **Attachments described as images only.** The attachments section
claimed PNG, JPEG, GIF, and WebP up to 10 MB. The upload allowlist also
accepts plain text, Markdown, CSV, JSON, and PDF; the cap is 10 MiB per
upload with at most 50 attachments per conversation, and Anthropic
models cap inline images at 5 MiB. Also notes that providers differ in
accepted file types and that rejected parts are downgraded to text.
- **Template ranking described as popularity sort.**
`docs/ai-coder/agents/platform-controls/template-optimization.md` said
templates are sorted by active developer count. `list_templates` ranks
by query relevance tiers first, then by an affinity score that weights
the user's own recent usage far above organization popularity. Wording
now matches `docs/ai-coder/agents/tools/index.md`, which already
documents the formula, and links to it.

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

<details><summary>Analysis evidence</summary>

| Claim | Source |
|-------|--------|
| `stop_workspace` is a root-chat platform tool registered alongside
`create_workspace` and `start_workspace` |
`coderd/x/chatd/chattool/stopworkspace.go`; registration in
`coderd/x/chatd/chatd.go` (`chattool.StopWorkspace`), root-only gate in
`builtinPlanToolAllowed`, disabled for explore sub-agents in
`allowedExploreToolNames` |
| `find_tools` requires the `mcp-tool-search` experiment and deferrable
MCP candidates | `coderd/x/chatd/chattool/findtools.go`;
`decideMCPToolSearch` in `coderd/x/chatd/mcp_tool_search.go` returns
false without `codersdk.ExperimentMCPToolSearch` or with no candidates;
wired in `coderd/x/chatd/generation_preparer.go` |
| `source:` accepts `created_by_me` and `shared_with_me`; passing both
returns owned plus shared; default is owned only |
`coderd/searchquery/search.go` (`Chats`): filter defaults to `OwnedOnly:
true`; the `source` parser rejects any other value, and both values
together set `OwnedOnly` and `SharedOnly`. The literal value `all`
appears in the doc comment but is not accepted by the parser, so it is
not documented. |
| Attachment allowlist, size caps, and per-conversation limit |
`codersdk/chats.go`: `AllChatAttachmentMediaTypes` covers
`application/json`, `application/pdf`, `image/gif`, `image/jpeg`,
`image/png`, `image/webp`, `text/csv`, `text/markdown`, `text/plain`;
`MaxChatFileSizeBytes = 10 * 1024 * 1024`; `MaxChatFileIDs = 50`;
`AnthropicInlineImageCapBytes = 5 * 1024 * 1024` |
| Anthropic and Bedrock share the inline image cap; rejected file parts
are downgraded to text | `coderd/x/chatd/chatprovider/chatprovider.go`:
`InlineImageCapBytes` and `Model.AcceptsFilePartMediaType` |
| Template ranking is relevance tiers then a composite affinity score |
`coderd/x/chatd/chattool/listtemplates.go`: `rankTemplates` sorts by
query score first; `computeAffinityScore` adds recency-decayed personal
usage at `listTemplatesPersonalWeight = 10.0` to `ln(1 +
active_developers)` at `listTemplatesOrgWeight = 1.0` |

Note: `MaxChatFileIDs` is enforced per chat, not per message
(`coderd/exp_chats.go`: "A chat can reference at most %d attachments"),
so the docs say per conversation.

Validation: `pnpm run format-docs` and `pnpm run lint-docs` both pass (0
errors). The formatter widened the touched tables, which accounts for
the reformatted rows in the diff.

</details>

Generated by Coder Agents on behalf of @nickvigilante.
2026-08-25 15:13:21 -04:00
Nick Vigilante 06c0d3918a docs: correct plan mode MCP tool availability (#28569)
`docs/ai-coder/agents/index.md` claimed that MCP tools are blocked in
plan mode. Root plan-mode chats actually receive external MCP tools for
each server configuration an administrator approved for plan mode; only
workspace MCP tools and plan-mode sub-agents get none.

Corrects the plan-mode tool-availability wording in both places it
appears in `index.md` so it matches
`docs/ai-coder/agents/architecture.md` and the implementation. The tool
table and attachment wording are out of scope here.

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

<details><summary>Analysis evidence</summary>

`coderd/x/chatd/chatd.go`, `filterExternalMCPConfigsForTurn`: in plan
mode, a chat with a parent gets no external MCP configs ("Plan-mode
subagents do not receive external MCP tools"); a root chat keeps every
config whose `AllowInPlanMode` flag is set and returns those IDs as
approved.

`coderd/x/chatd/generation_preparer.go`: the returned
`approvedPlanMCPConfigIDs` flows into `filterToolsForTurn` and
`activeToolNamesForTurn`, so approved external MCP tools remain exposed
for the turn.

`coderd/x/chatd/chatd.go`, `toolAllowedForTurn`: in plan mode a tool
passes only if it is on the built-in plan allowlist or is an MCP tool
whose `MCPServerConfigID()` is in the approved set. Workspace MCP tools
are not in the external config set, so they stay unavailable.

`docs/ai-coder/agents/architecture.md` already documents this behavior;
`index.md` now uses the same framing.

</details>

Generated by Coder Agents on behalf of @nickvigilante.
2026-08-25 19:02:35 +00:00
Nick Vigilante b146e6f262 docs: align Coder Agents docs with GA framing and licensing terms (#28571)
Removes early-access-program framing from the Coder Agents docs, drops a
stale `early access` manifest tag, and standardizes the licensing
wording on "Premium license with the Agent Hours entitlement".

- `docs/ai-coder/agents/getting-started.md`: replaces the "collaborative
evaluation between your team and Coder" and customer-specific Slack
channel feedback path with GitHub issues plus normal Coder support
channels, and rewrites the remaining evaluation-period wording to GA
tone. Rollout guidance (pilot group, cost planning, concurrency) is
kept.
- `docs/manifest.json`: removes `"state": ["early access"]` from
`ai-coder/agents/platform-controls/chat-debug-logging.md`, which is not
experiment-gated.
- Licensing terminology aligned across `getting-started.md`,
`licensing-usage.md`, and `platform-controls/index.md`.

No changes to `docs/reference/api/**` and no API path changes.

<details><summary>Analysis evidence</summary>

**Manifest state tag decisions (all `ai-coder/agents` pages)**

| Page | Tag before | Tag after | Why |
|------|-----------|-----------|-----|
| `platform-controls/chat-debug-logging.md` | `["early access"]` | none
| Routes at `coderd/coderd.go` (`GET`/`PUT /debug-logging`, `GET`/`PUT
/user-debug-logging`) sit outside any `RequireExperimentWithDevBypass`
group, there is no matching experiment in the `codersdk.Experiment`
list, and the page body already states the feature is not
experiment-gated. |
| `platform-controls/advisor.md` | `["early access"]` | unchanged |
Gated by `codersdk.ExperimentChatAdvisor` (`chat-advisor`); routes
wrapped in `RequireExperimentWithDevBypass`. |
| `platform-controls/virtual-desktop.md` | `["early access"]` |
unchanged | Gated by `codersdk.ExperimentChatVirtualDesktop`
(`chat-virtual-desktop`); routes wrapped in
`RequireExperimentWithDevBypass`. |
| `platform-controls/spend-management.md` | `["premium"]` | unchanged |
`premium` is a licensing tag, not a maturity tag, and the page states
budget endpoints require a license that includes AI Gateway. Flagging
for awareness rather than changing it. |
| All other `ai-coder/agents` pages | none | none | No maturity tags to
review. |

**Licensing mechanics**

`enterprise/coderd/license/license.go` decodes
`agent_runtime_hours_allocation`, `agent_runtime_hours_limit_soft`, and
`agent_runtime_hours_limit_hard` into
`codersdk.FeatureAgentRuntimeHours` on Premium licenses.
`enterprise/coderd/x/chatd/agentadmission.go` lifts the concurrency cap
only when that feature is enabled and usage is below the hard limit. So
the entitlement, not the license tier alone, is what removes the cap.
Wording is now "Premium license with the Agent Hours entitlement".

`licensing-usage.md` keeps "Agent Time" as the name of the measured
usage metric (matching `runtime_ms` reporting) and now says explicitly
that Agent Time draws down the Agent Hours entitlement. Renaming the
metric itself was left out of scope; flagging in case the product team
wants one name for both.

**Validation**

`pnpm install --frozen-lockfile`, `pnpm run format-docs` (no table
changes), `pnpm run lint-docs` (499 files, 0 errors).

</details>

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

Generated by Coder Agents on behalf of @nickvigilante.
2026-08-25 13:10:03 -04:00
Nick Vigilante 827c11f43a docs: update Coder Agents admin navigation to AI Settings (#28572)
## Summary

Fixes stale admin navigation on the three Coder Agents platform-controls
pages not covered by #28482: the retention pages pointed at tabs that do
not exist ("Behavior", the old Agents settings "Lifecycle" tab), and
template optimization pointed at the removed **Agents** > **Settings** >
**Manage Agents** navigation.

Breadcrumbs follow the **Admin settings** > **AI** > **Coder Agents**
convention established by #28482.

## Changes

- `docs/ai-coder/agents/platform-controls/chat-retention.md`: replace
the nonexistent **Behavior** tab with **Admin settings** > **AI** >
**Coder Agents** > **Lifecycle**.
- `docs/ai-coder/agents/platform-controls/chat-debug-retention.md`: same
page, same convention, aligned with chat-retention.md.
- `docs/ai-coder/agents/platform-controls/template-optimization.md`:
replace **Agents** > **Settings** > **Manage Agents** > **Templates**
with **Admin settings** > **AI** > **Coder Agents** > **Templates**.

## Scope note

The first revision also fixed `models.md`, `advisor.md`,
`chat-debug-logging.md`, and `platform-controls/index.md`. Those pages
are covered by #28482 with the same corrections, so this PR reverted
them to avoid conflicting edits and adopted that PR's breadcrumb
convention instead.

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

<details><summary>Analysis evidence</summary>

- `site/src/router.tsx` (~735-780):
`/ai/settings/{lifecycle,templates,coder-agents}` are the live routes;
`/agents/settings/{admin pages}` (~833-890) are `Navigate`-only
redirects.
- No "Behavior" tab exists in any router revision;
`RetentionPeriodSettings` and `DebugRetentionSettings` both render in
`LifecyclePageView.tsx`.
- Breadcrumb convention **Admin settings** > **AI** verified against
`AdminSettings.tsx` / `AISettingsSidebarView.tsx` in #28482.

</details>

Generated by Coder Agents on behalf of @nickvigilante.
2026-08-25 12:49:27 -04:00
Ethan 409049d1d8 docs: document org-scoped admin configuration for agents (#28482)
## Summary

Documents the organization scoping of Coder Agents admin configuration,
and corrects the navigation paths, access wording, and default-model
instructions that no longer matched the product. Documentation only, no
product code changes.

Follows #28473, which moved the organization model overrides into an
**Organization settings** section on **Admin settings > AI > Coder
Agents**. #28473 is merged, so this targets `main`.

Closes CODAGT-715

## Changes

- **New page**
`docs/ai-coder/agents/platform-controls/organizations.md`, registered in
`docs/manifest.json`. Covers the deployment/organization scope split,
what an upgrade changes, how an organization without models or MCP
servers behaves, who configures each scope, and how model and MCP server
sharing works.
- **`models.md`**: models are organization-scoped while providers and
their credentials stay deployment-wide. Each organization has one
default model, and the first model added becomes it. Documents the
**Default** badge and the **Set as Coder Agents default model** form
option in place of the star action that no longer exists, and points
model overrides at **Organization settings**.
- **`getting-started.md`**: replaces the Owner-only claim with the
actual access model, adds an organization selection step, and uses the
**Add model** label.
- **`platform-controls/index.md`**: separates deployment-wide controls
from organization-scoped controls, documents personal model overrides
alongside the model configuration section rather than as an enforcement
caveat, and adds `--agents-allowed` plus the `agents-allowed:` search
filter.
- **`platform-controls/advisor.md`** and
**`platform-controls/virtual-desktop.md`**: the Advisor and Virtual
desktop settings are cards in the **Deployment settings** section of the
**Coder Agents** page, not sidebar entries. **Providers** is a sidebar
item, not a tab.
- **`platform-controls/mcp-servers.md`**: slug uniqueness is per
organization, the **Add server** label is correct, and the page is no
longer described as admin-only.
- **`architecture.md`**, **`index.md`**,
**`tasks-to-chats-migration.md`**: organization scope corrections and
organization-scoped model routes.
- Breadcrumbs standardized to **Admin settings > AI > ...**, verified
against `AdminSettings.tsx` and `AISettingsSidebarView.tsx`.

<details>
<summary>Review follow-ups</summary>

The first revision leaked implementation detail into user-facing pages
and contained several claims that did not match the UI. The follow-up
commit removed and corrected the following.

Removed as implementation detail:

- The `chat_model_config` RBAC resource, its actions, and the token
scopes.
- The `available`, `unavailable_reason`, and `unsupported_providers`
response fields, along with the `missing_api_key`, `fetch_failed`, and
`user_api_key_required` values.
- Role and permission tables, ACL storage mechanics, audit internals,
and JSON error bodies on the new organizations page.
- Migration mechanics with no effect on what a user does.

Corrected against the product:

- The star action does not exist. The list shows a **Default** badge and
the add/edit form offers **Set as Coder Agents default model**
(`ModelRow.tsx`, `ModelFormFields.tsx`).
- The first model added to an organization becomes its default
automatically (`coderd/exp_chats.go`). An organization without a stored
default does not fail every chat, so that claim is gone.
- Advisor and Virtual desktop are cards under **Deployment settings**
(`CoderAgentsPageView.tsx`).
- The MCP servers page does not require deployment configuration edit
permission (`AISettingsSidebarView.tsx`).
- Button labels: **Add model** and **Add server**.
- The organization query parameter is `org`, confirmed by
`modelOrganizationSearchParam`.

Left alone deliberately: pre-existing defects outside the introduced
text, including the `/api/v2/chats` route prefixes, create-chat examples
missing `organization_id`, and the pre-existing MCP permissions table.

</details>

## Testing

- `pnpm run format-docs` and `pnpm run lint-docs` pass.
- `make lint/emdash` passes. No emdash or endash added.
- `grep -rn "Defaults & overrides" docs/` returns nothing.
- Every navigation path, button label, and access claim checked against
the corresponding file under `site/src/pages/AISettingsPage/` and
`site/src/modules/management/`.

---

This pull request was generated by Coder Agents on behalf of
@ethanndickson.
2026-08-25 17:24:39 +01:00
TJ c07bde80c4 fix: use medium badges and shorter shared key label on agent API keys page (#28557)
On `/agents/settings/api-keys`, bumps the provider key status badge and
the enabled model badges from `sm`/`xs` to the medium (`md`) size, and
shortens the status label "Using shared key" to "Shared key". Updates
the matching Storybook assertion and the status indicator name in
`docs/ai-coder/agents/models.md`.

Verified with `tsc` and the page's Storybook tests (15 passing).

---

*Created by Coder Agents on behalf of @tracyjohnsonux.*
2026-08-25 16:16:59 +00:00
Garrett Delfosse 7cf24b1a37 docs(docs/ai-coder/agents): document the chat search: full-text filter (#28474)
Documents the `search:` full-text filter in
`docs/ai-coder/agents/chat-search-syntax.md` and drafts the release
notes copy for chat history search.

Describes `main` plus #28319, which must merge first: stemming and
stopword removal apply to message content only; titles and PR titles
keep `simple` whole-word matching. All claims verified against the
implementation. Two statements in CODAGT-727 were inaccurate and are
documented as the code behaves:

- A value that tokenizes to no searchable words returns an **empty
list**, not HTTP 400
(`TestListChats_Search/NoSearchableWordsReturnsEmpty`). HTTP 400 covers
only an empty `search:` value, unsupported keys, bare terms, or
combining `search:` with `title:`, `pr_title:`, or `pr:`
(`coderd/searchquery/search.go`).
- Results are **paginated** with the standard chat list cursor (default
50), not a bounded non-paginated set (`GetChats`, `listChats`). Ordering
is pinned first, then most recently updated.

Also verified: message bodies are indexed by the dbpurge sweep
(10-minute tick, up to 5 x 10,000 rows, newest first) while titles and
PR titles are searchable immediately; numeric values match exact PR
numbers; `title:`, `pr_title:`, and `repo:` retain `ILIKE` semantics.

`pnpm run format-docs` and `pnpm run lint-docs` pass.

Closes
[CODAGT-727](https://linear.app/codercom/issue/CODAGT-727/chat-search-documentation-and-release-notes)

<details>
<summary>Release notes draft</summary>

### Chat history search

You can now search your chat history by what was said, not just by
title. The chat list `q` parameter accepts a new `search:` filter that
performs full-text search across chat titles, pull request titles, PR
numbers, and message content, for example `?q=search:"kubernetes
restart"`. Matching is case-insensitive and supports quoted phrases,
`OR`, and `-` negation. Message content additionally matches English
word stems (`refactor` finds a message containing `refactoring`).
`search:` cannot be combined with the `title:`, `pr_title:`, or `pr:`
filters; the existing substring filters are unchanged.

**Upgrading with existing chat history:** the message search index is
populated by a background job (every 10 minutes, up to 50,000 messages
per run, newest first). Upgrades are not blocked, and chat reads and
writes are unaffected while the index fills. Older messages appear in
search results progressively; messages indexed before the stemming
upgrade match exact word forms until re-indexed. Titles and PR titles
are searchable immediately.

</details>

---

🤖 This PR was generated by Coder Agents on behalf of @f0ssel.
2026-08-25 09:09:10 -04:00
Garrett Delfosse eedc0ece47 fix: avoid 500 when generating chat title from rename dialog and remove unused endpoint (#28306) 2026-08-25 06:52:45 -04:00
Cian Johnston 042421694f fix: surface duplicate AI provider hostname as warning, not error (#28208)
Two live `ai_providers` rows can share the same `base_url` hostname.
This is an intended configuration (AIGOV-97): the direct routing path
(`/api/v2/ai-gateway/{name}/...`) routes by provider name and fully
supports it. Only the MITM proxy path (`aibridgeproxyd`) cannot
disambiguate, because its `nameByHost` map is 1:1.

`classifyProviderRow` marked the second provider as
`ProviderStatusError`, which surfaced as a misleading log warning and a
`status=error` Prometheus label. The provider is not actually broken; it
is fully routable via the direct path. The error was only visible in
server logs and Prometheus, not in the API or UI.

This change:

- Extracts `BaseURLHostname` into `coderd/aibridged` and eliminates
three duplicate implementations (proxy classifier, chatprovider, and the
API layer now uses it for status checks).
- Downgrades the proxy classifier from `ProviderStatusError` to a new
`ProviderStatusProxyExcluded` status. The provider is not broken; it is
just not reachable via the MITM proxy path.
- Adds `Status *AIProviderStatus` to `codersdk.AIProvider` with
`Warnings []string`, matching the `WorkspaceProxy` precedent.
- Populates warnings on create, update, GET, and list when a provider's
hostname collides with another enabled provider.
- Adds an integration test proving that a duplicate provider is routable
via the direct path but not via the proxy path.

Refs AIGOV-596

Generated by Coder Agents



https://github.com/user-attachments/assets/bf323837-5121-4d1b-ab19-593f1d32374e
2026-08-24 13:27:22 +01:00
Atif Ali 54d4ae9aca fix: detect Xum client in aibridge after Mux rename (#28448) 2026-08-24 16:20:57 +05:00
Michael SuchaczandEthan Dickson 0ef331fcd0 feat!: scope chat model override settings to organizations (#28442)
Moves chat model override settings from deployment scope to organization
scope, following the org-scoping of chat model configs in #28440.

Depends on #28440 (based on
`ethan/chat-models-availability-consolidation`).

Remote dogfood UAT passed on this change, including multi-organization
scenarios on a licensed deployment with real models.

## Problem

Chat model configs are now owned by organizations, but the override
settings that reference them stayed deployment-wide: admin
subagent/title/compaction overrides in `site_configs`, personal
overrides in `user_configs`, and the advisor model embedded in the
advisor runtime JSON. A single deployment-level override can only point
at one organization's model config, so overrides effectively worked for
the default organization only, and title generation had to soften its
hard-failure contract to tolerate unusable overrides.

## Fix

Admin overrides (general, explore, title generation, compaction,
advisor) and personal overrides (root, general, explore) become
organization-scoped rows in two new typed tables,
`chat_organization_model_overrides` and `chat_user_model_overrides`.
Composite foreign keys on `(organization_id, model_config_id)` make
cross-organization model references unrepresentable. The migration
deletes the legacy serialized `site_configs`/`user_configs` override
keys instead of migrating them; admins and users re-select models in the
new organization-scoped settings.

New endpoints live under
`/api/experimental/organizations/{organization}/chats/model-overrides`
(admin defaults) and
`/api/experimental/organizations/{organization}/members/{user}/chats/model-overrides`
(personal overrides); the legacy deployment-level routes are removed.
chatd resolves overrides via the chat's organization, restoring the
hard-failure contract for configured-but-unusable title generation
overrides. The deployment-level `AllowUsers` switch and advisor runtime
limits stay deployment-scoped.

The Coder Agents settings UI gains a per-organization "Defaults &
overrides" page under AI Settings > Models, and the personal overrides
page gains an organization selector for users in multiple organizations.
Advisor telemetry now reports per-organization override rows.

**BREAKING CHANGE**: Existing deployment-level overrides are dropped,
not migrated. Every organization starts with no overrides after upgrade,
and model selections must be re-applied in the new settings. The legacy
deployment-level override endpoints are removed.

Closes https://linear.app/coder/issue/CODAGT-872

> [!NOTE]
> Xum (AI agent) authored this PR on behalf of @ibetitsmike.

<!-- xum-attribution: model=claude-opus-4-6 thinking=high -->

---------

Co-authored-by: Ethan Dickson <ethan@coder.com>
2026-08-24 11:20:26 +01:00
Ethan 3809314b31 refactor!: consolidate chat model availability (#28440)
## Summary

Consolidate chat model management and runtime availability into a single
organization model collection contract. The organization model response
now includes provider availability, unavailable reasons, and
unsupported-provider details, so callers no longer need a separate
availability request.

Depends on #28439.

## Problem

The organization-scoped API exposes two overlapping representations of
the same chat models:

```text
GET /api/experimental/organizations/{organization}/chats/models
GET /api/experimental/organizations/{organization}/chats/models/available
```

The collection route returns organization-owned model configurations and
redacted provider descriptors. The availability route returns a second
catalog-oriented response with provider availability and synthetic
catalog entries. Callers must fetch, reconcile, and cache both responses
even though they describe the same effective set of models.

This creates duplicated server logic and separate SDK, OpenAPI, and
frontend types. It can also produce inconsistent client state when one
request succeeds while the other fails or when the two responses are
refreshed at different times.

## Fix

Return all model-management and runtime-availability information from
the organization model collection route:

```text
GET /api/experimental/organizations/{organization}/chats/models
```

`OrganizationChatModelsResponse` continues to return the caller-readable
organization model configurations and redacted provider descriptors.
Provider descriptors now also include:

- `available`
- `unavailable_reason`

The response additionally includes `unsupported_providers`, allowing
clients to explain configurations that the Agents harness cannot use.

Frontend model settings, agent creation, existing chat recovery, and
model override surfaces now consume this single collection query. This
keeps model ownership, caller visibility, provider availability, and
unsupported-provider guidance in one cache entry and one authorization
path.

The default-organization compatibility route remains available:

```text
GET /api/experimental/chats/models
```

It now returns the same consolidated `OrganizationChatModelsResponse`
contract instead of the former availability response.

## Breaking change

This removes the separate organization model availability endpoint:

```text
GET /api/experimental/organizations/{organization}/chats/models/available
```

Clients using that endpoint must migrate to:

```text
GET /api/experimental/organizations/{organization}/chats/models
```

This PR also removes the corresponding public experimental client and
schema surface:

- `ExperimentalClient.ChatModelAvailability`
- `ChatModelAvailabilityResponse`
- `ChatModelProvider`
- `ChatModelCatalogEntry`
- The generated OpenAPI schema and frontend API/query types for the
availability endpoint

Callers must use `ExperimentalClient.ChatModels` and
`OrganizationChatModelsResponse` instead. Availability is now reported
on each `ChatModelProviderDescriptor`, and unsupported providers are
returned in `OrganizationChatModelsResponse.UnsupportedProviders`.

The default-organization compatibility route retains its URL, but its
response schema changes from `ChatModelAvailabilityResponse` to
`OrganizationChatModelsResponse`. Direct HTTP clients and generated
clients that decode the previous response type must be updated even if
they do not use the removed organization-scoped `/available` route.
2026-08-24 11:20:26 +01:00
Ethan 75ad45109d feat: use organization-scoped chat models (#27960)
Move chat model settings to
`/ai/settings/organizations/:organization/models`, add an organization
switcher, and redirect legacy settings paths. The pages use organization
permissions for read, create, update, and delete controls. They use
redacted provider descriptors.

Agent creation loads models for the selected organization. Existing
chats load models for the chat organization. Chat views warn about
unavailable historical models, select a usable local recovery model, and
disable generation when none exists. Settings that aggregate
organizations retain successful results when one request fails.

Depends on #27959

_This pull request description was generated by Coder Agents._
2026-08-24 11:20:25 +01:00
Paweł BanaszewskiandNick Vigilante 4ce8e8ed56 docs: address AI Gateway documentation review feedback (#28309)
Applies the review feedback from #27794. Prose only.

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-08-23 19:42:48 +00:00
Nick Vigilante c6deadbc6c docs: fix broken .style/ link and lift details block out of list item [DOCS-661] (#28180)
## What

Two small docs fixes, split out of the offlinedocs Fumadocs migration
(#27390) so that PR stays a focused tooling change and these land on
their own review track.

- `docs/about/contributing/documentation.md`: the Vale style-guide link
pointed at `docs/.style/style-guide/`, which is excluded from the
published docs corpus, so the relative link 404s on the live site.
Repointed to an absolute github.com URL.
- `docs/ai-coder/ai-gateway/monitoring.md`: lifted the "Possible client
values" `<details>` block out of the list item so it renders as a
top-level accordion, and restored a dropped blockquote continuation
marker (`>`).

## Why

Both are genuine docs bugs on their own:

- The `.style/` link is broken on the live site today, because that
directory is intentionally excluded from the published corpus.
- The `<details>` nested inside a list item renders inconsistently;
lifting it to a sibling block is portable across renderers.

They are also prerequisites for the offlinedocs Fumadocs migration,
whose stricter build-time sync hard-fails on unmapped inter-doc links
and only converts a `<details>` to an accordion when it is a list
sibling. Landing them here first lets the migration PR drop these two
files on its next rebase.

## Validation

- `make fmt/markdown` and `make lint/markdown`: clean (via
pre-commit-light).
- Docs-only change; no CI or build config touched.

> This PR was created with AI assistance (Coder Agents).
2026-08-20 19:09:46 +00:00
Susana Ferreira d989ae36cd docs: clarify who can set AI model prices and how they are keyed (#28401)
The docs named the `ai_model_price:update` permission but never said
which role holds it, and nothing anywhere explained that a price is
keyed by provider type and model, so every configured provider of that
type shares it. This names the Owner role, documents the keying and why
`openai-compat` cannot be priced, and repeats both in the CLI's
`--provider` descriptions and `update` help.

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by
@ssncferreira
2026-08-20 17:35:30 +01:00
Susana Ferreira d58788cb23 fix: clarify AI model price configuration (#28372)
## Description

Model prices displayed in the Agents model form are read-only because
they are managed by AI Gateway. Add guidance and a link to the model
price configuration documentation, and rename the related documentation
subsection to **Configure model prices**.

> [!NOTE]
> Generated with Coder Agents by @ssncferreira.
2026-08-20 12:55:51 +00:00
Susana Ferreira 50ecd6959f feat: add a source filter to the AI model price list (#28329)
## Description

With prices from the price book and prices set through the API both in the table, `list` showed only the price in effect and gave no way to tell where it came from. There was also no way to see the price book's entry for a model that had been overridden, since the listing resolves to the custom price.

This adds a `source` column to the output and a `--source` filter for narrowing to one source, or to every row with `all`.

Note: `--source` selects rows rather than models. A model carrying both a price book price and a custom one appears under either value, so the two filtered listings do not sum to the unfiltered one. `--source all` reports both rows at once.

## Changes

- Add `Source` to `codersdk.AIModelPrice` and `AIModelPricesFilter`, and map it in `db2sdk`, which previously dropped it.
- Filter `GetAIModelPrices` by source before resolution, so the price book's row for an overridden model stays reachable.
- Accept `all` as a source, which reports every price a model holds instead of resolving to one.
- Accept a `source` query parameter on the list endpoint, rejected with a 400 when outside the enum.
- Add `--source` to the list command and a `source` column to its output.
- Document the column and the filter, and lead the price section with `coder exp ai-model-prices list`.
- Distinguish a deployment's default prices from the price book that ships with each release.

Closes https://linear.app/codercom/issue/AIGOV-593

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by @ssncferreira
2026-08-20 11:56:58 +01:00
Susana Ferreira 19d1ee9fc8 feat: support custom prices for models in the price book (#28328)
## Description

The experimental CLI could only price models the price book does not cover, so an operator with a negotiated rate for a model Coder already prices had no way to record it. The restriction existed because a single row served both the price book and prices set through the API, and the startup seeder would overwrite an override on the next restart.

Each source now keeps its own row (https://github.com/coder/coder/pull/28204), so that no longer applies. This removes the restriction: a price set through the CLI takes effect over the price book for any model, and the book stays underneath it.

## Changes

- Remove the validation that rejected models the price book covers.
- Delete `prices.IsDefaultPriced` and the index behind it, which existed only for that check.
- Generalize the `coder exp ai-model-prices update` help.
- Document that a custom price overrides the price book and does not follow its updates.
- Rework the spend approximation callout around what a custom price can and cannot correct.

Closes https://linear.app/codercom/issue/AIGOV-594

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by @ssncferreira
2026-08-20 11:46:38 +01:00
Michael Suchacz 2f996d765a feat: remove task management MCP tools (#28354)
Removes the six task-management tools from the MCP tool surface in
`codersdk/toolsdk`:

- `coder_create_task`
- `coder_delete_task`
- `coder_list_tasks`
- `coder_get_task_status`
- `coder_send_task_input`
- `coder_get_task_logs`

Both the coderd-hosted MCP server (`coderd/mcp`) and the CLI `coder exp
mcp server` derive their tool list from `toolsdk.All`, so removing the
registry entries removes the tools from both servers with no server-side
changes.

The MCP server documentation (`docs/ai-coder/mcp-server.md`) is updated
to drop the task-management entry from the tool overview.

## What stays

- `coder_report_task` is intentionally kept: it is the agent-side
status-reporting mechanism (`WithTaskReporter`), already excluded from
the hosted MCP server, and required by `coder exp mcp server`, Claude
Code configuration, and scaletest.
- The `codersdk` Task SDK methods (`CreateTask`, `DeleteTask`, `Tasks`,
`TaskLogs`, etc.) and the Tasks feature (CLI, UI, API) are untouched;
this PR only removes MCP tool registration.
- The task-only `taskIDDescription` helper is deleted; `userDescription`
stays (used by `coder_create_workspace`).

The code change is deletion-only: 970 removed lines across `toolsdk.go`
and its test file, no added behavior.

## Validation

- `go build ./...`, `go test ./coderd/mcp/`, and targeted
`golangci-lint` pass. `go test ./codersdk/toolsdk/` passes all tests;
the package-level goleak failure (agentssh goroutines) reproduces
identically on unmodified `main` and is unrelated to this diff.
- `pnpm run lint-docs` passes on the docs change.
- Remote dogfood UAT ran against the toolsdk change and passed:
`tools/list` on both the hosted MCP endpoint and `coder exp mcp server`
confirms the six tools are absent and the remaining surface is intact
(34 hosted tools; CLI adds `search`/`fetch`), a `tools/call` of
`coder_get_authenticated_user` succeeds, and calling a removed tool
returns `-32602 unknown tool`. `coder_report_task` still registers in
the CLI server when `CODER_MCP_APP_STATUS_SLUG` is set.
- The failing `Pixel / Review` commit status is unrelated: this PR
contains no `site/` changes, and the same status fails on the last 8
`main` commits including this PR's merge base (`676b9bb06bf`).

> Mux acted on Mike's behalf to create this pull request.
2026-08-20 12:07:30 +02:00
Michael Suchacz 24b83dc727 feat: add organization picker to MCP server settings pages (#28150)
Adds an organization picker to the MCP server settings pages so
multi-org deployments can manage every organization's MCP servers
through the UI, not just the default organization's. Closes CODAGT-714
(scoped to MCP servers only; model configs stay deployment-wide until
CODAGT-709 lands).

## Stack Context

Top of the CODAGT-711/717/712/806 stack: MCP server configs are
org-scoped with RBAC, audit logging, per-config ACLs, and owner-scoped
user tokens. This layer makes the admin UI org-aware, resolving the
"default org only" limitation documented in the bottom PR.

## Summary

- The MCP servers list and add pages resolve the working organization
from an `org` search param (falling back to the default org), and render
an organization picker built on the existing `OrganizationAutocomplete`.
The picker only appears when more than one organization is visible, so
single-org deployments see no change.
- Selecting an organization rewrites the search param, refetches the
list for that org, and threads through to the add page so creation posts
to the selected organization.
- The update page now loads the server by ID (new organization-scoped
`GET /api/experimental/organizations/{organization}/mcp-servers/{id}`
frontend binding) instead of listing the default org and searching
client-side, so servers from any organization can be edited. Post-save
navigation returns to the owning organization's list via the server's
`organization_id`.
- Removes the now-unused `getDefaultOrganizationId` helper.
- Review hardening: organization display labels are disambiguated with
the unique org name when effective display names collide (picker
options, trigger text, and accessible name). Access is no longer
restricted to deployment admins: the pages, sidebar item, and nav entry
accept org-scoped `mcp_server_config` permissions, the picker lists only
organizations the user can view, content and affordances (add, edit,
delete) are gated on the selected organization's permissions, and
deployment admins keep full access everywhere.

## Testing

Storybook interaction stories cover: picker hidden with one org,
switching orgs refetches and swaps list contents, add posting to the
URL-selected org, add posting after an in-form org switch (asserting
typed form state survives the switch), and update loading by ID.
Red-green verified by breaking the search-param resolution and observing
the new stories fail.

> Mux acted on Mike's behalf for this PR.
2026-08-19 19:46:23 +00:00
david-fraley 8203b2ebaf feat!: hide Coder Tasks behind the enable-ai-tasks flag (#28008) 2026-08-19 14:46:10 -05:00
Michael Suchacz 7ca7c30f40 feat: add group and user ACLs to MCP server configs (#27944)
Adds group and user ACLs to org-scoped MCP server configs so
organizations can restrict specific MCP servers to subsets of members,
mirroring the template ACL pattern.

## Summary

- Migration adds `group_acl`/`user_acl` JSONB columns (nested `{"<id>":
{"permissions": [...]}}` shape) and seeds every existing config with its
organization's Everyone group read entry (the Everyone group ID equals
the org ID), so member access is unchanged by default. Creation seeds
the same entry.
- The blanket org-member read grant from the base PR is replaced by ACL
evaluation: Rego requires org membership for every ACL grant, and
`GetAuthorizedMCPServerConfigs` compiles ACL-aware SQL filters.
- New `ActionShare` (org admins) gates `GET|PATCH
/api/experimental/organizations/{organization}/mcp-servers/{mcpserverconfig}/acl`
(nested under the organization like the rest of the config surface).
PATCH validates principals against the config's organization, merges
sparse updates under a row lock, stamps `updated_by`/`updated_at`, and
is audited as a Write with `Old` captured before authorization. A config
deleted concurrently between the middleware fetch and the locked
re-fetch is concealed as 404, matching the update and delete handlers.
ACL columns are tracked in the audit table.
- ACL management is available in all editions (no enterprise
entitlement), documented in the MCP servers page. Revoking an ACL does
not retro-strip already-selected configs from existing chats; new
selection is blocked at chat create.
- Force On respects the ACL: the forced set is loaded as the chat owner,
so a `force_on` server whose ACL denies the owner never attaches at
create, send, or generation time.
- No rolling-upgrade machinery: upgrades run in scheduled maintenance
downtime, so the migration only backfills existing rows; the API sets
the Everyone read grant explicitly on every insert.

Stacked on #27943. Part of the MCP org-separation stack.

Closes https://linear.app/codercom/issue/CODAGT-712

UAT: verified on a dogfood instance with two members and a custom group:
Everyone-seed default visibility, group grant with Everyone removal
(non-member loses list/fetch/selection), foreign-principal rejection,
non-admin share denial (audited 403 / concealed 404), user_acl restore,
and audited ACL diffs.

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

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-19 19:25:18 +00:00
Michael Suchacz f7a0de7a11 fix: harden org-scoped MCP config chat gating, updates, and visibility (#28065)
Hardens the org-scoped MCP server config surface from #27942 with fixes
and regression pins that are independent of the core cutover:

- Keep chats sendable after a selected MCP server is disabled (persisted
selections are exempt from message-time rejection).
- Keep cached MCP selections usable after a background refetch error
(gate the composer on missing data, not `isSuccess`).
- Merge PATCH updates onto the current row so unset fields are not
clobbered.
- Give auditors the full management view of MCP configs their audit logs
reference (site and org auditor roles).
- Regression pins: frozen OAuth2 callback path, cross-org concealment
for item routes, OAuth callback token binding, and disconnect responses
indistinguishable from nonexistent config IDs.
- Storybook: semantic textbox queries in MCP loading stories; docs note
that the MCP settings page needs deployment access.

## Stack context

Part of the MCP org-separation stack (CODAGT-711 org scope -> apidocs ->
hardening -> CODAGT-717 audit -> CODAGT-712 ACLs -> CODAGT-806 token
RBAC). Split out of #27942 to keep the core cutover reviewable; each
change here builds on the org-scoped routes and chat gating introduced
below it.

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

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-19 18:50:31 +00:00
TJ dd43574990 refactor: remove AI add-on badge, seat column, and add-on wording leftovers (#28004)
Removes all "AI add-on" labeling from the UI, plus two leftover "AI
Governance add-on" wording items from the licensing repackaging (AI
Governance is now included with Premium).

- Remove the **AI add-on** badge from the group settings AI budget
section and the AI Governance add-on card on the Licenses page.
- Remove the **AI add-on** column (check icon showing AI seat
consumption) from the Users and Organization Members tables, along with
its help popover, the `AISeatCell` component, and the
`shouldShowAISeatColumn` entitlement helper.
- Update related Storybook stories.
- Drop "add-on" from the AI cost control route comments in
`enterprise/coderd/coderd.go` and the `coder exp ai-model-prices`
prerequisite in `docs/ai-coder/ai-gateway/cost-controls.md` (leftovers
not covered by #28075/#28077/#28268).

The `has_ai_seat` API field is left intact.

<details>
<summary>Removal scope</summary>

Badge usages removed:

- `site/src/pages/GroupsPage/GroupSettingsPageView.tsx`
-
`site/src/pages/DeploymentSettingsPage/LicensesSettingsPage/AIGovernanceAddOnCard.tsx`

AI seat column plumbing removed:

- `site/src/pages/UsersPage/UsersTable.tsx` and `UsersPage.tsx`
- `site/src/pages/OrganizationSettingsPage/OrganizationMembersTable.tsx`
and `OrganizationMembersPage.tsx`
- `site/src/modules/users/AISeatCell.tsx` (deleted)
- `AiAddonHelpPopover` in `site/src/modules/users/UserHelpPopovers.tsx`
- `shouldShowAISeatColumn` in
`site/src/modules/dashboard/entitlements.ts`

Add-on wording leftovers:

- `enterprise/coderd/coderd.go`: 7 route comments (comments only, no
behavior change)
- `docs/ai-coder/ai-gateway/cost-controls.md`: model prices CLI
prerequisite

</details>

---

🤖 This pull request was generated by Coder Agents on behalf of
@tracyjohnsonux.
2026-08-19 11:43:27 -07:00
Michael SuchaczandMathias Fredriksson 443e3b9b80 feat!: org-scope MCP server configs with RBAC (#27942)
Moves `mcp_server_configs` from deployment scope to organization scope
so each organization fully controls the MCP servers its members can use
with Coder Agents.

## Summary

- Migration: adds `organization_id` (NOT NULL, FK) and keeps existing
rows as the default organization's originals with credentials intact.
Other organizations start with no MCP servers and configure their own;
nothing is copied across organizations. Chats outside the default
organization keep any now-cross-organization `mcp_server_ids` entries;
the runtime already ignores IDs that do not resolve in the chat's
organization, so no data rewrite is needed. Slug uniqueness becomes
`(organization_id, slug)`.
- RBAC: new org-scoped `ResourceMCPServerConfig` with regosql converter
and `GetAuthorizedMCPServerConfigs`; org admins get in-org CRUD, org
members get read (replaced by ACL evaluation in the follow-up ACL PR in
this stack).
- API: all config routes nest under the organization, matching
templates: `POST|GET
/api/experimental/organizations/{organization}/mcp-servers` and
`GET|PATCH|DELETE .../mcp-servers/{mcpserverconfig}` (plus
`oauth2/connect`), resolved by a read-only param middleware that
conceals read-denied and cross-organization access as 404. Two routes
stay on the frozen `/api/experimental/mcp/servers/{mcpServer}` block:
the OAuth2 callback (the redirect URI baked into existing AS-side client
registrations) and `oauth2/disconnect`, which must remain reachable by
users removed from the organization so they can still revoke their token
grant.
- Chat runtime: selection validation and generation resolve configs
strictly by IDs, enabled state, and the chat's organization in SQL;
requested duplicates are normalized; invalid or cross-org IDs are
rejected with the precise ID list. IDs already persisted on a chat are
exempt from message-time rejection so disabling a selected server never
blocks sends; generation skips servers that are no longer usable.
- Frontend: API layer and admin settings pages target the new endpoints.
The admin page manages the default organization's servers; the org
picker is tracked separately (CODAGT-714).

- Security hardening from review: OAuth user grants are additionally
bound to `oauth2_revocation_url` (changing it invalidates grants, and a
racing OAuth callback gets 409 instead of recreating a grant).
Stack-wide SSRF protection for MCP config-directed traffic was split
into its own PR at the top of this stack (#28242) to keep this diff
reviewable; this PR keeps main's existing discovery IP-range guard.
OAuth2 auto-discovery now completes before the config row is inserted: a
failed discovery persists nothing, and there is no provisional row that
concurrent updates could race against.

Two follow-up PRs in this stack were split out to keep this diff
reviewable: #28064 completes the swagger annotations for the moved
routes (main already ships these experimental MCP handlers unannotated),
and #28065 carries hardening fixes and regression pins on top of the
cutover.

- Force On enforcement (landed on main mid-review) is org-scoped: the
forced set is read per chat organization
(`GetForcedMCPServerConfigsByOrganization`), so another organization's
`force_on` server never attaches to a chat.

## Breaking changes (experimental API)

The MCP server config endpoints move from the deployment-scoped
`/api/experimental/mcp/servers` block to organization-nested paths:
`POST|GET /api/experimental/organizations/{organization}/mcp-servers`
and `GET|PATCH|DELETE
/api/experimental/organizations/{organization}/mcp-servers/{mcpserverconfig}`
(plus `oauth2/connect`). The old paths are removed, so API consumers
must supply an organization. Two routes intentionally stay on the frozen
`/api/experimental/mcp/servers/{mcpServer}` block: the OAuth2 callback
(its redirect URI is baked into existing AS-side client registrations)
and `oauth2/disconnect` (must remain reachable by users removed from the
organization). These endpoints are under `/api/experimental`, so no
deprecation window is provided.

## Rolling upgrades

During a rolling deploy, an old replica creating an MCP config can fail
the new `NOT NULL organization_id` constraint until it is upgraded
(reads are unaffected: old binaries' generated queries select their own
column lists). This matches the repo's existing precedent for additive
NOT NULL migrations (000562) and affects only the admin config-create
path in the upgrade window.

Upgrades are expected to run in scheduled maintenance downtime with the
database locked during migration, so the migration ships no
rolling-upgrade compatibility machinery. The down migration deletes
organization-created configs (their chat references are cleaned by the
000510 delete trigger) and restores deployment-wide slug uniqueness.

Part of the MCP org-separation stack (CODAGT-711 -> CODAGT-717 audit ->
CODAGT-712 ACLs -> CODAGT-806 token RBAC).

Closes https://linear.app/codercom/issue/CODAGT-711

UAT: validated end to end on a two-org dogfood deployment, including a
real pre-migration to post-migration upgrade, cross-org isolation
(404s), same-slug-two-orgs, chat selection gating, and a live MCP tool
call through the org-scoped generation path. The migration was later
revised to keep existing rows in the default organization only (no
per-organization copies); that revision is covered by the migration test
suite.

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

<!-- mux-attribution: model=claude-fable-5 thinking=high -->

---------

Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
2026-08-19 18:04:13 +00:00
Atif Ali 7ff1278ab3 feat: track Junie as an AI Gateway client (#28266)
## Problem

Junie CLI works with AI Gateway, but every Junie session is recorded as
`Unknown`. Junie sends `User-Agent: Junie:SNAPSHOT` (observed directly
from the CLI), which `GuessClient` does not match, so usage, spend, and
audit views cannot attribute Junie traffic. There were also no docs for
pointing Junie at AI Gateway.

## Fix

- Detect the observed `junie:` user-agent prefix and add the `Junie`
client value.
- Add the Junie icon so sessions render with a logo instead of the
fallback question mark.
- Add a Junie client page and list it in the compatibility table.
- Add `Roo Code` and `Charm Crush` to the documented `client` filter
values. Both were already implemented but missing from the list.

## Supported configurations

| Provider  | API type          | Endpoint                 |
|-----------|-------------------|--------------------------|
| OpenAI    | `OpenAIResponses` | `/openai/v1/responses`   |
| Anthropic | `Anthropic`       | `/anthropic/v1/messages` |

BYOK works on both through `extraHeaders` with
`X-Coder-AI-Governance-Token`.

Preview:
https://coder.com/docs/@matifali-junie-ai-gateway-client/ai-coder/ai-gateway/clients/junie

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑‍💻
2026-08-19 21:13:49 +05:00