Commit Graph
676 Commits
Author SHA1 Message Date
Ethan c95f3a58f9 chore: remove the remaining export_test.go shims (#32434)
Closes CODAGT-1607

Follow-up to #32162, which left 5 `export_test.go` shims behind:
`coderd`, `aibridged`, `chatd`, `chatstate` and `mcpclient`. This PR
removes them. It's stacked on #32433, which deals with the chat
workspace functions in `coderd`.

Same approach as before. Tests of package internals are now
`*_internal_test.go` files, with no changes beyond what the move forces,
and tests that only needed a constant just use the value. `chatstate`
needed one small accessor, so `AllowedExecutionTransitionOutputs` is
just exported for real, and its tests stay where they were.
Unfortunately the `mcpclient` connect budget test needs an unexported
timeout, so it moved to an internal file and builds its own server
there.

I've removed `TestConnectAll_LateServerReaped`,
`TestAllExecutionStates_Enumeration` and a few assertions instead of
moving them, as I couldn't find a breakage that only they would catch.

While here, I've dropped the test-only `reaperDone` hook from
`mcpclient`. The wait for a connect to finish within its budget is now a
small function of its own, with a test that a session which connects too
late still gets closed. Nothing checked that before.

With no shims left, the `testpackage` path exclusion is gone, so a new
`export_test.go` now fails lint.
2026-12-01 00:17:20 +11:00
Ethan 2d725a1ced refactor(coderd): move the chat start decision into the start tool (#32433)
Closes CODAGT-292
Relates to CODAGT-1607

`coderd/export_test.go` re-exported `chatCreateWorkspace`,
`chatStartWorkspace`, `chatStopWorkspace` and
`chatRenderTemplateParameters`, just so four tests could call them
directly. This PR removes those tests and their aliases, and the last
alias in that file goes in the next PR in the stack.

The start and stop tests only checked which template version the build
ends up on. That decision lived in `coderd`, behind the function the
tool calls, so the only way to test it was to call that function
directly. Now `start_workspace` makes the decision itself, much like
`coder start` does: it checks whether the template requires its active
version, sends that version with the build request, and tells the model
how to retry when the update needs parameters. All of that is covered by
the tool's own tests. With the decision gone, the start and stop
functions were identical, so both tools now share `chatBuildWorkspace`,
which just creates a build as the workspace owner.

Two small behaviour changes. `start_workspace` now returns `template_id`
whenever it asks the model to retry with parameters. Previously it was
missing for templates on the classic parameter flow, even though the
message says to use it. The tool also reads the template's setting
directly, like `coder start`, so chat updates on start too when the
setting is still on after a licence lapses.

`TestStartWorkspaceTool_EndToEnd` now starts a workspace whose active
version needs a new parameter, so we still know the whole flow works
against a real `coderd`.

`chatRenderTemplateParameters` keeps a direct test, it's just an
internal one now, against a database instead of a whole `coderd`. It no
longer checks the owner default, as that's already tested in the
renderer and in the tool. The bind failure test needs a real
transaction, so it moves to `chatd` and runs through the
`create_workspace` tool.
2026-12-01 00:17:20 +11:00
Mathias Fredriksson c7b144cc76 fix(coderd/x/chatd): prevent a chat stream relay deadlock on repeated episode selection (#31187)
Stacked on #31196, which must merge first.

When a chat's worker runs on the same replica as the stream, the chat
stream relay can deadlock with the in-process parts endpoint. Live model
output then stops on that stream until the client reconnects, while
saved messages, status and queue updates keep arriving.

The stream loop configures the relay forwarder after every newer
snapshot, and queueing a message, deleting or promoting a queued one,
interrupting, and recording a retry keep the episode. The forwarder sent
a selection each time, and the endpoint answers each one by sending the
episode again from `seq` 1, so K updates on an N-part episode moved
about K times N parts. While the stream loop reads slowly, the resent
parts fill the buffers and the endpoint's serve loop waits to send.
Three unread selections fill the pipe's one-slot channel, the endpoint's
selection reader and its one-slot channel to the serve loop, and the
forwarder's next `WriteControl` never returns.

- The forwarder sends a selection only on a new connection or when the
target changes. Before #31196, only a repeated selection restarted live
output after the part buffer dropped a slow subscriber.
- The endpoint's selection reader replaces an unread selection instead
of waiting, so the endpoint does not depend on how a client sends
selections. After the first change the forwarder cannot practically
reach the cycle, since it drops other episodes' parts without waiting.
Dropping one loses nothing, because every selection starts again from
`seq` 1.

<details>
<summary>Investigation and decision log</summary>

### Evidence

`TestStreamRelayForwarderSelectsOnlyChangedTargets` configures one
200-part episode 10 times: before the forwarder change it sees 10
selections and 2000 parts, after it 1 selection and 200 parts.
`TestStreamPartsEndpointLatestSelectionWinsWhileBlocked` fails in 10 of
10 runs without the reader change and with a 15-slot queue that replaces
nothing.
`TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures`
stalls the stream loop until the buffers fill, configures the same
episode 1000 times, then requires a new part to arrive; it fails in 20
of 20 runs with both changes reverted and passes with either one alone.
All three pass with `-race -count=20`.

A goroutine dump taken with the world stopped, from a test that used the
real forwarder, local dialer and part buffer with a 2000-part episode,
shows the four goroutines at the waits described above and every buffer
full. The deadlock formed in 20 of 20 runs under `-race`, after 4 to 384
same-episode selections. After the test read every buffered part, added
live parts, configured the relay 11 more times (once for a new episode)
and fired the buffer's send timeout, no part arrived.

```
F goroutine 73 [select]: streamPartsChannelClientTransport.WriteControl stream_parts_transport.go:142 <- (*streamRelayForwarder).loop.func4 stream_relay.go:148 <- loop stream_relay.go:207
R goroutine 74 [select]: streamPartsEndpoint.serve.func1() stream_parts.go:84
E goroutine 83 [select]: streamPartsChannelServerTransport.WriteEvents stream_parts_transport.go:120 <- streamPartsEndpoint.serve stream_parts.go:169
L goroutine 84 [select]: (*streamPartsTransportSession).readLoop stream_parts_transport.go:236
f.parts=128/128 s.parts=128/128 eventsCh=128/128 controlCh=1/1 SelectEpisode started=13 returned=12
```

A test goroutine in place of the stream loop dropped repeated parts and
spent a fixed sync time on each hint before it selected the same episode
again (200 hints, 3 runs per row, real clock):

| Sync time per hint | Hint interval | Deadlock formed |
|--------------------|---------------|-----------------|
| 1 ms               | 1 ms          | 1 of 3          |
| 5 ms               | 5 ms          | 1 of 3          |
| 1 ms               | 2 ms or 5 ms  | 0 of 6          |
| 5 ms               | 10 ms         | 0 of 3          |

The deadlock formed only when selections arrived about as fast as the
stream loop handled them. How often that happens in production is not
measured.

Selecting a new episode every time under the same pressure did not
deadlock in 300 of 300 iterations, because the forwarder drops parts of
other episodes without waiting for the stream loop. Over the WebSocket
transport with the pipeline full, 1263 selections over 2999 iterations
all returned; when the stream loop then stopped reading, the server
heartbeat closed the parts connection about 35 seconds after it opened,
and the forwarder dialed again once the stream loop read again.

### Decisions

- `WriteControl` keeps its waiting send: the reader no longer waits
after reading the pipe, so the send returns, and replacing there changed
no test result.
- Replaced `TestStreamRelayLivePartsAfterSameEpisodeReselects`, which
waited for full buffers before every selection and so relied on the
replays the forwarder change removes, with a test that fills the buffers
once by stalling the stream loop.
- Rejected: having the serve loop read selections while it waits in
`WriteEvents`. The serve loop would have to abandon a send in progress
and drop its part, a larger change with the same result.

</details>

> 🤖 This PR was created with the help of Coder Agents.
2026-11-25 18:28:55 +02:00
Mathias Fredriksson 1d565409e4 fix(coderd/x/chatd): keep slow part subscribers attached while the episode is open (#31196)
The message part buffer dropped a subscriber of an open episode whose
send waited 10 seconds. The parts endpoint read the closed channel as
the end of the episode and kept the connection open, so live output
stopped for the rest of the model call. Only on the cross-replica
WebSocket could a longer stall end it: the endpoint's heartbeat closes
the socket 15 to 30 s after the relay stops reading, and the relay
reconnects and replays once it reads again. That path is unchanged. The
stream loop stops reading when its writes to the browser block.

The timeout keeps an unresponsive subscriber from holding an episode in
memory, but only closed episodes wait for subscribers. It now starts at
the close, also for a send already waiting then.

A drop after the close only cuts short the live preview, which the saved
message or the error event replaces. The buffer has no logger, so it is
not logged.

Cost: a subscriber that stops reading an open episode holds its
goroutine and batch until it reads, is cancelled, its context ends, the
buffer closes, or `SubscriberSendTimeout` passes after the episode
closes.

> 🤖 This PR was created with the help of Coder Agents.
2026-11-25 16:26:23 +02:00
Ethan 389cfeef2f fix(coderd): generate chat titles for users without the owner role (#32738)
Automatic title generation only works for chats created by a user with
the Owner role. For anyone else the chat keeps its fallback title (the
first message, truncated), and the only sign is a warning in the coderd
logs:

```
[warn]  coderd.chatd.processor: failed to resolve model for automatic title generation ...
    error= resolve fallback chat model for title:
         - get AI provider:
         - unauthorized: rbac: forbidden: ...
```

`GenerateChatTitleForMessagesAsync` runs its goroutine as the user who
made the request, and resolving the title model reads the `ai_provider`
row, which only Owners can read. Setting a title generation model
override doesn't help, as resolving the override reads the provider too.

To fix, we'll run the goroutine as chatd, as `ProposeChatTitle` already
does for the same reason. The model config lookup still loads the chat
owner's subject, so the owner's access still decides which model the
title call can use. That lookup now has the owner's full scope, where
before it had the scope of the API key that made the request.

`TestPostChats_AutomaticTitleGeneration` now creates the chat as a
member and asserts on the stored title, instead of waiting for the title
request to reach the provider.

I've confirmed this on a dev server (`./scripts/develop.sh`, one OpenAI
provider, `gpt-4.1-mini` as the default model, no title generation model
override), creating chats through the API on the same database before
and after the fix:

| Commit | Chat created by | Title |
|---|---|---|
| `6603069e8b` (`main`) | `admin` (Owner) | Generated after 2s: "Why the
sky is blue" |
| `6603069e8b` (`main`) | `member` (no roles) | Still the fallback after
90s, and coderd logged `failed to resolve model for automatic title
generation` |
| `549cbdfafb` (this PR) | `member` (no roles) | Generated after 2s:
"Why the sea is salty" |

It also reproduces on dogfood, where I don't have the Owner role: a chat
I created there on `main` kept its fallback title.
2026-11-25 18:20:18 +11:00
Thomas Kosiewski d4e66907c4 refactor(coderd/x/chatd/chatwebhook): keep only the Standard Webhooks verifier (#32614)
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
2026-11-25 07:22:44 +01:00
Garrett Delfosse 74a15cbcaa feat: adopt OpenTelemetry GenAI semantic conventions for Coder Agents traces (#32411)
Aligns Coder Agents traces with the [OpenTelemetry GenAI semantic
conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) so
customers can ingest per-user model usage, spend, and tool activity
without custom mapping. Scope follows the requesting team's Slack ask:
agent spans, inference spans with token usage, GenAI attributes,
per-user attribution, and visibility into tools that cannot be reached.

Closes CODAGT-1523.

## Changes

- Span names follow the conventions: `chat_turn` becomes `invoke_agent
coder`, `stream` becomes `chat {model}`, and `tool_call` becomes
`execute_tool {tool}`. Every stage span now carries a `stage` attribute
with the old stage name, which matches the Prometheus `stage` label.
Metrics are unchanged.
- GenAI spans carry `gen_ai.operation.name`, `gen_ai.conversation.id`
(the chat ID), `user.id` (the chat owner), and `coder.organization.id`,
`coder.workspace.id`, `coder.chat.parent_id`, `coder.chat.root_id`.
- `chat` spans are `CLIENT` spans with the provider, request model, and
`gen_ai.request.stream` set at creation (so samplers can see them), plus
requested max tokens and temperature, response ID (including OpenAI
Responses metadata on non-streaming calls), the finish reason the
provider reported (omitted when none, kept when Coder rejects the
response), `gen_ai.output.type=json` for native OpenAI structured
output, and token usage with cache read/write (only when nonzero) and
reasoning breakdown. `gen_ai.usage.input_tokens` includes cached tokens,
as the spec requires. Fantasy reports them separately (Google providers
use the OpenAI-compatible client, which does the same).
- `execute_tool` spans carry the tool name, call ID, and type
(`function` for built-in tools, `extension` for MCP and caller tools),
all set at creation.
- Every model call records a `chat` span: assistant streams
(`stage=stream`), and, as `stage=model_call`, the advisor, compaction
summaries plus titles, status labels, and chat summaries (via
`StageTracer.TraceModelCalls` in `resolveModelCall`). `model_call` has
no histogram, so the `stream` metric is unchanged.
- Failed spans get `error.type`. A tool that returns an error result, as
MCP clients do for an unreachable server, ends its span with
`error.type=tool_error` without recording the result text.
- GenAI attributes carry metadata only; prompts, responses, and tool
payloads are not recorded. The docs note that other spans and events in
the trace, such as AI Gateway spans and server log events, can contain
content.
- Docs state known limits: Anthropic server-tool responses undercount
input tokens in both spans and AI Gateway cost control (the client keeps
first-iteration occupancy), the OpenAI-compatible client drops reported
cache writes, request attributes are what Coder requested, and the
exporter is OTLP/gRPC, plaintext unless a certificate is configured.
- New docs page:
`docs/coder-agents/platform-controls/opentelemetry-tracing.md`.
- `coderd/x/chatd/ARCHITECTURE.md` gains a GenAI semantic conventions
subsection under Lifecycle tracing.

Existing attributes (`provider`, `model`, `chat_id`, `tool_name`, ...)
are kept so current queries on attributes keep working. Queries on span
names need to switch to the `stage` attribute or the new names.

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

- **Convention version:** semconv v1.41.0, the last core release that
ships the GenAI attributes. Later releases moved them to
`semantic-conventions-genai`. The PR uses the Go constants from
`go.opentelemetry.io/otel/semconv/v1.41.0`, which is already in the
module graph. No experiment gate: chatd is already under `x/`, and the
docs page notes that the conventions may change.
- **Rename vs. attributes only:** spans are renamed because the
conventions define the span names. The `stage` attribute keeps lifecycle
identity stable for dashboards and tests.
- **Agent name:** `gen_ai.agent.name=coder` for root chats and subagents
alike. `chat_kind` and `coder.chat.parent_id` tell them apart.
- **Provider name mapping:** configured provider type to well-known
values (`openai`, `anthropic`, `azure.ai.openai`, `aws.bedrock`,
`gcp.gemini`). Anthropic providers with Bedrock settings report
`aws.bedrock`. The `invoke_agent` span gets the provider after `prepare`
resolves the turn's model, since the turn span starts first. Other types
(`openrouter`, `openai-compat`, `vercel`, `copilot`) are passed through
as-is.
- **No content capture:** `gen_ai.input.messages`,
`gen_ai.output.messages`, and tool arguments/results are opt-in in the
conventions and not needed for usage and spend attribution, so they are
left for a follow-up behind an explicit deployment flag.
- **Out of scope:** GenAI metrics (`gen_ai.client.token.usage`,
`gen_ai.client.operation.duration`), an aggregated token total on the
`invoke_agent` span, a cost attribute, span links between subagent and
parent traces, and correlation IDs with AI Gateway interceptions (an
open question in the issue). Subagent turns join the parent only through
`coder.chat.root_id`; a span link needs the spawning span context
persisted across chats and runners. Spans carry tokens, not cost; cost
stays in the existing cost API.
- **Identity snapshot:** chat identity is taken when the turn opens. A
workspace created mid-turn appears on spans from the next turn.

</details>

---

Generated by Coder Agents on behalf of @f0ssel.
2026-11-24 11:41:03 -05:00
52427e8fd6 test(coderd/x/chatd): give TestProjectSkillsFollowProjectAccess a longer context (#32276)
`TestProjectSkillsFollowProjectAccess` runs six sequential model turns
on one context created with `testutil.WaitLong` (25s). In a recent CI
run ([job](https://github.com/coder/coder/actions/runs/43909622615)) the
turns took about 35s, so the context expired just as the last turn was
sent. The chat finished normally (its final update was published about
4s later), but every `GetChatByID(ctx, …)` inside `waitForChatProcessed`
then returned a deadline error, which the condition treats as not yet
processed, so `require.Eventually` failed with "Condition never
satisfied".

Use `testutil.WaitSuperLong`, as other multi-turn chatd tests do.

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VpiVZBgFqiSdRKrH8dPSPT)_

Co-authored-by: Garrett <garrett@coder.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:10:36 +02:00
Hugo Dutka 5f5c30eafb fix(coderd/x/chatd): prefer native subagents over ACP harnesses (#32604)
Agents sometimes call `acp_spawn_agent` when a native subagent
(`spawn_agent`) could do the job, even when the requested model is
available natively.

This adds one line to the `<acp-subagents>` system prompt block: "Prefer
using non-ACP subagents unless the user asks for an ACP harness or if
the requested model is only available through ACP."

Tests reference `acpSubagentPromptBlock` by constant rather than by
text, so no test changes are needed.
2026-11-23 12:11:44 +00:00
49cd380e67 test(coderd/x/chatd): ignore non-hook requests in hook consumers (#32277)
`TestPreToolUseHookAllow/passthrough` failed in CI
([job](https://github.com/coder/coder/actions/runs/43909622615/job/133447870881))
because its hook consumer received five requests with empty bodies:
`json.NewDecoder(r.Body).Decode` returned `EOF` each time. Every real
hook delivery in the test succeeded, and its other assertions passed.

The dispatcher only sends POSTs with a non-empty JSON body and an
`Authorization: Bearer` token, so those requests did not come from this
test's dispatcher. The likely source is port reuse. The package's tests
run in parallel, and a closed `httptest` server's port can be handed to
a new server while another test's client (for example an MCP
streamable-HTTP client reconnecting its GET stream) is still retrying
it. The logs don't show which client sent them.

The hook consumers in the chatd tests now answer anything that is not a
POST with a bearer token with 404, instead of failing the test while
decoding it. This uses a shared `isHookRequest` helper.
`TestHookDispatcherRequiresExperiment`, which asserts the consumer gets
no hook requests, now counts only hook deliveries.

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VpiVZBgFqiSdRKrH8dPSPT)_

Co-authored-by: Garrett <garrett@coder.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:47:45 +02:00
Jaayden Halko 17a2b62205 feat: add an API to attach templates to chat projects (#30754)
Adds the API for attaching workspace templates to a chat project, on the
schema and queries in #32309. A project can attach templates, turn on a
limit that restricts its chats to them, and set a default template with
either a default preset or default parameter values. Attaching a
template never grants access to it: every reader is checked against the
template's own sharing. This PR stores and returns `limit_templates`;
#32310 enforces it.

- The limit is opt-in. `limit_templates` is off unless a request turns
it on, which is what every existing project gets.
- Templates are attached and detached one at a time with `PUT` and
`DELETE /chats/projects/{project}/templates/{template}`, so a caller
never replaces a list they can only partly see. Attaching needs project
`update` and template `use`. Detaching needs project `update` and
template `read`, and a template the caller cannot read is reported as
not found. `POST /chats/projects` accepts `template_ids`,
`limit_templates`, and `default_template` for the new project.
- `PATCH /chats/projects/{project}` sets `limit_templates` and
`default_template`, and no longer changes which templates are attached.
The default must be an attached template the caller can read, and its
preset must belong to the template's active version. Default parameter
names and values are checked against that version for templates on the
classic parameter flow; dynamic parameters are checked when a workspace
is built. Detaching the default template clears the default.
- Project responses list only the attached templates the caller can
read, as `templates`, and count the rest as `hidden_template_count`.
`default_template` is omitted when the caller cannot read it. Deleted,
deprecated, and agent-disabled templates are left out and are not
counted as hidden.
- Editing uses `chat_project:update`, which the project owner and the
project `admin` ACL role have.
- Attaching and detaching are audited as writes to the project, with the
template list before and after, including the templates attached while
creating a project. Changes to `limit_templates` and the default
template are part of the project's own audit diff.

Not included: showing which project members lack access to an attached
template, and MCP server attachments.

Stack (merge top to bottom):
- #32309
- #30754 👈
- #32310
- #30755
- #32371
- #32372
- #30756
- #32373
- #32374
- #32375
- #30898
- #32376
- #32377
- #32378
- #32379
2026-11-18 20:36:34 +07:00
Ethan feea5ab959 feat: add GPT-6.2 Astra and GPT-6.2 Sol to Agents and AI Gateway (#32370)
Closes CODAGT-1608

This adds `gpt-6.2-astra` and `gpt-6.2-sol` to the Agents known models
catalog, so they're suggested when an admin adds a chat model, and
regenerates the AI Gateway price book from models.dev so the gateway can
price them.

| Model | Input | Output | Cache read | Cache write |
|---|---|---|---|---|
| GPT-6.2 Astra | $8 | $40 | $0.40 | $10 |
| GPT-6.2 Sol | $2 | $10 | $0.10 | $2.50 |

Prices are per 1M tokens, and both models have a 1,050,000 token context
window and 128,000 max output tokens. They're in the catalog for OpenAI
(with a suggested effort of `medium`, same as `gpt-6-astra` and
`gpt-6.1-sol`), OpenRouter and Vercel. models.dev doesn't list them on
Azure or Bedrock yet, so I've left those out for now.

Both models also reject the `none` and `minimal` reasoning efforts. A
model config only sets a default and a maximum effort, so the picker
always offers both, and picking either one fails the turn:

```
Unsupported value: 'none' is not supported with the 'gpt-6.2-astra' model. Supported values are: 'low', 'medium', 'high', 'xhigh', and 'max'.
```

We already send `low` instead for `gpt-6-astra` and `gpt-6.1-sol`, so to
fix, we'll just do the same for the two new models. All four now live in
one list of model ID prefixes, rather than a helper each. I checked this
against the real models: all four return a 400 like the one above for
`none` and `minimal`, and accept `low`. `gpt-6-sol` and `gpt-6.1-terra`
still accept `none`, so they're left alone.

Regenerating the price book also brings in everything else models.dev
changed since the last weekly refresh, mostly on OpenRouter and Vercel:
22 other new entries (4 of them `-pro` and `-fast` variants of these
two), 29 it dropped and 51 price changes. 6 existing catalog entries get
new prices or limits the same way.
2026-11-19 00:33:46 +11:00
Ethan da0bd0750f chore: remove most export_test.go shims (#32162)
Follow-up to https://github.com/coder/coder/pull/25601, where I missed
the other way agents avoid `*_internal_test.go`: an `export_test.go`
file that re-exports unexported symbols, just so a `package foo_test`
test can reach them. There were 13 of these on `main`, most recently
from #32063.

This PR removes 8 of them. Tests of package internals are now
`*_internal_test.go` files, with no changes beyond the package name and
the symbols they call. `messagepartbuffer` and `agentcontext` only
needed one small accessor each, so `Buffer.EpisodeCount` and
`Manager.Started` are just exported for real, and their tests stay where
they were.

To stop new ones appearing, the `testpackage` linter no longer skips
`export_test.go` (the 5 that are left are excluded by path), and
`AGENTS.md` and `.claude/docs/TESTING.md` now state the rule.

`export_test.go` is an agent idiom, and imo we should try and get rid of
it. So, once this PR is approved, we'll fix up all the remaining ones in
a follow-up PR, somehow, and undo the lint exclusion when we do.
2026-11-18 14:14:27 +11:00
Ethan 166b9d25e3 test(coderd): remove low-value cron and chatwebhook tests (#32164)
The tests from #32063 and #32062 are two to three times the size of the
code they cover, and a lot of them can't fail for a reason we'd care
about. This PR removes those, with no production changes.

In `coderd/schedule/cron`, two tests rebuilt the schedule rule a second
time to compare against, which was also the only use of
`export_test.go`, so that goes too. Most of the rest, in both packages,
are table rows that take the same branch as a row that stays. I also
dropped a copy of the webhook scheme list and a repeated-request test
that belongs at the route.

What's left is a row per reject branch, the RFC cases, the regression
test for the `Next` hang and the constant-time scan. I replayed each fix
commit from the two PRs against the smaller suite, and the pre-fix code
still fails a test for every one, other than a fix to the wording of a
zone error.

One row that stays is changed: the bearer wrong-scheme case used
`Basic`, which was only rejected because of where its space lands, so
nothing covered the scheme word. It's now `Digest`.

#32162 overlaps with this in `cron`. With the shim's users gone it no
longer needs to touch that package, so it's now stacked on top of this
PR.
2026-11-18 14:14:26 +11:00
Callum Styan d412c38afb perf: validate chat transitions from the locked row (#30886)
One of the main costs in terms of DB load from chats is extra round
trips during transactions. This results in locks being held for longer
periods of time -> an increase in lock waits for chats related queries.

One of the opportunities for reducing some of the round trips is to
eliminate extra chat row reads after we have just read the row in order
to lock it.

In this PR `ChatMachine.Update` now seeds the transaction struct with
the row returned by `LockChatAndBumpSnapshotVersion`, plus a queue count
taken right after it. We can then pass it into `Update` as an optional
parameter validate against it, so neither re-reads the chat row from the
database while the row lock is held.

`updateChat` (send, edit, promote, tool results, interrupt, compact,
clear, reconcile), hook failure, family archive, and the worker's
generation and task transitions use it instead of reloading the chat
under the lock.

This PR relative to main:
|measurement | main | this PR | percent change |
|-- | -- | -- | -- |
| Round trips under lock  | 180.9 | 142.0 | -39% |
| Statements under lock  | 86.1 | 66.6 | -23% |
| GetChatByID under lock | 54.1 | 35.8 | -34% |
| GetChatByID total | 75.5 | 57.1 | -25% |
| Statements  | 235.8 | 216.2 | -8% |

Generated by Coder Agents on behalf of @cstyan.
2026-11-13 09:59:39 -07:00
J. Scott MillerandGarrett Delfosse 38e74c4506 feat: add agent-plugins experiment and Agent API v2.17 plugin messages (#29320)
Linear:
[CODAGT-1101](https://linear.app/codercom/issue/CODAGT-1101/agent-plugins-read-only-support-behind-the-agent-plugins-experiment)

**tl;dr:** Adds the `agent-plugins` experiment and the Agent API v2.17
messages that carry Agent Plugins data from the agent to coderd. First
of eight stacked PRs adding read-only [Agent
Plugins](https://agent-plugins.org/) v1.0.0 support.

A plugin is a directory with a `plugin.json` manifest, skills under
`skills/`, and an optional `mcp.json`. Across the stack, the agent
discovers plugins in `plugins/` and `.agents/plugins/` under its scan
roots (for example `~/.coder/plugins/<name>`), chatd lists their skills
with plugin attribution, the agent runs the MCP servers of plugins in
the workspace working directory, and the Agents page shows plugin
attribution in the chat context. Hooks, commands, agents, install flows,
and org-managed plugins are out of scope. Background:
[research/agent-plugins-standard.md](https://github.com/coder/scott-misc/blob/main/research/agent-plugins-standard.md)
(internal).

This PR adds `codersdk.ExperimentAgentPlugins` and a `PluginBody` oneof
variant on `ContextResource` (tag 18) that carries the validated
manifest fields and nests the plugin's skills and MCP servers.
`Manifest` gains `agent_plugins_enabled` (field 23), which coderd sets
when the experiment is enabled; the agent discovers plugins only then.
coderd stores each nested resource as its own row with the plugin's name
in a new `plugin_name` column (migration 000642), which the hydrate, MCP
sync, and re-pin queries copy. With the experiment off,
`PushContextState` drops plugin resources and everything nested in them.
Otherwise it rejects pushes with plugin names that fail
`workspacesdk.ValidatePluginName` (the spec's name grammar, shared by
agent and coderd), OK plugins without a name or with a duplicate name, a
non-OK plugin that nests resources, nested entries of the wrong kind,
plugin skill sources outside `<plugin source>/skills/`, and plugin MCP
servers with an empty `server_name` or a source other than `<plugin
name>/<server_name>`. Nested resources count toward the 1000-resource
cap.

Agents now dial v2.17, so a new agent needs a coderd that supports it,
as with every Agent API minor. Turning the experiment off does not
remove plugin data already pinned to existing chats.

<!-- pr-map:start -->
<details><summary>PR map</summary>

`main..4b0cfc9657`

| Category | Files | + | - |
|---|---:|---:|---:|
| prod (backend) | 15 | 342 | 78 |
| test (backend) | 9 | 534 | 3 |
| migrations | 2 | 14 | 0 |
| generated (backend) | 7 | 1216 | 1027 |
| generated (frontend) | 1 | 2 | 0 |
| **Total** | 34 | 2108 | 1108 |

1. `coderd/agentapi/context.go` (+211/-51, API): drops plugin resources
when the experiment is off; otherwise validates plugin names and
nesting, and stores each nested skill and MCP server as its own row with
the plugin's name.
2. `agent/proto/agent.proto` (+39/-9, API): `PluginBody` with nested
`skills` and `mcp_servers`, and `Manifest.agent_plugins_enabled`.
3. `codersdk/workspacesdk/frontmatter.go` (+31/-0): `ValidatePluginName`
and `MaxPluginNameLength` (manifest name grammar).
4. `coderd/database/queries/chats.sql`, `workspaceagentcontext.sql`,
migration 000642 (+28/-7, DB): the `plugin_name` column on both context
resource tables, copied by the hydrate, MCP sync, and re-pin queries.
5. `codersdk/agentsdk/agentsdk.go`, `agent/agent.go` (+18/-4, API):
`Manifest.AgentPluginsEnabled` and `ConnectRPC217WithRole`; the agent
dials v2.17.
6. `coderd/agentapi/api.go`, `manifest.go` (+4): the manifest flag
follows the experiment.
7. `tailnet/proto/version.go` (+8/-1, API): Agent API v2.17.
8. `codersdk/deployment.go` (+4, API): the `agent-plugins` experiment.

</details>
<!-- pr-map:end -->

---

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

Co-authored-by: Garrett Delfosse <delfossegarrett@gmail.com>
2026-11-13 10:39:16 -05:00
Mathias Fredriksson d639ced1e0 fix: send only changed chat history over the stream (#29662)
A client could resume the chat stream only with after_id, a message
ID. A message ID does not identify what a client has received. A
reconnect could skip a message that another client sent, send no
history_reset for an edit the client missed, or resend the whole
history.

A client can now resume with the chat's snapshot_version, which the
newest messages page returns and the stream's events then include.
The stream sends what changed at that version or later. For an edit
it sends the ID of the edited message and the messages written
since, not the whole history. A stream opened without
snapshot_version sends the same events as before.

A write outside a chat state transition does not increase
snapshot_version, and a stream can miss it. The queries that only
tests used for such writes are removed.

When the stream cannot be set up, the server now returns 500 before
the WebSocket upgrade. It used to upgrade and send an error event,
which the web client shows as a chat error.

The Tasks to Chats migration guide told clients to reconnect with
after_id. It now describes snapshot_version.
2026-11-13 13:02:38 +02:00
Mathias Fredriksson 3086d4f4c0 fix: run queued messages on the chat's model when theirs is unavailable (#31632)
A queued message whose model was disabled, had its provider disabled,
or was deleted ran on the organization default, even when the chat was
on another available model, and the chat then moved to the default.

Promotion now tries the queued message's model, then the chat's last
model, then the organization default, the order a message sent without
a model already uses. Saving a queued edit without picking a model now
sends the picker's model when the row's model is no longer selectable,
as a history edit does.

Refs CODAGT-971
2026-11-12 12:48:35 +00:00
Hugo Dutka decaf6e8c5 fix(coderd/x/chatd): shorten tool input validation errors (#32078)
Nested builtin tool input errors repeat an absolute schema path at every
recursion level. Unwrap the validator's error chain to retain only the
innermost path wrapper and its cause, with a comment explaining the
dependency's wrapping behavior. Also remove the redundant sentence about
exact property names and duplicate keys from the retry guidance.

Existing schema-validation tests now assert complete tool error messages
for root failures, nested properties, arrays, and maps. Validation
behavior and diagnostics embedded in the cause are preserved.

Refs #31541.
2026-11-12 11:50:42 +01:00
Thomas Kosiewski 85e689c89c feat(coderd/x/chatd/chatwebhook): add bearer, github and standard_webhooks verifiers (#32062)
## Why

An automation webhook must prove that a request comes from the holder of
the automation's secret before Coder parses the JSON body. The approved
RFC ([Automations for Coder
Agents](https://app.notion.com/p/3ded579be59281e39950e686df02fa3d),
Webhooks section) puts that check behind one `WebhookVerifier` interface
with three schemes. This PR adds those verifiers as a pure Go package.
The webhook route that calls them comes in a later PR.

Part of CODAGT-1135.

## What changed

New leaf package `coderd/x/chatd/chatwebhook`:

- `WebhookVerifier`, with the three methods exactly as the RFC writes
them, and three verifiers: `bearer` (constant-time token compare, one or
more spaces after `Bearer` as in RFC 6750 section 2.1), `github`
(HMAC-SHA256 of the raw body in `X-Hub-Signature-256`) and
`standard_webhooks` (HMAC-SHA256 of `webhook-id.webhook-timestamp.body`,
`v1,` entries in `webhook-signature`, five-minute timestamp window,
`whsec_` secret).
- `Scheme` with the three RFC enum strings, and `NewVerifier(Scheme)`.
The package does not import `coderd/database`.
- Every `Verify` failure wraps `ErrRejected`, so the route can answer
`401`. Every `Verify` and `ValidateSecret` error is built from a fixed
string: it never holds the secret, the received token or a signature.
The package does not log. Only the `NewVerifier` error names the unknown
scheme.
- `GenerateSecret` reads 32 bytes from `crypto/rand` for `bearer` and
`github`. For `standard_webhooks` it returns `ok=false`, and
`ValidateSecret` checks the pasted `whsec_` secret.

## Scope

- No database, no HTTP route, no wiring, no new Go module. Nothing
imports the package yet, so `main` behaves as before with the
`chat-automations` experiment off.
- The map from the database enum to a verifier, and its "every enum
value has a verifier" test, belong to the route PR. It can call
`NewVerifier(chatwebhook.Scheme(automation.WebhookAuth))`. A
`NewVerifier` error is a server error, not a `401`.
- No deduplication by `webhook-id`, as in the RFC. The same valid
request verifies every time.

## Tradeoffs

- A pasted `whsec_` secret has no length bound. The spec describes
sender secrets of 24 to 64 bytes, but it does not tell a receiver to
reject others. A bound would lock out a sender that deviates, and it
protects only the owner from the sender's own key.
- The bearer verifier accepts one or more spaces between `Bearer` and
the token, as RFC 6750 section 2.1 and the API key middleware do. It
rejects a tab and an empty token. It also rejects trailing whitespace
after the token when it receives it, but an HTTP request cannot deliver
that: `net/http` strips trailing whitespace from the header value before
the verifier runs, so such a request is accepted with the right token.
- The signed Standard Webhooks content uses the `webhook-timestamp` text
as received. The reference Go library signs the reformatted number
instead. The two differ only for a timestamp with leading zeros, which a
conforming sender does not send.
- A `webhook-id` that contains `.` is rejected. The spec asks senders to
avoid it, because it makes `id.timestamp.body` ambiguous. A repeated
`Authorization`, `X-Hub-Signature-256`, `webhook-id` or
`webhook-timestamp` line is rejected for the same reason. Several
`webhook-signature` lines are read as one list.
- `TestSecretComparisonsAreConstantTime` reads the package source and
fails on `==`, `bytes.Equal` and similar on secrets. A correct
early-exit compare gives the same answers as a constant-time one, so a
request-level test cannot tell them apart. The scan is a guard against
the likely mistake, not a proof.

## Verification
- Test vectors come from the [GitHub
docs](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries)
and from `TestWebhookSign` in the [Standard Webhooks Go
library](https://github.com/standard-webhooks/standard-webhooks/blob/main/libraries/go/webhook_test.go).
The tests cite the URL beside each vector.
- Live lane: none. No route, CLI or UI reaches this code yet, so there
is no surface to exercise.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
2026-11-12 02:49:28 +01:00
Ethan af7cd184c8 chore: point charm.land/fantasy at coder/fantasy#85 (#31746)
Part of CODAGT-1430
Relates to CODAGT-1541

Stacked on #31743.

This bumps fantasy to pick up coder/fantasy#84 and coder/fantasy#85.

A Chat Completions tool message can only hold text, so fantasy sends
tool result media (images, audio, and now PDFs from #31384) in a `role:
"user"` message right after it. That gives whatever the tool returned
the authority of the user's own words, which Codex flagged on #31383 as
a prompt injection risk for MCP tools that return untrusted files.

coder/fantasy#84 starts that user message with a text part naming the
tool call and saying the content is tool output, not instructions from
the user. It only changes the Chat Completions paths (`openai` without
the Responses API, `openaicompat`, OpenRouter and Vercel); Anthropic and
Responses keep the media inside the tool result. AI Bridge records the
last user message's text as the prompt, so on the step after a tool
returns media, it'll now record the label. I think that's fine for now.

coder/fantasy#85 fixes the output token limit field. The OpenAI provider
sent `max_tokens` unless the model ID looked like a reasoning model, and
reasoning models reject it:

```
Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead.
```

That breaks any reasoning model whose ID fantasy doesn't recognise, e.g.
an Azure deployment name, which doesn't say what model it serves (Azure
providers start using this client in #31952). The OpenAI provider now
sends `max_completion_tokens` on every Chat Completions request, which
is what OpenAI deprecated `max_tokens` in favour of. `openaicompat`,
OpenRouter and Vercel keep `max_tokens`, so self-hosted servers behind
the OpenAI Compatible provider are unaffected. I've added a test that
checks the field on each route, and the models docs no longer say Max
Completion Tokens is only for reasoning models.
2026-11-11 00:06:42 +11:00
Ethan d4edf1631a fix: replay OpenAI web searches inline without item IDs (#31743)
Closes CODAGT-1425

Stacked on #31386.

coder/fantasy#78, which is already on `main`, fixed the searches with no
reasoning before them by sending them inline without their `id`. Stored
chats still send a search as an `item_reference` when a reasoning item
came right before it, though. The API pairs any stored ID with that
reasoning item and rejects the whole request if it's missing, and a
reference doesn't save any tokens over an inline item anyway.

This bumps fantasy to pick up coder/fantasy#77, which just never
references a search, so stored chats now replay earlier searches inline,
like unstored ones. It also drops the `id` from replayed computer calls,
which have the same problem.

I've had to stack this on the CODAGT-1430 PRs, as coder/fantasy#77
merged after coder/fantasy#73 and coder/fantasy#74, so any pin that has
it has them too. `TestOpenAIResponsesNoStaleWebSearchReplay` now covers
a stored chat, and I deleted
`TestOpenAIResponsesFullReplayPairsReasoningAndWebSearch`, as it
asserted the order of references we no longer send.
2026-11-11 00:06:41 +11:00
Ethan 661b7db7b5 feat(coderd/x/chatd/mcpclient): count only text toward the in-process tool result cap (#31386)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
Stacked on #31385.

Inline and in-process MCP servers cap each tool result at 256 KiB, and
media counts at its base64 size, so a PDF over about 190 KiB becomes an
error. In-process servers are our own code running in coderd, so we'll
count only their text toward the cap, and leave their media to the 10
MiB tool media cap in chatloop. Inline servers are untrusted, so they
still count base64 media.
2026-11-11 00:06:41 +11:00
Ethan e0e6accdd9 feat: return raw MCP results from workspace MCP tools (#31385)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
Stacked on #31384.

Workspace MCP tool results go through the agent's `convertResult`, which
turns an embedded resource into a `[embedded resource: ...]` string and
drops structured content, so a PDF from a workspace MCP server never
reaches the model. Remote MCP tools already go through `mcpclient`'s
converter, which keeps both.

When a call-tool request sets `include_result`, the agent now returns
the MCP `CallToolResult` as-is in `Result` and leaves `Content` empty.
chattool always sets it and converts the result with
`mcpclient.ConvertCallResult`, so workspace and remote MCP tools share
one converter. Older agents ignore the flag and send the legacy
`Content`, which we adapt to MCP content and pass to the same converter.
The workspace MCP docs get a short Tool results section too.
2026-11-11 00:06:41 +11:00
Ethan 7a12022f3d fix: use one route-aware media rule for files and tool results (#31384)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
Stacked on #31383.

We had two rules for which media a model can take.
`AcceptsFilePartMediaType` filtered user attachments, whilst
`ToolResultMediaOmission` filtered tool results with its own lists, and
only let images through on Anthropic. Now that fantasy converts tool
result media like user files, the two should agree, so we'll keep one
rule.

`chatprovider.Model` now carries the configured provider type, and
`AcceptsFilePartMediaType` reads a table keyed on the route, i.e. the
configured provider plus the transport. `replaceUnsupportedMedia`
applies it to user file parts and tool result media alike, including the
pending tail of the turn prompt. As a result, tool result PDFs now reach
Anthropic, and the 5 MiB inline image cap only applies to images.

Azure OpenAI Chat Completions rejects file content parts with a 400
(`This model does not support file content types`, see
https://github.com/Azure/azure-sdk-for-net/issues/51873), and Gemini's
OpenAI-compatible endpoint ignores them. chatd reaches both through the
openai-compat client, so the rule rejects PDFs there, and the model gets
a text note instead of a failed request or a silently dropped file.

Unsupported tool result media now gets the same note fantasy writes
("The tool returned `<type>` content, which cannot be displayed."), so
the model sees one wording whichever layer drops it. I've also added a
Tool results section to the MCP servers docs, and fixed the File
attachments docs, which said every rejected attachment becomes text.
Only text files do; a rejected PDF becomes a note that names it.

I've also tested this end to end on Bedrock. I ran chatd from this
branch with an Anthropic provider pointed at our AI gateway's Bedrock
route (InvokeModel, us-east-2), plus an MCP tool that returns a PDF with
a code word inside. Claude Haiku 5.5 and Claude Opus 5.5 (adaptive
thinking) both read the code word from the tool result, and read it
again on the next turn, when the PDF is replayed from history. The
request carries the PDF as a `document` block inside `tool_result`, the
same body chatd sends to Anthropic.
2026-11-11 00:06:40 +11:00
Ethan 5cbf086517 feat: send tool result media to providers like user files (#31383)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
This is the first of four stacked PRs.

Today a PDF in an MCP tool result reaches no provider. On Anthropic we
strip it in chatd. On OpenAI Chat Completions fantasy swaps it for a
"cannot be displayed" note, and on Responses it sends a placeholder that
points at a user message it never sends.

coder/fantasy#73 and coder/fantasy#74 make fantasy convert tool result
media with the converter it already uses for user files: an Anthropic
document inside `tool_result`, an `input_file` inside
`function_call_output` on Responses, and a user file part straight after
the tool message on Chat Completions. Both have merged, and this PR pins
`charm.land/fantasy` to the coder_2_33 tip that has them. Chat
Completions file parts now refuse text files, as Responses already did,
so `AcceptsFilePartMediaType` follows.

The converters take a filename, so an MCP embedded resource blob is now
named after the last element of its URI path, and we store the name with
the tool result so later turns send the same one. OpenAI picks the file
type from the extension, so we append the right one when it's missing or
wrong. We drop names with control characters, as Postgres `jsonb`
rejects NUL, and we redact the name like the rest of the tool response,
since a URI like `https://host/sse/<token>` would otherwise put the
token in the chat history.

There's also a test proving aibridge's Chat Completions re-encode keeps
a user file part, as that's where these PDFs end up.

Anthropic still strips tool result PDFs until the next PR in the stack.
2026-11-11 00:06:40 +11:00
Dean Sheather acbcd0e807 fix(coderd/x/chatd): remember quickgen parameter rejections per model (#31493)
On Claude Opus 5.5, chat title generation and the turn-status label each
made four upstream requests, three of them rejected with a 400. The
temperature retry in `generateQuickgenObject` called `generateObject`
again, which restarted from the forced tool call the model had already
rejected. Each turn left about six `bad_request` rows in
`aibridge_interceptions` and added 1.5 to 3.5 seconds of latency.

This replaces the per-call fallbacks with `quickgenParamModel`, a
wrapper applied in `resolveModelCall`. It falls back to plain JSON text
when the model rejects the forced `tool_choice`, drops `temperature`
when the model rejects it, and records each rejection in a replica-wide
`sync.Map` keyed by AI provider ID, model, and parameter, following the
existing `thinkingDropBlock` map. Entries expire after 6 hours so a
provider that starts accepting a parameter again is picked up without a
restart. Only quickgen calls `GenerateObject`, so chat turns are
unaffected.

| Opus 5.5 | Before | First job per replica (and after expiry) | Later
jobs |
|---|---|---|---|
| Title / status label | 4 (3 rejected) | 3 (2 rejected) | 1 |
| Summary | 2 (1 rejected) | 2 (1 rejected) | 1 |

Rejections are still detected by matching `tool_choice` or `temperature`
in a 400 body, as before. A false match now persists for the TTL on that
replica rather than one job; the worst case is text mode or no
temperature for that model.

Closes
[CODAGT-1411](https://linear.app/codercom/issue/CODAGT-1411/quickgen-side-jobs-make-3-rejected-requests-per-run-on-claude-opus-55)

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

- Opus 5.5 reports one rejected parameter per 400, so a job that knows
nothing yet needs 3 requests; the issue's "2 requests" target for the
minimal fix isn't reachable.
- A per-job flag (first iteration) only got jobs to 3 requests. Sharing
rejections across jobs gets steady state to 1 without a hardcoded model
list, which wouldn't match gateway aliases such as Bedrock IDs anyway.
- Per-replica memory over a database column or admin setting: no
migration, no request-path writes, self-healing via TTL. Each replica
pays the learning cost once per model per TTL window.
- Keyed by provider ID plus model so the same model name behind
different providers is learned independently.

</details>

> Generated by Coder Agents on behalf of @deansheather.
2026-11-09 22:39:29 +11:00
Michael SuchaczandEthan Dickson 082668fbc1 feat: run computer use on OpenAI-compatible AI providers (#31895)
Computer use only ran on Anthropic and OpenAI AI providers. Chatd
derives the tool flavor from the AI provider type, and `openai-compat`
had no flavor, so every self-hosted model was marked unavailable for
`type=computer_use`, including the model a single-provider deployment
already uses for chat.

Hosted computer tools are not an option on those servers: an
OpenAI-compatible endpoint accepts a `computer_20250124` tool over
`/v1/messages` and a `computer-use-preview` tool over `/v1/responses`
and then drops both, so the model never sees a way to act. Computer use
is now declared as an ordinary function tool for those providers. The
model sends one action per call and every call answers with a fresh
screenshot, which is the shape these models already handle through the
shared action runner. The tool omits `zoom`, which the agent desktop
cannot perform. The desktop clamps a point outside the screen to its
edge, so the tool rejects a coordinate outside the declared screenshot
with an error that states the valid range, and a model that aims off the
screen learns that it missed. Media tool results reach the model because
the pinned fantasy fork promotes them to user-role messages, so no
dependency changed.

Coder can't verify an arbitrary OpenAI-compatible model, so those models
keep the unverified warning icon in the admin UI. The virtual desktop
docs, the Coder Agents index, the chatd architecture doc, and the
organization model settings copy now list OpenAI-compatible providers as
supported, and the docs say what to check before using one.

Three shared behaviors needed fixing to make this usable. A coordinate
of `[0,0]` is the top-left pixel and decoded as an omitted field, so the
desktop rejected those clicks with a missing-coordinate error;
coordinates now decode by key presence, which also keeps an absent
coordinate absent. A `scroll_amount` of zero or less, or a key `repeat`
of zero, was also forwarded as omitted, so the desktop scrolled its
default of three clicks or pressed the key once; the runner now rejects
both, and the function tool declares a minimum of 1 for each. And
because a chat completions model sends one action per call, it plans
every call of a step against one screen, so a failed action now halts
the later calls of that step, as it already did for Anthropic. The
hosted OpenAI flavor still differs here on purpose: it delivers an array
of actions in one call. Halting would strand a mouse press whose release
was planned for a later call, so the function tool offers
`left_click_drag` instead of separate press and release actions, and
rejects any action it does not declare.

Provider types that reuse the chat completions client without being
OpenAI-compatible (Azure, Google, OpenRouter, Vercel, Copilot) stay
unsupported until each is verified.

> [!NOTE]
> `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
`docs/reference/api/schemas.md` and `site/src/api/typesGenerated.ts` are
hand-edited to match the new enum value, because the environment that
prepared this change had no pnpm to re-run the generators. The same
environment had no node, so `pnpm run typecheck`, biome and prettier did
not run locally; CI is the validator for the `site/` change and the
generated files.

> [!NOTE]
> Prepared by Xum, Mike's coding agent, from the measurement that showed
an OpenAI-compatible server dropping both hosted computer tools.

---------

Co-authored-by: Ethan Dickson <ethanndickson@gmail.com>
2026-11-09 17:26:10 +11:00
Ethan 9fa68ac013 feat: hold every steer message while one is under edit (#31748)
Whilst a steer message is under edit, every steer message now waits, not
just the one under edit and the ones behind it.

Say Next step holds A, B and C, and you edit B. Before this, A went to
the agent at the next model call whilst B and C waited. Now nothing goes
out until the edit ends, then A, B and C go in together. If the turn
ends whilst a steer message is under edit, the chat pauses, the same as
it already does for a queue message. `GetChatQueuedMessageHead` now
returns a steer message under edit first, so the paused check still
finds it when it isn't the first row.

Queue messages are unchanged: editing one holds it and the messages
behind it.

On the site, every other row shows "Waiting" whilst a steer message is
under edit, and Enter on an empty composer won't send the first held
message whilst it's waiting on an edit. The docs are updated to match.

The first version of this PR refused edits on steer messages instead,
following [Mathias's review of
#30074](https://github.com/coder/coder/pull/30074#pullrequestreview-5352986208).
Mathias has since suggested holding the whole steer lane, so the agent
never starts working on part of what you sent.

Part of CODAGT-1140
2026-11-09 15:55:18 +11:00
Ethan a0be9d0e1d feat: make message_agent always steer (#31175)
`message_agent` no longer takes an `interrupt` flag, and always steers.
If the child is busy, it gets the message before its next model call and
keeps working. To correct or redirect a busy child, the parent just
calls `message_agent`, and `interrupt_agent` only stops it, which is the
same split the API has after #31174. The tool result also drops
`interrupted`, as it was just whether the child was running before the
send.

That was the last caller of the interrupt busy behaviour, so chatd and
chatstate drop it too. `SendMessage` never interrupts now. On a busy
chat it only ever adds the message to a lane, so the sends that moved a
running chat to interrupting, or a `requires_action` chat back to
running, are gone, along with the send's inline interruption finish for
chats with no worker. Most of the diff is deleted tests.

A steer send to a paused chat, or to an errored chat whose next message
is being edited, no longer fails with a 429 at the queue limit when it's
delivered straight away, which is whenever the message being edited is a
queue message.

Part of CODAGT-1140
2026-11-09 15:55:17 +11:00
Ethan a40ff12c8c feat!: steer chat messages by default and remove the interrupt busy behavior (#31174)
Breaking API Change for changelog:

> `POST /api/v2/chats/{chat}/messages` now steers by default. If the
chat is busy, the message is delivered before the agent's next model
call, instead of after the turn ends. `busy_behavior` accepts `steer` or
`queue`, and `interrupt` now returns a 400. To redirect the agent, just
send a message, and only call `POST /api/v2/chats/{chat}/interrupt` to
stop it. Queued messages now include their `busy_behavior`.

This is where steering becomes the default for API clients. A send
without a `busy_behavior` used to wait for the turn to end, and now it
goes in the steer lane, so the agent sees it before its next model call
and keeps going. `queue` still waits for the turn to end.

Interrupt isn't a busy behaviour any more. Since #31155 it just meant
"interrupt, then steer", so the API now returns a 400 for it, and
`codersdk.ChatBusyBehaviorInterrupt` is gone. `coder_send_chat_message`
in the MCP server gets the same default and enum. A steer message
already corrects a busy agent, and combining it with an interrupt goes
wrong in either order, so the docs and the MCP tool descriptions now say
to send a message to redirect the agent, and to interrupt only to stop
it.

Queued messages now report their `busy_behavior`, and the queue lists
the steer lane first, so clients can show which messages go in at the
next step and which wait for the turn to end. A message moved with Send
now reports `steer`.

The site doesn't send a `busy_behavior`, so its sends start steering
with this PR, but its queue UI doesn't know about the steer lane until
#31173. chatd still accepts `interrupt` internally, as `message_agent`
uses it, and #31175 removes both.

Part of CODAGT-1140
2026-11-09 15:55:17 +11:00
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
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
Jon Ayers 31a85e6b8c fix: fix flaky TestChatTurnStopsAtStepLimit (#31759) 2026-11-04 15:10:20 -06: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
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
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 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
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
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