mirror of
https://github.com/coder/coder.git
synced 2026-11-23 20:38:59 +08:00
d798ce4e5b8cdbfcc1111d92559ea4637de0d6e0
2069
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
813b8c151f |
feat: make AI Gateway content recording optional (#30031)
Add `--ai-gateway-disable-content-recording`, which stops user prompts,
tool
calls and model thoughts from being stored. Cost control reads none of
those
tables, so budgets, spend accounting and enforcement are unaffected.
A dropped record is still logged, so pairing the option with
`--ai-gateway-structured-logging-source=gateway` keeps the SIEM export
for
records that are never persisted. The gateway warns at startup when
content is
dropped while coderd is the only emitter, since those records then reach
neither
the database nor a SIEM.
Covered end to end for the embedded and the standalone gateway, and
documented
alongside cost controls.
<details>
<summary>Why the stack is ordered this way</summary>
The final design is a chain of recorder decorators:
+---------------------+
| AsyncRecorder | all records except the interception start
+---------------------+
| LogRecorder | emit the structured record
+---------------------+
| ValidatingRecorder | refuse malformed records
+---------------------+
| caller middleware | record policy, e.g. drop content
+---------------------+
| TraceRecorder |
+---------------------+
| DRPCRecorder | acquire client, send to coderd
+---------------------+
Ordering constraints:
- The record type constants (1) are the vocabulary both emitters and the
validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
doing nothing but client acquisition, which is why it is folded into
`DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
arrives, rather than as an unused hook beforehand.
</details>
---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
|
||
|
|
23fb35d185 |
feat: let the AI Gateway emit the structured interception records (#30030)
coderd emitted the structured interception records as they arrived over
DRPC, so
a record the gateway never sends cannot be exported.
- Add `--ai-gateway-structured-logging-source` (`coderd`, `gateway`,
`both`) and
teach the gateway's `LogRecorder` to emit the same format where the
records
originate. Gateway lines omit `thread_parent_id` and `thread_root_id`,
which
are resolved by a database lookup only coderd can perform.
- Reaching the serving pool required repairing the pool options: they
were
derived at construction sites and discarded, so the server always built
its
pool with the defaults. They are now derived from the deployment
configuration
in one place and passed to the pool that serves requests. The server
reports
those options, and its ownership of the `key_pool_state` collector, so a
second
registration cannot silently reappear and panic startup.
- The standalone gateway inherits both structured logging options, since
it is
now one of the processes that can emit.
This is the keystone of the stack: the flag, the mechanism that carries
it and
the behavior it selects land together, so
`TestAIGatewayStart_InheritedOptions`
and the gateway help output stay truthful at every commit.
<details>
<summary>Why the stack is ordered this way</summary>
The final design is a chain of recorder decorators:
+---------------------+
| AsyncRecorder | all records except the interception start
+---------------------+
| LogRecorder | emit the structured record
+---------------------+
| ValidatingRecorder | refuse malformed records
+---------------------+
| caller middleware | record policy, e.g. drop content
+---------------------+
| TraceRecorder |
+---------------------+
| DRPCRecorder | acquire client, send to coderd
+---------------------+
Ordering constraints:
- The record type constants (1) are the vocabulary both emitters and the
validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
doing nothing but client acquisition, which is why it is folded into
`DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
arrives, rather than as an unused hook beforehand.
</details>
---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
|
||
|
|
faa9815cd6 |
feat: configure Claude Platform for AWS on Anthropic providers (#29049)
This PR adds configuration plumbing for Claude Platform on AWS ## Summary Makes Claude Platform for AWS configurable as a settings variant of `type=anthropic`, discriminated by `_type: "claude_platform_aws"`. Settings contain only `region` and `workspace_id`, plus the schema version. No new provider type or database enum is introduced. The API persists and projects those settings to the gateway. Provider keys can be added or removed independently: allowed BYOK takes precedence, followed by stored keys, then ambient SigV4 when neither key source applies. Model-availability hints and keyless provider construction reflect that ambient capability. Rejected or exhausted keys do not fall back to IAM. Removes Claude Platform-specific AWS identity fields, secret redaction/merge behavior, external-ID handling, and mode/key consistency checks. Bedrock configuration remains intact. Environment-based provider seeding was removed upstream and is not restored. The Claude Platform form and Experimental label remain follow-up work in #29050. ## Authentication limitation Each Claude Platform provider uses either the gateway's ambient AWS credentials when no provider keys are stored, or its stored API-key pool. In either case, a client credential takes precedence when BYOK is enabled. Rejected BYOK or an exhausted provider key pool does not fall back to ambient IAM. There is no per-provider AWS identity selection: keyless providers on the same gateway share its ambient AWS credential chain and cannot configure separate AWS access keys or assumed roles. Each provider still has its own Claude Platform workspace ID and separate provider attribution in Coder's usage/cost records; this does not imply separate AWS billing accounts. ## Validation - Race tests passed for SDK, daemon projection, db2sdk, chatprovider, and targeted CLI/API configuration tests. - Installed pre-commit hook passed, including generation, frontend/Go lint, and build. - Tests cover settings round trips, validation, adding/removing the last key without settings changes, keyless construction, model availability, and Bedrock regressions. Generated by Coder Agents on behalf of @johnstcn and @Shelnutt2 Co-authored-by: Cian Johnston <cian@coder.com> |
||
|
|
10a22c8302 |
feat: support Claude Platform for AWS on the Anthropic provider (#29048)
## Summary Adds Claude Platform for AWS as a variant of the Anthropic provider, preserving the native Messages protocol and model IDs. Builds on the merged SigV4 extraction in #29047. Configuration and UI follow in #29049 and #29050. A provider-owned transport handles both bridged and passthrough requests, sets the configured workspace header, and re-signs SDK retries. Credential precedence is allowed BYOK, then the stored key pool, then ambient AWS SigV4 when neither key source applies. Rejected keys or an exhausted pool do not fall back to IAM. AWS configuration loads lazily, so key-authenticated requests do not require working AWS credentials. There are no explicit authentication-mode, static AWS credential, Role ARN, or external-ID fields for Claude Platform. Bedrock behavior and PRM attribution remain separate. Anonymous Anthropic Messages support is out of scope. ## Validation - Full offline `go test -race ./aibridge/...` passed on this PR tip. - Installed pre-commit hook passed, including generation, lint, and build. - Tests cover workspace-header signing, retries, key precedence/failover, lazy credential recovery/cache, cancellation, and stream lifetime. - `TestClaudePlatformLive` sends a small real request through the bridge when explicitly enabled. It was not run against AWS. Co-authored-by: Cian Johnston <cian@coder.com> |
||
|
|
dffa890d8f |
ci: add macOS runner telemetry and a stall detector to test-go-pg (#30050)
Add telemetry to diagnose intermittent macOS `test-go-pg` stalls and preserve timeout diagnostics. - Log runner details at startup; sample load, swap, and `vm_stat` every second and `top` every 10 seconds to identify runner-wide pauses. - Add stall detection to `cli` and `agent` `TestMain`, logging heap, GC, and goroutine counts when ticks arrive more than 5 seconds late. - Run artifact uploads with `always() && !success()` so canceled test steps do not skip diagnostics. - Add a `TEST_TIMEOUT` override: use 20m on macOS to leave room for goroutine dumps within the 30m job, retaining the 25m default for the nightly gauntlet. Validated with race tests, binary compilation, `actionlint`, local macOS checks, and Makefile timeout checks. |
||
|
|
797dc6b2d1 |
feat: refresh header commands based on JWT expiration (#29760)
Adds opportunistic JWT parsing for values returned from the `--header-command`. If a JWT is parsed we use the value of its `exp` field to determine when we should re-run the command to refresh the values. |
||
|
|
f5092aaa4a |
feat: make chat limits configurable deployment options (#28927)
Adds deployment options for the chat limits that shape turn behavior and API acceptance, replacing hardcoded constants in `coderd/x/chatd` and the chat API. Defaults are unchanged. | Option | Default | Limit | |---|---|---| | `CODER_CHAT_MAX_STEPS_PER_TURN` | 1200 | steps (model responses) in a chat turn | | `CODER_CHAT_MAX_GENERATION_RETRIES` | 25 | consecutive retries after a model generation fails with a transient error | | `CODER_CHAT_MAX_QUEUED_MESSAGES_PER_CHAT` | 20 | messages that can be queued in a chat | | `CODER_CHAT_MAX_ATTACHMENTS_PER_CHAT` | 50 | files linked to a chat; linking more deletes the earliest uploads | | `CODER_CHAT_MAX_PROMPT_BYTES` | 131072 | system prompt, plan mode instructions, and each user's custom prompt | | `CODER_CHAT_MAX_CONCURRENT_RECORDING_UPLOADS` | 25 | desktop recordings each server stores at the same time | `codersdk.DefaultChat*` constants remain the single source of truth. Values below 1 fail startup validation, and each option's description ends with "Must be at least 1." `chatd.New` fills any zero field in `chatd.Config.Limits` with its default once, `LimitsFromConfig` is a plain conversion, and the code that receives a limit as a parameter (the `chatstate` queue and file link checks, the turn step check, `chatretry.Retry`, and `chatadvisor.NewRuntime`) returns an error for a limit below 1 instead of choosing a default or disabling the limit. The options are documented in the generated configuration reference and in the platform controls docs. `CODER_CHAT_MAX_GENERATION_RETRIES` counts consecutive retries, and the count resets after each successful step. The default allows 25 retries (26 attempts) where the old constants allowed 24. The same limit now applies to each nested advisor model call and to background title, summary, and turn status label generation, which previously used fixed `chatretry` budgets. Chat creation and tool result bodies keep the fixed 256 KiB limit from main. The prompt-saving endpoints accept bodies up to twice the prompt limit, for JSON escaping and characters that sanitization removes, but never less than 256 KiB, so small prompt limits still return the 400 length error. At the default this equals the 256 KiB limit on main. Four settings from earlier revisions were removed, and the fixed limits from main are back: - `CODER_CHAT_MAX_TOOL_OUTPUT_BYTES`: the agent already keeps a 16 KiB head and a 16 KiB tail of command output, so raising it had no effect and lowering it cut the tail. - `CODER_CHAT_MAX_DYNAMIC_TOOLS_PER_CHAT`: tool definitions share the 256 KiB chat creation body limit, so raising the count did little. - `CODER_CHAT_DEBUG_MAX_BODY_BYTES`: one setting covered two unrelated debug caps. - `CODER_CHAT_DEBUG_MAX_TEXT_RUNES`: the name did not say what it applied to. Root and subagent concurrency caps stay fixed because they are licensing behavior, and `MaxChatFileSizeBytes` stays fixed because the web UI hardcodes the generated constant for client-side checks. `codersdk.MaxChatFileIDs` is removed; the web UI's "Attachment expired" tooltip no longer quotes the number because the cap is now per deployment, and it says that attaching a file beyond the limit permanently deletes the chat's earliest-uploaded attachments. ## Review record | Round | Reviewed head | Result | Disposition | |---|---|---|---| | Codex 1 and 2 (Sep 2 to 3) | `7f10a1572f8`, `8ee09f8fa3b`, `197bb78d5b` | 10 findings, then OK on `197bb78d5b` | all threads resolved | | Codex 3 (Sep 17) | `e4efac249a5` (pre-rebase) | 4 findings | advisor retry limit confirmed and fixed in `9e462b7b3d0` (rebased from `67341e458e8`); ARCHITECTURE.md TODOs added; JSON-escaping body sizing and streamed-argument rune cap declined as pre-existing design (evidence in threads) | | Codex 4 (Sep 18) | `9e462b7b3d0` | 6 findings | recording evicted at attachment cap 1 confirmed and fixed in `5b61895decb`; `Limits` field docs and zero-value fallback documented; prompt retro-enforcement, generated multi-sentence lines, and tool-output truncation metadata declined as pre-existing design (evidence in threads) | | Codex 5 (Sep 18) | `5b61895decb` | 1 finding | over-cap batch of already-linked files accepted after lowering the cap: confirmed and fixed in `f44063e74e5` | | mafredri (Sep 23) | `f44063e74e5` | 24 threads, changes requested | all fixed in `05e3e3d622a`, `c1f78e09e8b`, `709ddb67977`, `d0587a49829`, `ca4347b24de`, and `1f6c9e2a46f`, then answered and resolved; the ARCHITECTURE.md text was written at the author's direction and approved by the author | | Sibling sweep (Sep 24) | `1f6c9e2a46f` | author-requested audit of all 24 mafredri threads for sibling issues, plus a test refactor | fixed in `37eaf07d34d` through `1f14ac041b7`: the advisor retry limit, `chatretry.Retry`, and the turn step check reject values below 1 instead of disabling retries or the limit; limit tests run against both the default and configured values set through `chatd.Config` or `DeploymentValues`; the expired-attachment tooltip is concrete. A required coder-frontend-review run (8 roles in one agent, CD re-run once) found a stale story comment, removed. | | Codex 6 (Sep 27) | `a71383e3a31` | OK, no findings | requested after the rebase at the author's direction, past the six-pass review budget | The branch was rebased onto main `4851c7b60c8` on Sep 27; the previous head was `91b84000adb`, and the earlier SHAs in the review record predate the rebase. Conflicts in the `chatstate` transitions and `CreateChat` keep both main's `InitialStatus` and this PR's `MaxFileLinks`, and main's rewrite of `advisor_internal_test.go` in #28754 keeps main's version plus this PR's limit tests. Two tests added on main needed the new retry arguments: `TestGenerateStructuredTitleWithUsage_FallsBackToTextWhenToolChoiceRejected` and `TestAdvisorRunStreamsReasoningDeltasSeparatelyFromAdvice`. Validation on `a71383e3a31`: the pre-commit hook (generation, golangci-lint, build), the full `coderd/x/chatd/...` suite (20 packages), the chat tests in `codersdk`, `coderd`, and `enterprise/coderd`, the CLI help tests, race-detector runs of the `chatd`, `chatstate`, `chatadvisor`, and `chatretry` packages, and `go build` plus `go vet` on each of the 27 commits. No remote UAT was run. > Xum acted on behalf of @ibetitsmike for this pull request. |
||
|
|
6826da9397 |
feat: restore agents-access as a default organization role (#30004)
Restores `agents-access` (**Coder Agents User**) as a built-in organization role and adds it to every organization's `default_org_member_roles`. Members keep Coder Agents by default, and admins can now restrict it per organization by removing the role from the defaults and granting it through IdP role sync or direct assignment. Since #28186, chat permissions lived in the organization-member floor, so the only way to limit Coder Agents was narrowing per-model access lists, which did not hide the feature. - Migration 000602 appends `agents-access` to every organization's defaults, so upgrading keeps every member's access. New organizations get it from `rbac.DefaultOrgMemberRoles()`. - Service accounts do not inherit the role from the defaults (`GetAuthorizationUserRoles`), so they still need an explicit grant for chat. - Owners and Organization Admins keep chat access regardless of defaults. Chats shared with a user stay readable without the role. - Role sync is unchanged. It does not store default roles, so after the default is removed a mapped user gets `agents-access` at their next sign-in. - The retired-role mechanism (`IsRetiredRoleName`) is removed. - `PATCH /api/v2/organizations/{organization}` rejects duplicate `default_org_member_roles` entries (the CLI already de-duplicated them). - Custom organization role requests treat built-in role names case-insensitively, since custom role names are stored lowercase and `Agents-Access` would otherwise become an undeletable shadow of the built-in role. - The Agents permission alert tells restricted members their chats are kept, and the model selector for users without chat permission no longer claims that no models are configured. Docs add "Control who can use Coder Agents" to the Agents getting-started guide. **NOTE**: Migration 000602 deletes custom roles named `agents-access`, which the built-in role would shadow. The down migration does not restore them. Stored member grants of `agents-access` from the earlier built-in role or a deleted custom role stay and now grant chat access. ## Validation - Remote dogfood [UAT](https://dogfood.cdr.dev/agents/e1c18dc6-f6f0-49a1-b6cd-6ce014b51a86) passed on |
||
|
|
f64ccfb836 |
feat: add experimental inline MCP servers (#29546)
Closes CODAGT-1131 Fifth PR in the inline MCP servers stack, on top of #29520. A chat owner can now declare MCP servers by URL and headers on their own chat, and chatd connects to them every turn alongside the org-configured ones. They go in a new `inline_mcp_servers` field on `POST /api/v2/chats` and `POST /api/v2/chats/{chat}/messages`, which replaces the whole set (omit to keep, `[]` to remove). Root chats only. `GET /api/v2/chats/{chat}` returns them, with the URL blanked for non-owners and header values never returned. Subagents only get servers marked `allow_in_subagents`, a root chat in explore mode gets none, and a root chat in plan mode gets all of them. URLs must be `https`, or `http` to an IP literal in `CODER_MCP_ALLOWED_PRIVATE_CIDRS`. Header values have no minimum length, so anything under the redactor's 8 byte floor from #29518 is accepted but not redacted, which the docs call out. Every cap is exported from `codersdk`. It's behind the `chat-inline-mcp-servers` experiment, and the `--disable-chat-caller-supplied-tools` kill switch from #29466 covers it too. With either off, declaring servers gets a 403 and existing chats stop connecting to theirs, but `[]` still works so a client can detach. Load failures show up in the chat debug panel as failed connections, as do org servers with an invalid config. Docs are hand-written in `mcp-servers.md`. |
||
|
|
c1af0793e5 |
feat: add caller-supplied tools kill switch for chats (#29466)
This is the first PR in a stack that adds experimental support for attaching MCP servers to a chat when it's created, and then deprecates `unsafe_dynamic_tools` in favour of them. Both are "caller-supplied tools", i.e. tools the client hands to coderd at chat creation rather than tools an admin has configured, so we want a single switch admins can use to turn all of them off. This PR adds that switch: `--disable-chat-caller-supplied-tools` (`CODER_DISABLE_CHAT_CALLER_SUPPLIED_TOOLS`). It follows the existing `disable-*` deployment flag pattern (`--disable-chat-sharing` etc.), so there's no new API route and it's independent of any experiment. When set, `POST /api/v2/chats` returns a `403` if the request includes `unsafe_dynamic_tools`, and chats that already have dynamic tools run without them; a call to one gets a tool error result and the model just continues. Later in the stack, chat-attached MCP servers are gated behind the same flag. It's unset by default, so nothing changes unless you opt in. Part of CODAGT-1131 |
||
|
|
99a3425333 |
fix: advertise install.sh with curl -fsSL everywhere (#29801)
## Summary The install one-liner is advertised as `curl -L` in most docs pages, the README, and the CLI's default version-mismatch hint, while `install.sh` itself and the deployment-local hint use `curl -fsSL`. Without `-f`, curl writes an HTTP error body to stdout, and the one-liner pipes that error page into `sh`. This PR standardizes every `install.sh` invocation on `-fsSL` so a failed download fails closed. ## Changes - Docs: `install/cli.md`, `install/operate/upgrade.md` (twice), `get-started/index.md`, `start/local-deploy.md`, `install/operate/provisioners/index.md`, `admin/templates/managing-templates/change-management.md` (twice), `user-guides/workspace-access/zed.md`, and `README.md`. - CLI: `defaultUpgradeMessage` in `cli/root.go` now prints `curl -fsSL`, matching the deployment-local branch in the same function. - `codersdk/deployment.go`: the `--cli-upgrade-message` description now says `curl -fsSL`; the server help goldens, `server-config.yaml.golden`, `docs/reference/cli/server.md`, and `docs/admin/setup/configuration-reference.md` are regenerated to match. - `install.sh`: the "To run" header comment now matches the script's own usage text. - Style guide: a new "Commands that pipe a download into a shell" rule in `docs/.style/style-guide/formatting.md`, and the tabs example uses `-fsSL`. The coder.com download page already builds its command from `-fsSL` in coder/coder.com#1093, and coder.com `main` has no other `install.sh` one-liners outside test fixtures, so no coder.com change is needed. DatoCMS content and a release verification page are not in this PR. `main` since moved the upgrade and provisioner pages under `docs/install/operate/` and removed the install one-liner from `docs/install/index.md` in #29304, so that page no longer appears in this diff. ## Testing - `TZ=UTC go test ./cli -run='Test(CommandHelp|ServerYAML|ErrorExamples|.*Golden)' -update` and `go test ./enterprise/cli -run=TestEnterpriseCommandHelp -update` pass and produce the committed golden diffs. - `go test ./cli -run 'Test.*Version|TestWrapTransport'` passes, including `Test_wrapTransportWithVersionCheck`. - `go run ./scripts/configdocgen` output contains the new `curl -fsSL` description. - `markdownlint-cli2` on the edited style guide page reports 0 errors. - `git grep` finds no remaining `curl -L …install.sh` outside the style guide's **Don't** example. - After merging `main`: `make pre-commit` passes, and `make test`, `make test-js`, and `make site/out/index.html` pass. Linear: https://linear.app/codercom/issue/DOCS-964/standardize-installsh-curl-flags-on-fssl-across-docs-codercom-and-the --- 🤖 Built with AI assistance. |
||
|
|
442b08fee5 |
docs: drop duplicated 'the the' in scaletest flag help and OIDC docs (#29107)
Two doubled-word typos: - `cli/exp_scaletest.go`: the `--connect-url` flag description shown by `coder exp scaletest --help` read "inside **the the** workspace over WireGuard" - `docs/admin/users/oidc-auth/index.md`: "as **the the** username" Docs/help text only. |
||
|
|
9c0c3948c9 |
feat: narrow ssh and bash tool client.Workspace calls with include_related (#29542)
Part of the lite `codersdk.Workspace` work ([GRU-82](https://linear.app/codercom/issue/GRU-82), [RFC](https://app.notion.com/p/coderhq/Lite-Workspace-API-Requests-3aad579be5928060b5e7cc65c539717f)). Stacked on #29541. Narrows the two production `client.Workspace` (get-by-ID) call sites that read only a subset of the returned workspace. - **`cli/ssh.go`** (`notifyCondition`) reads `TTLMillis` and `LatestBuild.Deadline`. `TTLMillis` is computed server-side from the template (`AllowUserAutostop`/`DefaultTTL`), so this requests `template` and `latest_build` (the deadline is on the build itself; no job, resources, or template version needed). - **`codersdk/toolsdk/bash.go`** (`findWorkspaceAndAgent`) refetches after autostart only to locate the first agent, so it requests `latest_build.resources.agents`. Callers read only the agent plus the top-level `Name`/`OwnerName`. The other production by-ID callers were left on the default (full) selection because they need the whole object: `support/support.go` serializes the workspace into the support bundle, `codersdk/toolsdk/chatgpt.go` JSON-marshals it for the model, and `codersdk.ResolveWorkspace` is a generic resolver whose callers expect everything. CLI paths that use `WorkspaceByOwnerAndName` are not touched because that endpoint does not parse `include_related` yet. ### Testing - `TestWorkspaceBash` and `TestWorkspaceBashTimeout` pass; the autostart-refresh branch has no dedicated test, so its selection was verified by tracing the fields read from the returned workspace and agent. - `cli` and `codersdk/toolsdk` build/vet/lint clean; the SSH deadline notifier has no dedicated test, so its selection was verified the same way (and by confirming the server derives `TTLMillis` from the template). --- *Generated by Coder Agents on behalf of @spikecurtis.* |
||
|
|
0c98308ca9 | feat: default the CLI workspace search to the user filter (#29753) | ||
|
|
83bef8a12d | fix: consolidate pg and nats pubsub metrics generation into one (#26843) | ||
|
|
988520477e |
feat!: remove the experimental chat API mounts after the transition window (#29548)
Remove the `/api/experimental` duplicates of the promoted chat API. #28496 double-mounted the chat, organization chat and MCP server, member model-override, AI provider key, and MCP OAuth2 disconnect routes under both prefixes for the one-release compatibility window decided in CODAGT-921; that window closed with v2.37.0, so these routes now answer only on `/api/v2`. The change also deletes what existed only for the dual mount: the `chatAPIPrefix` plumbing, the shared cross-prefix files rate limiter (`RateLimitByAPICompatibilityEndpoint`), the 410 tombstones for the legacy `chats/providers` and `chats/user-provider-configs` collections with their `ExperimentalClient` SDK methods, and the `/providers` and `/user-provider-configs` 404 reservations on `/api/v2`. Signed chat file download URLs now point at `/api/v2`. Routes that were never promoted stay on `/api/experimental`: the experiment-gated `chats/config/advisor` and `chats/config/computer-use-provider`, `chats/{chat}/stream/desktop`, `chats/{chat}/debug/runs`, and the MCP OAuth2 callback, whose path is pinned as a registered redirect URI with external providers. The frontend already calls `/api/v2` for every promoted route, so only `typesGenerated.ts` changes. Because the experimental mount no longer reserves the removed collection segments, requests such as `GET /api/experimental/chats/models` now fall into the `{chat}` wildcard and return 400 instead of 404; the experimental prefix carries no stability guarantee and the compatibility window is over, so no new reservations were added. `coderd/x/chatd/ARCHITECTURE.md` now describes the single `/api/v2` mount and the remaining experimental routes, and its endpoint headings use the `/api/v2` paths. Closes CODAGT-922 (https://linear.app/codercom/issue/CODAGT-922/remove-experimental-chats-api-paths-after-transition-window). Refs #28496. ## Delivery record - Remote dogfood UAT (Coder Agents chat https://dogfood.cdr.dev/agents/c016b549-201a-4eca-a50f-3c0b7c339db6): verdict PASS on b008976a4dfba3524b220ca846ea3c3492e9cc9c. The branch was since rebased onto main (which had a duplicate migration 000596 until #29568) and gained one docs-only commit (`coderd/x/chatd/ARCHITECTURE.md` only); the current head |
||
|
|
9974294ca9 |
feat: report arbitrary workspace agent session types (#28338)
Report session counts as a dynamic app-name map from the agent, the SSH CLI, and the workspace usage API, so a new IDE flows end to end without a schema, proto, or server change. - Report through `Stats.session_counts` on Agent API v2.11. Older agents keep reporting through the deprecated count fields. - Accept arbitrary names from `coder ssh --usage-app` and the workspace usage API. A name the registry does not recognize keeps its identity and is attributed to the `unknown` family. - Add reconnecting PTY counts to the map without overwriting the counts SSH reported. - Normalize and merge names before applying the deterministic 64-name cap, ordered by known apps, then count, then name. Overflow sums into `unknown`, and non-positive counts cannot cancel valid activity. - Strip control characters, treat whitespace-only HTTP app names as absent, and require the exact environment variable prefix when you extract an SSH session type. - Count overflow entries in `coderd_agentstats_session_counts_overflow_total` and keep raw payloads out of logs. - Change the usage API's `app_name` to a string, and update the SDK types and API reference. closes #27410 |
||
|
|
057475c4e8 | feat: control notification scaletest load via template deletion count (#29151) | ||
|
|
8e159a8053 | chore: remove stale TODO shims and dead code (#29252) | ||
|
|
c47eb47393 |
feat: add stateless AI Gateway proxy mode (#29349)
Adds proxy mode to the AI Gateway. No AI provider is supported in this mode yet. |
||
|
|
aae145bdc9 |
feat: make NATS pubsub opt-out via no_nats_pubsub experiment (#29283)
Makes the embedded NATS pubsub an opt-out feature instead of opt-in. The `nats_pubsub` experiment is removed and replaced with a `no_nats_pubsub` experiment, so NATS pubsub is now the default and can be disabled to fall back to PostgreSQL pubsub. NATS clustering requires this replica's routable address, resolved into `clusterHost` from either `--cluster-host` (`CODER_CLUSTER_HOST`) or the DERP relay URL. When neither is set (allowed when DERP is disabled on the primary), NATS cannot form a cluster, so startup logs a big error and falls back to PostgreSQL pubsub. The NATS cluster CA is only minted/rotated when NATS clustering is actually active (experiment not set and a cluster host is present). <details> <summary>Implementation notes</summary> - `codersdk/deployment.go`: removed `ExperimentNATSPubsub` (`nats_pubsub`), added `ExperimentNoNATSPubsub` (`no_nats_pubsub`, display name "No NATS Pubsub"). - `cli/server.go`: NATS is used by default unless `no_nats_pubsub` is enabled; if `clusterHost` is empty, log an error and keep the PostgreSQL pubsub. - `coderd/coderd.go`: gate NATS CA minting/rotation on `!ExperimentNoNATSPubsub && ClusterHost != ""` (i.e. only when NATS clustering is active). - `enterprise/coderd/licenses.go`: updated a stale comment. - `enterprise/coderd/coderd_test.go`: `TestMultiReplica_NATSPubsubPeers` no longer sets the removed experiment. - Regenerated `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`, `docs/reference/api/schemas.md`, `site/src/api/typesGenerated.ts`. </details> --- *This PR was generated by Coder Agents on behalf of @spikecurtis.* |
||
|
|
77479408b4 |
feat: make the Coder Agents stream silence timeout configurable (#29394)
The `chatloop` stream silence guard cancels and retries a model attempt after `10m` of silence, and it was hard-coded. It's armed before the request opens, so it also bounds time to first token, and slow local models (e.g. `llama-server` on a large prompt) can spend longer than that on prompt processing alone, meaning every attempt just gets cancelled and retried. This PR adds `--chat-stream-silence-timeout` / `CODER_CHAT_STREAM_SILENCE_TIMEOUT` (default `10m`) and passes it to both the main loop and the advisor. Setting it to `0` disables the guard entirely, and anything above `24h` is rejected, which also keeps the watchdog arithmetic below from overflowing. Whilst doing this I ran into the runner's `15m` task watchdog, which kept counting during an open stream. That silently cancelled any healthy stream longer than `15m`, and would've stopped a silence timeout above `15m` from ever firing. To fix, the silence guard now kicks the watchdog out to `max(15m, silence + 5m)` whenever it arms or sees a part. Silent streams still fail through the guard, healthy streams can run for as long as they like, and hang detection is unchanged everywhere else. With the guard disabled there's nothing to kick against, so arming it just stops the watchdog for the rest of the attempt. That does mean the DB write after the stream isn't bounded either when `0` is set; I think that's fine for an opt-in setting, and a user can still stop the chat from the UI if it wedges there. I did consider removing the guard entirely, but the provider HTTP clients have no timeout, so a provider that holds the connection open would only ever be caught as a generic task hang, which is what #25782 was fixing. |
||
|
|
a90ad83af3 |
feat!: add a hidden flag to disable dynamic parameter closure evaluation (#29356)
**What changed** Dynamic parameter rendering now evaluates only the coder parameter blocks and what they reference. Other root-module resources are skipped. Parameter, preset, and tag values are unchanged; optimizing rendering on large templates. **How to revert** Set `CODER_DYNAMIC_PARAMETERS_FULL_EVALUATION=true` (or `--dynamic-parameters-full-evaluation`) on `coder server` to restore full evaluation. The flag is hidden and needs no restart of workspaces. If you need it, please [open an issue](https://github.com/coder/coder/issues/new) with the template so we can fix the root cause. **Troubleshooting** Symptoms would be a parameter default, option list, preset value, or workspace tag that shows as unknown or empty after upgrading, when it was populated before. Confirm by setting the flag above; if the value comes back, report it. Templates written in `.tf.json` are not affected (they always use full evaluation). **Why** Rendering re-ran the entire template graph on every parameter change in the workspace form, which dominated latency on large templates. Resources a workspace would create cannot feed a parameter, so evaluating them is wasted work. The optimization lives in coder/preview#226 (coder/trivy#74); this PR adds the deployment-level escape hatch. --- - `CODER_DYNAMIC_PARAMETERS_FULL_EVALUATION` / `--dynamic-parameters-full-evaluation` (hidden, default `false`) on `DeploymentValues`. - `dynamicparameters.PreviewOptions(dv)` maps it to `preview.OptionFullEvaluation()`; `dynamicparameters.WithPreviewOptions` threads it through the loader to `preview.Preview`. - Wired at the three render paths that hold deployment values: the template version tags extractor, the dynamic parameters websocket, and `wsbuilder` builds created from `coderd` (which call `.DeploymentValues(...)`). Not covered: the autobuild lifecycle executor and the enterprise prebuilds reconciler construct `wsbuilder` without deployment values, so builds started from those paths use preview's default regardless of the flag. Those only re-render for builds, not the keystroke websocket path the optimization targets. Prepared with Coder Agents assistance. |
||
|
|
26e4429362 |
test: fold near-identical test bodies into tables across eight packages (#29463)
Folds groups of near-identical test bodies (same parent, same parallel flag, differing only in inputs and expected values) into table-driven tests in eight packages: `coderd/templatebuilder`, `scripts/develop`, `agent/agentfiles`, `coderd/x/chatd/chatloop`, `coderd/x/chatd/chatdebug`, `enterprise/aibridgeproxyd`, `cli`, and `coderd/database/db2sdk`. One commit per package. Every case keeps its previous subtest name, `t.Parallel()` placement is unchanged, and the set of `=== RUN` names is identical except where standalone `TestX_Y` funcs became `TestX/Y` subtests (chatloop: 9 funcs into `TestExecuteLocalTools_BatchRuntime`; chatdebug: 15 funcs into two tables). Members whose bodies differ in more than data stayed as they were (listed per package in the commit messages). In `agent/agentfiles` the four `TestFuzzyReplace_*` funcs were already tables, so the shared request plumbing was hoisted into one helper instead of merging the funcs and losing their per-rule docs. Net -1035 lines across 9 test files; runtime is unchanged (all sub-100ms unit tests). | Package | Diff | Funcs removed | Subtests | RUN lines | |---|---|---|---|---| | coderd/templatebuilder | +237 / -291 | 0 | 31 -> 31 | 33 -> 33 | | scripts/develop | +194 / -246 | 0 | 27 -> 27 | 28 -> 28 | | agent/agentfiles | +117 / -260 | 0 | unchanged | 58 -> 58 | | coderd/x/chatd/chatloop | +224 / -306 | 9 | 3 -> 12 | 14 -> 15 | | coderd/x/chatd/chatdebug | +251 / -537 | 13 | 0 -> 15 | 42 -> 44 | | enterprise/aibridgeproxyd | +287 / -419 | 0 | 31 -> 31 | 32 -> 32 | | cli | +143 / -326 | 0 | 15 -> 15 | 16 -> 16 | | coderd/database/db2sdk | +130 / -233 | 0 | 9 -> 9 | 10 -> 10 | ## Validation - Per package: `go test -count=1 -tags=testsmallbatch -parallel=8 ./<pkg>/ -run <regex> -v` before and after, with the `=== RUN` name sets diffed - `go test -race -count=2 -shuffle=on` on each converted test: pass - `golangci-lint run ./<pkg>/...` with a fresh cache: 0 issues in all eight packages - Repository pre-commit hook (including lint/go) passed on every commit Part of the test-suite speedup series (see #29457); independent of the other PRs. ## Remote validation Remote run on a dogfood workspace (separate compute), chat https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44, tested head `d7c55d6b0e8` against base `9d973372774`: all eight packages pass on the head and under `-race -count=3 -shuffle=on`; package times are sub-second on both sides (unchanged). `=== RUN` name sets: chatloop 15 to 16 lines with all nine `TestExecuteLocalTools_<X>` leaves surviving as `TestExecuteLocalTools_BatchRuntime/<X>`; chatdebug 42 to 44; `aibridgeproxyd` `TestNew` 32 to 32, byte-identical sorted list. One correction to the text above: seven chatdebug leaves are renamed, not preserved verbatim (`TestRecordingTransport_*UnknownLength*` became `TestRecordingTransport_UnknownLengthClose/<name without "UnknownLength">`), so `-run` filters keyed on those old names need updating. Endorsed verdict: PASS. > Xum (an AI agent) authored this PR on behalf of @ibetitsmike. |
||
|
|
d2e94e299a | chore: delete dead functions and skip-only or duplicated tests (#29461) | ||
|
|
6694db0d39 | test(cli): stabilize TestSSH_OneShotCommandMode flake (#29142) | ||
|
|
7bb049f24c |
feat: log the OAuth2 provider state and registered apps at startup (#29267)
PLAT-492: Log OAuth2 provider state at startup Log whether the OAuth2 provider is enabled and name CODER_OAUTH2_PROVIDER_ENABLE. When disabled, warn if OAuth2 applications are still registered and tell admins how to re-enable the provider. Startup continues if the application lookup fails. Add tests for enabled, disabled, registered-app, and query-error cases. Manually verified upgrade behavior, route gating, token preservation, dashboard visibility, and all supported flag forms. |
||
|
|
4ee70c66c3 |
feat: gate the OAuth2 provider on CODER_OAUTH2_PROVIDER_ENABLE (#29251)
Second of five for PLAT-492. Gates all OAuth2 provider routes and dashboard navigation on CODER_OAUTH2_PROVIDER_ENABLE instead of the oauth2 experiment. The flag is off by default, so deployments using CODER_EXPERIMENTS=oauth2 must set it before upgrading or OAuth2 clients will receive 404s. Existing apps, tokens, secrets, and DCR settings are unchanged. Stacked on #29248 and labeled release/breaking; the next PR makes the old experiment a no-op with a migration warning. |
||
|
|
1cc73bc43f |
feat: add the CODER_OAUTH2_PROVIDER_ENABLE deployment flag (#29248)
First of five PRs for PLAT-492, adding the opt-in CODER_OAUTH2_PROVIDER_ENABLE flag for the OAuth 2.1 provider. It defaults to false and is not enforced yet, so there is no behavior change. Adds the CLI/env/YAML flag and exposes oauth2_provider in build info. Enables it by default in tests to prepare for route gating. Updates tests, golden files, and frontend fixtures. Follow-ups will gate routes/UI, retire the experiment, add startup logging, and update docs. |
||
|
|
1f610fa20d |
chore: apply some missed code review nits from 29256 (#29289)
Addresses follow-ups from #29256 |
||
|
|
2cf819bfca |
feat: add break-glass user email update (#29256)
Adds an owner-only experimental API and hidden CLI command for break-glass user email corrections. The operation verifies the existing email, updates it transactionally, clears outstanding password-reset state, revokes the target user's Coder sessions and API tokens, and records successful and failed authenticated attempts in the audit log. External-auth links remain unchanged. Generated by Coder Agents. |
||
|
|
940f988cfb |
feat: add deployment-level option to disable Terraform module caching (#29187)
<!-- Generated by Coder Agents on behalf of @Emyrk. --> <img width="762" height="239" alt="Screenshot From 2026-09-11 17-09-41" src="https://github.com/user-attachments/assets/9f31fd1e-4cb2-47ab-8d37-4073df9f0a7c" /> Closes #22834. Adds `CODER_PROVISIONER_DISABLE_MODULE_CACHE` so an admin can disable Terraform module caching for every template at once instead of toggling ~100 templates by hand. - The deployment setting wins. Templates cannot opt back in, and the per-template toggle becomes read-only while the deployment setting is on. - Modules stay cached at template import, so dynamic parameter rendering still resolves module-defined parameters. Only the workspace build is denied the cached files. - Templates report `module_cache_disabled_by_deployment`, and template settings shows why the checkbox is locked. <details><summary>Agent context</summary> Decisions taken with @Emyrk before implementing: 1. **Precedence.** `deployment || template`, no per-template override, so no migration and no nullable column. The rule lives in one place, `codersdk.ModuleCacheDisabled`. 2. **Import-time caching untouched.** `dynamicparameters/render.go` overlays `cached_module_files` at `.terraform/modules` to render module-defined parameters. Skipping the cache there would reproduce the `Module not loaded. Did you run terraform init?` failure reported by a customer, so the deployment setting only affects what `AcquireJob` hands the provisioner. 3. **Write path.** A PATCH carrying `disable_module_cache` is discarded while the deployment setting is on, rather than persisted. Persisting it would silently keep templates opted out after the deployment setting is removed. 4. **API shape.** `disable_module_cache` keeps its meaning (this template's stored value) and the new read-only `module_cache_disabled_by_deployment` reports the deployment state. Reading the effective value from `/deployment/config` was rejected because template admins may lack deployment-config read permission. 5. **Naming.** `CODER_PROVISIONER_DISABLE_MODULE_CACHE` over the issue's `CODER_DISABLE_TERRAFORM_MODULE_CACHE`, to match the provisioning option group. Note: `InsertTemplateParams` has no `disable_module_cache` binding, so new templates always store `false`. With deployment precedence they still behave as opted out, so the create path needed no change. Out of scope and tracked elsewhere: the `coderd_template` Terraform provider attribute (separate repo) and backporting the per-template toggle to `release/2.30`. </details> --- <sub>Coder Agents on behalf of @Emyrk.</sub> |
||
|
|
b405d57638 |
feat: resolve bedrock inference profiles when a provider is written (#29112)
Follow-up to #28877, which resolved Bedrock application inference profile (AIP) ARNs while constructing a provider in the gateway. Review found two consequences of putting an AWS call on that path: a transient failure dropped the provider from the reloaded snapshot until the next provider change or restart, and the initial reload blocked `coder server` startup for up to 30s per AIP-configured provider under an uncancelable context. Resolution now happens once, in coderd, when a provider is created or updated. The result is stored with the provider and travels to the gateway in the existing provider payload, so the gateway makes no Bedrock control-plane call at startup, on reload, or on a request. The resolved identifiers live in the provider's encrypted settings blob as `resolved_model` and `resolved_small_fast_model`. A table keyed by ARN was tried and dropped: the server always writes the resolution as part of the same provider write, so it needs no separate lifecycle, migration, or clearing rules. Resolution runs before the write, so a failed lookup rejects the save and stores nothing. Create resolves its own request, which carries the complete configuration. Update cannot: a `PATCH` supplies the model identifiers but inherits credentials from the stored row, so stored + patch is merged before the transaction to resolve against, then merged again inside it against the row being written. Both merges take the model identifiers from the patch, so they cannot disagree, and no AWS call happens inside a database transaction. Reporting the failure at save time means an operator learns immediately that an ARN is wrong, deleted, or that the identity lacks `bedrock:GetInferenceProfile`, instead of discovering it later through a Bedrock 400 on adaptive-only models. Providers configured with plain model IDs store no resolution and make no AWS call, because those identifiers are already model identities. Resolution uses the provider's own credential configuration: static access keys when set, otherwise the AWS default credential chain, and the role from `role_arn` when configured. An AIP ARN embeds the account ID, so resolving under a different principal cannot return another account's profile; it can only fail with a permission error, which surfaces as a rejected write. Using an AIP ARN now requires coderd to reach `bedrock.{region}.amazonaws.com`. Deployments where only the gateway has AWS egress cannot configure AIP ARNs, and they find out when they save. <details> <summary>Implementation plan</summary> ## Goal Resolve Bedrock AIP ARNs once, when a provider is created or updated, and persist the result. The gateway reads the resolved model from the provider payload and makes no AWS call on the boot, reload, or request paths. ## Identity coderd resolves for every credential mode. An AIP ARN carries the account ID, so resolving under a different principal either succeeds with the same answer or fails with a permission error. The risk is a false negative, not a wrong answer. - **Static access keys, with or without `role_arn`.** The settings fully determine the identity, so coderd reaches the same principal the gateway will. - **AWS default credential chain.** coderd resolves under its own environment, which may legitimately lack `bedrock:GetInferenceProfile` even where the gateway has it. The save then reports an actionable message. ## Behavior at write time 1. Skip when neither `model` nor `small_fast_model` is an AIP ARN. This is the common case and costs nothing. 2. Otherwise resolve both identifiers with a short deadline, before the provider write. 3. On success, store the resolved identifiers in the same provider write and publish normally. 4. On failure, surface the AWS error and store nothing. The remedy is to fix the ARN, configure static access keys, or grant `bedrock:GetInferenceProfile`. 5. Re-resolve on every save. Bedrock has no `UpdateInferenceProfile`, so an ARN means one model forever, but re-resolving proves this provider's own identity can read the profile. ## Gateway `ResolvedModelWithFallback` and `ResolvedSmallFastModelWithFallback` return the stored resolution when present and the configured identifier otherwise. The fallback covers plain model IDs and providers saved before this change, degrading to pre-#28877 behavior rather than dropping the provider from the pool. ## Out of scope - Normalizing directly configured system inference profile ARNs. - Provisioned throughput and prompt router identifiers. - Any gateway-side resolution, including a lazy fallback. - Displaying the resolved model in the UI. </details> Relates to https://linear.app/codercom/issue/AIGOV-488 Created by Coder Agents on behalf of @evgeniy-scherbina. |
||
|
|
df1a910815 |
chore: remove AI task support from the provisioner protocol (#28790)
Removes AI task support from the provisioner protocol: the task-related proto fields, terraform scanning for `coder_ai_task` resources, echo provisioner support, the regenerated `.pb.go` and `provisionerGenerated.ts`, and the terraform testdata that exercised them. The provisioner API version change lives in `provisionerd/proto/version.go`. **Stack context:** Coder Tasks removal stack (CODAGT-642): #28743 frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084 notifications and usage → #29085 build reasons → #29086 tables → #28750 permissions. The last four PRs replace the single data-drop migration that used to live in #28750; each carries one concern and a focused migration test. **Why:** the proto fields lost their last consumer in #28789; this deletes the producer side and the wire format. **What to scrutinize:** the proto/version handling, and that `coder_ai_task` resources in existing templates are now ignored rather than errors (template imports simply no longer scan for them). **Validation:** `go build ./...`, `go test ./provisionersdk/... ./provisionerd/...`, `go test ./provisioner/terraform -run TestConvertResources`, provisioner list golden regenerated, site tsc, pre-commit hooks. **Size:** +580/-1,286 over 76 files; most files are mechanical testdata and generated-code updates. > Created by Xum (AI agent) on behalf of @ibetitsmike. |
||
|
|
9cd38b5373 |
feat!: remove the Tasks API from coderd and codersdk (#28789)
Removes the Tasks API and task orchestration from coderd and codersdk: the `/api/v2/tasks` handlers, task middleware and search filters, task name generation, autobuild pause/resume logic, task notification enqueues, telemetry, and the codersdk task types. Regenerates apidoc, the API reference docs, and `typesGenerated.ts`. **Breaking change:** the Tasks API is removed; requests to `/api/v2/tasks` fail. Tasks was deprecated in v2.34. **Stack context:** Coder Tasks removal stack (CODAGT-642): #28743 frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084 notifications → #29085 build reasons → #29086 tables → #28750 permissions. The last four PRs replace the single data-drop migration that used to live in #28750; each carries one concern and its own migration number. **Why:** with the UI (#28743) and CLI (#28788) gone, this deletes the server surface. Database tables, RBAC, and notification templates stay until the top of the stack so every layer builds and migrates independently. **What to scrutinize:** - The `enable-ai-tasks` option is removed outright (review feedback): configs still carrying `enableAITasks` fail to parse until the key is deleted. - provisionerdserver now writes `HasAITask: false` on template/build flags; the column and these lines are dropped in #29085. - `codersdk.ResourceTypeTask` stays so audit logs recorded before the removal keep rendering. **Validation:** `go build ./...`, `go vet ./...`, `go test ./codersdk/...`, site biome and tsc, CLI goldens regenerated, pre-commit hooks. **Size:** +242/-10,792 over 76 files; additions are regenerated docs/goldens and test fixture updates. > Created by Xum (AI agent) on behalf of @ibetitsmike. |
||
|
|
d0de33cdf1 |
chore: remove the Coder Tasks CLI and task automation (#28788)
Removes every in-repo Tasks client: the `coder exp tasks` CLI command family, the tasks scaletest runner, and the task-driven triage automation (`traiage.yaml`, `code-review.yaml`, `classify-issue-severity.yml`, `scripts/traiage.sh`). Triage runs through `triage-via-chat-api.yaml` and coder/create-agent-chat-action instead. **Stack context:** Coder Tasks removal stack (CODAGT-642): #28743 frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084 notifications and usage → #29085 build reasons → #29086 tables → #28750 permissions. The last four PRs replace the single data-drop migration that used to live in #28750; each carries one concern and a focused migration test. **Why:** clients come off before the API they call. After this layer nothing in the repo invokes the Tasks API outside coderd itself. **What to scrutinize:** all but three files are whole-file deletions. `triage-via-chat-api.yaml` gets a comment fix. `NavbarView.tsx` and its stories carry two small repairs to the frontend layer below (unused `user` prop, stale `TasksFilter` story wiring) so the stack lints clean from this layer up; they rebase away if folded into #28743. **Validation:** `go build ./...`, `go test ./cli -run TestCommandHelp`, site tsc, pre-commit hooks (gen, fmt, lint). **Size:** +4/-6,938 over 42 files; effectively pure deletion, so it reads much faster than the line count suggests. > Created by Xum (AI agent) on behalf of @ibetitsmike. |
||
|
|
74d1eef834 |
feat: support non-Anthropic models on Bedrock Mantle (#28404)
Migrates bedrock-typed provider construction to the standalone Bedrock provider introduced by #28420, then removes the legacy Bedrock behavior from the Anthropic provider. Existing provider and integration tests are updated to use the new type; legacy environment configuration preserves the `anthropic` route name while reporting provider type `bedrock`. Adds chatd model-ID inference for Bedrock providers: `anthropic.*` models keep the Anthropic Messages client, while other models use the OpenAI Responses client. BYOK header format follows the inferred wire shape. A credential-gated live integration test discovers the Mantle catalog from `/v1/models` and probes every model through the bridge. The `openai.gpt-oss-*`, `google.gemma-4-*`, and `xai.grok-*` families are documented as currently unsupported because Mantle serves them only on routes the prefix-based rules cannot reach. Depends on #28420. ## Smoke tests Validated against a local `develop.sh` server on August 22, 2026: - Coder Agents passed with Anthropic over InvokeModel, and Anthropic, OpenAI, and Mistral models over Mantle. - Claude Code passed the InvokeModel and Mantle Anthropic flows. - Crush passed all four flows, including Mantle OpenAI and third-party Chat Completions. Models tested: `us.anthropic.claude-sonnet-4-6`, `anthropic.claude-sonnet-5`, `openai.gpt-5.6-luna`, and `mistral.ministral-3-14b-instruct`. > Generated by Coder Agents |
||
|
|
65d01ef9b7 | fix: error on CLI HTTP redirects instead of following them (#29104) | ||
|
|
8472a6884f |
chore!: remove env-based AI provider configuration (#29053)
> AI tools were used to create this PR Removes deprecated AI provider configuration through environment variables, CLI flags, and YAML. Deletion includes indexed providers and legacy OpenAI, Anthropic, and Bedrock options under both AI Gateway and AI Bridge branding, eg. `CODER_AI_GATEWAY_PROVIDER_<N>_*` or `CODER_AI_GATEWAY_ANTHROPIC_KEY`. Removes the associated startup-seeding code. Updates tests and documentation. **Breaking change:** Remove [obsolete AI provider CLI flags and YAML keys](https://coder.com/docs/ai-coder/ai-gateway/providers#database-management-of-providers) before upgrading, otherwise Coder will fail to start with an `unknown flag` or `unknown option` error. Provider environment variables are ignored and no longer seed the database. Existing database-stored provider configuration is preserved. |
||
|
|
df4a7644fd | feat: import template metadata from README frontmatter on push (#28465) | ||
|
|
150c680a4b |
fix: return MCP server tool execution errors as tool results (#29051)
Coder's MCP server currently sends most tool execution failures as
top-level JSON-RPC errors. The underlying error text is transmitted like
this:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "workspace name cannot be empty"
}
}
```
Not all clients handle it well, and some may return a generic "MCP tool
request failed." to the model instead of passing the details as tool
output.
This PR starts returning execution failures as tool results with
`isError: true` and descriptive content like this:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"isError": true,
"content": [
{
"type": "text",
"text": "workspace name cannot be empty"
}
]
}
}
```
This should make the MCP server work better across a broader range of
MCP clients.
|
||
|
|
dc1faecbf8 |
test: bind more server tests to loopback (#29042)
Follow up to https://github.com/coder/coder/pull/28980. The tests modified in this PR have the same flake potential as the test fixed in #28980. Fixes https://linear.app/codercom/issue/PLAT-583/flake-testserveryamlwritethenreadconfig |
||
|
|
1ecb834300 |
test(cli): bind GitHub OAuth tests to loopback (#28980)
On macOS, the Coder test server listening on all addresses could share a port with another test’s loopback listener. Go enables `SO_REUSEADDR` by default, allowing overlapping addresses such as `[::]:61025` and `127.0.0.1:61025`. The OAuth test’s SDK connects to `127.0.0.1:61025`, so its requests could reach the other server and report GitHub authentication as disabled despite the intended server being correctly configured. Bind the GitHub OAuth default-provider tests to `127.0.0.1:0`, matching the SDK’s address and preventing this overlap. Remove the retries introduced in #28358 and #28622: they were unnecessary to fix the flake. To test this fix, I had an agent connect to a live GitHub macOS runner with [wush](https://github.com/coder/wush), reproduce the flake, and verify the new changes actually resolve it. Refs https://linear.app/codercom/issue/ENG-3285/flake-testserveroauth2githubdefaultprovidernewdeployment <sub>Generated by Coder Agents on behalf of @hugodutka.</sub> |
||
|
|
760c8ed8bd |
refactor: always reuse users in notifications scaletest (#28793)
Signed-off-by: Callum Styan <callumstyan@gmail.com> |
||
|
|
3aeb7f85d9 |
feat: correlate coder CLI workspace sessions with client_session_id (#28313)
## Summary Implements DEVEX-664: the coder CLI commands that open a workspace connection now generate a client session ID and attach it to their requests, logs, and existing network telemetry, per the connection-log RFC. Commands opt in explicitly with a `client_session_id` annotation. The opted-in set is `coder ssh`, `coder start`, `coder stop`, and `coder update`. Long-running daemon commands (`coder server`, `agent`, `provisionerd`, and so on) deliberately stay out, so they never carry a meaningless session ID in their logs, request baggage, or telemetry. - **Generate / resolve**: a 16-byte lowercase-hex session ID is generated per opted-in invocation. When `CODER_TRACE_SESSION_ID` is set (so Toolbox and the VS Code plugin can correlate the CLI they spawn), that value is used verbatim; a warning is logged if it is not the canonical 32-char lowercase hex form, since coderd/agent middleware drop non-canonical values. - **Requests**: the ID is attached to every request as `client_session_id` W3C baggage via a transport wrapper, independent of whether tracing is enabled. The already-merged coderd tracing middleware (#27671) reads it. - **Coordinate websocket**: the ID is also set explicitly as baggage on the tailnet coordinate handshake in `workspacesdk.DialAgent`, so coderd's `/api/v2/workspaceagents/{id}/coordinate` endpoint logs it (it does not rely on the CLI transport for that dial). - **Logs**: the ID is added to the command's log context. - **Existing telemetry**: the ID is added to tailnet `TelemetryEvent` (`client_session_id`, new field 20; proto minor version bumped) and plumbed from the CLI through `workspacesdk.DialAgent`. Scope is the coder CLI client only (RFC glossary + requirement 5), and within the CLI only the opted-in workspace-connecting commands above. This PR is independent of #28039 (the agent middleware that consumes the baggage); it depends only on `tracing.SessionIDBaggageKey`, which is already on `main` via #27671. ## Out of scope RFC requirements 7-16 (connection-state change logging, `connection_logs` columns, log buffering, routing/disconnect-reason logs, coordination-protocol plumbing, `agentssh`/`reconnectingpty` command logging, support-bundle log capture) and requirements 4.2/4.3 (VS Code telemetry, Prometheus stats) are separate tickets. IDE plugins, Toolbox, and the daemon commands are also out of scope. ## Testing - `go test ./coderd/tracing/... ./cli/... ./tailnet/... ./codersdk/workspacesdk/...` (unit tests for the generator, the env/generate resolver, per-command opt-in, the baggage transport wrapper, the coordinate-dial baggage helper, and the telemetry field). - `go build ./...`, `go vet`, and `golangci-lint` pass on the touched packages. - `make tailnet/proto/tailnet.pb.go` regenerated the proto; the proto minor version was bumped and `postStartup` now connects at the current agent API version so `TestWorkspaceAgent_Startup/OK` tracks it. > Note: the pre-commit `enterprise/cli/.gen-golden` step could not run in this environment (no Postgres: `open postgres connection: EOF`). `cli/testdata/.gen-golden` passed; this change adds no serpent flags, so there is no CLI help/golden drift. <details> <summary>Implementation plan</summary> ### Scope mapping (RFC -> DEVEX-664) In scope (the CLI workspace-connecting subset of RFC phase 2): - Req 1: generate a 16-byte session ID as 32-char lowercase hex. - Req 2: add the session ID to every log the command makes for the session. - Req 3: attach the session ID to every API request via `client_session_id` baggage, including the coordinate websocket handshake. (The query-param fallback is browser-only; not applicable to the CLI.) - Req 4.1: attach the session ID to CLI network telemetry. - Req 5 / 5.3: support `CODER_TRACE_SESSION_ID`; when set, use it instead of generating. ### Resolved decisions - Scope: opt-in per command via a `client_session_id` annotation; opted-in set is `coder ssh`, `coder start`, `coder stop`, `coder update`. Daemon commands are excluded. - `CODER_TRACE_SESSION_ID`: when set, use the value verbatim; warn if it is not canonical 32-char lowercase hex. When unset, generate a fresh ID. - Existing telemetry = CLI network telemetry (tailnet `TelemetryEvent`); requires a new proto field + plumbing and a proto minor version bump. - Coordinate endpoint: set the session ID as baggage on the coordinate handshake explicitly in `DialAgent` (header, not query param) so it is logged server-side without relying on the CLI transport. - Shared helper: add `tracing.NewSessionID()` and export the validator as `tracing.ValidSessionID` for a single source of truth. ### Implementation 1. `coderd/tracing`: add `NewSessionID()` (16 random bytes, hex-encoded); export `ValidSessionID`. 2. `cli`: resolve the ID from `CODER_TRACE_SESSION_ID` or generate; attach `client_session_id` baggage to every request via `wrapTransportWithSessionIDHeader`, gated on the `annotationClientSessionID` opt-in; add it to the command log context. 3. `tailnet` + `codersdk/workspacesdk`: add `client_session_id` to `TelemetryEvent`, an `Options.ClientSessionID`/`Conn.clientSessionID` set in `newTelemetryEvent`, a `DialAgentOptions.ClientSessionID` plumbed from the opted-in commands, and the coordinate-handshake baggage in `DialAgent`. </details> --- _This PR was created by Coder Agents on behalf of @aqandrew._ |
||
|
|
4875ae218a |
feat: enforce user secret file policy (#28518)
Adds the deployment option `--user-secrets-disable-file-path` / `CODER_USER_SECRETS_DISABLE_FILE_PATH` / `userSecretsDisableFilePath` (default `false`). When it is set, the create and batch-create user-secret endpoints reject requests with a non-empty file path, and PATCH validates the post-update state under a `SELECT ... FOR UPDATE` row lock, rejecting a new or changed file path as well as enabled states that would have no effective delivery target. Legacy stored paths are preserved, so users can still edit, disable, clear the path, or migrate the secret to env delivery. This is PR 1 of a 4-PR stack; follow-ups cover manifest filtering, the dashboard, and CLI/docs. Refs #27488 Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder. |
||
|
|
5f90c2da69 |
fix: deflake config-ssh tests with per-invocation contexts (#28803)
Closes [PLAT-563](https://linear.app/codercom/issue/PLAT-563/flake-testconfigssh-multiple-variants) ## Problem `TestConfigSSH` and `TestConfigSSH_NoWildcard` both failed at `cli/configssh.go:568` with `context deadline exceeded` in [this run](https://github.com/coder/coder/actions/runs/33414383561/job/99561585574). - Both commands made their API calls promptly, then went silent for ~18.4s, then printed `Updated ".../.ssh/config"` and failed the next HTTP call. - The only code in that window is `atomic.WriteFile`, which calls `f.Sync()`. fsync takes no context and cannot be cancelled. - Both gaps ended in the same millisecond while other goroutines in both processes kept logging on schedule, so this was a shared filesystem stall, not CPU starvation or a crashed server. - `configssh.go:568` is the reporting site, not the fault site. The fsync drained the context, so the next request failed before dialing. - Both tests made this easier to hit by creating one `WaitMedium` context before server, agent, and workspace setup, so the command ran on whatever budget was left over. ## Fix - One context per `config-ssh` invocation, created just before it runs, so setup and prior runs cannot drain it. - `WaitMedium` (15s) to `WaitLong` (25s), to cover a slow disk on top of the HTTP calls. - `TestConfigSSH` passes that context to the invocation, so `StartWithWaiter` inherits it instead of injecting a second, independent `WaitMedium` deadline. Failed 20/20 under 4.8x CPU oversubscription before the change, 0/20 after. This buys margin, it does not remove the failure mode: an uncancellable fsync still sits inside a context-bounded command. The higher-leverage follow-up is CI side (the Postgres container runs `log_statement=all` on Docker's json-file driver, and `$RUNNER_TEMP` is not on tmpfs for Linux). Filing that separately. |
||
|
|
1fa6ebe5c3 |
fix: support first-user-trial in non-interactive login (#28321)
## Summary `coder login --first-user-trial=true` was unusable in non-interactive environments: the trial info fields could only be collected via interactive prompts, so scripted setup failed with a bare `EOF`. This adds flags and env vars for every trial info field, extracts the functions into a helper, turns the EOF into an actionable error, and fixes a related quirk where enabling the trial via env didn't reliably suppress the trial prompt. Fixes coder/coder#23264 ## Changes * Add a flag + env var for each trial field (matching the existing `first-user-*` convention): `--first-user-trial-{first-name,last-name,phone-number,job-title,company-name,country,developers}` and their `CODER_FIRST_USER_TRIAL_*` env vars. * When a trial field is missing with no input available, return an error naming the exact flag/env instead of a raw EOF. * Read `CODER_FIRST_USER_TRIAL` from `inv.Environ` instead of `os.Getenv` so the flag binding and the "Start a trial?" prompt gate agree (previously the env toggle could hit an EOF prompt that silently reset `trial` to `false`). * Regenerate `coder_login_--help.golden` and `docs/reference/cli/login.md`. ## Testing * Non-interactive login via flags and via env vars (env test asserts the trial is actually provisioned via a recording `TrialGenerator`). * Missing trial info returns the clear flag-naming error instead of hanging. * Existing interactive `TestLogin` subtests pass; `golangci-lint` clean. ## Notes No strict CLI validation of `country`/`developers` against the UI option lists: the server doesn't enforce them, and the existing fixture uses `developers=10-50` which isn't in the CLI bucket list. Can add if preferred. --- *Created by Coder Agents on behalf of* @snagles\*.\* |
||
|
|
c73f34c35d |
feat: honor the deployment registry mirror in template builder bases (#28727)
## Summary Threads the deployment's configured module registry (`CODER_TEMPLATE_BUILDER_REGISTRY_URL`) into template-builder **base** rendering, so a base that embeds a catalog module (e.g. the quickstart base's `git-clone`) resolves its `source` through a registry mirror the same way wizard-composed modules already do. Previously base-embedded module sources hardcoded `registry.coder.com`, so on a mirror/private-registry deployment a base-embedded module reached the public registry while wizard modules used the mirror. Implements [DOCS-610](https://linear.app/codercom/issue/DOCS-610). ## What changed * `BaseRenderContext.RegistryBase` (new field), mirroring `ModuleRenderContext.RegistryBase`. `Compose` threads the deployment registry through `renderBase` into the base render context, and the four hardcoded base module sources (`quickstart` git-clone, `azure-linux`/`gcp-linux`/`gcp-windows` region modules) now use `{{ .RegistryBase }}`. Because the value defaults back to `registry.coder.com`, rendered sources stay byte-identical; the only golden change is the removal of the now-stale quickstart "follow-up" note. * **Boot-time validation.** `codersdk.ValidateTemplateBuilderRegistryURL` runs in `DeploymentValues.Validate()`, gated on the builder being enabled, matching the chat-hook precedent. A malformed value fails at server start naming the option, instead of surfacing as a per-request error to a template author who cannot fix it. It uses `net/url` in authority form to reject a scheme, path, query, fragment, trailing slash, or credentials and accept a bare `host[:port]`; it does not canonicalize the host. * `Compose` **trusts the validated value**, defaulting an unset one and defensively rejecting a malformed one for direct callers that bypass boot. ## Tests * `codersdk`: validator accept/reject matrix (incl. credentials-without-echo) and a `DeploymentValues.Validate` boundary test with a disabled-skips-validation case. * `templatebuilder`: a base honors the mirror and falls back to the default when unset, plus a defensive-reject case; existing compose tests updated to bare-host registry values. <details><summary>Design decision log</summary> This PR is a deliberately minimal reimplementation of the [DOCS-610](https://linear.app/codercom/issue/DOCS-610/template-builder-base-embedded-modules-should-honor-the-deployment) scope, started fresh from `main` rather than carrying forward an earlier, larger draft (coder/coder#28480). Key decisions: * **Scope kept to the ticket.** The ticket's fix is three bullets: add a registry field to `BaseRenderContext`, thread the deployment `RegistryURL` through `Compose` -> `renderBase`, and use it in base module sources. Independent hardening explored in the earlier draft was dropped as out of scope: `terraform-svchost`-based IDN/punycode/port canonicalization, a rendered-HCL backstop with a 500 mapping, and HCL module-source extraction helpers. Telemetry misclassification of mirror modules is tracked separately ([DOCS-712](https://linear.app/codercom/issue/DOCS-712/telemetry-misclassifies-registry-mirror-modules-as-non-coder)) and is not addressed here. * **Default lives in the render layer.** `templatebuilder.DefaultRegistryBase` holds the fallback host; `codersdk` keeps its own option-default literal. An earlier version exported the constant from `codersdk`, which only emitted a dead `typesGenerated.ts` entry that nothing in the frontend consumed, so it was moved out. The `codersdk` validator is a function, so it generates no TS type. * **Validate at the config boundary, fail fast.** The repo convention is to hard-fail structurally invalid config in `DeploymentValues.Validate()` (access URL, OAuth lifetimes, chat hook URL) and to warn only for functional-but-risky settings. A malformed registry host is structurally invalid, so it fails at boot. This also puts the error in front of the admin who set it, rather than a template author hitting a per-request error they cannot fix. * `net/url`**, not a regex.** The codebase validates identifiers/names with regexes but host/URL-shaped config with `url.Parse` (chat hook URL, OAuth redirect URIs, AI provider base URL). This value is host-shaped, so it follows that convention. `url.Parse("//" + v)` with `u.Host == v` rejects a scheme/path/query/fragment/trailing-slash in one check. </details> > This PR was created with AI assistance (Coder Agents). |
||
|
|
d6b67e8e31 |
feat: enforce SSRF protection for MCP config-directed traffic (#28242)
Routes all MCP config-directed traffic from coderd and chatd through a shared SSRF-protected HTTP client, now that organization admins, not only deployment admins, control MCP server URLs (#27942 and its stack below). ## Summary - Uses the [`coder/safedial`](https://github.com/coder/safedial) library: it blocks private and special-purpose destinations at dial time (validating resolved addresses at connection time so DNS rebinding cannot bypass the check) and rejects cross-origin redirects. - Covers the complete traffic surface: OAuth2 discovery, dynamic client registration, code exchange, token refresh, revocation, and runtime MCP connections from chatd. - Deployments that intentionally host internal MCP servers opt in via the new `--mcp-allowed-private-cidrs` (`CODER_MCP_ALLOWED_PRIVATE_CIDRS`) option. - Includes the deployment configuration surface, generated docs, CLI goldens, TypeScript types, and regression coverage for each traffic path. ## Merge window This protection originally lived inside #27942 and was split out to keep that diff reviewable. Until this PR lands, the stack below ships with only main's existing discovery IP-range guard (`CODER_MCP_OAUTH2_DISCOVERY_ALLOWED_IP_RANGES`), while org admins can already point MCP configs at arbitrary URLs. This PR should merge promptly after the stack below it. Top of the MCP org-separation stack (CODAGT-711 -> CODAGT-717 audit -> CODAGT-712 ACLs -> CODAGT-806 token RBAC -> CODAGT-714 org picker -> this PR). > Mux (AI agent) authored this PR on Mike's behalf. <!-- mux-attribution: model=claude-fable-5 thinking=high --> |