Commit Graph
5007 Commits
Author SHA1 Message Date
Ethan 63e08e231e feat(coderd): steer queued messages on Send now (#31156)
"Send now" on a queued message (`POST
/api/v2/chats/{chat}/queue/{queuedMessage}/promote`) now just moves it
to the end of the steer lane. It never interrupts the chat, so it can't
cancel the step that would have answered it. The endpoint's request
doesn't change. Before, it moved the message to the head of the queue
with `MIN(position) - 1`, so if you pressed "Send now" on two messages,
the second one went first. With a queue of `Q1 Q2 Q3 S4`, "Send now" on
`Q1` then `Q3` now delivers `S4 Q1 Q3`, and `Q2` keeps waiting.

If the chat has errored or is paused, the steer lane goes in straight
away, like a send. Otherwise it goes in at the next delivery point:
before the next model call, when the turn ends, or when an interrupt
finishes. Stop is the only thing that interrupts.

"Send now" and "Remove" on a message that's already been delivered now
return a 404 instead of a 409, the same as editing one, and "Remove" on
an archived chat returns a 400.

In chatstate, `SteerQueuedMessage` replaces `PromoteQueuedMessage`. It
moves the message to the end of the steer lane, and on an errored or
paused chat it also delivers the steer lane and resumes the chat, like a
send does. The `SteerChatQueuedMessage` query sets `position =
nextval(...)` and replaces `ReorderChatQueuedMessageToHead`. Most of the
diff is tests.

#31174 then makes `steer` the API default and removes `interrupt` as a
busy behaviour, #31175 makes `message_agent` always steer, and #31173
updates the site.

Part of CODAGT-1140
2026-11-09 15:55:16 +11:00
Ethan 5138fa300f feat: store interrupt sends in the steer lane (#31155)
An interrupt send to a running or interrupting chat now goes to the end
of the steer lane, and the whole steer lane goes in once the
interruption finishes. Before, it went to the head of the queue lane if
it started the interruption, or the tail if the chat was already
interrupting, and only the head went in. So if you sent two messages
with interrupt whilst the agent was stopping, the second one went to the
back of the queue. Now both go in once it stops, in the order you sent
them.

Interrupt is still a send option here, it just means "interrupt, then
steer" now. #31174 removes it from the API and #31175 from
`message_agent`, so you call the interrupt endpoint first, then send.

There's one gap until #31156. "Send now" still only moves a message to
the head of its own lane, so if you send with interrupt and then press
"Send now" on a queued message before the agent stops, only the steer
lane goes in when it stops, and the "Send now" message waits for the
next turn end. #31156 makes "Send now" steer too, so both go in.

The `codersdk` change is just the doc comment on
`ChatBusyBehaviorInterrupt`.

Part of CODAGT-1140
2026-11-09 15:55:16 +11:00
Ethan ace278e2d6 feat(coderd/x/chatd): deliver steer messages before each model call (#30074)
This is where the steer lane gets delivered mid-turn. Before each
assistant model call, the generation task now runs
`DeliverSteerMessages`. If there are steer messages queued, they go into
history and the task returns without calling the model, and the history
change starts a new generation task that sends them to the model. It
never cancels anything, it just waits for the in-flight call and that
step's tool calls to finish. Queue messages still wait for turn end, and
compaction calls don't deliver steer messages, as they don't answer the
user.

A delivered steer message is a new prompt, so tracing treats it like any
other newer prompt: a new `chat_turn` span starts at it, and the span
before it ends as `abandoned`.

`chatd.SendMessage` now accepts `steer`, but the HTTP handler and
`message_agent` still only pass `queue` or `interrupt`, so the API
doesn't change in this PR. #31174 makes `steer` the API default. Outside
of tests, nothing creates steer messages until #31155 stores interrupt
sends in the steer lane, so this PR doesn't change behaviour for users
on its own.

I've split the earlier version of this PR up, so some of the review
comments are now addressed elsewhere in the stack. #31153 moves queue
delivery into one helper, #31154 adds the two lanes, #31155 stores
interrupt sends in the steer lane, and #31156 makes "Send now" steer,
which also fixes two presses being delivered in reverse order.

This supersedes #29784.

Since the first review, a steer message delivered before a model call
also records `queue_wait`, like the other delivery points.

Part of CODAGT-1140
2026-11-09 15:55:16 +11:00
Ethan 0616658cb5 feat(coderd): add a steer lane to queued chat messages (#31154)
As suggested on #30074, steer messages are now their own lane, rather
than queue rows that jump ahead with a lower position. chatstate uses a
queued message's `busy_behavior` as its lane, and the steer lane always
goes first. `GetChatQueuedMessages` lists the steer lane first, so the
queue is shown in the order it'll actually be delivered.

At turn end, when an interruption finishes, and on a send to an errored
chat, the whole steer lane goes in. If there aren't any steer messages,
the queue head goes in like it does today. So with a queue of `Q1 S1 Q2
S2`, turn end delivers `S1 S2`, and `Q1` waits for the next turn end.

chatstate accepts `steer` here, but nothing sends it yet, so users won't
see a change. Until later in the stack, a few things still ignore the
steer lane:

- An interrupt send goes to the head of the queue lane, so it waits
behind any steer messages. #31155 moves it to the end of the steer lane.
- "Send now" on a running or interrupting chat only moves the message to
the head of its own lane, so when the interruption finishes, the steer
lane goes in instead of it.
- "Send now" on an errored chat, or one waiting on tool results, puts
the message into history straight away, ahead of any queued steer
messages.

#31156 fixes both "Send now" cases by making it steer. None of these can
happen yet, as there are no steer messages to get in the way.

I've added a "Queued message lanes" section to the chatd architecture
doc. Most of the diff is new cases in the transition matrix tests.

Since the first review, lane rule 3 in the architecture doc also says
that delivery stops at a message under edit, and which model and
reasoning effort a batch of delivered messages uses.

Part of CODAGT-1140
2026-11-09 15:55:15 +11:00
Ethan bfff9e6874 refactor(coderd): deliver queued chat messages through one helper (#31153)
`FinishTurn`, `FinishInterruption` and a send to an errored chat with a
queue each had their own code for moving a queued message into history.
They now share `deliverQueuedRows`, which takes a list of queued rows,
so the next PR can deliver the whole steer lane at once instead of just
the queue head. Delivery still only takes the queue head here, so this
doesn't change behaviour. `PromotedMessages` on the turn and
interruption results is now a slice to match.

"Send now" on an errored chat, or one waiting on tool results, still has
its own copy of that code in `PromoteQueuedMessage` for now. #31156
replaces it with a move into the steer lane, which then goes through
`deliverQueuedRows` like everything else.

I've also deleted `GetChatQueuedMessagesByPosition` and
`GetChatQueuedMessageHead`, as `GetChatQueuedMessages` already returns
the queue in delivery order.

Part of CODAGT-1140
2026-11-09 15:55:15 +11:00
Ethan 8230004d73 chore(coderd): store a delivery mode on queued chat messages (#30073)
Queued chat messages now store a delivery mode. Later in this stack,
`steer` messages go in before the next model call instead of at turn
end, so chatd needs to know which queued rows are steer rows.

The migration adds the enum `chat_busy_behavior` (`queue`, `steer`) and
the column `chat_queued_messages.busy_behavior`. It's `NOT NULL DEFAULT
'queue'`, so existing rows get `queue`, and chatstate still passes
`queue` on every insert for now, so this doesn't change behaviour. The
old `InsertChatQueuedMessage` query doesn't set the column and just gets
the default, but only tests use it.

There's no `interrupt` value on purpose. An interrupt isn't a delivery
mode, it's something that happens to the chat, and #31174 stops the API
accepting it as a busy behaviour.

This supersedes #29783.

Part of CODAGT-1140
2026-11-09 15:55:15 +11:00
TJ 3e76feeaa0 fix(coderd): keep the full message in fallback chat titles (#29949)
Fallback chat titles (used when AI title generation doesn't run or
hasn't finished) cut the first user message to six words and added "…".
Clients then showed titles cut at word boundaries no matter how much
space they had.

Fallback titles now keep the whole message with whitespace collapsed,
and only add an ellipsis at the existing 80-rune storage cap. Clients
truncate to fit their layout.

- Subagent fallback titles reuse `chatprompt.FallbackTitle` instead of a
duplicate six-word helper that used "...".
- Auto-titling is unaffected: since #29486 it checks `title_source`, not
whether the title text matches the fallback, so no compatibility shim
for older six-word titles is needed.
- Titles already stored in the old format are not rewritten.

Follow-up to #29942, where shared chats in the sidebar showed these
pre-truncated titles.

Testing: `make pre-commit`; `go test ./coderd/x/chatd/...`;
`TestPostChats*` and `TestChatMessageWithFiles` in `coderd`.

---

_Generated by Coder Agents on behalf of @tracyjohnsonux._
2026-11-06 23:52:48 +02:00
Garrett DelfosseandClaude Opus 5.5 b0fe0ba261 fix(coderd): tighten up database connection errors (#31850)
Tightens up database connection errors so they stay concise, and logs
internal error details server-side instead of returning them in API
responses.

Adds tests covering the error output.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:10:50 -05:00
Ethan f8ab27ff7c feat: allow computer use on Claude models from AWS Bedrock AI providers (#31745)
Closes
https://linear.app/codercom/issue/CODAGT-1525/allow-computer-use-with-claude-models-from-aws-bedrock-ai-providers

Computer use was only available on models from Anthropic and OpenAI AI
providers, as we decided support from the AI provider type alone, in
five separate places (spawn, turn setup, override validation, telemetry
and the settings UI). A Bedrock AI provider serves Claude models over
the Anthropic Messages API though, and chatd already routes those
through the Anthropic fantasy client, so there's no reason computer use
shouldn't work on them.

To fix, there's now a single rule,
`chatprovider.ComputerUseProvider(providerType, model)`, derived from
the client chatd builds for the model (`chatprovider.ClientProvider`,
previously `aibridgeClientProvider`). If the model uses the Anthropic
client, it gets the Anthropic computer use tool. The OpenAI tool is
still only offered on OpenAI AI providers, as I haven't tested it
against Bedrock Mantle, and I couldn't find anyone else doing it either.
All five places now call this function.

The UI can't re-derive Bedrock routing without duplicating the model ID
heuristic, so `ChatModel` gets a read-only `computer_use_provider` field
(`anthropic`, `openai`, or omitted when computer use isn't supported).
The computer use model override endpoint now accepts Bedrock Claude
models, and its 400 message has changed.

Whilst in here I also fixed a latent bug where the default model
credential check looked up the user's keys under the tool flavour
(`anthropic`) instead of the provider type (`bedrock`).

One caveat: on a Bedrock AI provider using InvokeModel, AI Gateway runs
the provider's configured model rather than the chat model, whilst we
pick the computer use tool version from the chat model ID. It's not
specific to computer use, and should go away with
[AIGOV-747](https://linear.app/codercom/issue/AIGOV-747/deprecate-the-bedrock-invokemodel-protocol-with-model-translation).
In the meantime, #30752 warns when an InvokeModel provider ignores the
chat model identifier.
2026-11-06 13:12:49 +11:00
Kyle Carberry 4fe64af03b refactor: replace gonum in agent/unit with an adjacency map graph (#31235)
**Stack:**
- #31232
- #31233
- #31234
- #31235
- #31236
- #31237

`agent/unit.Graph` used gonum's `simple`, `topo`, and `encoding/dot`
packages, which pull in `gonum/mat` and friends (~2 MB) for a graph with
a handful of nodes.

Replace it with forward/reverse adjacency maps, a DFS reachability check
for cycle detection, and a small DOT writer. The existing golden files
are unchanged.

<details>
<summary>Context: binary size investigation</summary>

Measured with full `make build/coder_linux_amd64` builds (zstd `-22
--ultra`) of `main` vs. the whole stack:

| Artifact | Before | After |
|---|---|---|
| `coder` (fat, linux/amd64) | 469 MB | 339 MB |
| `coder-slim` (linux/amd64) | 62 MB | 52 MB |
| Embedded `site/out` | 169 MB | 72 MB |
| Embedded `coder.tar.zst` | 83 MB | 60 MB |

Stack, each PR removes one source of size:

1. Hidden frontend source maps (~97 MB of embedded assets)
2. Slim tarball ordering so zstd `--long` dedupes across OSes (~14 MB on
the embedded archive)
3. `aisdk-go` only supplied two struct types but pulled in `openai-go`
v1 and `genai`
4. `gonum` used only for a tiny DAG in `agent/unit`
5. `gofakeit` root package links every faker; only two word lists are
used
6. Hugo `pageparser` used only to read YAML front matter in `templates
push`

Sizes were attributed with `go-size-analyzer` and an import-graph
dominator pass. Not in this stack: compiling out trivy's module download
resolvers in `coder/trivy` (~29 MB, drops go-getter, GCS, and S3 SDKs),
swagger-ui's bundled source maps (~7 MB), and OPA's embedded historical
capability JSON (~4 MB).
</details>

---
_Generated by Coder Agents on behalf of @kylecarbs._
2026-11-05 15:16:40 -05:00
Nick Vigilante 6de3d92883 fix: correct invalid and nonexistent Swagger parameters (#30124)
Several parameter annotations produced a wrong or invalid spec.

- `GET /api/v2/settings/idpsync/available-fields` and `field-values`
documented a required `organization` path parameter that their URLs do
not contain. The annotations were copied from the organization-scoped
routes.
- `format(uuid)` on the `ids` array query parameter of the provisioner
jobs and daemons routes put `format: uuid` on the array rather than its
items. swag cannot set an item format, so the description now says the
IDs are UUIDs.
- Swagger 2.0 does not allow `example` on header parameters, which
failed strict validation. The `Authorization` and `Content-Disposition`
examples move to `x-example` vendor extensions, which Swagger 2.0 allows
on parameters and the docs generator uses for the curl samples.
- `TestSwaggerParametersValid` reads every path in the generated spec
and fails on a non-body parameter with `example`, an array parameter
with `format`, or a path parameter missing from its route.

Part of DOCS-1122, split from #30121.

---
🤖 Built with AI assistance.
2026-11-05 14:22:30 -05:00
Nick Vigilante 585485c8bf fix: document raw JSON as objects and byte fields as base64 strings (#30123)
Swagger renders `json.RawMessage` and `[]byte` fields as integer arrays,
so the API reference showed chat tool calls as `"args": [0]` even though
tool arguments and results are JSON values.

Render every `json.RawMessage` as an object with one `.swaggo` replace
rule, and tag `[]byte` fields, which JSON-encode as base64,
`swaggertype:"string" format:"byte"`. This covers
`ChatMessagePart.args`, `.result`, `.data`, `ToolResult.output`,
`DynamicTool.input_schema`, both workspace build `state` fields,
`TemplateBuilderModuleVariable.default`, and
`CreateTestAuditLogRequest.additional_fields`.

`ChatMessagePart.provider_metadata` is internal only, so it is hidden
with `swaggerignore:"true"` like its siblings. `ChatMessagePart.result`
and `ToolResult.output` can hold any JSON value, and
`TemplateBuilderModuleVariable.default` holds a string, number, or
boolean, so `object` is an approximation for all three and the field
comments say so. swag rejects an untyped `.swaggo` override for
`json.RawMessage`.

Part of DOCS-1122, split from #30121.

---
🤖 Built with AI assistance.
2026-11-05 13:15:40 -05:00
Kyle Carberry 36b472991d refactor: replace aisdk-go tool types with codersdk/toolsdk/tooldef (#31234) 2026-11-05 09:45:21 -05:00
cdrciandgithub-actions[bot] f820cba82a chore: refresh AI model price book (#31775)
## Price book changes

9 models added, 14 models removed, 40 models changed.

<details>
<summary>Added</summary>

- openrouter/inclusionai/ling-3.0-tiny
- openrouter/ricursiveai/ripple-65b-preview
- openrouter/stealth/crouton-alpha
- openrouter/tencent/hy4
- openrouter/z-ai/glm-5.3-flashx-legal
- vercel/inclusionai/ling-3.1-flash-1019
- vercel/meituan/longcat-2.5
- vercel/tencent/hy4
- vercel/zai/glm-5.3-flashx-legal
</details>

<details>
<summary>Removed</summary>

- openrouter/nousresearch/hermes-3-llama-3.1-405b
- openrouter/nousresearch/hermes-3-llama-3.1-70b
- openrouter/poolside/laguna-s-2.1
- openrouter/poolside/laguna-s-2.1:free
- openrouter/poolside/laguna-xs-2.1
- openrouter/poolside/laguna-xs-2.1:free
- openrouter/thinkingmachines/inkling-small:free
- openrouter/thinkingmachines/inkling:free
- openrouter/upstage/solar-pro-3
- vercel/arcee-ai/trinity-large-thinking
- vercel/meituan/longcat-2.5-preview
- vercel/poolside/laguna-s-2.1-free
- vercel/xiaomi/mimo-v2.5
- vercel/xiaomi/mimo-v2.5-pro
</details>

<details>
<summary>Changed</summary>

- openrouter/deepseek/deepseek-v3.2
- openrouter/deepseek/deepseek-v4-flash-0731
- openrouter/deepseek/deepseek-v4-pro
- openrouter/deepseek/deepseek-v4-pro-0813
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/google/gemma-4-26b-a4b-it
- openrouter/ibm-granite/granite-4.2-8b
- openrouter/meta-llama/llama-3.1-70b-instruct
- openrouter/meta-llama/llama-3.2-3b-instruct
- openrouter/meta-llama/llama-3.3-70b-instruct
- openrouter/meta-llama/llama-4-maverick
- openrouter/minimax/minimax-m2.5
- openrouter/mistralai/mistral-large-4-0
- openrouter/moonshotai/kimi-k2.7-code
- openrouter/moonshotai/kimi-k3
- openrouter/openai/gpt-oss-120b
- openrouter/openai/gpt-oss-20b
- openrouter/particle-ai/particle-1
- openrouter/qwen/qwen3-235b-a22b-2507
- openrouter/qwen/qwen3-coder-30b-a3b-instruct
- openrouter/qwen/qwen3-next-80b-a3b-instruct
- openrouter/qwen/qwen3.8-27b
- openrouter/z-ai/glm-4.6v
- openrouter/z-ai/glm-4.7
- openrouter/z-ai/glm-5.2
- openrouter/z-ai/glm-5.3-flash
- openrouter/z-ai/glm-5.3-flashx
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-pro-latest
- openrouter/~deepseek/deepseek-v4-flash-latest
- openrouter/~moonshotai/kimi-latest
- openrouter/~x-ai/grok-latest
- openrouter/~z-ai/glm-flash-latest
- vercel/deepseek/deepseek-v4-flash-0731
- vercel/deepseek/deepseek-v4-pro
- vercel/deepseek/deepseek-v4.1-flash
- vercel/deepseek/deepseek-v4.1-flash-1017
- vercel/mistral/mistral-large-4
- vercel/moonshotai/kimi-k3.1-pro
- vercel/zai/glm-5.2
</details>

## Review notes

Regenerated by `make gen/aibridge-prices` from the live
[models.dev](https://models.dev) catalog. Both artifacts come from one
snapshot, so they ship together:

- `coderd/aibridge/prices/data/prices.json`
- `site/src/modules/aiModels/knownModels/knownModelsGenerated.json`

These are customer-visible cost numbers taken from upstream data, so
this PR is never merged automatically. The summary above lists what
moved; check the diff for exact figures before approving.

Opened automatically by the [aigateway-prices-refresh
workflow](https://github.com/coder/coder/actions/runs/41999352102).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-05 09:48:48 +00:00
coder[bot]andNick Vigilante a7f3e3b685 docs: promote the AI sections and Templates to the top level of the sidebar (#31645)
> [!NOTE]
> Generated by Coder Agents. The branch and this description were
written by an AI agent and need human review.

## Summary

First of three stacked PRs for the docs IA overhaul (Proposal 1, section
3). This PR dissolves `docs/ai-coder/` into four top-level sidebar
sections, in this order, where "Run AI coding agents in Coder" used to
be: **Coder Agents**, **AI Governance** (with Agent Firewall and AI
Gateway nested under it), **Agent Relay**, and **MCP server**.

- Files move with `git mv`, so `git log --follow` keeps their history.
The move includes every file in the moved folders, including pages that
are not in the sidebar, such as `agent-firewall/example-policy.md`, and
pages added to `main` after the first version of this PR, such as
`agents/projects.md` (#30684) and `agents/acp-subagents.md` (#31430).
- `docs/ai-coder/index.md`, `best-practices.md`, and `ide-agents.md` are
deleted. Each has a redirect (see below).
- `docs/manifest/` mirrors the new folders: `coder-agents.yml` (+
`coder-agents/`), `ai-governance.yml` (+ `ai-governance/`),
`agent-relay.yml`, and `mcp-server.yml`. `ai-coder.yml` is deleted. The
Projects and ACP subagents entries from `main` move with Coder Agents.
- Every relative link and image path is fixed, both in the moved pages
(their base directory changed) and in pages that link to them. This was
done in one scripted pass from a clean `main` checkout. Every link was
then checked to resolve on disk.
- Commit 2, `chore: point in-product docs links at the new docs paths`,
updates docs URLs outside `docs/`: `site/` `docs()` links, Go error
strings and comments, `README.md`, `server.json`, templatebuilder
modules, and the doc-check skill. Commit 4 reverts the unversioned
`https://coder.com/docs/...` URLs among them (see below), so after this
PR only these differ from `main` outside `docs/`: the `site/` `docs()`
links, the versioned `cli/cliui` troubleshooting links, and repo file
paths in comments and the doc-check skill's examples
(`docs/coder-agents/...`, `docs/templates/...`). You can drop commit 2;
the redirects cover the old URLs.
- **#31646 (Templates) was squash-merged into this branch** as
`98377a3a3b`. This PR now also carries the Templates move
(`docs/admin/templates/**` → `docs/templates/**`, plus
`template-from-scratch.md` and `testing-templates.md`) and its chore
changes. Refer to #31646 for that part's move map, redirects, and
review.
- Commit 4, `fix: keep docs links healthy before the release`, keeps
links working on the live site until a release that includes this stack
becomes the default docs version:
- Hand-written pages that linked to moved pages with absolute
`https://coder.com/docs/...` URLs now use relative links, anchors kept.
The new paths 404 on the live site today, but relative links resolve for
every version and are checked locally.
- Hardcoded, unversioned `https://coder.com/docs/<new path>` URLs
outside `docs/` that the chore commits introduced (Go strings including
the prebuilds metric help, CLI help, the
`agentFallbackTroubleshootingURL` default, `README.md`, `server.json`,
examples, templatebuilder files, and one `site/` constant) go back to
their current paths. Then `make gen` regenerated the generated table in
`docs/admin/integrations/prometheus.md`,
`scripts/metricsdocgen/generated_metrics`, the CLI golden files, and
`docs/reference/cli/templates/{create,edit}.md`. See "Post-release
follow-up".
- The `site/` `docs()` changes and the `cli/cliui` links stay, because
those URLs are versioned (`/docs/@vX.Y.Z/...`) and resolve once the
release ships.
- Commit 5, `docs: prefix relative links in the moved pages with ./`,
adds `./` to 13 relative links that the move script wrote without it, in
`docs/mcp-server.md` and three Templates pages.
They resolved, but every other relative link in the docs starts with
`./` or `../`.
- Commit 6, `docs: keep the coding agent module guidance in the
templates docs`, adds an **AI agent modules** section to
`docs/templates/extending-templates/modules.md`.
Deleting `docs/ai-coder/index.md` removed the only instructions for
adding a terminal coding agent to a template with a registry module.
The example (`registry.coder.com/coder/claude-code/coder`, `version =
"~> 5.2"`) passes `terraform validate`, and the Template Builder labels
it cites match `site/src/pages/TemplateBuilder/ModuleSelectStep.tsx`.

Stack: **this PR** (with #31646 squash-merged in) →
`docs/ia-tutorials-nav` (#31647, Tutorials + nav renames) →
`docs/ia-workspaces-folder` (#31650, folder rename).

Refs: Linear DOCS-1154, DOCS-1179, and DOCS-1479 for the coder.com and
router redirect fix.

## Move map

| Old | New |
| --- | --- |
| `docs/ai-coder/agents/**` (25 files) | `docs/coder-agents/**` |
| `docs/ai-coder/ai-governance.md` | `docs/ai-governance/index.md` |
| `docs/ai-coder/agent-firewall/**` (9 files) |
`docs/ai-governance/agent-firewall/**` |
| `docs/ai-coder/ai-gateway/**` (26 files) |
`docs/ai-governance/ai-gateway/**` |
| `docs/ai-coder/agent-relay/**` (3 files) | `docs/agent-relay/**` |
| `docs/ai-coder/mcp-server.md` | `docs/mcp-server.md` |
| `docs/ai-coder/index.md` | deleted |
| `docs/ai-coder/best-practices.md` | deleted |
| `docs/ai-coder/ide-agents.md` | deleted |

## Redirects added

Appended to `docs/redirects.json`, using the absolute `/docs/...` format
that `main` validates today. Wildcards cover every page under each moved
folder, including pages that are not in the sidebar and the pages added
to `main` since the first version of this PR.

| Source | Destination |
| --- | --- |
| `/docs/ai-coder` | `/docs/coder-agents` (deleted hub, **please
confirm**) |
| `/docs/ai-coder/best-practices` | `/docs/coder-agents` (deleted,
**please confirm**) |
| `/docs/ai-coder/ide-agents` | `/docs/user-guides/workspace-access`
(deleted, **please confirm**) |
| `/docs/ai-coder/ai-governance` | `/docs/ai-governance` |
| `/docs/ai-coder/mcp-server` | `/docs/mcp-server` |
| `/docs/ai-coder/agents/:path*` | `/docs/coder-agents/:path*` |
| `/docs/ai-coder/agent-firewall/:path*` |
`/docs/ai-governance/agent-firewall/:path*` |
| `/docs/ai-coder/ai-gateway/:path*` |
`/docs/ai-governance/ai-gateway/:path*` |
| `/docs/ai-coder/agent-relay/:path*` | `/docs/agent-relay/:path*` |

None of the 3 existing rules in `docs/redirects.json` points into
`ai-coder/`, so no destinations needed updating.

**coder.com and router static redirects.**
coder.com applies its own `redirects.json` and the rules it generates
from this file before it hands `/docs` to the docs-engine router, which
applies its own static `redirects.json` before the page.
Three older static rules in both repos send `/docs/templates`,
`/docs/templates/open-in-coder`, and `/docs/templates/troubleshooting`
to `/docs/admin/templates/...`, and the `/docs/admin/templates/:path*`
rule here sends them back, so each loops once a release with this layout
is the docs mainline.
A static `/docs/workspaces` rule would also hide the new
`docs/workspaces/index.md` page from #31650.
coder/coder.com#1201 and coder/docs-engine#304 (draft, DOCS-1479) remove
those rules; they must merge when that release becomes the mainline, not
before, because the old-layout mainline still needs them.
A chain simulation of every page and static source on each branch of
this stack finds no other loops or hidden pages.
The `/docs/ai-coder/...` and other legacy rules there still work; some
now take two redirects.

## Deviations from the proposal

- **Glossary "IDE agent" entry.** The proposal says to remove this link
and leave plain text. I pointed it at Access your workspace
(`docs/user-guides/workspace-access/index.md`) instead, the same page
the `ide-agents` redirect uses, because "Refer to IDE agents." with no
link reads as a dead end. The "Coding agent" entry now links to Coder
Agents, as the proposal says.
- **Top-level icons.** The new sections need icons. I chose `wand.svg`
(Coder Agents, the old ai-coder icon), `ai_intelligence.svg` (AI
Governance), `link.svg` (Agent Relay), and `plug.svg` (MCP server).
- **Coding agent module guidance.** Kept on the Reuse template code page
(commit 6) instead of deleted with `docs/ai-coder/index.md`. The
best-practices and IDE-agent pages are deleted as proposed.
- **Order relative to Administration.** In this PR the four sections sit
where `ai-coder` was, after Administration. PR C moves Administration
after MCP server to reach the final order.
- **`docs/mcp-server.md` repo link.** A relative link to
`codersdk/toolsdk/toolsdk.go`, outside `docs/`, was re-based for the new
depth.
- **Left unchanged on purpose:**
- Database migrations and the notification `.golden` files rendered from
them still contain `coder.com/docs/ai-coder/...` URLs. Existing
migrations can't be edited, so those links rely on the redirects.
- `aibridge/client/client.go` links to a commit-pinned GitHub permalink,
which still resolves.
- Test fixtures in `scripts/docsredirectscheck` and
`.github/workflows/test-docs-preview-mapper.sh` use `ai-coder` as sample
data.
-
`site/src/pages/AgentsPage/components/ChatElements/tools/Tool.stories.tsx`
uses `https://coder.com/docs/ai-coder/ai-gateway` as a sample web search
result. Changing it would only change a visual snapshot.

## Open questions for Nick

1. Do you agree with the three redirect targets for the deleted pages
above?
2. Should the "IDE agent" glossary entry link to Access your workspace
(current) or be plain text (proposal)?
3. Are the icons for the new top-level sections OK?
4. Open PRs that touch the moved files, checked with `git merge-tree`
against this branch. I didn't change them.
- #31169 merges cleanly: Git's rename detection carries its edit to
`docs/ai-governance/ai-gateway/clients/claude-code.md`, and its new
relative link still resolves at the new path.
- #30262 now targets `tk/ai-gateway-responses-ws-endpoint` and conflicts
with `main` in 21 files. Against this branch it conflicts in the same 21
files, with `codex.md` at its new path, so this PR doesn't add new
conflicts. Its new relative links still resolve after the move.
- #30805 conflicts in `docs/redirects.json`. It already conflicts with
`main` there, because `main` added the `/docs/about/screenshots` and
`/docs/install/cli` rules.

## Release

No backport to `release/2.39` for now; Nick may apply it by hand later.
A cherry-pick of this branch onto `release/2.39` conflicts in 25 files,
and #31647 and #31650 would need the same treatment to keep the stack
together.
coder/coder.com#1201 and coder/docs-engine#304 merge when the first
release line that carries this layout becomes the docs mainline (2.38
today).

## Known limitations

- **CLI newer than its server.** The `cli/cliui` troubleshooting links
append `/templates/troubleshooting#...` to the server's versioned docs
URL.
A CLI from this release against an older server prints
`/docs/@v2.38.x/templates/troubleshooting#...`.
The router's static
`/docs/templates/:page(open-in-coder|troubleshooting)` rule redirects
that to the old page today, but coder/docs-engine#304 removes that rule
to fix the loop, so after the cutover that case gets the version's
not-found page.

## Post-release follow-up

After a release that includes this stack becomes the default docs
version on coder.com, point these hardcoded URLs at the new paths. They
work today and redirect after the release, so nothing breaks in the
meantime. Anchors are unchanged. Rerun `make gen` afterward to update
`docs/admin/integrations/prometheus.md`,
`scripts/metricsdocgen/generated_metrics`, the CLI golden files, and
`docs/reference/cli/templates/{create,edit}.md`.

| Current (old) URL | Post-release URL | Files |
| --- | --- | --- |
| `https://coder.com/docs/ai-coder/agents` |
`https://coder.com/docs/coder-agents` |
`.claude/skills/doc-check/output.md`, `README.md` |
| `https://coder.com/docs/ai-coder/agents/architecture` |
`https://coder.com/docs/coder-agents/architecture` |
`coderd/x/chatd/chattool/execute_test.go`,
`codersdk/toolsdk/workspacetools/execute.go` |
| `https://coder.com/docs/ai-coder/ai-gateway` |
`https://coder.com/docs/ai-governance/ai-gateway` | `README.md`,
`coderd/templatebuilder/modules/claude-code/module.json`,
`coderd/templatebuilder/modules/codex/module.json` |
| `https://coder.com/docs/ai-coder/mcp-server` |
`https://coder.com/docs/mcp-server` | `server.json` |
| `https://coder.com/docs/admin/templates` |
`https://coder.com/docs/templates` | `README.md` |
|
`https://coder.com/docs/admin/templates/extending-templates/docker-in-workspaces`
|
`https://coder.com/docs/templates/extending-templates/docker-in-workspaces`
| `examples/templates/docker-devcontainer/main.tf` |
|
`https://coder.com/docs/admin/templates/extending-templates/parameters`
| `https://coder.com/docs/templates/extending-templates/parameters` |
`examples/parameters-dynamic-options/README.md`,
`examples/parameters/README.md`, `examples/parameters/main.tf`,
`examples/templates/kubernetes-envbox/README.md`,
`examples/workspace-tags/README.md` |
|
`https://coder.com/docs/admin/templates/extending-templates/prebuilt-workspaces`
|
`https://coder.com/docs/templates/extending-templates/prebuilt-workspaces`
| `coderd/prebuilds/api.go`,
`enterprise/coderd/prebuilds/metricscollector.go` (metric help text) |
|
`https://coder.com/docs/admin/templates/extending-templates/workspace-tags`
| `https://coder.com/docs/templates/extending-templates/workspace-tags`
| `examples/workspace-tags/README.md` |
| `https://coder.com/docs/admin/templates/managing-templates` |
`https://coder.com/docs/templates/managing-templates` |
`cli/templatecreate.go`, `cli/templateedit.go` (CLI help) |
|
`https://coder.com/docs/admin/templates/managing-templates/image-management`
| `https://coder.com/docs/templates/managing-templates/image-management`
| `coderd/templatebuilder/bases/docker/README.md`,
`coderd/templatebuilder/bases/kubernetes/README.md` |
| `https://coder.com/docs/admin/templates/troubleshooting` |
`https://coder.com/docs/templates/troubleshooting` |
`agent/agentscripts/agentscripts.go`,
`coderd/render/escape_internal_test.go`, `codersdk/deployment.go`
(`agentFallbackTroubleshootingURL` default) |
| `https://coder.com/docs/tutorials/template-from-scratch` |
`https://coder.com/docs/templates/template-from-scratch` |
`site/src/pages/TemplateBuilder/TemplateAlternatives.tsx` |

## Validation run

- `make gen/docs-manifest`: clean diff afterward.
- `make lint/docs-manifest`, `lint/docs-redirects` (`go run
./scripts/docsredirectscheck -base origin/main`: 15 rules OK, no
removed-route warning), `lint/docs-html`, `lint/emdash`: pass.
- `pnpm check-docs` (markdownlint + table formatter): pass.
- Vale (`vale --no-exit docs/`): the same 12 warnings and 1 error as
`main`, all pre-existing. Suggestions drop from 646 to 645; the one
removed was in the deleted `ide-agents.md`.
- Local relative-link check over `docs/**/*.md`: 0 unresolved links or
images (also 0 on `main`).
- Pre-commit hook: `make pre-commit-light` on the docs commit, and the
full `make pre-commit` (gen, fmt, lint/go, lint/ts, build, and others)
on the chore commit. Both passed.
- Targeted tests:
- Go: `go test ./coderd/x/chatd/chattool/... ./codersdk/toolsdk/...
./coderd/templatebuilder/...`.
- Site: Vitest for the touched directories (107 files, 1879 tests), and
the story tests for `CoderAgentsProductCard`, `GroupSettingsPageView`,
`GatewayKeysPageView`, and `ModelForm` (4 files, 63 tests).
- Every `docs()` path and anchor in the `site/` and Go diff resolves to
a page and heading in this branch.
- Frontend deep review (all 8 roles) on the `site/` diff of PRs A and B:
no blocking or should-fix findings. Nits on existing code that this PR
only touched, not changed here: a single-use `docsLink` constant in
`ChatAccessDeniedAlert.tsx`, and assertion-only `play` functions in the
`GatewayKeysPageView`, `ModelForm`, `CoderAgentsProductCard`, and
`GroupSettingsPageView` stories.
- Page counts: `docs/**/*.md` (excluding `.style`) 490 → 487;
`manifest.json` routes 495 → 492. With #31646 squash-merged in, the
counts don't change, because the Templates move only moves files.
- **Link health (commit 4):**
- linkspector 0.5.6 with `.github/.linkspector.yml` over all of `docs/`,
like the weekly docs job (`umbrelladocs/action-linkspector`, `reporter:
local`, `filter_mode: nofilter`). I ran it locally with Chrome in
`--no-sandbox` mode.
- `origin/main`: 0 errors. Before the fix (`17e54ad555`): 6 errors, all
`https://coder.com/docs/<new path>` 404s (`shared-workspaces.md:19`,
`esr-2.24-2.29-upgrade.md:80-82`, `tasks-to-chats-migration.md:73`,
`prometheus.md:298`). After the fix (`def074caab`): 0 errors. A first
run after the fix also flagged a Red Hat URL in
`install/server/openshift.md`. That URL is unchanged from `main`, and it
passed on a rerun, so the failure was transient.
- After the fix: `make gen/docs-manifest` (clean), `lint/docs-manifest`,
`lint/docs-redirects` (15 rules OK against `origin/main`),
`lint/docs-html`, `lint/emdash`, `pnpm check-docs`, and the
relative-link check (0 unresolved in 3416 links) pass. The full `make
pre-commit`, including `make gen`, passed on the commit.
  - Tests after the fix:
- Go: `go test ./cli -run 'TestCommandHelp|TestServerYAMLConfig'`,
`./enterprise/cli -run TestEnterpriseCommandHelp`, `./coderd/render`,
`./agent/agentscripts`, `./coderd/prebuilds`,
`./enterprise/coderd/prebuilds`, `./coderd/x/chatd/chattool/...`,
`./codersdk/toolsdk/...`, `./coderd/templatebuilder/...`.
    - Site: Vitest for `src/pages/TemplateBuilder` (7 files, 67 tests).
- **After the rebase onto `ccf5ec74ae`** (commits 5 and 6 included):
`make gen/docs-manifest` (clean), `lint/docs-manifest`,
`lint/docs-redirects` (15 rules OK), `lint/docs-html`, `lint/emdash`,
`pnpm check-docs`, and a relative-link and anchor check over the changed
pages pass.
The only unresolved anchor,
`docs/ai-governance/ai-gateway/cost-controls.md` →
`enterprise.md#list-organization-ai-spend-by-user`, is also broken on
`main`.
The pre-commit hook (`make pre-commit-light`, because both new commits
touch only `docs/`) passed on commits 5 and 6. The rebased code commits
rely on CI for Go and TypeScript checks.
- **Redirect chains:** a Node simulation of coder.com's static rules,
its generated rules from this branch's `docs/redirects.json`, the
router's static rules, the page, then this branch's rules on a miss,
over every page and exact static source, reports the 3 loops above and
nothing else new; with coder/coder.com#1201 and coder/docs-engine#304
applied, 0.
- **Skipped:** the docs-engine sync check, which was not available in
this environment.

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

- Rebuilt on `main` at `ccf5ec74ae` (2026-11-03) to clear conflicts with
`main`, after an earlier rebase the same day onto `1a963c628d`. The
previous rebuild was on `9839406ff7` (2026-11-02), and the first version
on `9b8d880d63` (2026-10-23).
- Rebase conflicts with #31603, which added `target="_blank"
rel="noreferrer"` to docs links: 4 `site/` files in the chore commit and
5 in the Templates commit. Each kept `main`'s version of the link with
only the docs path changed. Vitest for the 7 affected page directories
(233 tests) and the story tests for the 8 changed or affected stories
(102 tests) pass, and every `docs()` path in `site/src` resolves except
the same 13 that are unresolved on `main`.
- Rebase conflict: `docs/manifest/coder-agents.yml`. `main` added
`docs/ai-coder/agents/bring-your-own-mcp-servers.md`; it moves to
`docs/coder-agents/` with its sidebar entry, and its
`../../user-guides/` links become `../user-guides/`.
- Folded into the Templates commit: a link that `main` added to
`docs/user-guides/workspace-dotfiles.md` (#31606) now points at
`../templates/extending-templates/environment-variables.md`.
- `git range-diff` against `def074caab`, the head before both rebases,
shows only those changes.
- The move script reads every page from the clean `main` checkout and
resolves each relative link (inline, reference-style, and HTML
`src`/`href`) against the page's **old** directory. It maps the target
through the move map and recomputes the link from the page's **new**
directory. It runs once and refuses to run on a dirty `docs/` tree, so
it can't apply the path math twice. It also rewrites absolute
`coder.com/docs/...` and
`github.com/coder/coder/(blob|edit|tree)/main/docs/...` URLs, and skips
fenced code blocks and inline code.
- Before reusing the script, I ran it on the old base and diffed the
result against the old commit. The only differences were the two
hand-edited glossary entries and table padding from the formatter, so
the rebuild applies the same changes to the current `main`.
- Afterward, `grep -r ai-coder docs/` finds matches only in
`docs/redirects.json`.
- Changes from the earlier version of this branch: 2 more pages move
(`agents/projects.md`, `agents/acp-subagents.md`) and their sidebar
entries move with them. The chore commit also updates
`SessionSummaryTable.tsx` (new on `main`) and the doc-check skill's
`output.md` (its examples moved there from `SKILL.md`). The
`AICostControl.tsx` anchor question is gone, because `main` fixed it.

</details>

---------

Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com>
Co-authored-by: Nick Vigilante <nick.vigilante@coder.com>
2026-11-04 17:15:42 -05:00
Jon Ayers 31a85e6b8c fix: fix flaky TestChatTurnStopsAtStepLimit (#31759) 2026-11-04 15:10:20 -06:00
dylanhuff-at-coderandClaude Opus 5.5 8efd1fc86e fix(coderd/workspaceapps)!: strip session tokens before proxying to apps (#31633)
The workspace app proxy stripped Coder cookies before forwarding a
request to the app, but not the `Coder-Session-Token` header or the
`coder_session_token` query parameter. App auth accepts both, so a
client that authenticated that way (the CLI and codersdk, or an IDE
extension pointed at a path app URL) passed its API key through to
whatever runs behind the app. That matters most for shared apps and
ports, where the caller's token reached a workspace owned by someone
else.

This strips both before proxying. The query parameter is removed from
the raw query string, so everything else in the query reaches the app
byte-for-byte. `Authorization` and `access_token` are still forwarded
since apps can use them for their own auth. Stripping those safely needs
to know which credential Coder actually used, so that's tracked in
[CORE-817](https://linear.app/codercom/issue/CORE-817/strip-authorization-and-access-token-from-app-proxy-requests-when).

This is marked breaking because an app that relied on the caller's Coder
token arriving through that header or query param won't get it anymore.
Cookie-authenticated requests were already covered, so this only affects
callers that send the token in that header or query param. Nothing in
this repo depends on it. Apps that need to call the Coder API as the
visitor should use the OAuth2 provider instead.

Covered by the shared app proxy tests, which run against coderd and
wsproxy, for both the owner on a path app and another user on a shared
subdomain app, plus unit tests for the query filtering.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:59:50 -08:00
Jon Ayers 2138549ed2 fix(coderd/provisionerdserver): store import module archives outside the transaction (#31576)
Fixes a race where two template imports finishing at the same time with
identical module archives fail one of them on
`files_hash_created_by_key`.
2026-11-04 10:32:03 -06:00
Michael SuchaczandEthan Dickson 79e3601535 fix: bound workspace agent responses and stop relaying agent 401s (#30183)
Follow-up to the chat workspace-upload security review (ISSUE-1,
ISSUE-10).

Workspace code can impersonate the workspace agent HTTP API, so coderd
shouldn't trust what comes back from it. This PR fixes two places where
it did.

First, coderd read agent responses without a size limit. The worst case
was the `propose_plan` tool, which the model can call at any time and
which ran `io.ReadAll` on a `ReadFile` body, but `DebugLogs`,
`DebugMagicsock`, `DebugManifest`, `PrometheusMetrics` and
`StopDesktopRecording` did the same. To fix, every agent request in
`workspacesdk` now goes through one limit in `apiRequestWithOptions`: 32
MiB by default, with larger per-request limits for the few endpoints
that legitimately return more (support bundle files, debug logs, desktop
recordings, and `ReadFile` up to the requested limit). Reads past the
limit fail rather than truncate. Error bodies are capped at 64 KiB for
every status, including on the ACP client and `CancelToolCall`. Nothing
legitimate gets close to 32 MiB; the biggest is a desktop screenshot at
around 8 MB.

Second, coderd relayed agent statuses straight to the browser. The
container list and devcontainer delete/recreate handlers passed through
any agent status and response, so an agent answering 401 made the site's
`RequireAuth` interceptor sign the user out. The workspace page lists
containers automatically, so this hit anyone viewing the workspace, not
just the owner. The chat upload handler had the same problem. To fix,
these handlers now turn an agent 401, 407, or anything outside 4xx/5xx
into a 502, with the agent's message in a truncated `Detail`. A real
agent never sends any of those, so every status it does send (403, 404,
409, 500, 503) still passes through unchanged. A 404 on upload still
maps to 409 (outdated agent).

An earlier revision of this PR relayed only an allowlist of expected
statuses with a coderd-written message, but that turned real 500s and
503s into 502s and replaced the agent's own messages. There's no reason
to change the statuses a real agent sends today, so we just block the
ones that can sign the user out.

The composer upload pill still truncates the error message and never
shows `Detail`; that's left for a follow-up.

> [!NOTE]
> Opened by Xum on behalf of @ibetitsmike. Rebased by Coder Agents on
behalf of @ibetitsmike. Updated by Xum on behalf of @ethanndickson.

---------

Co-authored-by: Ethan Dickson <ethanndickson@gmail.com>
2026-11-04 12:15:55 +11:00
Steven Masley bc5dd20a05 feat: report Agent Relay builds in telemetry (#31407)
Telemetry builds now report whether Agent Relay created them. Before
this, relay workspaces looked like any other build.

A start build counts as a relay build when it has the
`agent_relay_session_id` parameter. Stop and delete builds never get the
field. For those builds, the new `agent_relay` field on `WorkspaceBuild`
reports:

- `provider`: `claude_code`, `cursor`, `ambiguous`, or `unknown`
- `client_platform`: Claude Code only. Lowercased, characters outside
`[a-z0-9_]` become `_`, and cut to 15 characters
- `attempt`: omitted when missing or not an integer, so `0` is sent
- `session_id_hash` and `pool_hash`: SHA-256 hashes

No other parameter values are sent. Other builds leave the field out.

The snapshot fetches these parameters with one new batch query. The
workspace-create event reads the stored parameters with one extra query,
only when telemetry is enabled, so it reports the same data as the
snapshot. `docs/admin/setup/telemetry.md` lists the parameters that are
read.

The collector side is
[coder/coder-telemetry-server#56](https://github.com/coder/coder-telemetry-server/pull/56).
Merge this PR first.

Refs
[RELAY-9](https://linear.app/codercom/issue/RELAY-9/telemetry-report-agent-relay-usage-from-codercoder)

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

- **Detect relay builds from parameters.** This needs no relay changes.
Relay registration or
[CORE-426](https://linear.app/codercom/issue/CORE-426) provenance
metadata can come later.
- **Builds only, not workspaces.** `GetWorkspaces` doesn't return the
latest build's parameters, so a workspace field would cost another
query. The collector can join on `workspace_id`.
- **Provider comes from parameter names only.**
`agent_relay_claude_code_*` means Claude Code and `agent_relay_cursor_*`
means Cursor. A build with both reports `ambiguous`; a build with
neither reports `unknown`. coderd stores every declared parameter on
every build (ephemeral ones with their default), so a Claude Code start
after a stop still reports `claude_code`.
- **Start builds only.** Stop and delete builds of a relay workspace
carry the same parameters but are not dispatches, so the snapshot skips
them before querying parameters.
- **Hash session ID and pool.** Pool names are user content, and
sessions only need counting.
- **Known gaps.** Cursor has no client platform. Relay version and
health would need relay registration.
- **Parameter names are shared with coder/agent-relay.** If agent-relay
renames one, telemetry silently stops reading it.

</details>

<details>
<summary>Manual test on <code>develop.sh</code></summary>

Ran on `8ad7cd491f` with `CODER_TELEMETRY_ENABLE=true
CODER_TELEMETRY_URL=http://127.0.0.1:8081` and `go run
./scripts/telemetry-server --port 8081` as the collector.

Pushed three templates with no infrastructure, each declaring the same
parameters as the real modules:

- `relay-claude`: `agent_relay_session_id`, `_delivery_id`, `_pool`,
`_client_platform`, plus ephemeral `agent_relay_attempt` and
`agent_relay_claude_code_lock_to_account`
- `relay-cursor`: `agent_relay_session_id`, `_delivery_id`, `_pool`,
`agent_relay_cursor_pool_name`, `_idle_release_timeout`, `_repo_url`
- `relay-plain`: `region`

Created workspaces with `POST /api/v2/users/me/workspaces` and
`rich_parameter_values`, the same call the relay makes. Then ran stop
and start builds on the relay workspaces, and restarted coderd to get a
periodic snapshot.

| Workspace | Build 1 (create event and snapshot) | Builds 2 and 3
(stop, start) |
|---|---|---|
| Claude (`claude_in_slack`, attempt 1) | `claude_code`, platform,
attempt 1 | `claude_code`, platform, no attempt |
| Cursor | `cursor` | `cursor` |
| Plain | field omitted | n/a |
| Claude template, no session ID | field omitted | n/a |

- Stop and start builds keep `agent_relay_claude_code_lock_to_account`,
with an empty value, so Claude Code rebuilds still report `claude_code`.
- No session ID, pool name, or `region` value appears in the captured
telemetry. The hashes match `sha256` of the inputs.
- Fed the captured snapshot through the conversion code in
coder/coder-telemetry-server#56: all 8 builds converted, 6 of them with
`agent_relay` set.
- No telemetry errors or panics in the coderd logs.

This run predates the start-only change: build 2 (stop) carried the
field then. Stop and delete builds are now omitted, which
`TestTelemetry_WorkspaceBuildAgentRelay` covers.

</details>


---

*Generated by Coder Agents on behalf of @Emyrk.*
2026-11-03 15:48:10 -06:00
Susana Ferreira c83914f514 feat: resolve the chat organization for Coder Agents AI Gateway requests (#31584)
## Description

Resolves Coder Agents requests to the chat's organization instead of the
organization of the user's effective group, so budgets and cost follow
the chat's organization. coderd checks that the user is still a member
of that organization and that it isn't deleted, and rejects the request
otherwise.

## Changes

- Add `delegated_organization_id` to `IsAuthorizedRequest`, part of
aibridged API v1.6, which is not released yet.
- aibridged sends the chat organization from the delegated attribution
on delegated requests.
- `IsAuthorized` accepts the delegated organization only on delegated
(`key_id`) requests, and rejects it otherwise.
- The org resolver resolves the chat organization with source `chatd`,
after checking membership. The membership check is shared with the
workspace path.
- Add `TestAuthorization_DelegatedOrgResolution`, extend
`TestServeHTTP_ResolvedOrganization` with a delegated chat request, and
make `TestIntegrationResolvedOrganization` table-driven, with a case per
organization source and a delegated request with a workspace.

Closes AIGOV-713

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-03 16:39:43 +00:00
Susana Ferreira 8d5026c57a feat(coderd): send the chat organization in Coder Agents AI Gateway requests (#31583)
## Description

Every Coder Agents chat belongs to an organization, but its AI Gateway
requests don't carry it. AI Gateway instead uses the organization of the
user's cost control effective group, which can be a different one. So a
chat in org A can have its budget and cost attributed to org B. This PR
makes Coder Agents send the chat's organization with its delegated
attribution, so AI Gateway can use the chat's organization for the whole
request. AI Gateway starts using it in the next PR in this stack, so
behaviour doesn't change here.

## Changes

- Add `DelegatedOrganizationID` to `aibridge.Attribution`, and fix the
`WorkspaceID` comment, which applies to workspace session tokens too.
- Set it from the chat in `newModel` when routing Coder Agents requests
through AI Gateway.
- Extend `TestNewModelAttributionImmutablePerRequest` to check the
organization.

Related to AIGOV-713

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-03 16:39:42 +00:00
Jaayden Halko 820689dc0b feat: include the owner in the chat project ACL response (#31244)
The chat project ACL response now includes the project's owner, so the
project page can show who owns a project to everyone who can read it.

`GET
/api/experimental/organizations/{organization}/chats/projects/{project}/acl`
returns a new `owner` field (`MinimalUser`). The owner is never in
`users`, and `GET /api/v2/users/{id}` returns 404 to regular
organization members, so project members and project admins currently
see the owner as "Unknown". The handler loads the owner with a
system-restricted context after the existing read and sharing-disabled
checks, matching how it already loads shared users and groups.

`TestChatProjectSharing/User` and `/Admin` now check the owner as seen
by the owner, a `use` sharee and an `admin` sharee, and that both
sharees still get 404 from the users endpoint. Dogfood UAT on a dev
deployment confirmed the field for all three callers, no owner data for
callers without access (404), and the unchanged 403 when chat sharing is
disabled.

Stack (merge bottom first):
- 👉 this PR
- #31245
- #31246
- #31247
2026-11-03 23:03:37 +07:00
Hugo Dutka 788c38ae18 fix(coderd/x/chatd): validate tool inputs against schemas (#31541)
Builtin tool calls could reach handlers with missing required fields or
other arguments that violate their declared schemas. Validate
model-proposed inputs before hook dispatch and persistence, return tool
errors so the model can correct them, and reject invalid hook overrides.
2026-11-03 15:47:54 +00:00
Mathias Fredriksson 540552f7b7 feat: expose the workspace template to agent commands (#31606)
The agent now sets CODER_WORKSPACE_TEMPLATE_ID and
CODER_WORKSPACE_TEMPLATE_NAME for every command it runs, from new
template_id and template_name manifest fields. Templates run different
scripts in different orders, so a user's own script needs to know which
template it runs under to coordinate with that template's scripts.

The Agent API goes to v2.16 because release/2.39 shipped v2.15.
CODER_WORKSPACE_BUILD_ID loses its nil checks: an agent only connects
to servers that support its API version, and those always send the
build ID. The environment variables docs now list the variables the
agent sets.
2026-11-03 12:34:49 +02:00
Ethan ff40ec6900 fix: pick the Anthropic computer use tool version from the model on every platform (#31657)
#31521 made computer use send `computer_toolset_20260801` to Claude 4.8
and later, but swapped it back to `computer_20251124` on Claude Platform
on AWS and Bedrock, since Anthropic's docs say neither offers the
toolset. That's wrong for Claude Platform on AWS, so computer use on
dogfood's Opus 5.5 fails with `'claude-opus-5-5' does not support tool
types: computer_20251124`.

I probed the AI gateway, and Claude Platform on AWS accepts exactly the
versions the Claude API does, e.g. the toolset for Opus 4.8 and 5.5, and
`computer_20251124` for Opus 4.6. The harnesses that get this right
(Anthropic's computer-use demo and SDK toolset helpers, the Vercel AI
SDK, LiteLLM) pick the version from the model ID alone and leave the
wire format to the platform client, so we'll do the same and drop the
override. fantasy's doc comment repeated the docs, which
coder/fantasy#83 fixed, so this bumps fantasy too.

Bedrock follows the same model table. AWS's Opus 4.8 model card only
lists `computer_20251124`, but it's just behind: Anthropic's Bedrock
docs list Opus 4.8 as taking the toolset with no beta header, and
`anthropic.claude-opus-4-8` on Bedrock (via Mantle in us-east-1)
returned a `screenshot` tool call for the toolset with no beta.
Dogfood's InvokeModel route, which runs Opus 5.5, does the same.

Bedrock was also broken on `main`, since aibridge's Bedrock beta
allowlist drops `computer-use-2025-11-24`, so `computer_20251124` never
got through validation. I've added it. On InvokeModel, Opus 4.7 returned
a `computer` tool call for `computer_20251124` once the flag reached
Bedrock, but a 400 when the flag went through dogfood's gateway, which
runs `main` and drops it. Unlike the effort and context management
flags, the flag doesn't need gating per model, as Bedrock accepts it on
models that don't support `computer_20251124`. On Bedrock InvokeModel in
us-east-2, Haiku 4.5 returned a 200 with the flag on its own and with
`computer-use-2025-01-24` and a `computer_20250124` tool, whilst a
made-up flag got a 400. Bedrock only rejects the tool type itself, and
the model table never sends `computer_20251124` to Haiku 4.5 anyway.

InvokeModel does still run the provider's `settings.model` rather than
the model the chat config names, so the version can disagree with what
actually runs if the two differ. That's the known model swap in #29511,
and it's no worse here, as `main` picked the version from the model
config too. The documented setup is one provider per model, so the two
match, and the native `bedrock-runtime` protocol will remove the swap.

I verified Claude Platform on AWS end to end, running Coder Agents from
this branch against dogfood's AWS gateway route. Computer use on Opus
5.5 and Sonnet 5.5 sent the toolset and got a 200 on every request,
across multi-step turns, an interrupted turn, a page reload, and a chat
that switched to Opus 4.6 (which sent `computer_20251124`) and back. The
same setup on `main` reproduced the 400.

I also ran the same scenarios against dogfood's Bedrock InvokeModel
route. Opus 5.5 and Haiku 5.5 got a 200 on every computer use request,
with up to 22 screenshots in the history, including a chat that switched
to Opus 4.6 on Claude Platform on AWS and back. That went through
dogfood's gateway, so it covers what Bedrock accepts from Coder Agents,
but not a Bedrock provider configured in Coder itself, which I still
haven't run end to end.
2026-11-03 16:52:56 +11:00
Ethan ba068876cd feat: register MCP OAuth2 clients when MCP server configs are updated (#31559)
Relates to CODAGT-779

We only ran Dynamic Client Registration when an MCP server config was
created. If an admin later switched an existing server to OAuth2, or
changed the URL of a server whose client Coder had registered, the
server was left without a working client, and users couldn't connect to
it.

To fix, create and update now go through the same planner, which
registers a client whenever a save needs one. That's when a config
becomes `dynamic` (on create, when the auth type changes to OAuth2, or
when `oauth2_client_registration` changes from `manual` to `dynamic`),
or when the URL of a `dynamic` config changes. The update request gets
an optional `oauth2_client_registration` field. When it's omitted, we
use `dynamic` if the resulting config has no client ID, auth URL or
token URL, and keep the stored value otherwise.

Coder owns the client ID, secret, auth URL and token URL of a `dynamic`
config, so we ignore them when a request leaves them empty or repeats
them, and any other value fails with a 400 unless the request also sets
`manual`. Updates that touch auth fields are also validated now, so a
`manual` config without a client ID, auth URL or token URL is rejected.
A new client replaces the client ID, so it deletes every user's stored
token. If discovery or registration fails, nothing changes, and if the
config changes whilst we're registering, the request fails with a `409
Conflict`.

There are a few gaps I've left for now, and documented. A change to the
deployment's access URL doesn't register a new client. Configs broken by
the old behaviour stay `manual` until an admin switches them to
`dynamic`. We also don't re-register when the provider rejects the
client with `invalid_client`.
2026-11-03 12:39:30 +11:00
Ethan d70ce38559 feat: record the OAuth2 client registration method of MCP server configs (#31558)
Relates to CODAGT-779

Currently we can't tell whether the OAuth2 client of an MCP server
config was entered by an admin, or registered by Coder with Dynamic
Client Registration (RFC 7591). The next PR in the stack needs to know
this, so it can register a new client when a config is updated.

This PR adds `mcp_server_configs.oauth2_client_registration` (`manual`
or `dynamic`) and returns it to admins on the API. Create stores
`dynamic` when it registers the client, and `manual` otherwise. An
update resets it to `manual` when it switches away from the `oauth2`
auth type, or when it changes the client ID, secret, auth URL or token
URL of a `dynamic` config, since the admin has replaced Coder's client.

Existing rows default to `manual`, as there's nothing in the data that
tells us which clients came from Dynamic Client Registration.
2026-11-03 12:39:30 +11:00
Ethan 7123db883d refactor(coderd): extract MCP server config merge, registration, and grant binding (#31557)
Relates to CODAGT-779

This is just a refactor to keep the next PRs in the stack small. I've
moved the update handler's per-field merge and auth type clearing into
`applyMCPServerConfigChange`, the create handler's discovery and Dynamic
Client Registration into `registerMCPOAuth2Client`, and the grant
comparison shared by the update handler and the OAuth2 callback into
`mcpOAuth2GrantBindingOf`.

There should be no behaviour change.
2026-11-03 12:39:29 +11:00
Michael SuchaczandEthan Dickson b6dc7158b4 feat: use the Anthropic computer use toolset for Claude 4.8 and later (#31521)
> Xum acted for Mike: this PR was written and opened by an AI agent on
Mike's behalf.

Computer use subagents on Claude 5.5 models (`claude-opus-5-5`,
`claude-sonnet-5-5`) failed on their first request: these models reject
`computer_20251124` and accept only the GA toolset
`computer_toolset_20260801`.

chatd now picks the Anthropic computer use tool version from the chat's
model with `ComputerUseToolVersionForModel` from coder/fantasy: the
toolset for Claude 4.8 and later, `computer_20251124` for Opus 4.5 to
4.7, Sonnet 4.6 and model IDs it cannot parse, and `computer_20250124`
for Haiku and Sonnet 4.5. Claude Platform on AWS and Amazon Bedrock
offer computer use only through the earlier versions, so an Anthropic
provider configured for either declares `computer_20251124` where the
model would take the toolset. For the toolset, chatd answers like
Anthropic's SDK tool runner: actions answer with text and only
`screenshot` returns an image, `cursor_position` returns the position as
text, `key` honors `repeat` (1 to 100), and zoom is declared disabled
because the agent desktop has no zoom action. The earlier versions still
answer every action with a screenshot.

A step's computer calls run one at a time in call order. For every
Anthropic version, the calls after one that failed, or that was rejected
before it ran (malformed input or a pre_tool_use hook denial), return
`Not executed: an earlier computer action in this turn failed.` without
running, which is the SDK runner's text. The chat loop enforces this
halt, so the computer tool keeps no state between calls. `wait` and
`hold_key` durations are read as seconds (capped at 300).

The frontend marks Claude Opus 5.5 and Sonnet 5.5 as verified for
computer use, and the computer tool row now labels each action ("Left
click", "Type", "Press key") instead of "Screenshot", shows text output,
and shows the error of failed or halted calls inline. The error block is
shared with the write_file and edit_files rows as
`ToolCall.ErrorDetail`.

Uses coder/fantasy#80 and coder/fantasy#82, both merged. `go.mod` pins
the fork to `7882f906a89a`.

<details>
<summary>UAT</summary>

TL;DR: it works. A remote Coder Agents UAT on dogfood passed on
`00143d5b12`, with all model traffic logged through a proxy:

- `claude-opus-5-5`, `claude-sonnet-5-5` and `claude-opus-4-8` declared
`computer_toolset_20260801` with zoom disabled and no beta header.
`claude-opus-4-6` and an unknown model ID declared `computer_20251124`
with the `computer-use-2025-11-24` beta, `claude-haiku-4-5` declared
`computer_20250124`, and a Claude Platform on AWS provider declared
`computer_20251124`. Opus 5.5, Sonnet 5.5, Opus 4.6 and Haiku 4.5 each
completed a desktop task.
- Toolset actions answered with text and only `screenshot` returned an
image. `repeat` 100 ran, 150 failed, and `wait` 400 stopped at 300
seconds.
- A failed call (`repeat` 150 on the toolset, a desktop error on 4.6)
and a pre_tool_use hook denial each halted the rest of the step without
touching the desktop. The next step ran normally.
- The computer tool rows showed action labels, text output and the halt
error. Opus 5.5 and Sonnet 5.5 showed no warning in the computer use
model selector. Switching a chat between 4.6 and 5.5 worked in both
directions.

Not tested: the tool type on Bedrock, and a halt after malformed model
input. Known, unchanged behavior: the desktop reports success for
unknown key names and off-screen coordinates, the model can still emit
`zoom`, which fails, and `scroll` up fails in `agent/x/agentdesktop`
because the negative amount is read as a flag. Both failures halt the
rest of their batch.

</details>

---------

Co-authored-by: Ethan Dickson <ethanndickson@gmail.com>
2026-11-02 21:28:22 +11:00
Michael Suchacz cd1361fae8 test(coderd/x/chatd): make the zero wait timeout test reach the default (#30985)
`ZeroTimeoutUsesDefault` passed a zero timeout to
`awaitSubagentCompletion`, but it marked the child chat `waiting` first,
so the call returned before it normalized the timeout. The test passed
with the normalization deleted. This PR deletes it and turns the
`Timeout` subtest into a two-row table, `Explicit` (1 s) and
`ZeroUsesDefault` (0, which must become 5 minutes). Each row checks the
duration of the trapped `subagent_await` timer, then advances the mock
clock until the call times out.

## Why it is safe

Mutants, applied with `go test -overlay` to
`TestAwaitSubagentCompletion`:

| Mutant | Old tests | New tests |
| --- | --- | --- |
| Delete `if timeout <= 0 { timeout = defaultSubagentWaitTimeout }` |
pass | `ZeroUsesDefault` fails: `0s`, want `5m0s` |
| `defaultSubagentWaitTimeout = 1 * time.Minute` | pass |
`ZeroUsesDefault` fails: `1m0s`, want `5m0s` |
| Always use the default timeout | `Timeout` fails after 25 s |
`Explicit` fails: `5m0s`, want `1s` |

`ZeroUsesDefault` expects `5 * time.Minute` rather than the constant, so
it also pins the `wait_agent` schema text "Defaults to 5 minutes." The
deleted subtest's assertions (no error, the child's ID, its report)
duplicate `AlreadyWaiting`, which runs the same early-return path. With
`handleSubagentDone` mutated to return an error, an empty chat, or an
empty report, `AlreadyWaiting` fails each time.

## Review focus

The clock moves in steps of at most 5 s, because the pubsub fallback
poll ticks every 5 s and the mock clock cannot advance past a pending
tick in one step. The zero row takes 60 steps and runs in about 0.2 s.

## Validation

- `go test ./coderd/x/chatd/ -run '^TestAwaitSubagentCompletion$'
-count=1`: pass.
- `go test ./coderd/x/chatd/ -race -run
'^TestAwaitSubagentCompletion$/^Timeout$' -count=20`: pass.
- Mutants: a copy of `subagent_manager.go` with a syntax error fails to
build, so the overlay applies.
- The pre-commit hook (`make pre-commit`) passed.

## Stack

This PR is stacked on #28758, which moves `awaitSubagentCompletion` into
`subagent_manager.go`.

1. #28758 refactor(coderd/x/chatd): extract subagent manager
2. #30985 test(coderd/x/chatd): make the zero wait timeout test reach
the default (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-11-02 05:33:57 +00:00
Michael SuchaczandEthan Dickson 97b68e37f9 refactor(coderd/x/chatd): move subagent operations out of tool closures (#28758)
Moves the subagent tools' logic (`spawn_agent`, `wait_agent`,
`message_agent`, `interrupt_agent`, `list_agents`,
`list_subagent_models`) out of large inline closures in `subagent.go`.
Child chat operations become typed `*Server` functions in
`subagent_operations.go` that other code can call, such as the workflow
prototype in #31189. The tools become adapters that parse arguments,
apply defaults and build the JSON.

## Changes

- `subagent_operations.go`: operations take chat IDs, a timeout or a
busy behavior and return plain values. `awaitSubagent` wraps
`awaitSubagentCompletion` with the computer_use desktop recording and a
last status check, and returns the chat, report and recording, a
timeout, or a `*subagentStatusError`. `sendSubagentMessage` and
`interruptSubagent` are main's, unchanged. `listSubagents` returns
unarchived children, most recently updated first. The helpers they call
move from main unchanged.
- `subagent.go`: keeps main's model override resolution. Each tool
parses `chat_id`, applies the wait timeout or list paging defaults,
reads the target chat so errors carry its `type`, and builds the JSON.
`spawnAgent` validates the `spawn_agent` arguments.
- Tool outputs are typed structs whose fields follow sorted key order,
so the JSON the model sees is byte-identical to main's map output.

## Behavior

No intended behavior change. Error strings, tool names, descriptions and
schemas, hook fail-closed handling, the wait loop and recording lifetime
match main. `wait_agent` reads the target chat once more, for the
recording decision.

> Xum (an AI coding agent) rebuilt this PR on behalf of @ibetitsmike.

---------

Co-authored-by: Ethan Dickson <ethanndickson@gmail.com>
2026-11-02 16:25:40 +11:00
Michael Suchacz 0a71846385 refactor(coderd/x/chatd/chattool): drop the read_skill alias fallback (#31123)
When `ReadSkillOptions.ResolveAlias` is nil, `read_skill` and
`read_skill_file` build a workspace skill from `GetSkills` and serve it.
Only tests leave the resolver nil. The one production caller,
`skillOpts` in `turn_environment.go`, always sets it to
`skillspkg.Lookup` over the merged personal, organization, project, and
workspace skills.

This PR deletes `resolveSkillAlias` and that fallback. Without a
resolver, both tools now return `skill alias resolver is not
configured`, as they already do for the other unset options. The tests
resolve names with the real `skillspkg.MergeSkills` and
`skillspkg.Lookup` instead of hand-written fakes. `read_skill_file`
still serves a workspace skill hidden from the model (#31147): it checks
for a nil resolver before `resolveSkillFileTarget`, which now calls
`ResolveAlias` directly. The PR adds 89 lines and removes 160.

## Why it is safe

- `git grep 'ReadSkillOptions{'` finds one non-test caller, and it sets
`ResolveAlias`. Behavior with a resolver does not change.
- `GetSkills` and `findSkill` stay. They still supply the pinned body,
the directory, and the supporting files of a resolved workspace skill.
- `TestReadSkillTool/ModelHiddenSkill` is deleted. It checked that the
fallback hid a skill that disables model invocation. With the real
resolver, `TestModelHiddenWorkspaceSkillsLeftOutOfModelSkills` checks
that, and it fails when the model-invocable filter in
`workspaceSkillsForResolution` is removed.
`ListedSkillServesFileThatDisablesModelInvocation` now sets a resolver.

Mutants of `skill.go` (`go test -overlay`, `-run TestReadSkill`), on
`main` at 27db7ace68 and on this branch:

| Mutant | Fails on `main` | Fails on this branch |
|---|---|---|
| Fallback restored (`skill.go` from `main`) | n/a |
`TestReadSkillToolsRequireAliasResolver` |
| No nil check in `ReadSkill`, or in `ReadSkillFile` | n/a |
`TestReadSkillToolsRequireAliasResolver` (nil function call) |
| Response `name` is `resolved.Alias` | nothing |
`PersonalQualifiedAliasPreservesAlias`, `WorkspaceQualifiedAlias` |
| Pinned body empty | `PinnedBodyFromMeta`,
`PinnedBodyServedWhenWorkspaceUnreachable`, `WorkspaceQualifiedAlias` |
the same, and `CollisionAliasRoundTrip` |
| 10 others: no `dir`, no supporting files, empty file content,
ambiguity reported as not found, resolver or loader error text returned,
deleted stored skill reported as a load failure, file read allowed for a
personal skill, hidden skill not matched, hidden skill meta file served
| at least one test each | the same tests |

A copy of `skill.go` with a syntax error fails to build in both runs, so
the overlay applies.

## Review focus

- The qualified alias tests are stronger. The fakes returned the alias
they got, so on `main` a tool that echoed `resolved.Alias` passed. The
real lookup resolves `personal/my-skill` to the bare alias `my-skill`,
so the tests now check that the tool returns the requested name.
- `CollisionAliasRoundTrip` no longer calls the resolver itself. It
checks each response body instead. The fake said that a bare `deploy`
was not found; the real lookup says it is ambiguous, which
`AmbiguousLookupSurfacesAliases` covers.
- `ResolveAliasErrorIsSanitized` keeps a fake, because the real lookup
returns only not-found and ambiguous errors.
- #29323 (plugin skills) replaces `ResolveAlias` and rewrites
`resolveSkillAlias`, so it conflicts with this PR. Whichever merges
second must reconcile.

## Validation

- `go test ./coderd/x/chatd/chattool/ -count=1`: pass.
- `go test ./coderd/x/chatd/chattool/ -race -count=3 -run Skill`: pass.
- `go test ./coderd/x/chatd/ -run Skill`: pass.
- `go vet ./coderd/x/chatd/chattool/ ./coderd/x/chatd/`: no issues.
- Mutants: each fails as listed.
- `make pre-commit` with `CODER_HOOK_RUN_ALL=1` passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 21:52:43 +01:00
Michael Suchacz 4ae6f632b0 refactor(coderd): move chat and chat project ACL reads onto the shared helpers (#31016)
Moves the chat ACL and chat project ACL reads onto `resolveACLUsers` and
`resolveACLGroups`, and the chat ACL update onto `applyACLReadRoles`. It
deletes `chatACLUsers`, `chatACLGroups`, `chatProjectACLGroups`, and the
user lookup in `chatProjectACLUsers`: 26 lines added, 174 removed. Both
reads counted group members with one query per group; the shared
resolver counts every group in one query.

Both reads still list groups from every organization (`uuid.Nil`), and
the project read still drops users outside the project's organization
before it resolves them. The resolvers' doc comments and `nolint`
reasons now say that callers authorized reading the ACL, because these
two reads check read access, not share.

**What changes:** successful responses stay the same. A stored key that
is not a UUID is skipped without a warning log, `500` details use the
shared texts, and an empty project ACL runs its lookups with empty ID
lists instead of returning early.

**Why it is safe:** #31014 pins the member counts and user fields of
both reads. I ran 5 mutants of the changed lines with `go test
-overlay`: apply group roles to users or user roles to groups in the
chat ACL update, keep project users from other organizations, filter
project groups by organization, and drop the stored entry of project
users. The tests fail on each.

**Review focus:** `chatProjectACLUsers`, which filters by membership and
then resolves users through the shared helper.

#29663 batches the same per-group count query in
`coderd/exp_chats_acl.go`, so the two conflict. The chat ACL update
still writes request keys as sent, as on `main`; #31037 canonicalizes
them. It merges with this PR without conflicts, and whichever merges
second will merge `main` first.

Validation: on `main` and on this branch, `go test ./coderd -count=1`
passes with `-run '(?i)acl|mcp|skill'` (24 tests, 62 with subtests) and
with `-run
'^(TestChatProjectSharing|TestChatSharingDisabled|TestListChatsSharedScope|TestSharedReaderStreamChat|TestChatFileDownloadURL)$'`
(5 tests, 22 with subtests), and `go test ./enterprise/coderd -run
'(?i)acl|mcp|skill|TestEnterpriseAuditLogs' -count=1` passes (9 tests,
46 with subtests). The pre-commit hook passed.

## Stack

This stack moves the chat, chat project, and chat model ACL handlers
onto the organization ACL helpers that MCP server configs and
organization skills share, and deletes their copies. Successful ACL
responses do not change.

1. #31014 Pin member counts and user details in chat and project ACL
reads
2. #31015 Move chat model ACL handlers onto the shared ACL helpers
3. #31016 Move chat and chat project ACL reads onto the shared helpers

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 20:27:10 +00:00
Michael Suchacz cdac1d08cb refactor(coderd): move chat model ACL handlers onto the shared ACL helpers (#31015)
Moves the chat model ACL handlers onto the organization ACL helpers in
`coderd/mcp_acl.go`, which MCP server configs and organization skills
already share. It deletes the model copies of the user and group
resolvers, the member count query, the list of available principals, the
organization and duplicate ID checks, and the role update loop: 30 lines
added, 321 removed.

Two shared helpers change:

- `resolveACLUsers` and `resolveACLGroups` pass each stored ACL entry to
the callback, so the model ACL reads each role from it.
- `resolveACLGroups` takes an organization ID. The model ACL passes its
organization, so groups from other organizations stay hidden. MCP server
configs and organization skills pass `uuid.Nil`, which keeps every
organization, as today.

**What changes:** successful responses stay the same. On error paths, a
stored key that is not a UUID is skipped without a warning log (`PATCH`
validation rejects such keys), `500` details use the shared texts (`get
ACL users` instead of `hydrate chat model ACL users`), duplicate ID
errors come back in the same `400` as the other validation errors
because the check now runs inside the write transaction, and a failed
membership lookup skips the group check.

**Why it is safe:** `TestChatModelACL` checks that groups from other
organizations stay hidden, and `TestChatModelACLValidationIsAtomic`
covers the duplicate check. I ran 9 mutants of the changed lines with
`go test -overlay`: ignore the organization in `resolveACLGroups` or
pass `uuid.Nil` from each handler, drop the stored entry given to either
callback, report zero members, and apply group roles to users or user
roles to groups. The tests fail on each.

**Review focus:** `uuid.Nil` means every organization in
`resolveACLGroups`, as it does in `GetGroups`.

Validation: on `main` and on this branch, `go test ./coderd -run
'(?i)acl|mcp|skill' -count=1` passes (24 tests, 62 with subtests) and
`go test ./enterprise/coderd -run
'(?i)acl|mcp|skill|TestEnterpriseAuditLogs' -count=1` passes (9 tests,
46 with subtests). The pre-commit hook passed (`make gen`, formatting,
golangci-lint, slim build).

## Stack

This stack moves the chat, chat project, and chat model ACL handlers
onto the organization ACL helpers that MCP server configs and
organization skills share, and deletes their copies. Successful ACL
responses do not change.

1. #31014 Pin member counts and user details in chat and project ACL
reads
2. #31015 Move chat model ACL handlers onto the shared ACL helpers
3. #31016 Move chat and chat project ACL reads onto the shared helpers

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 20:15:50 +00:00
Michael Suchacz d46a94770b test(coderd): pin member counts and user details in chat and project ACL reads (#31014)
Adds five assertions to `TestChatProjectSharing` and
`TestChatACLSharingLifecycle`. It is the test-first layer for the
refactor above it, so it adds 8 test lines and removes none.

**Why it is needed:** the next layers move the chat and chat project ACL
reads onto the shared resolvers in `coderd/mcp_acl.go`, which also
replaces the per-group member count query of the project read with one
batched query. No test checked a group's member count or any user field
other than the ID in those reads, so a wrong count or a dropped username
would still pass.

The new assertions check that:

- the project ACL lists the `Everyone` group with 3 members and a custom
group with 1,
- the project and chat ACL users carry their usernames.

**Proof:** the tests pass on `main` and on this branch. I ran 5 mutants
of the `main` read code with `go test -overlay`: report a zero member
count, count the members of the wrong group, count system users, and
return only the user ID in the project read and in the chat read. Each
mutant fails these tests and passes the tests on `main`.

Validation: `go test ./coderd -run
'^(TestChatProjectSharing|TestChatACLSharingLifecycle)$' -count=1`
passes, and the pre-commit hook passed (`make gen`, formatting,
golangci-lint over every package, and the slim build).

## Stack

This stack moves the chat, chat project, and chat model ACL handlers
onto the organization ACL helpers that MCP server configs and
organization skills already share, and deletes their copies. ACL
responses do not change.

1. #31014 Pin member counts and user details in chat and project ACL
reads
2. #31015 Move chat model ACL handlers onto the shared ACL helpers
3. #31016 Move chat and chat project ACL reads onto the shared helpers

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 19:07:36 +00:00
55573833d0 fix(coderd/database): lock the workspaces row when claiming a prebuild (#31518)
`ClaimPrebuiltWorkspace` locked the `workspace_prebuilds` view with `FOR
UPDATE ... SKIP LOCKED`, but the view is built from CTEs, so nothing got
locked. Concurrent claims picked the same prebuild and the losers got a
409 (a customer saw 28 of 30 fail).

This locks the `workspaces` row directly (`FOR NO KEY UPDATE SKIP
LOCKED`), rechecks owner and deleted on it, and checks eligibility with
per-workspace index lookups instead of the views. It uses `=` instead of
`IN` so one claim can't take two prebuilds, filters on the preset's
template so other templates' prebuilds aren't scanned, and claims oldest
first so prebuilds are used before they hit the preset TTL. Query-only,
no migration, applies cleanly to release/2.38. Builds on #31468 by Kevin
Ha (Canva).

Benchmarks (Postgres 17, 20k users, 320k builds, 600 ready prebuilds):
~12 ms per claim (was ~640 ms), and 500 concurrent claims got distinct
prebuilds in ~1.5 s.

Known limitations:

- Each claim still checks every prebuild of the preset's template (other
presets included) before sorting. That's a few ms at hundreds of
prebuilds per template.
- Pre-existing: a reconciler delete during a claim can still 409.
Follow-up is a `deleting_at` marker the claim skips.

---------

Co-authored-by: Kevin Ha <kevinh@canva.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 08:43:52 -07:00
Mathias Fredriksson b0a571888c refactor(coderd/x/chatd): validate model overrides once (#31347)
`SendMessage`, `EditMessage` and `EditQueuedMessage` validate a
requested model config once, before hooks and the chat transaction.
Model config writes serialize on an organization advisory lock that
chat transactions do not take, so a second check under the chat row
lock could not stop a concurrent disable. If the config is disabled
after the check, the turn runs on the organization default model.
Fallback resolution stays in the transaction because it reads the
locked chat.

Refs CODAGT-971
2026-10-30 15:03:28 +00:00
Mathias Fredriksson f8a138065d refactor(coderd/x/chatd): link files inside message transitions (#31353)
`Tx.SendMessage`, `Tx.EditMessage` and `Tx.EditQueuedMessage` take
`FileIDs` and `MaxFileLinks`, as `CreateChatInput` does, and call
`LinkFiles` themselves, so a link failure rolls back the whole message
write. `store_chat_attachment.go` keeps its direct call because it
links a file without a message transition.

Refs CODAGT-971
2026-10-30 14:23:13 +00:00
Mathias Fredriksson c3436cb3e0 fix(coderd/x/chatd): keep wait_agent waiting on a paused child (#29292)
`wait_agent` treated every status except `running` and `interrupting`
as done, so a paused child returned its last assistant message as its
final report while a queued message was still under edit. A paused
child is not done: `wait_agent` keeps waiting, and on timeout returns
`status: "paused"` with `timed_out: true`. The `wait_agent` and
`list_agents` descriptions say a paused timeout is expected.

Closes CODAGT-1026
Refs CODAGT-971
2026-10-30 15:58:05 +02:00
Mathias Fredriksson c0f7663e95 feat: support editing queued chat messages (#29215)
The owner of a chat can edit a queued message through
`PATCH /api/v2/chats/{chat}/queue/{queuedMessage}`. chatd never sends
a row under edit (`editing_since`): rows ahead of it still send in
order, and a turn that ends at it puts the chat in the new `paused`
status. Ending the head's edit, deleting it, or promoting a queued row
continues the chat. Interrupting sends still run ahead of the queue.

The chat state machine classifies a queue whose head is under edit as
its own sub-state (R1P, I1P, A1P, E1P, XE1P, P), so every path to
`paused` is in the transition matrix. A chat whose family has a paused
member cannot be archived, and auto-archive skips that family. Queue
edit and delete are owner-only, because both can send the next message
with the owner's credentials.

`ChatQueuedMessage` gains `editing_since` and `reasoning_effort`, and
`ChatStatus` gains `paused`.

Closes CODAGT-1028
Refs CODAGT-971
2026-10-30 15:52:22 +02:00
Sas Swart 5baa8eff01 feat: price AI Gateway token usage with the request organization (2/2) (#31121)
Cost looks up model prices site-wide only, so an organization's own
prices never apply, even though #31118 now stores the request
organization on each interception.

Pass the interception's stored organization to
`GetAIModelPriceForProvider`. The lookup already falls back from the
organization's price to the site-wide custom price, then to the price
book. An interception without an organization (old rows, old gateways)
uses only site-wide prices, as before.

| Stored org | Org price | Site-wide custom | Price used |
|---|---|---|---|
| none | any | any | site-wide custom, then price book |
| B | live | any | B's price |
| B | soft-deleted or absent | present | site-wide custom |
| B | absent | absent | price book, or NULL cost |

Remove `TODO(AIGOV-716)`. Make `TestRecordTokenUsageAuthorized` store an
organization and assert that its price wins under the strict authorizer.

Part of AIGOV-716. Stacked on #31120.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-30 13:35:23 +02:00
Sas Swart 15365c69cf feat: use the resolved organization for AI Gateway budgets and cost (1/2) (#31120)
`IsAuthorized` resolves the workspace organization, but uses it only to
reject requests; nothing downstream reads it. The budget check and cost
each resolve the group site-wide, so a user working in an org B
workspace can be billed in org A, and no interception records its
organization.

Resolve the request organization once, in `IsAuthorized`. A workspace
session token resolves to the workspace's organization (source
`workspace`). Any other request, including chatd requests until
AIGOV-713, resolves to the organization of the user's site-wide
effective group (source `effective_group`). Return the source in
`IsAuthorizedResponse`.

Have aibridged pass the organization to `IsBudgetExceeded`, which
resolves the budget inside it, and stamp the organization and source on
`RecordInterception`. Resolve cost's effective group inside the
organization stored on the interception. When there is no organization,
behave site-wide as before.

Move `resolveOrganization` and the workspace checks into
`orgresolver.go`, and leave a slot for the chat organization
(AIGOV-713). Bump the aibridged API to v1.6, adding
`IsAuthorizedResponse.organization_source` and
`IsBudgetExceededRequest.organization_id`.

aibridged checks only the shape of the organization (both fields or
neither, and a valid non-nil UUID), not the source value. That lets a
newer coderd add a source without breaking older gateways.

Behaviour changes to review:

- Spend follows the workspace's organization. A user whose budgets are
all in org A has no limit in an org B workspace if B has none.
- A database error while resolving the organization now returns 403 from
`IsAuthorized`, instead of 500 from `IsBudgetExceeded`.
- Requests without a workspace make up to three extra budget queries in
`IsAuthorized`.
- The user spend status endpoint (`GET /api/v2/users/{user}/ai/spend`)
stays site-wide, so it can disagree with where a request was charged.

The org-aware price lookup follows in #31121.

Part of AIGOV-716. Stacked on #31119.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-30 13:35:23 +02:00
Michael Suchacz 78fa9a8613 refactor(coderd/x/chatd)!: retire the close_agent tool alias (#31005)
This PR breaks compatibility with chat histories that contain
`close_agent` tool calls, which chats from v2.34 and earlier have.
#26673 (v2.35) renamed `close_agent` to `interrupt_agent` and kept a
hidden alias, so a model that copied the old name from such a history
still interrupted the child. This PR deletes the alias:
`subagentToolNameAliases`, `ExecuteLocalToolsOptions.ToolNameAliases`
with `(*toolBatch).resolve` and its five call sites in `chatloop`, the
alias step in builtin input validation, and the `close_agent` entries in
the unbilled tool set, the plan policy, and the chatprompt lifecycle
list. Coder Agents is experimental (`coderd/x`), and our rule for
experimental persisted data is to drop the legacy shape outright and
delete the code that existed only to support it, instead of carrying it
forward.

What happens to an old chat:

- Replay does not change, because the replay path does not look up tool
names: the model still sees the historical `close_agent` call and its
stored result, and the UI renders them as before. The write path reads a
tool name only to parse `execute` commands and to keep structured error
results from subagent lifecycle tools. Dropping `close_agent` from that
lifecycle list changes nothing, because its calls are now rejected with
a plain-text error.
- If the model calls `close_agent` again, nothing runs and the child
keeps running. The tool result is the error `Tool not active in this
turn: close_agent`, and the model can retry with `interrupt_agent`.

**Why it is safe**

- Deleted alias-only tests:
`TestExecuteSingleTool_ResolvesToolNameAlias`, the
`AliasNamesClassifyAsCalled` billing row, the alias subtest of
`TestPartitionAmbiguousToolCallsGatesOnBuiltins`, the alias loop in
`TestUnbilledSubagentToolNamesMatchCatalog`, and the aliased calls that
#30939 added to `TestExecuteToolsSerialToolCallOrder` and
`TestExecuteLocalTools_ProviderToolRunner`; both tests are back to their
#30938 form.
- `TestExecuteSingleTool_UnknownAliasFallsThrough` is now
`TestExecuteSingleTool_RejectsUnknownTool` and asserts the exact error
above. The observer tests call the tool by its real name.
- Mutants of the active tool check, step observer notification, serial
dispatch, the unbilled set, the plan policy and builtin input validation
each fail a remaining test. Only the deleted alias test caught an empty
name passed to the tool handler; no chatd tool reads that name (MCP
tools use their original name).
- `git grep` finds no use of the removed identifiers and no backend code
that resolves `close_agent`. The rejection test still uses that name as
its input. The frontend keeps its `close_agent` display mapping, which
old histories still use.

**Review focus**

- A rejected `close_agent` call is now billed like any rejected tool
call; the rejection is immediate.
- `ARCHITECTURE.md`, "Generation goroutine": this PR deletes the
sub-bullet that called `close_agent` a deprecated alias of
`interrupt_agent`.
- The `resolved_tool_name` debug log field is gone. It differed from
`tool_name` only for aliased calls, and the alias is gone.

**Validation**

- `go test -count=1 ./coderd/x/chatd/ ./coderd/x/chatd/chatloop/
./coderd/x/chatd/chatprompt/`: ok
- `go vet` and `golangci-lint run --fix=false ./coderd/x/chatd/...`:
clean
- `paralleltestctx -custom-funcs="testutil.Context,chatdTestContext"
./coderd/x/chatd/...`: clean
- pre-commit hook: passed

**Stack**

This stack retires chatd compatibility paths for chat data that older
Coder versions stored.

This PR replaces #31003 and carries its change, adapted to the
`toolBatch` code that #30938 and #30939 merged. Mike chose to keep the
fallbacks that #31001 and #31002 removed, so those two layers and #31003
left the stack.

1. #30996 stamp chat message fixtures with the current content version
2. #30997 drop tests of the legacy content codec
3. #30998 retire the V0 chat message content decoder
4. #31000 inline the model config provider identity
5. #31005 retire the `close_agent` tool alias (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 02:00:59 +00:00
Michael Suchacz 08a10228db refactor(coderd/x/chatd): inline the model config provider identity (#31000)
This PR deletes `modelConfigProviderIdentity` and its test table; both
callers now use `AIProviderID.UUID.String()` directly. The helper fell
back to the provider type name for model configs without an
`ai_provider_id`. It changes no behavior, because no such config reaches
either caller: the `chat_model_configs_ai_provider_required_when_active`
check constraint allows a NULL `ai_provider_id` only on deleted configs,
and both callers reject such a config before they read the identity.

- Turn preparation resolves the chat's config through
`gatewayProviderForConfig`, which returns "AI Gateway routing requires
AI provider metadata" for a config without a provider ID.
- History sanitization resolves each row's origin config through
`resolveNormalizedProviderForModelConfig`, which returns
`sql.ErrNoRows`. The sanitizer treats that origin as unavailable and
strips the row's provider-specific state (fail closed), as before.

**Why it is safe**

The deleted table tested the helper. Its live contract is that identity
is the provider instance UUID, so two providers of the same type are
distinct. I mutated the two inlined lines and ran `./coderd/x/chatd/`
with `go test -overlay`. The tests catch all three mutants:

- Turn target identity set to the provider type:
`TestActiveServer_AnthropicProviderToolPreRequestGuard`,
`TestOpenAIResponsesFullReplayPairsReasoningAndWebSearch` and others
fail.
- Origin identity set to the normalized type: the same tests fail.
- Both sites set to the type, so they agree:
`TestOpenAIResponsesReasoningNotReplayedAfterModelConfigChange/ProviderMoved`
and `TestProviderSwitchSanitizesAndRestoresPEToolHistory` fail.

`git grep modelConfigProviderIdentity` finds no references left in the
repository, including `site/`, `enterprise/`, `cli/` and `docs/`.

**Review focus**

`sanitizeForeignProviderStateRows` now discards the normalized provider
name that `resolveModelConfigAndNormalizedProvider` returns. It still
calls that function, because the function also checks that the config is
enabled and its provider is valid.

**Validation**

- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: ok
- `go vet ./coderd/x/chatd/` and `golangci-lint run --fix=false
./coderd/x/chatd/...`: clean
- pre-commit hook: passed

**Stack**

This stack retires chatd compatibility paths for chat data that older
Coder versions stored.

1. #30996 stamp chat message fixtures with the current content version
2. #30997 drop tests of the legacy content codec
3. #30998 retire the V0 chat message content decoder
4. #31000 inline the model config provider identity (this PR)
5. #31005 retire the `close_agent` tool alias

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 01:30:11 +00:00
Ethan ea79a9885a fix: return a partial page from read_file instead of an error (#31470)
Closes CODAGT-435

When a `read_file` response would go over 32 KB, the agent returned an
error and no content, telling the model to "Read less at a time using
offset and limit parameters". That's most source files over about 32 KB,
so the model would lose a turn on each one just to pick a smaller range.
#22400 made these hard errors on purpose, so the model wouldn't answer
from partial data, but most of the prior art I looked at (pi-mono,
Gemini CLI, opencode, Cline) just returns what fits and says where to
continue. I think that handles the partial data concern better, as the
model is told exactly which lines it has.

So, the agent now ends the page at whichever comes first of `limit`,
2000 lines, 32 KB, or the end of the file, and returns it as a success.
`workspacetools.ReadFile` then adds a `note` to any page that stops
before the end of the file, so the chat tool and the MCP tool both get
it. Reading `agent/agentfiles/files.go` with no `offset` or `limit` used
to error, and now gives 956 lines with:

> Showing lines 1-956 of 1576. To read more, call this tool again with
offset=957.

The issue suggested returning a chunk plan (e.g.
`[[0,200],[200,600],...]`) instead. The model needs one call per page
either way, and a chunk list would depend on the current limits and line
lengths, whereas the next offset is just `offset + lines_read`.

A `limit` over 2000 is now clamped rather than erroring, and
`total_lines` no longer counts a trailing newline as an extra line,
since the note's maths depends on it. I also dropped the "use offset and
limit to read a portion" hint from the 1 MB error, as that check runs
before `offset` and `limit` are applied. Workspaces running an older
agent will keep returning the error until their agent is updated.

I tested this on a dev deployment through Coder Agents, asking Claude
Haiku 4.5 and GPT-4.1 mini to read a 108 KB and a 118 KB file (3000 and
3200 lines) using only `read_file`, then report the last line. Both
followed the note through to the end of the file (Haiku in 4 calls,
GPT-4.1 mini in 5) and got the last line right, whereas on `main` the
first call just errors. `coder_workspace_read_file` over MCP gives the
same note. The only odd behaviour I saw was Haiku once skipping straight
to the end of a file when the prompt only asked about the last line,
which I think is on the model rather than the tool.
2026-10-30 12:23:17 +11:00
Michael Suchacz 0a737cd857 refactor(coderd)!: retire the V0 chat message content decoder (#30998)
This PR breaks compatibility with chat messages stored in the legacy
content format (`chat_messages.content_version = 0`). No release stored
such messages, because Coder Agents (#22290) and `content_version`
(#23042) first shipped together in v2.32.0. Only deployments that ran a
preview build of `main` between 2026-02-27 and 2026-03-13 (in practice,
dogfood) have them: migration 000434 (#23042) stamped every row that
existed then with version 0, and nothing converts them later. The PR
deletes the legacy decoder from `chatprompt`: `ContentVersionV0`,
`parseLegacyContent` and its per-role parsers, the fantasy envelope
detector `isFantasyEnvelopeFormat`, `ExtractFileID`, and the legacy
tool-row type `toolResultRaw`. Coder Agents is experimental
(`coderd/x`), so we drop legacy persisted shapes and the helpers that
parse them outright instead of carrying a migration.

What happens to those messages: `ParseContent` now returns `unsupported
content version 0`. Throwaway API tests on this head show the effect on
a chat with version 0 rows:

- `GET /api/v2/chats/{chat}/messages` returns 200, but the version 0
messages have no content.
- A send to a waiting or errored chat, and an edit, first parse the last
assistant message (for an edit, the last one before the edited message)
to cancel its pending tool calls. If it is version 0, they return 500
(`Failed to create chat message.` or `Failed to edit chat message.`,
detail `execute transaction: parse assistant message: unsupported
content version 0`). By code reading, promote does the same.
- Otherwise they return 200, and an edit deletes the edited message and
every later one. If a version 0 row remains before the new message, the
turn fails in the worker (`build chat prompt: unsupported content
version 0`) and the chat goes to error.
- Recovery: editing the first user message deletes it and every later
row, so a new turn runs; another send alone leaves the chat in error.
Chats created through the API on those preview builds cannot recover
this way: each starts with its system prompt stored as a version 0 row,
which no edit deletes, so their users must start a new chat.

Chats with only version 1 rows do not change.

**Why it is safe**

- New content is always written as `CurrentContentVersion` (1), and
`content_version` is `NOT NULL` with no default, so no new row gets
version 0.
- The layer below removed the tests of the legacy encodings. This PR
handles the last version 0 test cases. It moves the six cases of
current-format parts in `TestParseContent_BackwardCompat` to version 1
rows in `TestParseContent_V1`, and their checks do not change. It
deletes the version 0 malformed-input cases of
`TestParseContent_ErrorPaths`; the version 1 cases with the same input
stay. Every mutant that `main` catches, out of the 17 listed in #30996,
is still caught on this head.
- `git grep` for each removed symbol across the repository, including
`site/`, `enterprise/`, `cli/`, `docs/` and `scripts/`, finds nothing on
this head. Before this PR, the only hit outside `chatprompt.go` was
`coderd/exp_chats_test.go`, which now writes the version as a literal
`0`. That test checks that the SQL `jsonb_typeof` guard skips scalar
JSON rows.

**Review focus**

Version 0 rows now take the existing `unsupported content version`
branch of `ParseContent`; the PR adds no new error path.

**Validation**

- `go test ./coderd/x/chatd/... ./coderd/database/db2sdk/ -count=1 -p 4
-parallel 4`: ok
- `go test ./coderd/ ./enterprise/coderd/ -run
'(?i)chat|agent|mcp|skill' -count=1 -p 4 -parallel 4`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: 0
issues; pre-commit hook: passed
- Throwaway API tests (not committed) of GET, send and edit with version
0 rows: results above

**Stack**

This stack retires chatd compatibility paths for chat data that older
Coder versions stored.

1. #30996 stamp chat message fixtures with the current content version
2. #30997 drop tests of the legacy content codec
3. #30998 retire the V0 chat message content decoder (this PR)
4. #31000 inline the model config provider identity
5. #31005 retire the `close_agent` tool alias

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 01:00:48 +00:00
Michael Suchacz e973f00480 test(coderd/x/chatd/chatprompt): drop tests of the legacy content codec (#30997)
This PR deletes the tests of the legacy chat message encodings (plain
strings, fantasy envelopes and legacy tool rows, all stored with
`content_version` 0), and the test-only writers that built those rows
(`MarshalContent` and `MarshalToolResult` in `export_test.go`). It
changes tests only. The next layer removes the legacy decoder that these
tests cover.

**Why it is safe**

Deleted tests that covered only the legacy format:

- The legacy cases of `TestParseContent_BackwardCompat`: legacy system
strings, fantasy envelopes and legacy tool rows. Its six cases of
current-format parts in version 0 rows stay, because they need no legacy
writer. The next layer moves them to version 1 rows.
- `TestInjectFileID_StripsInlineData`: the test-only `MarshalContent`
writer.
- `TestSDKPartsNeverProduceFantasyEnvelopeShape`: the invariant behind
`isFantasyEnvelopeFormat`, the legacy format detector.
- `TestParseContent_ErrorPaths/unknown_role`: the role switch in the
legacy decoder. The V1 decoder has no role switch. The version 0
malformed-input cases of this test stay, because they need no legacy
writer. The next layer deletes them with the decoder.

Deleted tests that also covered current behavior, checked with mutants
of `chatprompt.go`:

- `TestConvertMessagesWithFiles_BackwardCompat` (file ID resolution):
dropping resolved file data, or not collecting user file IDs, still
fails more than 10 remaining tests, including
`TestConvertMessagesWithFiles_ResolvesFileData`.
- `TestProviderMetadataRoundTrip` (provider metadata becomes provider
options): dropping the conversion still fails
`TestConvertMessagesWithFiles_Conversation` and
`TestAssistantWriteRoundTrip`.
- `TestProviderExecutedResult_LegacyToolRow` (provider-executed results
in legacy tool rows are dropped before replay): keeping
provider-executed results in `injectMissingToolUses` still fails
`TestInjectMissingToolUses_DropsProviderExecutedOrphans` and
`TestInjectMissingToolUses_DropsOnlyProviderExecutedMessage`.

The 17 mutants from the layer below give the same result here as on that
layer.

**Review focus**

The `export_test.go` deletion. `MarshalToolResult` uses `toolResultRaw`,
which the next layer deletes, so the writer goes first.

**Validation**

- `go test ./coderd/x/chatd/chatprompt/ -count=1`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: 0
issues
- pre-commit hook: passed

**Stack**

This stack retires chatd compatibility paths for chat data that older
Coder versions stored.

1. #30996 stamp chat message fixtures with the current content version
2. #30997 drop tests of the legacy content codec (this PR)
3. #30998 retire the V0 chat message content decoder
4. #31000 inline the model config provider identity
5. #31005 retire the `close_agent` tool alias

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 00:19:19 +00:00
Michael Suchacz 31b8fd1b88 feat: graduate the chat advisor from experiments (#31414) 2026-10-29 23:24:18 +01:00
Mathias Fredriksson 48a3d3ff12 fix: keep OpenAI web searches in later turns (#31355)
OpenAI chats dropped every earlier web search from the next request
with store false, so on later turns the model said it made no tool
calls. Fantasy replayed a search only as an item_reference, which
OpenAI cannot resolve for an unstored item.

The fantasy pin moves to coder_2_33 with coder/fantasy#78, which sends
a search inline as an id-less web_search_call, rebuilt from its result
metadata, whenever it does not go back as an item_reference. With
store true it also covers searches from an unstored response, as when a
chat moves to a stored model config or a zero data retention org, and
searches with no reasoning before them. The model gets the action it
took, not the page contents, which OpenAI does not keep for references
either.

TestChatOpenAIResponsesWebSearch now sends a second turn and asserts
the exact inline item for each action shape through the chat API and
chatd's prompt builder. The fake OpenAI server accepts inline searches
without an id, returns OpenAI's 404 for references to items it served
with store false, and sends sources only on search actions. The tests'
reference checks now also catch references without a type, which
openai-go omits.

Relates to CODAGT-1482
2026-10-29 19:50:34 +00:00