mirror of
https://github.com/coder/coder.git
synced 2026-11-22 11:28:40 +08:00
feea5ab959f59cd2135443ed2a0c19bf7643db8f
665
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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> |
||
|
|
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. |
||
|
|
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 |
||
|
|
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. |
||
|
|
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`_ |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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> |
||
|
|
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 |
||
|
|
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 |
||
|
|
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
|
||
|
|
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
|
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
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._ |
||
|
|
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. |
||
|
|
31a85e6b8c | fix: fix flaky TestChatTurnStopsAtStepLimit (#31759) | ||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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>
|
||
|
|
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.
|
||
|
|
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> |
||
|
|
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
|
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
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
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
31b8fd1b88 | feat: graduate the chat advisor from experiments (#31414) | ||
|
|
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 |
||
|
|
1acacc9c30 | feat: graduate MCP tool search from experiments (#31327) | ||
|
|
846daa80e4 | fix(coderd/x/chatd): add ACP subagent prompt guidance (#31498) | ||
|
|
d1f308d9f3 |
feat: let organization members turn off organization skills in chats (#31134)
## Stack Organization skills load into every member's Coder Agents chats in their organization, with no way for a member to opt out. This stack adds a per-organization setting that lets members turn them off for their own chats, bottom to top: 1. **#31134** data model, API, and chatd (this PR) 2. #31135 admin and member controls in the dashboard, the `/` menu, and docs ## What changes Organizations get `members_can_disable_skills`, off by default. Users who can update organization skills change it with `PUT /api/experimental/organizations/{organization}/skill-settings`, which writes an organization audit entry. Anyone who can read the organization can `GET` it. While the setting is on, each member saves their own choices with `PATCH /api/experimental/organizations/{organization}/members/{user}/skill-preferences`: `all_skills_disabled` (a master switch that also covers skills created later) and `skills`, a sparse map from skill ID to on or off. `GET` returns the setting, the master switch, and `disabled_skill_ids`. The routes follow the personal-settings rules: without `read_personal` or `update_personal` on that user the caller gets 404, a PATCH while the setting is off gets 403, and a key that is not an organization skill that member can read gets a 400 that names the key. The check runs as the member, not the caller, so an owner or user admin editing someone else's choices is held to that member's skills. Turning the setting off keeps the choices but ignores them. Migration 000636 adds the column and two tables keyed by organization membership. Both cascade when the membership goes away, and the per-skill table also cascades when the skill is deleted, so a recreated skill loads by default. chatd reads the preferences as the chat owner when it builds the skill index and when it loads a body for `read_skill` or for a structured skill invocation (#30861). A skill the member turned off is left out of the index, and both loads report it as not found, including later in a running chat. If the preferences cannot be read, turn preparation fails, as it already does when the skill metadata cannot be read. Older migration tests created organizations with `dbgen.Organization` and `GetDefaultOrganization`, which now select the new column before it exists, so they insert organizations with raw SQL instead. ## Review focus - Authorization in `coderd/organizationskillpreferences.go` and the five new dbauthz methods (`read_personal` and `update_personal` on the user, `organization_skill` update for the setting). - `GetOrganizationSkillMemberPreferencesRow.Excludes` is the one rule chatd applies; #31135 mirrors it in `activeOrganizationSkills`. ## Testing - Go tests cover the queries and cascades, dbauthz, both routes (including the audit diff and each 400 case), and chatd (index, `read_skill`, skill invocations, master switch, a change during a chat). Each new test fails with its code path removed. - Remote dogfood UAT (10 scenarios, real model) passed on the pre-split branch head `186c28d81ab`, which has the same code except the fix below. It found one issue: two spellings of one skill ID with opposite values stored a random result. The PATCH now rejects every aliased key with a 400. A second run on the stack's top head at the time, `718dd6d1bd1`, passed: every aliased form returns 400 and stores nothing, and chats leave out a skill the member turned off, including in `read_skill`. - Polish and the test audit stayed inside the implementation diff. No new dependencies. - Rebased on main as one commit. The migration is now 000636, after main's 000634 and 000635. Every organization skill load passes the chat owner, including main's skill invocation path, so `/skill` invocations honor the opt-out too. The model's skill index leaves out a skill that is not model-invocable or that the member turned off. Apart from that, the diff is unchanged. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |