mirror of
https://github.com/coder/coder.git
synced 2026-11-24 05:18:07 +08:00
ddf89cc69a347cebec1db6c692ecc0decf11d98f
5037
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
871eb9bd3e |
feat(coderd/schedule/cron): add Standard schedule constructor (#32063)
## Why Automations store a five-field cron expression and an IANA time zone. The scheduler and the management API will parse both with `coderd/schedule/cron`, as the "Schedules" section of the [Automations RFC](https://app.notion.com/p/3ded579be59281e39950e686df02fa3d) says. This adds the parser they will call. Part of CODAGT-1135. ## What changed - `cron.Standard(spec, timeZone)` parses a five-field spec that runs on the wall clock of an IANA zone. Every field can be restricted. It returns an error for an empty spec, a wrong field count, a `CRON_TZ=` or `TZ=` prefix, an empty or unknown zone, a zone name with an empty, `.` or `..` segment such as `./localtime`, a name that starts with `posix/` or `right/` (directories of zone data that some hosts have, with other versions of the zones), `Local` (a Go name for the host's zone), a name whose last segment is `localtime`, `posixrules` or `Factory` (files in a host's zone data that are not zones), and a spec that never runs, such as `0 0 30 2 *`. - `Next` on a `Standard` schedule follows the RFC's daylight saving rule. A repeated local time runs once, at its first instance. A nonexistent local time runs at the first local time after the change. `robfig/cron` does neither: in America/New_York it runs `30 1 * * *` twice on 2026-11-01 and skips `30 2 * * *` on 2026-03-08. So `Standard` walks the matching wall-clock readings and resolves each one to an instant from the zone's UTC offsets. Every loop has a fixed bound, and `Next` always returns a later time for a `Standard` schedule. It searches at least 16 years ahead, past the eight years between two leap days across 2100. `Weekly`, `Daily` and `TimeRange` keep their behavior. - `Schedule.MinInterval()` returns the shortest distance between two times of day at which the schedule runs, counted around the clock. One time of day gives 24 hours. The management API will compare it with the deployment's minimum interval. ## Scope This PR adds no minimum interval policy and no configuration. Nothing calls the new code yet. The scheduler loop and the API come in later PRs. ## Tradeoffs - `MinInterval` reads only the hour and minute fields, with no calendar. The RFC allows a minimum interval of one minute to 24 hours, so the value only has to be right below 24 hours, and a scan over the calendar kept missing cases. While the zone's UTC offset does not change, no two runs are closer than the value. The doc comment states two limits, and a test pins each. - A change of the UTC offset (daylight saving) can shorten a gap that spans it by up to the size of the change: `1,58 1,3 * * *` in America/New_York gives 57 minutes, and its runs on 2026-03-08 are 3 minutes apart. - A pair of times across midnight counts even when the day fields never match two days in a row: `0,58 0,23 * * 1` gives 2 minutes, but its runs are 58 minutes apart at least, so a check can reject a schedule that the minimum allows. - The RFC rule, read as written, means a wildcard schedule such as `*/15 * * * *` does not run during the second pass of a repeated hour. In America/New_York on 2026-11-01 it runs at 01:45 EDT and next at 02:00 EST. - `Standard` resolves a reading from the zone's offsets and does not use Go's zone period bounds, which are wrong after the last transition in a zone's data. ## Live check None. This is a library that nothing calls yet. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_ |
||
|
|
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 |
||
|
|
a48a8c0cd7 |
fix(coderd): skip validation for unexpired chat git tokens (#31921)
Avoid provider validation requests when OAuthToken().Valid() is true. They count against the provider's API rate limit without changing which access token the chat resolver returns. Keep token refresh behavior for tokens within OAuth2's early-expiry margin or past expiry, and preserve provider validation for other external-auth callers. Refs CODAGT-1543 |
||
|
|
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. |
||
|
|
eb6094979b |
chore: refresh AI model price book (#32072)
## Price book changes 32 models added, 18 models removed, 42 models changed. <details> <summary>Added</summary> - anthropic/claude-fable-5-2 - azure/claude-fable-5-2 - bedrock/anthropic.claude-fable-5-2 - bedrock/global.anthropic.claude-fable-5-2 - bedrock/global.moonshotai.kimi-k3.1 - bedrock/us.anthropic.claude-fable-5-2 - bedrock/us.moonshotai.kimi-k3.1 - copilot/claude-fable-5.2 - copilot/gemini-4-carbon - google/gemini-4-carbon - openrouter/anthropic/claude-fable-5.2 - openrouter/baidu/ernie-5.5-flash-preview:free - openrouter/baidu/ernie-light-dt-1.0-intl - openrouter/google/gemini-4-carbon - openrouter/google/gemini-omni-1.1-flash - openrouter/google/gemini-omni-1.2-flash - openrouter/kt/midm-k-3.0-pro - openrouter/liquid/lfm-3-1.7b - openrouter/liquid/lfm-3-1.7b:free - openrouter/meta/muse-ember - openrouter/motif-technologies/motif-3 - openrouter/nex-agi/nex-n2.6 - openrouter/thinkingmachines/inkling-2-small:free - openrouter/unbiased/pareto-26.10-preview - vercel/alibaba/qwen3.6-35b-a3b - vercel/anthropic/claude-fable-5.2 - vercel/anthropic/claude-fable-5.2-fast - vercel/deepseek/deepseek-v4.1-flash-1017-ultrafast - vercel/google/gemini-4-carbon - vercel/google/gemini-omni-1.2-flash - vercel/humansand/ampersand-v0.1 - vercel/meta/muse-ember </details> <details> <summary>Removed</summary> - openrouter/bytedance-seed/seed-1.6 - openrouter/bytedance-seed/seed-1.6-flash - openrouter/bytedance-seed/seed-2.0-code - openrouter/inception/mercury-2 - openrouter/inception/mercury-2.5 - openrouter/inception/mercury-3 - openrouter/minimax/minimax-01 - openrouter/minimax/minimax-m1 - openrouter/minimax/minimax-m2 - openrouter/minimax/minimax-m2-her - openrouter/minimax/minimax-m2.1 - openrouter/nvidia/nemotron-3.5-content-safety:free - openrouter/qwen/qwen-2.5-7b-instruct - openrouter/stealth/crouton-alpha - openrouter/xingchen-agi/xing4.0-29b-a4b:free - vercel/bytedance/seed-1.6 - vercel/bytedance/seed-1.8 - vercel/google/gemini-3.1-flash-image-preview </details> <details> <summary>Changed</summary> - openrouter/anthracite-org/magnum-v4-72b - openrouter/deepseek/deepseek-chat - openrouter/deepseek/deepseek-v4-flash - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4-flash-vision-exp - openrouter/deepseek/deepseek-v4-pro - openrouter/deepseek/deepseek-v4-pro-0813 - openrouter/deepseek/deepseek-v4.1-flash - openrouter/google/gemma-4-26b-a4b-it - openrouter/ibm-granite/granite-4.2-8b - openrouter/inclusionai/ling-3.1-flash - openrouter/mancer/weaver - openrouter/meta-llama/llama-3.1-8b-instruct - openrouter/meta-llama/llama-3.2-3b-instruct - openrouter/meta-llama/llama-3.3-70b-instruct - openrouter/minimax/minimax-m2.5 - openrouter/minimax/minimax-m2.7 - openrouter/mistralai/mistral-small-3.2-24b-instruct - openrouter/moonshotai/kimi-k2.5 - openrouter/moonshotai/kimi-k2.7-code - openrouter/moonshotai/kimi-k3.1-pro - openrouter/nvidia/nemotron-3-super-120b-a12b - openrouter/nvidia/nemotron-3.5-super-vl - openrouter/openai/gpt-oss-120b - openrouter/qwen/qwen3-14b - openrouter/qwen/qwen3-next-80b-a3b-instruct - openrouter/qwen/qwen3.5-397b-a17b - openrouter/qwen/qwen3.5-9b - openrouter/qwen/qwen3.6-27b - openrouter/reflection/beam-1.0-501b-a23b - openrouter/undi95/remm-slerp-l2-13b - openrouter/z-ai/glm-4.5-air - openrouter/z-ai/glm-5.2 - openrouter/z-ai/glm-5.3-flash - openrouter/~anthropic/claude-fable-latest - openrouter/~deepseek/deepseek-flash-latest - openrouter/~deepseek/deepseek-pro-latest - openrouter/~deepseek/deepseek-v4-flash-latest - openrouter/~moonshotai/kimi-latest - openrouter/~z-ai/glm-flash-latest - vercel/alibaba/qwen3.8-27b - vercel/nvidia/nemotron-3.5-lightning </details> ## Review notes Regenerated by `make gen/aibridge-prices` from the live [models.dev](https://models.dev) catalog. Both artifacts come from one snapshot, so they ship together: - `coderd/aibridge/prices/data/prices.json` - `site/src/modules/aiModels/knownModels/knownModelsGenerated.json` These are customer-visible cost numbers taken from upstream data, so this PR is never merged automatically. The summary above lists what moved; check the diff for exact figures before approving. Opened automatically by the [aigateway-prices-refresh workflow](https://github.com/coder/coder/actions/runs/43188102112). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
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`_ |
||
|
|
e307f1d5cf |
feat: add the user-scoped chat-automations experiment (#32064)
## Why The Automations RFC controls availability with one user-scoped experiment. Its text: "The user-scoped `chat-automations` experiment controls availability. Operators configure defaults with `--experiments` and can change per-user rules while Coder is running. Each surface checks the relevant caller or automation's owner, and experiment evaluation fails closed." The later backend PRs (management routes, the `manage_automations` tool, `Publish`) need that check first. This PR registers the experiment and proves the per-user, fail-closed check. Nothing consumes it yet. Part of CODAGT-1135 ## What changed - Registers `chat-automations` in `ExperimentsKnown` and `ExperimentsUserScoped`. An earlier experiment with this name was removed in #30412, and this PR restores none of its consumers. - Keeps it out of `ExperimentsSafe`, so `--experiments=*` does not turn it on. Automations act with their owner's authority, and a test pins the choice. - Adds the name to the `userScopedExperimentStaticCheck` ruleguard rule, so server code cannot decide it from the static list. `TestExperimentsUserScopedRuleguard` keeps the rule in step with `ExperimentsUserScoped`. - Regenerates the swagger files, `docs/reference/api/schemas.md` and `typesGenerated.ts`. - Adds tests for the real experiment name. The evaluator tests cover the startup default, stored `on`, `off` and condition rules for two users, and an off decision on a rules read error, a malformed rule, an unknown mode, an attribute read error, a condition error and a nil subject. A coderd test with a real database checks the same per-user behavior through `api.ExperimentEvaluator` and `GET /api/v2/experiments`. ## Scope No routes, tool, UI or chatd change. I added no helper: `Evaluator.Enabled(ctx, userID, ex)` already decides per user and fails closed, and API handlers reach it through `api.ExperimentEvaluator`. chatd has no evaluator handle on main, because #31327 removed the unused field. The first chatd consumer adds it together with its read. ## Blast radius With the experiment off, which is the default, behavior on main does not change. Two things become visible. `GET /api/experimental/experiments/rules` and `coder exp experiment-rules list` show a `chat-automations` row, and an administrator can store a rule for it. A deployment that already passes `--experiments=chat-automations` sees three small differences: the startup log reports an opted-in hidden experiment where it reported an unknown one, the deployment Overview page stops flagging the name as invalid, and the rules row shows the static default as on. Nothing reads the experiment yet, so no feature turns on. ## Live check A local `./scripts/develop.sh` deployment built from this head ran with no flag, with `--experiments=*` and with `--experiments=chat-automations`. `GET /api/v2/experiments` lists `chat-automations` for the owner and for a member only when the startup list or a rule turns it on, and `--experiments=*` does not turn it on. A condition rule `user.username == "member"` turned it on for the member and off for the owner without a restart, and `reset` restored the startup default. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_ |
||
|
|
b61ec4395e |
fix(coderd/coderdtest): read the swagger doc once in TestSwaggerEnumsNotNarrowed (#32065)
## Why
The `test-go-race-pg` job fails intermittently with `WARNING: DATA RACE`
in `swag.(*Spec).ReadDoc`, on pull requests whose changes do not cause
it. It failed CI runs 43102680650 and 43103681536 on two unrelated pull
requests. A green rerun of the same commit passes, so it hides as a
flake.
## Cause
swag's `Spec.ReadDoc` writes shared state, so parallel tests that each
call it race. #31829 addressed this by reading the spec once through
`swaggerDoc`, a `sync.OnceValue`. #30122 then added
`TestSwaggerEnumsNotNarrowed` with a direct
`apidoc.SwaggerInfo.ReadDoc()` call, which races with the tests that
still read the shared value.
## What changed
`TestSwaggerEnumsNotNarrowed` calls `swaggerDoc()`, like the other
tests. It was the only direct call outside the generated
`coderd/apidoc/docs.go`.
## Reproduction
- On `main` (
|
||
|
|
1126533c31 |
feat: export workspace last used time to Prometheus (#31346)
Add an opt-in coderd_workspace_last_used_timestamp_seconds gauge that reports workspaces.last_used_at, the value the dormancy threshold measures inactivity from. To enable it, set --prometheus-collect-workspace-stats or CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS. A separate WorkspaceStats collector refreshes the gauge once a minute in the background from a new GetWorkspaceLastUsedForMetrics query. Each series has a workspace_id label, so a workspace that reuses a deleted workspace's name starts a new series. Workspaces owned by deleted users are excluded. Closes CLIENT-1065 |
||
|
|
0a7ef88af9 |
feat: add option to disable the embedded AI Gateway (#31967)
Adds `--ai-gateway-embedded-enabled` / `CODER_AI_GATEWAY_EMBEDDED_ENABLED` (default `true`) so standalone-only deployments can stop `coderd` from starting the in-memory AI Gateway. `CODER_AI_GATEWAY_ENABLED` stays the global switch: the AI Gateway entitlement, `/api/v2/ai-gateway/serve`, and cost-control metrics still depend only on it. The embedded daemon now starts only when both options are `true`. | `ENABLED` | `EMBEDDED_ENABLED` | Result | |---|---|---| | `true` | `true` | Unchanged | | `true` | `false` | No embedded gateway; standalone gateways keep working | | `false` | any | No AI Gateway | Refs AIGOV-514 ## Open questions for reviewers - **Coder Agents does not work with the embedded gateway disabled.** `chatd` still starts, but model calls fail with "AI Gateway transport factory is not configured" because there is no in-process transport. AIGOV-597 (routing Agents through standalone gateways) was canceled. The docs and option help state that Agents requires the embedded gateway. Is that acceptable, or should `chatd` also be turned off in this mode? - **Option name:** the ticket proposed `CODER_AI_GATEWAY_EMBEDDED_ENABLED` tentatively. OK to keep? ## Verification ``` $ go test ./cli/ -run 'TestServer_AIGateway' -count=1 ok github.com/coder/coder/v2/cli 0.518s $ go test ./enterprise/coderd/ -run 'TestAIGatewayServe' -count=1 ok github.com/coder/coder/v2/enterprise/coderd 0.755s ``` `TestServer_AIGatewayEmbedded` fails when the new check is removed. <details> <summary>Implementation notes</summary> - `codersdk/deployment.go`: new option and `AIBridgeConfig.EmbeddedEnabled` field; updated `--ai-gateway-enabled` description. - `cli/server.go`: outer `if Enabled` sets up cost-control metrics and the blocked-users collector (the standalone `/serve` endpoint uses these too). Inner `if EmbeddedEnabled` creates the daemon, registers the in-memory handler, and adds its cleanup. - `cli/server_test.go`: `TestServer_AIGatewayEmbedded` covers the three modes by checking for the embedded daemon's startup log. - `enterprise/coderd/aibridgeserve_test.go`: `TestAIGatewayServeEmbeddedDisabled` checks the entitlement and `/serve` still work with embedded disabled. - `docs/ai-governance/ai-gateway/standalone.md`: new "Disable the embedded gateway" section. - Remaining files are generated by `make gen`. - Found during review: keeping metrics inside the embedded check would have dropped cost-control metrics for standalone gateways. </details> --- Generated with Coder Agents; reviewed, revised, and verified by @mollymaefraser. |
||
|
|
fb12d6018f |
fix!: redact agent environment variable values in API responses (#31932)
Workspace, build, and agent API responses (`/workspaces`,
`/workspacebuilds/{id}`, `/workspaceagents/{id}`, and so on) returned
agent environment variable values in plain text. Template authors often
pass credentials such as API tokens through `coder_env`, so anyone who
could read the workspace could read those secrets.
`db2sdk.WorkspaceAgent` now replaces every non-empty value with
`***REDACTED***` and keeps the keys. This is the same marker the support
bundle (`sanitizeEnv`) and the agent `/debug/manifest` endpoint already
use. The agent still gets the real values through its manifest
(`db2sdk.WorkspaceAgentEnvironment`), and nothing in the CLI or frontend
reads these values from the API.
Every value is redacted because neither `coder_env` nor
`coder_agent.env` in the Terraform provider has a sensitive flag, and
`proto.Env` has no field to carry one. Selective redaction would need
changes to the provider, the proto, and the database.
## For changelog
- Agent environment variable values are redacted in API responses
(#31932)
> Workspace, workspace build, workspace agent, and template version API
responses now return `***REDACTED***` for every non-empty agent
`environment_variables` value. Keys and empty values are unchanged. The
agent still receives the real values, so workspaces behave as before.
>
> Migration: Update scripts and integrations that read agent environment
variable values from the API or from `coder list -o json`. Read the
values inside the workspace instead.
Closes ENG-1505 (coder/security#51)
<details>
<summary>Decision log</summary>
- Confirmed the leak on `main` (
|
||
|
|
7301cee2c4 |
fix: list every enum value the API can return in the Swagger spec (#30122)
The API reference is generated from Swagger comments and struct tags, and several `enums:"..."` tags narrowed a named enum type, so the docs omitted values the server returns. For example, `User.status` listed only `active` and `suspended`, not `dormant`, and `TemplateVersion.warnings` listed `DEPRECATED_PARAMETERS`, which is not a value of the type. Remove 34 `enums` tags that narrow or duplicate a named type so the referenced type's full value list is used. Tags that describe an intentional subset stay: ACL role fields (which omit the `""` deleted sentinel used only in update requests), `APIKey.scope`, and plain-string fields. `Template.provisioner` keeps its tag because `.swaggo` replaces `ProvisionerType` with `string`. Also fix enum defects that break code generators: - The provisioner jobs and daemons `status` query parameters listed their enum twice (Swagger 2.0 requires unique `enum` items) or with the wrong type. Both are now `[]codersdk.ProvisionerJobStatus` and `[]codersdk.ProvisionerDaemonStatus`, matching what each handler parses, including comma-separated values. The daemons route previously documented job statuses, which the handler rejects with a 500. - Replace the `_` zero placeholder of `WatchErrorCode` with `iota + 1`, so the spec no longer lists 0 or `x-enum-varnames: ["_", ...]`. Wire values are unchanged. Where the narrowed tag hid values the server returns, the SDK type now includes them: `LoginTypeOAuth2ProviderApp`, `BuildReasonAutodelete`, and `MissingTemplateParameter` widen the generated TypeScript unions. The dashboard attributes `autodelete` builds to Coder like other system builds. `APIKey.login_type` and `AuthorizationCheck.action` set explicit examples so the generated samples stay representative. `TestSwaggerEnumsNotNarrowed` fails when a property's enum list drops values of its named type (other than the 15 allowlisted intentional subsets), lists a value the type lacks, or repeats a value. Part of DOCS-1122, split from #30121. --- 🤖 Built with AI assistance. |
||
|
|
3728e7a4e1 |
perf: use the build parameter index in GetTemplateParameterInsights (#31765)
Speeds up `GetTemplateParameterInsights`, which the insights collector runs every 5 minutes on every replica. The `@>` array join could only hash on `name`, so every run scanned all of `workspace_build_parameters`. Unnesting the build IDs and joining on `(workspace_build_id, name)` lets the existing unique index serve it, and the results don't change since each build ID shows up at most once per group. On 8.4M synthetic build parameters the collector's 5 minute window went from 5,193 ms to about 31 ms. `TestGetTemplateParameterInsights` is new and passes on both the old and new SQL. This also fixes the Prometheus docs example, which summed per-replica copies of the same metric. I split the `workspace_app_stats` index into #31766 so this one has no migration and can be backported to 2.34 through 2.39 (2.34 to 2.38 without the docs hunk). The pre-push hook skipped tests on this push because of a stale `origin/main` in my checkout. An earlier full run only failed in `agent/` and `site/`. Part of [CORE-439](https://linear.app/codercom/issue/CORE-439). |
||
|
|
66dca90c91 |
fix(coderd/database/migrations): renumber the workspace_app_stats index migration to 000641 (#31997)
#31766 and #31748 both added a `000640` migration and both merged, so main currently has two migrations with the same number. Migrations fail to load with `duplicate migration file: 000640_workspace_app_stats_session_ended_at_idx.down.sql`, which breaks every test that sets up a database. This moves the `workspace_app_stats` index to `000641`. It's a rename only and `dump.sql` regenerates unchanged. `go test ./coderd/database/migrations/...` and the insights and dbrollup tests pass with it. Part of [CORE-439](https://linear.app/codercom/issue/CORE-439). |
||
|
|
78e1b280d1 |
perf(coderd/database): index workspace_app_stats by session_ended_at (#31766)
Adds an index on `workspace_app_stats(session_ended_at)`. The table had
no time index and is never purged, so the insights collector's app usage
query scanned all of it every 5 minutes on every replica. On 3M
synthetic rows that query went from 124 ms to 19 ms.
**NOTE**: the index build holds a lock that blocks app stat writes until
the migration batch commits (about 1.4 to 3.4 s per 3M rows in testing),
and active session upserts stop being HOT updates.
This is separate from #31765 so that one can be backported without a
migration. dbrollup's `UpsertTemplateUsageStats` still needs its own
query change to use this index on Postgres 17+ (noted on
[CORE-776](https://linear.app/codercom/issue/CORE-776)). The migration
number may need a bump at merge time.
I skipped the pre-push hook for this push since `make pre-push` also
fails on clean `main` in my workspace. This branch only failed in tests
it doesn't touch.
<details><summary>Failing pre-push tests</summary>
Clean `main` (
|
||
|
|
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. |
||
|
|
1ec94c74dc |
fix(coderd): return 500, not 403, when AI Gateway authorization hits a database error (#31617)
When coderd's `IsAuthorized` hits a database error, the AI Gateway answers 403. A coderd outage therefore looks to clients like a permission problem. The gateway can't tell coderd's own failures from rejected requests, because coderd returns both as plain errors. Worse, the API key and user lookups turn any database error into `ErrUnknownKey` or `ErrUnknownUser`. coderd now marks each database failure in `IsAuthorized` with the dRPC error code `proto.ErrCodeInternal`, where the failure happens. This covers the key, user, workspace, organization membership and effective group lookups. The key and user lookups return `ErrUnknownKey` and `ErrUnknownUser` only for `sql.ErrNoRows`. Rejections carry no code. The gateway answers a coded error with 500 and every other error with 403. dRPC sends the code with the error, so the protocol version doesn't change. A gateway and coderd on different versions keep today's 403, because the older side neither sets nor reads the code. A connection that drops during the `IsAuthorized` call still gets a 403. That's left for a follow-up. `TestAuthorization_InternalErrors` covers each database failure and each rejection on the direct, workspace token and delegated paths. `TestServeHTTP_FailureModes` covers the gateway's status codes. Refs AIGOV-737 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
5563b7444d |
fix: keep in-flight builds from blocking the prebuild hard limit (#30060)
Fixes #30058. Fixes an issue where in-flight prebuilds prevent presets from reaching their failure hard limit. `GetPresetsAtFailureLimit` now considers only completed builds (`succeeded`, `failed`, `canceled`) when evaluating consecutive failures. Pending and running builds no longer mask earlier failures, while successful and canceled builds still break the failure streak. ### Tests - Added query tests covering in-flight builds with and without a reached failure limit. - Added a reconciler test confirming hard-limited presets do not create additional prebuilds. - Fixed the test helper to properly mark successful jobs as completed. - Verified the new tests fail before the fix and pass afterward. - All relevant tests and `golangci-lint` pass. **Live validation:** A preset with builds failing after 90s (longer than the 60s reconcile interval) stopped after 4 failures, with no additional builds during a 20-minute observation. Previously, the same scenario produced 156 failed builds in approximately 2 hours. ### AI disclosure Written with AI assistance (Claude Code). I reviewed the changes, ran the tests, and verified the fix on a live deployment. Co-authored-by: Bryson Henneberger <591079+PushTheLimit@users.noreply.github.com> Co-authored-by: Bobby Ho <bobby@coder.com> |
||
|
|
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. |
||
|
|
0399d8610a |
fix(coderd/x/gitsync): verify chat workspace before storing agent git refs (#31494)
When a workspace agent requests external auth, it can send a `chat_id`
(from `CODER_CHAT_ID`) so the current git branch is linked to that chat.
`gitsync.Worker.MarkStale` trusted that ID and never checked that the
chat belongs to the agent's workspace. As a result, any workspace agent
could set the git branch, origin, and PR shown on another user's chat,
and the refresh worker would then fetch PR status with that chat owner's
git token.
`MarkStale` now ignores the request and logs a warning unless both the
requested chat and the root chat that receives the ref are bound to the
calling agent's workspace. Subagent chats are created with their
parent's `workspace_id` (`coderd/x/chatd/subagent.go`), so their
legitimate updates still reach the root chat. The root is checked too
because rebinding a chat's workspace does not rebind its existing
subagent chats. Both external-auth handlers in
`coderd/workspaceagents.go` pass the chat ID through `MarkStale`, so
this single check covers both.
Tests:
- `TestWorker_MarkStale_WithChatID` is now table-driven. A chat on the
same workspace is updated. A chat on another workspace, a chat with no
workspace, and a missing chat get no update and no event.
- `TestWorker_MarkStale_SubagentChatID_UsesRootChat` binds the chats to
real workspaces and adds two calls that must not reach the root: one
from another workspace using the child's ID, and one from the old
workspace through a child after the root is rebound to a new workspace.
- `TestWorker_MarkStale_StripsOriginCredentials` binds its chat to the
caller's workspace, since that test relied on the missing check.
Refs CODAGT-1420, SEC-856. Affects v2.32.0 onward; backports are needed
for every supported release line from 2.32.
<details>
<summary>Investigation notes</summary>
- Source of the chat ID: `agent/agentproc/process.go` sets
`CODER_CHAT_ID` in the process environment, and `cli/gitaskpass.go`
sends it as `chat_id`. Anyone with access to the workspace can set this
value.
- The path without a chat ID already filtered by workspace
(`GetChatsByWorkspaceIDs`); only the chat-ID path skipped the check.
- Open question from the issue (do child chats inherit `workspace_id`?):
yes, `CreateChatWithID` in `subagent.go` sets `WorkspaceID:
parent.WorkspaceID`.
- Edge case (from review): `UpdateChatWorkspaceBinding` rebinds only the
chat it targets, so a child can stay bound to the old workspace after
its root is rebound. Checking only the requested chat let the old
workspace write to the rebound root, so the root's workspace is checked
too.
- I did not add a second rejection in the handlers (optional item 3 in
the issue). `MarkStale` is the only consumer of the chat ID, and
rejecting there would change the external-auth response for git
operations.
</details>
> 🤖 Generated by Coder Agents on behalf of @deansheather.
|
||
|
|
70f62ae429 |
fix(coderd/coderdtest): render the Swagger spec once in parallel tests (#31829)
## Why `test-go-race-pg` fails on PRs that touch no Go product code, for example two runs on #31782. Since #30124, two parallel tests in `coderd/coderdtest` call swag's `Spec.ReadDoc`, which writes shared state, so the race detector fails the whole package (`WARNING: DATA RACE` in `swag.(*Spec).ReadDoc`, `swagger_test.go:41` and `:77`). ## What changed `swagger_test.go` renders the spec once through `sync.OnceValue`, and both tests read that string. ## Verification - On `main`, `go test -race -count=20 -run 'TestSwaggerParametersValid|TestChatModelPathParametersFormatted' ./coderd/coderdtest/` reported 4 data races and failed. - With this change, the same command passed with 0 races. - `golangci-lint` reports 0 issues for `./coderd/coderdtest/` with both the main and the new-code configs. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
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._ |
||
|
|
b0fe0ba261 |
fix(coderd): tighten up database connection errors (#31850)
Tightens up database connection errors so they stay concise, and logs internal error details server-side instead of returning them in API responses. Adds tests covering the error output. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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. |
||
|
|
4fe64af03b |
refactor: replace gonum in agent/unit with an adjacency map graph (#31235)
**Stack:** - #31232 - #31233 - #31234 - #31235 - #31236 - #31237 `agent/unit.Graph` used gonum's `simple`, `topo`, and `encoding/dot` packages, which pull in `gonum/mat` and friends (~2 MB) for a graph with a handful of nodes. Replace it with forward/reverse adjacency maps, a DFS reachability check for cycle detection, and a small DOT writer. The existing golden files are unchanged. <details> <summary>Context: binary size investigation</summary> Measured with full `make build/coder_linux_amd64` builds (zstd `-22 --ultra`) of `main` vs. the whole stack: | Artifact | Before | After | |---|---|---| | `coder` (fat, linux/amd64) | 469 MB | 339 MB | | `coder-slim` (linux/amd64) | 62 MB | 52 MB | | Embedded `site/out` | 169 MB | 72 MB | | Embedded `coder.tar.zst` | 83 MB | 60 MB | Stack, each PR removes one source of size: 1. Hidden frontend source maps (~97 MB of embedded assets) 2. Slim tarball ordering so zstd `--long` dedupes across OSes (~14 MB on the embedded archive) 3. `aisdk-go` only supplied two struct types but pulled in `openai-go` v1 and `genai` 4. `gonum` used only for a tiny DAG in `agent/unit` 5. `gofakeit` root package links every faker; only two word lists are used 6. Hugo `pageparser` used only to read YAML front matter in `templates push` Sizes were attributed with `go-size-analyzer` and an import-graph dominator pass. Not in this stack: compiling out trivy's module download resolvers in `coder/trivy` (~29 MB, drops go-getter, GCS, and S3 SDKs), swagger-ui's bundled source maps (~7 MB), and OPA's embedded historical capability JSON (~4 MB). </details> --- _Generated by Coder Agents on behalf of @kylecarbs._ |
||
|
|
6de3d92883 |
fix: correct invalid and nonexistent Swagger parameters (#30124)
Several parameter annotations produced a wrong or invalid spec. - `GET /api/v2/settings/idpsync/available-fields` and `field-values` documented a required `organization` path parameter that their URLs do not contain. The annotations were copied from the organization-scoped routes. - `format(uuid)` on the `ids` array query parameter of the provisioner jobs and daemons routes put `format: uuid` on the array rather than its items. swag cannot set an item format, so the description now says the IDs are UUIDs. - Swagger 2.0 does not allow `example` on header parameters, which failed strict validation. The `Authorization` and `Content-Disposition` examples move to `x-example` vendor extensions, which Swagger 2.0 allows on parameters and the docs generator uses for the curl samples. - `TestSwaggerParametersValid` reads every path in the generated spec and fails on a non-body parameter with `example`, an array parameter with `format`, or a path parameter missing from its route. Part of DOCS-1122, split from #30121. --- 🤖 Built with AI assistance. |
||
|
|
585485c8bf |
fix: document raw JSON as objects and byte fields as base64 strings (#30123)
Swagger renders `json.RawMessage` and `[]byte` fields as integer arrays, so the API reference showed chat tool calls as `"args": [0]` even though tool arguments and results are JSON values. Render every `json.RawMessage` as an object with one `.swaggo` replace rule, and tag `[]byte` fields, which JSON-encode as base64, `swaggertype:"string" format:"byte"`. This covers `ChatMessagePart.args`, `.result`, `.data`, `ToolResult.output`, `DynamicTool.input_schema`, both workspace build `state` fields, `TemplateBuilderModuleVariable.default`, and `CreateTestAuditLogRequest.additional_fields`. `ChatMessagePart.provider_metadata` is internal only, so it is hidden with `swaggerignore:"true"` like its siblings. `ChatMessagePart.result` and `ToolResult.output` can hold any JSON value, and `TemplateBuilderModuleVariable.default` holds a string, number, or boolean, so `object` is an approximation for all three and the field comments say so. swag rejects an untyped `.swaggo` override for `json.RawMessage`. Part of DOCS-1122, split from #30121. --- 🤖 Built with AI assistance. |
||
|
|
36b472991d | refactor: replace aisdk-go tool types with codersdk/toolsdk/tooldef (#31234) | ||
|
|
f820cba82a |
chore: refresh AI model price book (#31775)
## Price book changes 9 models added, 14 models removed, 40 models changed. <details> <summary>Added</summary> - openrouter/inclusionai/ling-3.0-tiny - openrouter/ricursiveai/ripple-65b-preview - openrouter/stealth/crouton-alpha - openrouter/tencent/hy4 - openrouter/z-ai/glm-5.3-flashx-legal - vercel/inclusionai/ling-3.1-flash-1019 - vercel/meituan/longcat-2.5 - vercel/tencent/hy4 - vercel/zai/glm-5.3-flashx-legal </details> <details> <summary>Removed</summary> - openrouter/nousresearch/hermes-3-llama-3.1-405b - openrouter/nousresearch/hermes-3-llama-3.1-70b - openrouter/poolside/laguna-s-2.1 - openrouter/poolside/laguna-s-2.1:free - openrouter/poolside/laguna-xs-2.1 - openrouter/poolside/laguna-xs-2.1:free - openrouter/thinkingmachines/inkling-small:free - openrouter/thinkingmachines/inkling:free - openrouter/upstage/solar-pro-3 - vercel/arcee-ai/trinity-large-thinking - vercel/meituan/longcat-2.5-preview - vercel/poolside/laguna-s-2.1-free - vercel/xiaomi/mimo-v2.5 - vercel/xiaomi/mimo-v2.5-pro </details> <details> <summary>Changed</summary> - openrouter/deepseek/deepseek-v3.2 - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4-pro - openrouter/deepseek/deepseek-v4-pro-0813 - openrouter/deepseek/deepseek-v4.1-flash - openrouter/google/gemma-4-26b-a4b-it - openrouter/ibm-granite/granite-4.2-8b - openrouter/meta-llama/llama-3.1-70b-instruct - openrouter/meta-llama/llama-3.2-3b-instruct - openrouter/meta-llama/llama-3.3-70b-instruct - openrouter/meta-llama/llama-4-maverick - openrouter/minimax/minimax-m2.5 - openrouter/mistralai/mistral-large-4-0 - openrouter/moonshotai/kimi-k2.7-code - openrouter/moonshotai/kimi-k3 - openrouter/openai/gpt-oss-120b - openrouter/openai/gpt-oss-20b - openrouter/particle-ai/particle-1 - openrouter/qwen/qwen3-235b-a22b-2507 - openrouter/qwen/qwen3-coder-30b-a3b-instruct - openrouter/qwen/qwen3-next-80b-a3b-instruct - openrouter/qwen/qwen3.8-27b - openrouter/z-ai/glm-4.6v - openrouter/z-ai/glm-4.7 - openrouter/z-ai/glm-5.2 - openrouter/z-ai/glm-5.3-flash - openrouter/z-ai/glm-5.3-flashx - openrouter/~deepseek/deepseek-flash-latest - openrouter/~deepseek/deepseek-pro-latest - openrouter/~deepseek/deepseek-v4-flash-latest - openrouter/~moonshotai/kimi-latest - openrouter/~x-ai/grok-latest - openrouter/~z-ai/glm-flash-latest - vercel/deepseek/deepseek-v4-flash-0731 - vercel/deepseek/deepseek-v4-pro - vercel/deepseek/deepseek-v4.1-flash - vercel/deepseek/deepseek-v4.1-flash-1017 - vercel/mistral/mistral-large-4 - vercel/moonshotai/kimi-k3.1-pro - vercel/zai/glm-5.2 </details> ## Review notes Regenerated by `make gen/aibridge-prices` from the live [models.dev](https://models.dev) catalog. Both artifacts come from one snapshot, so they ship together: - `coderd/aibridge/prices/data/prices.json` - `site/src/modules/aiModels/knownModels/knownModelsGenerated.json` These are customer-visible cost numbers taken from upstream data, so this PR is never merged automatically. The summary above lists what moved; check the diff for exact figures before approving. Opened automatically by the [aigateway-prices-refresh workflow](https://github.com/coder/coder/actions/runs/41999352102). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
a7f3e3b685 |
docs: promote the AI sections and Templates to the top level of the sidebar (#31645)
> [!NOTE] > Generated by Coder Agents. The branch and this description were written by an AI agent and need human review. ## Summary First of three stacked PRs for the docs IA overhaul (Proposal 1, section 3). This PR dissolves `docs/ai-coder/` into four top-level sidebar sections, in this order, where "Run AI coding agents in Coder" used to be: **Coder Agents**, **AI Governance** (with Agent Firewall and AI Gateway nested under it), **Agent Relay**, and **MCP server**. - Files move with `git mv`, so `git log --follow` keeps their history. The move includes every file in the moved folders, including pages that are not in the sidebar, such as `agent-firewall/example-policy.md`, and pages added to `main` after the first version of this PR, such as `agents/projects.md` (#30684) and `agents/acp-subagents.md` (#31430). - `docs/ai-coder/index.md`, `best-practices.md`, and `ide-agents.md` are deleted. Each has a redirect (see below). - `docs/manifest/` mirrors the new folders: `coder-agents.yml` (+ `coder-agents/`), `ai-governance.yml` (+ `ai-governance/`), `agent-relay.yml`, and `mcp-server.yml`. `ai-coder.yml` is deleted. The Projects and ACP subagents entries from `main` move with Coder Agents. - Every relative link and image path is fixed, both in the moved pages (their base directory changed) and in pages that link to them. This was done in one scripted pass from a clean `main` checkout. Every link was then checked to resolve on disk. - Commit 2, `chore: point in-product docs links at the new docs paths`, updates docs URLs outside `docs/`: `site/` `docs()` links, Go error strings and comments, `README.md`, `server.json`, templatebuilder modules, and the doc-check skill. Commit 4 reverts the unversioned `https://coder.com/docs/...` URLs among them (see below), so after this PR only these differ from `main` outside `docs/`: the `site/` `docs()` links, the versioned `cli/cliui` troubleshooting links, and repo file paths in comments and the doc-check skill's examples (`docs/coder-agents/...`, `docs/templates/...`). You can drop commit 2; the redirects cover the old URLs. - **#31646 (Templates) was squash-merged into this branch** as `98377a3a3b`. This PR now also carries the Templates move (`docs/admin/templates/**` → `docs/templates/**`, plus `template-from-scratch.md` and `testing-templates.md`) and its chore changes. Refer to #31646 for that part's move map, redirects, and review. - Commit 4, `fix: keep docs links healthy before the release`, keeps links working on the live site until a release that includes this stack becomes the default docs version: - Hand-written pages that linked to moved pages with absolute `https://coder.com/docs/...` URLs now use relative links, anchors kept. The new paths 404 on the live site today, but relative links resolve for every version and are checked locally. - Hardcoded, unversioned `https://coder.com/docs/<new path>` URLs outside `docs/` that the chore commits introduced (Go strings including the prebuilds metric help, CLI help, the `agentFallbackTroubleshootingURL` default, `README.md`, `server.json`, examples, templatebuilder files, and one `site/` constant) go back to their current paths. Then `make gen` regenerated the generated table in `docs/admin/integrations/prometheus.md`, `scripts/metricsdocgen/generated_metrics`, the CLI golden files, and `docs/reference/cli/templates/{create,edit}.md`. See "Post-release follow-up". - The `site/` `docs()` changes and the `cli/cliui` links stay, because those URLs are versioned (`/docs/@vX.Y.Z/...`) and resolve once the release ships. - Commit 5, `docs: prefix relative links in the moved pages with ./`, adds `./` to 13 relative links that the move script wrote without it, in `docs/mcp-server.md` and three Templates pages. They resolved, but every other relative link in the docs starts with `./` or `../`. - Commit 6, `docs: keep the coding agent module guidance in the templates docs`, adds an **AI agent modules** section to `docs/templates/extending-templates/modules.md`. Deleting `docs/ai-coder/index.md` removed the only instructions for adding a terminal coding agent to a template with a registry module. The example (`registry.coder.com/coder/claude-code/coder`, `version = "~> 5.2"`) passes `terraform validate`, and the Template Builder labels it cites match `site/src/pages/TemplateBuilder/ModuleSelectStep.tsx`. Stack: **this PR** (with #31646 squash-merged in) → `docs/ia-tutorials-nav` (#31647, Tutorials + nav renames) → `docs/ia-workspaces-folder` (#31650, folder rename). Refs: Linear DOCS-1154, DOCS-1179, and DOCS-1479 for the coder.com and router redirect fix. ## Move map | Old | New | | --- | --- | | `docs/ai-coder/agents/**` (25 files) | `docs/coder-agents/**` | | `docs/ai-coder/ai-governance.md` | `docs/ai-governance/index.md` | | `docs/ai-coder/agent-firewall/**` (9 files) | `docs/ai-governance/agent-firewall/**` | | `docs/ai-coder/ai-gateway/**` (26 files) | `docs/ai-governance/ai-gateway/**` | | `docs/ai-coder/agent-relay/**` (3 files) | `docs/agent-relay/**` | | `docs/ai-coder/mcp-server.md` | `docs/mcp-server.md` | | `docs/ai-coder/index.md` | deleted | | `docs/ai-coder/best-practices.md` | deleted | | `docs/ai-coder/ide-agents.md` | deleted | ## Redirects added Appended to `docs/redirects.json`, using the absolute `/docs/...` format that `main` validates today. Wildcards cover every page under each moved folder, including pages that are not in the sidebar and the pages added to `main` since the first version of this PR. | Source | Destination | | --- | --- | | `/docs/ai-coder` | `/docs/coder-agents` (deleted hub, **please confirm**) | | `/docs/ai-coder/best-practices` | `/docs/coder-agents` (deleted, **please confirm**) | | `/docs/ai-coder/ide-agents` | `/docs/user-guides/workspace-access` (deleted, **please confirm**) | | `/docs/ai-coder/ai-governance` | `/docs/ai-governance` | | `/docs/ai-coder/mcp-server` | `/docs/mcp-server` | | `/docs/ai-coder/agents/:path*` | `/docs/coder-agents/:path*` | | `/docs/ai-coder/agent-firewall/:path*` | `/docs/ai-governance/agent-firewall/:path*` | | `/docs/ai-coder/ai-gateway/:path*` | `/docs/ai-governance/ai-gateway/:path*` | | `/docs/ai-coder/agent-relay/:path*` | `/docs/agent-relay/:path*` | None of the 3 existing rules in `docs/redirects.json` points into `ai-coder/`, so no destinations needed updating. **coder.com and router static redirects.** coder.com applies its own `redirects.json` and the rules it generates from this file before it hands `/docs` to the docs-engine router, which applies its own static `redirects.json` before the page. Three older static rules in both repos send `/docs/templates`, `/docs/templates/open-in-coder`, and `/docs/templates/troubleshooting` to `/docs/admin/templates/...`, and the `/docs/admin/templates/:path*` rule here sends them back, so each loops once a release with this layout is the docs mainline. A static `/docs/workspaces` rule would also hide the new `docs/workspaces/index.md` page from #31650. coder/coder.com#1201 and coder/docs-engine#304 (draft, DOCS-1479) remove those rules; they must merge when that release becomes the mainline, not before, because the old-layout mainline still needs them. A chain simulation of every page and static source on each branch of this stack finds no other loops or hidden pages. The `/docs/ai-coder/...` and other legacy rules there still work; some now take two redirects. ## Deviations from the proposal - **Glossary "IDE agent" entry.** The proposal says to remove this link and leave plain text. I pointed it at Access your workspace (`docs/user-guides/workspace-access/index.md`) instead, the same page the `ide-agents` redirect uses, because "Refer to IDE agents." with no link reads as a dead end. The "Coding agent" entry now links to Coder Agents, as the proposal says. - **Top-level icons.** The new sections need icons. I chose `wand.svg` (Coder Agents, the old ai-coder icon), `ai_intelligence.svg` (AI Governance), `link.svg` (Agent Relay), and `plug.svg` (MCP server). - **Coding agent module guidance.** Kept on the Reuse template code page (commit 6) instead of deleted with `docs/ai-coder/index.md`. The best-practices and IDE-agent pages are deleted as proposed. - **Order relative to Administration.** In this PR the four sections sit where `ai-coder` was, after Administration. PR C moves Administration after MCP server to reach the final order. - **`docs/mcp-server.md` repo link.** A relative link to `codersdk/toolsdk/toolsdk.go`, outside `docs/`, was re-based for the new depth. - **Left unchanged on purpose:** - Database migrations and the notification `.golden` files rendered from them still contain `coder.com/docs/ai-coder/...` URLs. Existing migrations can't be edited, so those links rely on the redirects. - `aibridge/client/client.go` links to a commit-pinned GitHub permalink, which still resolves. - Test fixtures in `scripts/docsredirectscheck` and `.github/workflows/test-docs-preview-mapper.sh` use `ai-coder` as sample data. - `site/src/pages/AgentsPage/components/ChatElements/tools/Tool.stories.tsx` uses `https://coder.com/docs/ai-coder/ai-gateway` as a sample web search result. Changing it would only change a visual snapshot. ## Open questions for Nick 1. Do you agree with the three redirect targets for the deleted pages above? 2. Should the "IDE agent" glossary entry link to Access your workspace (current) or be plain text (proposal)? 3. Are the icons for the new top-level sections OK? 4. Open PRs that touch the moved files, checked with `git merge-tree` against this branch. I didn't change them. - #31169 merges cleanly: Git's rename detection carries its edit to `docs/ai-governance/ai-gateway/clients/claude-code.md`, and its new relative link still resolves at the new path. - #30262 now targets `tk/ai-gateway-responses-ws-endpoint` and conflicts with `main` in 21 files. Against this branch it conflicts in the same 21 files, with `codex.md` at its new path, so this PR doesn't add new conflicts. Its new relative links still resolve after the move. - #30805 conflicts in `docs/redirects.json`. It already conflicts with `main` there, because `main` added the `/docs/about/screenshots` and `/docs/install/cli` rules. ## Release No backport to `release/2.39` for now; Nick may apply it by hand later. A cherry-pick of this branch onto `release/2.39` conflicts in 25 files, and #31647 and #31650 would need the same treatment to keep the stack together. coder/coder.com#1201 and coder/docs-engine#304 merge when the first release line that carries this layout becomes the docs mainline (2.38 today). ## Known limitations - **CLI newer than its server.** The `cli/cliui` troubleshooting links append `/templates/troubleshooting#...` to the server's versioned docs URL. A CLI from this release against an older server prints `/docs/@v2.38.x/templates/troubleshooting#...`. The router's static `/docs/templates/:page(open-in-coder|troubleshooting)` rule redirects that to the old page today, but coder/docs-engine#304 removes that rule to fix the loop, so after the cutover that case gets the version's not-found page. ## Post-release follow-up After a release that includes this stack becomes the default docs version on coder.com, point these hardcoded URLs at the new paths. They work today and redirect after the release, so nothing breaks in the meantime. Anchors are unchanged. Rerun `make gen` afterward to update `docs/admin/integrations/prometheus.md`, `scripts/metricsdocgen/generated_metrics`, the CLI golden files, and `docs/reference/cli/templates/{create,edit}.md`. | Current (old) URL | Post-release URL | Files | | --- | --- | --- | | `https://coder.com/docs/ai-coder/agents` | `https://coder.com/docs/coder-agents` | `.claude/skills/doc-check/output.md`, `README.md` | | `https://coder.com/docs/ai-coder/agents/architecture` | `https://coder.com/docs/coder-agents/architecture` | `coderd/x/chatd/chattool/execute_test.go`, `codersdk/toolsdk/workspacetools/execute.go` | | `https://coder.com/docs/ai-coder/ai-gateway` | `https://coder.com/docs/ai-governance/ai-gateway` | `README.md`, `coderd/templatebuilder/modules/claude-code/module.json`, `coderd/templatebuilder/modules/codex/module.json` | | `https://coder.com/docs/ai-coder/mcp-server` | `https://coder.com/docs/mcp-server` | `server.json` | | `https://coder.com/docs/admin/templates` | `https://coder.com/docs/templates` | `README.md` | | `https://coder.com/docs/admin/templates/extending-templates/docker-in-workspaces` | `https://coder.com/docs/templates/extending-templates/docker-in-workspaces` | `examples/templates/docker-devcontainer/main.tf` | | `https://coder.com/docs/admin/templates/extending-templates/parameters` | `https://coder.com/docs/templates/extending-templates/parameters` | `examples/parameters-dynamic-options/README.md`, `examples/parameters/README.md`, `examples/parameters/main.tf`, `examples/templates/kubernetes-envbox/README.md`, `examples/workspace-tags/README.md` | | `https://coder.com/docs/admin/templates/extending-templates/prebuilt-workspaces` | `https://coder.com/docs/templates/extending-templates/prebuilt-workspaces` | `coderd/prebuilds/api.go`, `enterprise/coderd/prebuilds/metricscollector.go` (metric help text) | | `https://coder.com/docs/admin/templates/extending-templates/workspace-tags` | `https://coder.com/docs/templates/extending-templates/workspace-tags` | `examples/workspace-tags/README.md` | | `https://coder.com/docs/admin/templates/managing-templates` | `https://coder.com/docs/templates/managing-templates` | `cli/templatecreate.go`, `cli/templateedit.go` (CLI help) | | `https://coder.com/docs/admin/templates/managing-templates/image-management` | `https://coder.com/docs/templates/managing-templates/image-management` | `coderd/templatebuilder/bases/docker/README.md`, `coderd/templatebuilder/bases/kubernetes/README.md` | | `https://coder.com/docs/admin/templates/troubleshooting` | `https://coder.com/docs/templates/troubleshooting` | `agent/agentscripts/agentscripts.go`, `coderd/render/escape_internal_test.go`, `codersdk/deployment.go` (`agentFallbackTroubleshootingURL` default) | | `https://coder.com/docs/tutorials/template-from-scratch` | `https://coder.com/docs/templates/template-from-scratch` | `site/src/pages/TemplateBuilder/TemplateAlternatives.tsx` | ## Validation run - `make gen/docs-manifest`: clean diff afterward. - `make lint/docs-manifest`, `lint/docs-redirects` (`go run ./scripts/docsredirectscheck -base origin/main`: 15 rules OK, no removed-route warning), `lint/docs-html`, `lint/emdash`: pass. - `pnpm check-docs` (markdownlint + table formatter): pass. - Vale (`vale --no-exit docs/`): the same 12 warnings and 1 error as `main`, all pre-existing. Suggestions drop from 646 to 645; the one removed was in the deleted `ide-agents.md`. - Local relative-link check over `docs/**/*.md`: 0 unresolved links or images (also 0 on `main`). - Pre-commit hook: `make pre-commit-light` on the docs commit, and the full `make pre-commit` (gen, fmt, lint/go, lint/ts, build, and others) on the chore commit. Both passed. - Targeted tests: - Go: `go test ./coderd/x/chatd/chattool/... ./codersdk/toolsdk/... ./coderd/templatebuilder/...`. - Site: Vitest for the touched directories (107 files, 1879 tests), and the story tests for `CoderAgentsProductCard`, `GroupSettingsPageView`, `GatewayKeysPageView`, and `ModelForm` (4 files, 63 tests). - Every `docs()` path and anchor in the `site/` and Go diff resolves to a page and heading in this branch. - Frontend deep review (all 8 roles) on the `site/` diff of PRs A and B: no blocking or should-fix findings. Nits on existing code that this PR only touched, not changed here: a single-use `docsLink` constant in `ChatAccessDeniedAlert.tsx`, and assertion-only `play` functions in the `GatewayKeysPageView`, `ModelForm`, `CoderAgentsProductCard`, and `GroupSettingsPageView` stories. - Page counts: `docs/**/*.md` (excluding `.style`) 490 → 487; `manifest.json` routes 495 → 492. With #31646 squash-merged in, the counts don't change, because the Templates move only moves files. - **Link health (commit 4):** - linkspector 0.5.6 with `.github/.linkspector.yml` over all of `docs/`, like the weekly docs job (`umbrelladocs/action-linkspector`, `reporter: local`, `filter_mode: nofilter`). I ran it locally with Chrome in `--no-sandbox` mode. - `origin/main`: 0 errors. Before the fix (`17e54ad555`): 6 errors, all `https://coder.com/docs/<new path>` 404s (`shared-workspaces.md:19`, `esr-2.24-2.29-upgrade.md:80-82`, `tasks-to-chats-migration.md:73`, `prometheus.md:298`). After the fix (`def074caab`): 0 errors. A first run after the fix also flagged a Red Hat URL in `install/server/openshift.md`. That URL is unchanged from `main`, and it passed on a rerun, so the failure was transient. - After the fix: `make gen/docs-manifest` (clean), `lint/docs-manifest`, `lint/docs-redirects` (15 rules OK against `origin/main`), `lint/docs-html`, `lint/emdash`, `pnpm check-docs`, and the relative-link check (0 unresolved in 3416 links) pass. The full `make pre-commit`, including `make gen`, passed on the commit. - Tests after the fix: - Go: `go test ./cli -run 'TestCommandHelp|TestServerYAMLConfig'`, `./enterprise/cli -run TestEnterpriseCommandHelp`, `./coderd/render`, `./agent/agentscripts`, `./coderd/prebuilds`, `./enterprise/coderd/prebuilds`, `./coderd/x/chatd/chattool/...`, `./codersdk/toolsdk/...`, `./coderd/templatebuilder/...`. - Site: Vitest for `src/pages/TemplateBuilder` (7 files, 67 tests). - **After the rebase onto `ccf5ec74ae`** (commits 5 and 6 included): `make gen/docs-manifest` (clean), `lint/docs-manifest`, `lint/docs-redirects` (15 rules OK), `lint/docs-html`, `lint/emdash`, `pnpm check-docs`, and a relative-link and anchor check over the changed pages pass. The only unresolved anchor, `docs/ai-governance/ai-gateway/cost-controls.md` → `enterprise.md#list-organization-ai-spend-by-user`, is also broken on `main`. The pre-commit hook (`make pre-commit-light`, because both new commits touch only `docs/`) passed on commits 5 and 6. The rebased code commits rely on CI for Go and TypeScript checks. - **Redirect chains:** a Node simulation of coder.com's static rules, its generated rules from this branch's `docs/redirects.json`, the router's static rules, the page, then this branch's rules on a miss, over every page and exact static source, reports the 3 loops above and nothing else new; with coder/coder.com#1201 and coder/docs-engine#304 applied, 0. - **Skipped:** the docs-engine sync check, which was not available in this environment. <details> <summary>Implementation notes</summary> - Rebuilt on `main` at `ccf5ec74ae` (2026-11-03) to clear conflicts with `main`, after an earlier rebase the same day onto `1a963c628d`. The previous rebuild was on `9839406ff7` (2026-11-02), and the first version on `9b8d880d63` (2026-10-23). - Rebase conflicts with #31603, which added `target="_blank" rel="noreferrer"` to docs links: 4 `site/` files in the chore commit and 5 in the Templates commit. Each kept `main`'s version of the link with only the docs path changed. Vitest for the 7 affected page directories (233 tests) and the story tests for the 8 changed or affected stories (102 tests) pass, and every `docs()` path in `site/src` resolves except the same 13 that are unresolved on `main`. - Rebase conflict: `docs/manifest/coder-agents.yml`. `main` added `docs/ai-coder/agents/bring-your-own-mcp-servers.md`; it moves to `docs/coder-agents/` with its sidebar entry, and its `../../user-guides/` links become `../user-guides/`. - Folded into the Templates commit: a link that `main` added to `docs/user-guides/workspace-dotfiles.md` (#31606) now points at `../templates/extending-templates/environment-variables.md`. - `git range-diff` against `def074caab`, the head before both rebases, shows only those changes. - The move script reads every page from the clean `main` checkout and resolves each relative link (inline, reference-style, and HTML `src`/`href`) against the page's **old** directory. It maps the target through the move map and recomputes the link from the page's **new** directory. It runs once and refuses to run on a dirty `docs/` tree, so it can't apply the path math twice. It also rewrites absolute `coder.com/docs/...` and `github.com/coder/coder/(blob|edit|tree)/main/docs/...` URLs, and skips fenced code blocks and inline code. - Before reusing the script, I ran it on the old base and diffed the result against the old commit. The only differences were the two hand-edited glossary entries and table padding from the formatter, so the rebuild applies the same changes to the current `main`. - Afterward, `grep -r ai-coder docs/` finds matches only in `docs/redirects.json`. - Changes from the earlier version of this branch: 2 more pages move (`agents/projects.md`, `agents/acp-subagents.md`) and their sidebar entries move with them. The chore commit also updates `SessionSummaryTable.tsx` (new on `main`) and the doc-check skill's `output.md` (its examples moved there from `SKILL.md`). The `AICostControl.tsx` anchor question is gone, because `main` fixed it. </details> --------- Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com> Co-authored-by: Nick Vigilante <nick.vigilante@coder.com> |
||
|
|
31a85e6b8c | fix: fix flaky TestChatTurnStopsAtStepLimit (#31759) | ||
|
|
8efd1fc86e |
fix(coderd/workspaceapps)!: strip session tokens before proxying to apps (#31633)
The workspace app proxy stripped Coder cookies before forwarding a request to the app, but not the `Coder-Session-Token` header or the `coder_session_token` query parameter. App auth accepts both, so a client that authenticated that way (the CLI and codersdk, or an IDE extension pointed at a path app URL) passed its API key through to whatever runs behind the app. That matters most for shared apps and ports, where the caller's token reached a workspace owned by someone else. This strips both before proxying. The query parameter is removed from the raw query string, so everything else in the query reaches the app byte-for-byte. `Authorization` and `access_token` are still forwarded since apps can use them for their own auth. Stripping those safely needs to know which credential Coder actually used, so that's tracked in [CORE-817](https://linear.app/codercom/issue/CORE-817/strip-authorization-and-access-token-from-app-proxy-requests-when). This is marked breaking because an app that relied on the caller's Coder token arriving through that header or query param won't get it anymore. Cookie-authenticated requests were already covered, so this only affects callers that send the token in that header or query param. Nothing in this repo depends on it. Apps that need to call the Coder API as the visitor should use the OAuth2 provider instead. Covered by the shared app proxy tests, which run against coderd and wsproxy, for both the owner on a path app and another user on a shared subdomain app, plus unit tests for the query filtering. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2138549ed2 |
fix(coderd/provisionerdserver): store import module archives outside the transaction (#31576)
Fixes a race where two template imports finishing at the same time with identical module archives fail one of them on `files_hash_created_by_key`. |
||
|
|
79e3601535 |
fix: bound workspace agent responses and stop relaying agent 401s (#30183)
Follow-up to the chat workspace-upload security review (ISSUE-1, ISSUE-10). Workspace code can impersonate the workspace agent HTTP API, so coderd shouldn't trust what comes back from it. This PR fixes two places where it did. First, coderd read agent responses without a size limit. The worst case was the `propose_plan` tool, which the model can call at any time and which ran `io.ReadAll` on a `ReadFile` body, but `DebugLogs`, `DebugMagicsock`, `DebugManifest`, `PrometheusMetrics` and `StopDesktopRecording` did the same. To fix, every agent request in `workspacesdk` now goes through one limit in `apiRequestWithOptions`: 32 MiB by default, with larger per-request limits for the few endpoints that legitimately return more (support bundle files, debug logs, desktop recordings, and `ReadFile` up to the requested limit). Reads past the limit fail rather than truncate. Error bodies are capped at 64 KiB for every status, including on the ACP client and `CancelToolCall`. Nothing legitimate gets close to 32 MiB; the biggest is a desktop screenshot at around 8 MB. Second, coderd relayed agent statuses straight to the browser. The container list and devcontainer delete/recreate handlers passed through any agent status and response, so an agent answering 401 made the site's `RequireAuth` interceptor sign the user out. The workspace page lists containers automatically, so this hit anyone viewing the workspace, not just the owner. The chat upload handler had the same problem. To fix, these handlers now turn an agent 401, 407, or anything outside 4xx/5xx into a 502, with the agent's message in a truncated `Detail`. A real agent never sends any of those, so every status it does send (403, 404, 409, 500, 503) still passes through unchanged. A 404 on upload still maps to 409 (outdated agent). An earlier revision of this PR relayed only an allowlist of expected statuses with a coderd-written message, but that turned real 500s and 503s into 502s and replaced the agent's own messages. There's no reason to change the statuses a real agent sends today, so we just block the ones that can sign the user out. The composer upload pill still truncates the error message and never shows `Detail`; that's left for a follow-up. > [!NOTE] > Opened by Xum on behalf of @ibetitsmike. Rebased by Coder Agents on behalf of @ibetitsmike. Updated by Xum on behalf of @ethanndickson. --------- Co-authored-by: Ethan Dickson <ethanndickson@gmail.com> |
||
|
|
bc5dd20a05 |
feat: report Agent Relay builds in telemetry (#31407)
Telemetry builds now report whether Agent Relay created them. Before this, relay workspaces looked like any other build. A start build counts as a relay build when it has the `agent_relay_session_id` parameter. Stop and delete builds never get the field. For those builds, the new `agent_relay` field on `WorkspaceBuild` reports: - `provider`: `claude_code`, `cursor`, `ambiguous`, or `unknown` - `client_platform`: Claude Code only. Lowercased, characters outside `[a-z0-9_]` become `_`, and cut to 15 characters - `attempt`: omitted when missing or not an integer, so `0` is sent - `session_id_hash` and `pool_hash`: SHA-256 hashes No other parameter values are sent. Other builds leave the field out. The snapshot fetches these parameters with one new batch query. The workspace-create event reads the stored parameters with one extra query, only when telemetry is enabled, so it reports the same data as the snapshot. `docs/admin/setup/telemetry.md` lists the parameters that are read. The collector side is [coder/coder-telemetry-server#56](https://github.com/coder/coder-telemetry-server/pull/56). Merge this PR first. Refs [RELAY-9](https://linear.app/codercom/issue/RELAY-9/telemetry-report-agent-relay-usage-from-codercoder) <details> <summary>Decision log</summary> - **Detect relay builds from parameters.** This needs no relay changes. Relay registration or [CORE-426](https://linear.app/codercom/issue/CORE-426) provenance metadata can come later. - **Builds only, not workspaces.** `GetWorkspaces` doesn't return the latest build's parameters, so a workspace field would cost another query. The collector can join on `workspace_id`. - **Provider comes from parameter names only.** `agent_relay_claude_code_*` means Claude Code and `agent_relay_cursor_*` means Cursor. A build with both reports `ambiguous`; a build with neither reports `unknown`. coderd stores every declared parameter on every build (ephemeral ones with their default), so a Claude Code start after a stop still reports `claude_code`. - **Start builds only.** Stop and delete builds of a relay workspace carry the same parameters but are not dispatches, so the snapshot skips them before querying parameters. - **Hash session ID and pool.** Pool names are user content, and sessions only need counting. - **Known gaps.** Cursor has no client platform. Relay version and health would need relay registration. - **Parameter names are shared with coder/agent-relay.** If agent-relay renames one, telemetry silently stops reading it. </details> <details> <summary>Manual test on <code>develop.sh</code></summary> Ran on `8ad7cd491f` with `CODER_TELEMETRY_ENABLE=true CODER_TELEMETRY_URL=http://127.0.0.1:8081` and `go run ./scripts/telemetry-server --port 8081` as the collector. Pushed three templates with no infrastructure, each declaring the same parameters as the real modules: - `relay-claude`: `agent_relay_session_id`, `_delivery_id`, `_pool`, `_client_platform`, plus ephemeral `agent_relay_attempt` and `agent_relay_claude_code_lock_to_account` - `relay-cursor`: `agent_relay_session_id`, `_delivery_id`, `_pool`, `agent_relay_cursor_pool_name`, `_idle_release_timeout`, `_repo_url` - `relay-plain`: `region` Created workspaces with `POST /api/v2/users/me/workspaces` and `rich_parameter_values`, the same call the relay makes. Then ran stop and start builds on the relay workspaces, and restarted coderd to get a periodic snapshot. | Workspace | Build 1 (create event and snapshot) | Builds 2 and 3 (stop, start) | |---|---|---| | Claude (`claude_in_slack`, attempt 1) | `claude_code`, platform, attempt 1 | `claude_code`, platform, no attempt | | Cursor | `cursor` | `cursor` | | Plain | field omitted | n/a | | Claude template, no session ID | field omitted | n/a | - Stop and start builds keep `agent_relay_claude_code_lock_to_account`, with an empty value, so Claude Code rebuilds still report `claude_code`. - No session ID, pool name, or `region` value appears in the captured telemetry. The hashes match `sha256` of the inputs. - Fed the captured snapshot through the conversion code in coder/coder-telemetry-server#56: all 8 builds converted, 6 of them with `agent_relay` set. - No telemetry errors or panics in the coderd logs. This run predates the start-only change: build 2 (stop) carried the field then. Stop and delete builds are now omitted, which `TestTelemetry_WorkspaceBuildAgentRelay` covers. </details> --- *Generated by Coder Agents on behalf of @Emyrk.* |