mirror of
https://github.com/coder/coder.git
synced 2026-12-04 05:30:06 +08:00
352d75eca22d2c4facfcf5f53778874f2ff1b989
5132
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
352d75eca2 |
fix(coderd): serialize MCP OAuth token refresh per token (#32616)
--- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
02567e9194 |
feat: serve agent previews on strict preview hosts (#32439)
Agent-written pages are untrusted, because a prompt-injected agent can write any HTML. The security review (coder/security-assessments#437) showed that serving them like ordinary apps lets them reach the user's apps in every workspace. Previews therefore get their own strict host mode instead of the app path: a sandboxing CSP, framing only by the dashboard, no shared app cookie, and no top-level loads. Preview hosts sit under the existing wildcard app hostname, so operators need no new DNS or certificates. The experiment stays out of the safe experiments, so `--experiments='*'` does not enable it, until we have more experience running previews. That is a rollout choice, not a known safety problem. <details> <summary>Implementation details</summary> Adds the `open-preview` experiment, which is hidden from `--experiments='*'` and must be named explicitly, and serves agent previews on preview hosts under the existing wildcard app hostname in a strict mode. A security review (coder/security-assessments#437) showed that agent-written pages served like ordinary apps can reach the user's apps in every workspace, so preview hosts are locked down: - `preview--<id>--<agent>--<workspace>--<owner>` serves a file preview from the agent API (port 4), and `preview--<port>--…` serves a port. Both use the owner sharing level and ignore port shares. The port forwarding display app only hides the dashboard's ports UI, so it does not gate port previews, just as it does not gate port URLs. Connection logs record file previews as `workspace_app` and port previews as `port_forwarding`, under the `preview--` slug. - `coderd/x/previewhost` decides how previews are hosted. Coderd and workspace proxies build one `Hosting` at startup with `previewhost.Strict`, and every preview host request goes through `servePreview`. A later preview domain on another site would add a second constructor. `Hosting.Sandbox`, `Hosting.URL` and `PreviewID.Slug` are used by the sign-in (#32522) and tool (#32440) PRs. `API.previewsUnavailable` and `previewhost.ErrHostPrefixCookieOff` have no reader here beyond the startup log; the sign-in (#32522) and tool (#32440) PRs read them. - `Hosting.ApplyPolicy` adds the CSP (`sandbox`, `default-src 'self'`, `form-action 'self'`, `frame-ancestors` the dashboard) and drops `Link` headers, `Clear-Site-Data` and cookies with a `Domain` attribute. A response writer applies it to every response coderd writes on a preview host, including its own sign-in, error and 403 pages, at `WriteHeader`, because Go's `ReverseProxy` clears response headers after a 1xx. The writer drops 1xx responses other than 101. `ReverseProxy` writes a WebSocket 101 to the hijacked connection instead, so the proxy also applies the policy to every proxied response in `ModifyResponse`. - Requests whose `Origin` is another preview host of the same server get a 403, before CORS is applied. - `DBTokenProvider.Issue` refuses previews unless the experiment is on, `--host-prefix-cookie` is enabled, the request is a subdomain request, and the caller owns the workspace. The host-prefix requirement keeps a preview's script from replacing the user's Coder session cookie; without it, coderd still starts and logs a warning. - A preview without a session gets a 401 page that posts a `coder-preview-sign-in-needed` message to the dashboard, which then signs the user in once (see #32522). - A top-level open of a preview host gets a 403 page that links to the dashboard, so a preview never loads outside the dashboard's wrapper. Browsers send no fetch metadata to a plain-HTTP host other than localhost, so there the page says previews need an HTTPS access URL. Service workers are refused. </details> **Stack** (review bottom-up). Replaces the closed #31282 stack. Security review: coder/security-assessments#437. 1. #32438 Agent file previews 2. #32439 Strict preview hosting and experiment, this PR 3. #32522 Preview sign-in 4. #32440 open_preview chat tool 5. #32441 Agents UI 6. #32442 Docs 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
991c59d33d |
feat: serve published HTML previews from the workspace agent (#32438)
Previews are served by the workspace agent because the files the agent
writes live in the workspace, and the agent already has an HTTP API that
coderd and workspace proxies can reach. Serving from disk on each
request makes a file preview a live view: edits show on reload, and
coderd stores nothing.
The ID is a hash of the path the agent asked for, so a stored
`open_preview` result keeps pointing at the same preview after a
republish, an agent restart, or a change to a symlink in that path. The
model chooses the path, so `os.Root` keeps every request inside it, and
names that start with a dot below it are refused.
<details>
<summary>Implementation details</summary>
The workspace agent can publish an absolute `.html` file, or a directory
containing `index.html`, and serve it from its existing HTTP API (port
4) under `/api/v0/previews/{id}/`. Publishing does not resolve symlinks,
so a path under a symlinked directory such as macOS `/tmp` publishes as
given, which the response returns. The preview ID is the first eight hex
digits of the SHA-256 of that path, so publishing a path again, even
after the agent restarts, returns the same ID. A different path whose ID
is already taken gets a 409. Adds `AgentConn.OpenPreview` to the
workspace SDK, which decodes the ID as `appurl.PreviewID` and returns
`ErrPreviewsUnsupported` when the agent predates the route.
Each request opens the published directory again through `os.Root`, so a
directory that is deleted and rebuilt keeps serving without publishing
it again. Symlinks and junctions are followed only while they stay
inside the published path, only regular files are served, and names that
start with a dot below a published directory, such as `.git` and `.env`,
are refused. Publishing a directory requires `index.html` at its root,
and there are no listings. On Windows, names containing `\`, `:` or `~`
are refused, because Windows reads them as a path separator, an
alternate data stream or a short name such as `HIDDEN~1`. Responses are
`no-store` and `nosniff`.
</details>
**Stack** (review bottom-up). Replaces the closed #31282 stack. Security
review: coder/security-assessments#437.
1. #32438 Agent file previews, this PR
2. #32439 Strict preview hosting and experiment
3. #32522 Preview sign-in
4. #32440 open_preview chat tool
5. #32441 Agents UI
6. #32442 Docs
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
8e569c9c2e |
refactor: share AI spend fields between organization spend types (#32663)
`UserOrganizationAISpend` and `OrganizationMemberAISpendStatus` now share their effective group, budget and spend fields through a new embedded `codersdk.AISpendBudgetStatus`, as suggested in https://github.com/coder/coder/pull/32203#discussion_r4583554893. The organization member AI spend handler now builds the budget with the existing `aiBudgetLimitToSDK` helper instead of by hand. The wire format does not change. Embedded struct fields serialize at the top level of the JSON object, so both responses keep the same keys. In the generated swagger, only the property descriptions change, because the doc comments were merged to fit both types. `typesGenerated.ts` now uses `extends AISpendBudgetStatus` with the same fields. The tests change only because Go composite literals must name the embedded struct. _Generated by Coder Agents on behalf of @SasSwart._ |
||
|
|
ef2b9d2af1 |
fix: address review follow-ups on per-organization AI spend (#32664)
Follow-ups from the review of the per-organization AI spend stack (#32202, #32203, #32204). **Behaviour** - **A $0 AI budget is exceeded, everywhere.** `getSeverity(0, 0)` now returns `exceeded` and `usageProgressPercentage(0, 0)` returns 100, because AI Gateway blocks requests once spend reaches the limit. Before, the user menu and the Agents usage indicator each patched this locally, and the group budget pages showed a $0 budget with no spend as normal. The local patches are removed. As a result, the user menu bar for a $0 budget is now full instead of empty under "Limit exceeded". - **Organization selector:** the trigger now sets `aria-controls` to the expanded list. **Tests** - `getSpendSeverity` unit tests for unlimited and missing spend. The $0 case is covered in `budget.test.ts`. - Story assertions: - `AISpendZeroLimit` checks "Limit exceeded", "AI requests are paused until" and a full bar. - `MultiOrgAISpend` checks the selector and the shown spend. - `MultiOrgAISpendExceeded` checks "AI requests in this organization are paused until". - `MultiOrgAISpendUnavailable` checks "AI spend unavailable" with the selector still shown. - The single-organization AI spend stories seed `meOrganizationsAISpendKey`, so they no longer send that request to a server. - `TestGetUserAISpendByEffectiveGroupsSince` checks the period start boundary, a requested group with no spend returning 0, and the exclusion of other users and unrequested groups. **Backend** - `userAISpendStatus` builds `AIBudgetLimit` with `aiBudgetLimitToSDK`. #32203's `organizationMemberAISpendStatus` has the same change in #32663, which also shares one type between the two organization spend responses. <details> <summary>Review threads addressed</summary> | PR | Thread | Change | | --- | --- | --- | | #32204 | `UserDropdownAISpend.tsx:90`: $0 limit shows a 0% bar | Shared helpers return 100% / exceeded | | #32204 | `viewedSpend.ts:44`: menu-only fork of `getSeverity` | Rule moved into `getSeverity`. `UsageIndicator` and `AIBudgetAmount` now agree | | #32204 | `UserDropdownOrgSelect.tsx:49`: no `aria-controls` | Added | | #32204 | `viewedSpend.test.ts:8`: `getSpendSeverity` untested | Added | | #32204 | `UserDropdown.stories.tsx:304`: exceeded step checks nothing | Assertions added | | #32204 | `UserDropdown.stories.tsx:379`: multi-org stories have no assertions | Assertions added | | #32204 | `UserDropdown.stories.tsx:141`: single-org stories fire a real request | Seeded. A shared constant is added to each story, because a story's `queries` replaces the meta's | | #32202 | `aicostcontrol.sql:294`: querier test for `GetUserAISpendByEffectiveGroupsSince` | Added | | #32203 | `aibridge.go:1399`: use `aiBudgetLimitToSDK` | Same fix applied to `userAISpendStatus` here | Not in this PR, still open for a decision: the avatar badge reflecting other organizations (#32204 `UserDropdown.tsx:62`) and `DropdownMenuSub` (#32204 `UserDropdownOrgSelect.tsx:49`). </details> > Generated by Coder Agents on behalf of @SasSwart. |
||
|
|
1ab0cc4db5 |
fix: use upstream terraform-config-inspect for template parsing (#32401)
Terraform 1.15 lets a module `source` or `version` reference `const` variables and locals. Our fork of `terraform-config-inspect` rejected those with "Variables not allowed", which failed template import for a config Terraform accepts. This drops the fork for upstream `hashicorp/terraform-config-inspect`, which fixed it in hashicorp/terraform-config-inspect#146. The fork only carried variable validation parsing that nothing here reads anymore. Upstream also reads Terraform Stacks files and panics on Stacks-only blocks, so `tfparse` now only passes it the `.tf` and `.tf.json` files Terraform loads for a module and turns a loader panic into an error diagnostic. A dynamic module source still only works through the variable's default, since `terraform init` runs without template variable values. Refs CORE-541 |
||
|
|
924e84d59a |
fix: gate chat instruction reads on deployment_config:read (#32928)
Closes WI-101 `GET /api/v2/chats/config/system-prompt` and `GET /api/v2/chats/config/plan-mode-instructions` both checked `deployment_config:update`, so a token that only needs to read them, e.g. for a `terraform plan`, also had to be able to write them, along with every other setting behind that permission. The check was `read` when #23616 first added it, and was switched to `update` in that same PR to match the gate on the settings form. To fix, we'll check `deployment_config:read` on both, as the other admin-only reads under `/chats/config` already do. The `PUT`s still need `update`. Both settings are now gated on `read` in `dbauthz` as well. Plan mode instructions already had a check there, which moves from `update`. As chatd only holds `read`, it had been borrowing the system identity for that read, and now reads them as itself. The system prompt had none, as chat creation read it as the chat's creator, so chatd now reads it itself too, like it does for organization instructions. As each `PUT` reads the old value for its audit entry, both now answer 403 for a token without `read`. Auditor is the only built-in role with `read` but not `update`, so auditors now get a read-only view of the deployment instructions on the Instructions page. The sidebar link to that page is shown for `read` too. A token scoped to `deployment_config:update` without `deployment_config:read` can no longer read or write either setting. Tokens have only been able to request these scopes since #32653, which isn't in a release yet. |
||
|
|
bf1240e050 |
fix: fixes race between CachedBridgePool.GetRequestHandler and RequestBridge.ServeHTTP (#32866)
Fixes the `TestAIGatewayStartE2E_ReconnectAfterDisconnect` flake: a request that lands during a provider reload can get `503 AI Gateway is shutting down`. --- _Generated by Coder Agents._ |
||
|
|
6173b0ac28 |
refactor: stop chatd reading the provider URL for Gemini thinking (#32902)
Relates to WI-97 Since #32849, chatd reads the AI provider's base URL to work out whether a Gemini request will reach Google. It needs to know, as it swaps `reasoning_effort` for a `thinking_config` when it will, and Google rejects a request that carries both, whilst every other upstream needs `reasoning_effort`. So chatd has to predict what AI Gateway is going to do with the request, and #32811 takes the base URL away from chatd. Instead, chatd now sends both fields for a thinking-capable Gemini model, whatever the provider, and AI Gateway drops `reasoning_effort` when it forwards a `thinking_config` to Google. It already leaves `extra_body` out for every other upstream, so those still only get `reasoning_effort`. chatd also stops stamping thought signatures, as AI Gateway drops them when it parses the request and stamps its own. I compared the request body that reaches the upstream on `main` and on this branch, across 315 combinations of provider, model, effort and pinned thinking config, and they're identical. The one difference is for other AI Gateway clients: a request that sends both fields to a Google provider is no longer rejected with a 400. I also ran live `gemini-3-flash-preview` chats on `main`, this branch and the top of the stack, against a provider that points at Google and one that doesn't, with different efforts, a pinned thinking level, a pinned budget and a tool call. Every turn finished, and what reached the upstream was the same on all three, apart from text the model wrote itself. Google was behind dogfood's AI Gateway, which doesn't serve a Gemini 2.5 model, so I didn't run one. I've put this at the bottom of the stack, as it only replaces how #32849 picks the request shape and doesn't depend on anything above it. |
||
|
|
b4d485bdb6 |
fix: send max_completion_tokens to Azure OpenAI reasoning models (#31952)
Closes #31714 Closes WI-31 Azure OpenAI reasoning models reject `max_tokens`: ``` Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead. ``` We pick between `max_tokens` and `max_completion_tokens` from the model name, and that check only knew names up to `gpt-5`, so a `gpt-6-luna` deployment failed on default settings. To fix, the fantasy bump (coder/fantasy#86, coder/fantasy#87 and coder/fantasy#88) extends the check to `gpt-6` through `gpt-9`. That bump is a full sync with upstream, so it also brings the other chatd changes listed there, which is why a few test expectations move here. On Azure that name is the deployment name though, which doesn't have to say what model it serves. So the model form now also shows the existing Reasoning Model setting for Azure models, and we obey it. With it on, we send `max_completion_tokens` and drop `temperature` and `top_p`, whatever the deployment is called. I confirmed against a real Azure `gpt-5.4` deployment that it rejects `max_tokens` and accepts `max_completion_tokens`, but that test resource has since gone, so I haven't run this exact change against Azure. This only fixes the `max_tokens` error. Going by [Microsoft's docs](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/reasoning), I think GPT-6 chats on Azure will then hit a second error, as on Chat Completions those models only accept tools with the reasoning effort set to `none`, or not at all. The OpenAI and Bedrock providers use the Responses API, so they aren't affected. I can't reproduce that for the same reason, so it's being tracked separately at [CODAGT-1655](https://linear.app/codercom/issue/CODAGT-1655). |
||
|
|
4aef0f6fdd |
feat: add chat project summaries (#32026)
Adds project summaries and share counts on top of #32025. The sidebar's pinned projects read the summaries; the Projects page reads the summaries and the counts. - **`GET /api/experimental/chats/projects/summaries`** returns one `ChatProjectSummary` for every project in the existing project list (the same set): `project_id`, `pinned`, `pin_order`, `own_chat_count`, `own_unread_count`, `own_running`, `own_needs_attention` (`requires_action`, `error` or `paused`) and `last_activity_at` (newest `updated_at` among the caller's counted chats). Counts use only the caller's own top-level, non-archived chats; unread uses the same rule as `has_unread`. `pin_order` is the stored order from #32025: it sorts the pinned projects, lowest first, and can have gaps. A summary does not repeat the project: clients pair it with `GET /chats/projects` by ID. - **Share counts on `ChatProject`:** every project response now carries `member_count` (the owner plus the users the project is shared with directly), `group_count` (shared groups, including Everyone) and `shared_with_everyone`. They count exactly the users and groups `GET .../projects/{project}/acl` lists: users outside the project's organization and deleted groups are left out, through the same helper the ACL endpoint uses. Group members are not expanded, so a list costs two extra queries (memberships and groups) for any number of projects. While chat sharing is disabled or the `chat-project-sharing` experiment is off, every project reports 1 member, 0 groups. - **Same numbers on both pages:** the project page heading already showed "N members, M groups" from the ACL. It now uses a shared formatter, `formatProjectMembers`, which the Projects page card (#32083) also uses, and names the Everyone group first instead of counting it: "Everyone, 2 members, 1 group". - **Why summaries are separate:** the pin and the caller's chat counts change with every chat event, and clients refetch them often, so they do not come with the project, its templates and permissions. - **Authorization:** summaries return only projects the caller can read. They also carry the caller's pins, so they ask RBAC for `read_personal` on the caller: an API key scoped without `user:read_personal` gets a 403. The summaries authorize each project with a full evaluation while the caller has fewer than 200, because the partial evaluation `rbac.Filter` prepares by default costs an organization member about 6 ms per request and a full evaluation about 0.03 ms per project. <details> <summary>Verification</summary> `make gen/db` and the API docs and TypeScript types regenerate cleanly; Go lint on the changed packages, the summaries, share counts, pin, chat list, ACL and dbauthz tests pass; `pnpm lint` and the project page tests pass. `TestChatProjectShareCounts` fails if either ACL filter (organization membership, existing groups) is removed. The summaries timings (1.6 ms at 10 projects, 4.6 ms at 50) are medians of 40 runs against a local Postgres 13, measured before the share counts change. Dogfood UAT with a premium license ran on an earlier response shape, which carried the project and a people count inside each summary. It was not repeated for this shape; the Go and Vitest tests cover it. </details> > [!NOTE] > Most of this PR was written by AI agents (Xum, with UAT run through Coder Agents). The verification above is from those runs. |
||
|
|
9c53f3d7ee |
feat: add per-user chat project pins (#32025)
Adds per-user chat project pins, the first backend layer of the Projects page and pinned projects design. Nothing in the UI reads pins yet; the sidebar and Projects page PRs stacked on top do. - **Schema:** migration `000647_chat_project_pins` adds the `chat_project_pins` table (`user_id`, `project_id`, `pin_order`, `source` of `migration`/`default`/`user`, `created_at`). Unpinning deletes the row. The migration pins every project to its owner in today's sidebar order (`lower(name), id`); shared projects are not pinned. - **Shared rule for which projects a user's list matches:** the migration also adds `chat_project_ids_for_user(viewer_id, include_grants)`: owned projects, plus projects whose ACL names the user or one of their groups (including Everyone) in an organization they belong to. The project list and `GetChats` call it instead of each keeping a copy of that predicate, and so do #32026's queries. Postgres inlines it, so the ACL indexes still apply (same results and timings as before on a 10,000-user, 305-project test database). - **Endpoints:** `PUT` and `DELETE /api/experimental/organizations/{organization}/chats/projects/{project}/pin` pin and unpin. `PUT` takes no body and pins at the end; a project that is already pinned keeps its place. `DELETE` removes the pin. The caller needs read access to a project they can use (anything else is a 404) and `update_personal` on themselves, because a pin is their personal data; an API key scoped without `user:update_personal` gets a 403. Pins are personal preferences, so they are not audited. - **Reordering:** `PUT /api/experimental/chats/projects/pins/order` takes `{"project_ids": [...]}`, the pinned projects in their new order. The server saves the listed pins in that order and keeps every other pin after them, in its current order. The table also holds pins the caller can no longer see (lost access, sharing disabled), and this way no write has to work out which pins those are. IDs the caller has not pinned are ignored, so a project unpinned in another tab does not fail a reorder. The route sits outside `/organizations/{organization}` because one pin list spans organizations. It needs only `update_personal` on the caller. Pins and reorders take a per-user advisory lock. The stored `pin_order` only sorts the pins: it can have gaps after an unpin or a deleted project, until the next reorder. - **New projects** get a `default` pin for their creator inside the create transaction, so an API key scoped to create projects needs the pin's two permissions as well, and gets a 403 without them. - **Chat list:** `exclude_own_project_chats=true` leaves out the caller's own unpinned chats in projects the caller can use; clients list those per project with `project_id`. Project pins don't change the result, so pinning or unpinning never changes the chat list. Shared chats and the caller's pinned chats are still returned, and so are chats in projects the caller can no longer use, because no project list reaches them. The filter sits in the same `WHERE` as the cursor, so pages stay full. User-facing docs land with the UI PR, since these routes stay under `/api/experimental` with `x-apidocgen skip` like the other project routes. <details> <summary>Verification</summary> `make gen` (clean diff), `go build ./...`, `make lint/go`, and the pin, chat list, migration (`TestMigration000647PinsOwnedProjects`, `TestMigrateUpWithFixtures`), dbauthz and codersdk tests pass. `make pre-commit` passes except `lint/actions/actionlint`, which needs a newer local mise and fails the same way on `main`. The dogfood UAT below ran when a pin took a `pin_order` position. It was not repeated after reordering became its own call; the Go tests cover that call, including overlapping reorders and pins. Dogfood UAT ran against a dev deployment with a premium license (groups and a second org created through the licensed APIs): upgrade from `main` with case-sensitive names, pin/reorder/unpin/re-pin, 400 and 404 paths, an 84-request concurrent pin burst with no 5xx, the chat list filter in each sharing mode (as `pinned_projects_only`, before the rename to `exclude_own_project_chats`), and cascade on project delete. Upgrade output: ```text username | name | pin_order | source ----------+---------+-----------+----------- usera | Alpha | 1 | migration usera | beta | 2 | migration usera | gamma | 3 | migration userb | bown | 1 | migration userb | Bshared | 2 | migration ``` Creating a project afterwards appends a `default` pin at position 4, and usera has no pin on userb's shared `Bshared`. </details> > [!NOTE] > Most of this PR was written by AI agents (Xum, with UAT run through Coder Agents). The verification above is from those runs. |
||
|
|
8fb77c1b94 |
test(coderd/x/chatd): wait for in-flight admissions before partitioning replica (#31830)
Fixes the `TestRunnerManager_HeartbeatDoesNotReviveStaleLease` flake ([CODAGT-1288](https://linear.app/codercom/issue/CODAGT-1288)). An admission on replica one that started before the simulated partition could finish after the test made chat A's lease stale, then admit chat B on replica one. Replica two never acquired B and the test timed out waiting for it. `partitionableLimiter` now holds a read lock for each `Admit` call, and `setPartitioned` takes the write lock. Setting the partition therefore waits for admissions already in flight, which see A's lease as fresh and refuse B. This is a test-only change. Verification: - With a 1s delay injected into `partitionableLimiter.Admit`, the original test failed 3/3 with the CI error. The fixed test passed 3/3 with the same delay. - `go test -race -count=20` passed for this test and the other tests in the file. - `golangci-lint` and `go vet` on `./coderd/x/chatd/...` are clean. > [!NOTE] > Generated by Coder Agents. Co-authored-by: Ethan Dickson <ethanndickson@gmail.com> |
||
|
|
2ff17caf5c |
fix(coderd/x): show Gemini 4 Carbon, Neon, Hydrogen thinking (#32849)
Agents chats on Gemini 4 Carbon, Neon, and Hydrogen show no reasoning. `googleSupportedThinkingLevels` did not recognize the `carbon`, `neon`, and `hydrogen` name tokens and failed closed, so `rewriteGoogleCompatThinkingConfig` left these requests as plain `reasoning_effort` with no `thinking_config`. Google's OpenAI-compatible endpoint returns no thought text unless `include_thoughts` is set, and the same check also drops a pinned `provider_options.google.thinking_config` from the model config. The three tokens now classify like `pro` and `argon`: LOW, MEDIUM, and HIGH. Neon and Hydrogen also accept XHIGH, but fantasy's Google provider has no such level, so they top out at HIGH. Live requests through dogfood's AI Gateway `agents-google` provider (Google's OpenAI-compatible endpoint) with `include_thoughts: true`: | `thinking_level` | Carbon | Neon | Hydrogen | |---|---|---|---| | `minimal` | 400 | 400 | 400 | | `low`, `medium`, `high` | 200, thought text | 200, thought text | 200, thought text | | `xhigh` | 400 | 200 | 200 | Neon with only `reasoning_effort` (`high` or `none`), the request shape before this change, returns 200 with no thought text. **Gemini patches now follow the AI provider's upstream.** chatd builds every model through AI Gateway, so the openai-compat client's base URL is always `http://coder-aibridge/v1`, and the Gemini patches (thinking config, thought signatures, thought response rewrite) were chosen by model ID. On an OpenRouter or Vercel provider, a `google/gemini-*` request had its effort moved into `extra_body.google.thinking_config`, which AI Gateway forwards only to Google, so the upstream received no reasoning effort. This already affected Argon and Gemini 3.x on those providers, and recognizing the new models would have extended it to them. `ModelFromConfig` now takes the AI provider's base URL, the URL the gateway sends the request to, and decides with `googleopenai.ShouldPatchGoogleUpstreamRequest`, the predicate the gateway uses for its own Google patches. On a Google provider, model IDs without a `gemini-` prefix now also get the thought response rewrite, which leaves responses without thought output unchanged. > 🤖 Created with the help of Coder Agents. |
||
|
|
2d65ff14c3 |
fix(coderd): sort built-in and custom roles for stable list order (#32463)
The role selector on the new user page showed roles in a different order
on every load. `SiteBuiltInRoles()` and `OrganizationRoles()` built
their lists by ranging over the `builtInRoles` map, so `GET
/api/v2/users/roles` and `GET /api/v2/organizations/{org}/members/roles`
returned built-in roles in random order.
Both functions now sort roles by name before returning. The
`CustomRoles` query also had no `ORDER BY`, so custom roles, which are
appended after the built-in ones, now come back ordered by `name,
organization_id`.
`TestListRoles` and `TestReadCustomRoles` now assert the exact order.
Each fails without its fix and passes with it.
Closes CLIENT-1104
---
*Generated by Coder Agents on behalf of @jeremyruppel.*
|
||
|
|
c0d12c9f4a |
chore: make concurrent migration PRs conflict in git (#32369)
Two PRs that add a migration with the same number can both pass CI and merge back to back, leaving main with a duplicate migration. Squash and Merge only reads the recorded status of each PR's head commit, so nothing blocks the second merge. Since March this has needed at least 8 follow-up fixes, two of them yesterday (#32335, #32329). This adds `coderd/database/migrations/LATEST`, a file that names the newest migration. Every migration PR rewrites the same line, so once one merges, GitHub marks the others as conflicting and disables their merge button. The file holds the full migration name rather than just the number, because two PRs that both wrote `000645` would be identical changes, and git merges identical changes cleanly. ## Changes - `scripts/check_migrations_latest.sh` checks that `LATEST` names the newest `*.up.sql` and that no two migrations share a number. It runs in `make lint/migrations`, which `make lint` and `lint-light` already include. With `--write` it rewrites `LATEST`. - `create_migration.sh` writes `LATEST` after creating the migration. - `fix_migration_numbers.sh` rewrites and stages `LATEST` after renumbering. It now reads the branch's migrations from the index instead of `HEAD`, so it works mid-rebase (where `HEAD` doesn't yet contain them) as well as mid-merge. It keeps a migration whose number is already free instead of failing on a same-name `mv`. It also stages its renames when the branch has no fixtures. Before, it returned before `git add` in that case. - Updated `contributing/backend.md` and `.claude/docs` with the conflict workflow. ## Workflow when another migration lands first 1. GitHub shows a conflict in `LATEST`. 2. Merge or rebase onto `main`. While the conflict is still open, run `./coderd/database/migrations/fix_migration_numbers.sh`. It renumbers your migrations only if their numbers are taken, rewrites and stages `LATEST`. 3. Commit, or continue the rebase. Stacked migration PRs also conflict on `LATEST` once the lower PR squash-merges. The same script handles that: it keeps numbers that are still free and only rewrites `LATEST`. ## Compared with #30734 and #30779 Those PRs post a status check that is refreshed when main moves. They still leave a window between a migration landing and the refresh, and they depend on `pull_request_target` and a required-status setup. A git conflict is evaluated at merge time, so this approach has no window and needs no workflow, token or branch protection change. A status check could still sit on top later for a friendlier message. ## Testing In a scratch repo with a local origin: - Two branches that each add `000645_*` and run `--write`: the second merge reports `CONFLICT (content): Merge conflict in coderd/database/migrations/LATEST`. Without `LATEST`, the same two branches merge cleanly into a duplicate `000645`. - After the conflict, rebasing, taking either side and running `fix_migration_numbers.sh` renumbers to `000646`, rewrites `LATEST`, stages everything, and the branch then merges cleanly. Also checked with a matching fixture. - The check fails on duplicates, a stale `LATEST`, or a missing `LATEST`, and passes on current main (`000644_chat_project_templates`). - Running `fix_migration_numbers.sh` while the `LATEST` conflict is still open renumbers and resolves it in both the merge and rebase flows (with a fixture in the rebase case). In a two-PR stack where the lower PR squash-merges, it keeps the upper PR's number and only rewrites `LATEST`. - The check accepts trailing whitespace and CRLF in `LATEST`. - `shellcheck -x` and `shfmt -d` pass on the three scripts, and `make pre-commit-light` passes. ## Notes - Release branches cut before this merges don't have `LATEST`, so cherry-picking a migration PR onto one conflicts on it. Drop the `LATEST` change in that cherry-pick. Release branches cut after this merges do have `LATEST`, so every migration backport conflicts on it, and `cherry-pick.yaml` falls back to its manual-resolution placeholder. Resolve it with `./scripts/check_migrations_latest.sh --write`. The same applies to reverting a migration PR after a later migration has landed. - Rollout: open PRs that add migrations and have green CI from before this merges can still merge without touching `LATEST`, because they don't conflict with it. That would leave `LATEST` stale on `main`, and since PR CI lints the merge ref, `lint/migrations` would fail on every open PR until someone bumps `LATEST`. When this lands, ask the authors of open migration PRs to update from `main`, and be ready to merge a one-line `LATEST` bump. - If a migration lands on main before this merges, `LATEST` needs a bump. `make lint/migrations` will flag it. |
||
|
|
6239c3ac94 |
fix(coderd/database): poll only root chat git refs (#31920)
Diff-status rows on subagent chats still consume provider requests. Move their refs to root chats so the root chat's Git panel shows them, and limit diff-status refresh to rows on root chats. Recognize a subagent chat when root_chat_id or parent_chat_id is set, matching Chat.IsSubChat. Keep existing root rows on conflict. Otherwise retain the most recently refreshed row from a subagent chat, with its metadata and timestamps. |
||
|
|
c95f3a58f9 |
chore: remove the remaining export_test.go shims (#32434)
Closes CODAGT-1607 Follow-up to #32162, which left 5 `export_test.go` shims behind: `coderd`, `aibridged`, `chatd`, `chatstate` and `mcpclient`. This PR removes them. It's stacked on #32433, which deals with the chat workspace functions in `coderd`. Same approach as before. Tests of package internals are now `*_internal_test.go` files, with no changes beyond what the move forces, and tests that only needed a constant just use the value. `chatstate` needed one small accessor, so `AllowedExecutionTransitionOutputs` is just exported for real, and its tests stay where they were. Unfortunately the `mcpclient` connect budget test needs an unexported timeout, so it moved to an internal file and builds its own server there. I've removed `TestConnectAll_LateServerReaped`, `TestAllExecutionStates_Enumeration` and a few assertions instead of moving them, as I couldn't find a breakage that only they would catch. While here, I've dropped the test-only `reaperDone` hook from `mcpclient`. The wait for a connect to finish within its budget is now a small function of its own, with a test that a session which connects too late still gets closed. Nothing checked that before. With no shims left, the `testpackage` path exclusion is gone, so a new `export_test.go` now fails lint. |
||
|
|
2d725a1ced |
refactor(coderd): move the chat start decision into the start tool (#32433)
Closes CODAGT-292 Relates to CODAGT-1607 `coderd/export_test.go` re-exported `chatCreateWorkspace`, `chatStartWorkspace`, `chatStopWorkspace` and `chatRenderTemplateParameters`, just so four tests could call them directly. This PR removes those tests and their aliases, and the last alias in that file goes in the next PR in the stack. The start and stop tests only checked which template version the build ends up on. That decision lived in `coderd`, behind the function the tool calls, so the only way to test it was to call that function directly. Now `start_workspace` makes the decision itself, much like `coder start` does: it checks whether the template requires its active version, sends that version with the build request, and tells the model how to retry when the update needs parameters. All of that is covered by the tool's own tests. With the decision gone, the start and stop functions were identical, so both tools now share `chatBuildWorkspace`, which just creates a build as the workspace owner. Two small behaviour changes. `start_workspace` now returns `template_id` whenever it asks the model to retry with parameters. Previously it was missing for templates on the classic parameter flow, even though the message says to use it. The tool also reads the template's setting directly, like `coder start`, so chat updates on start too when the setting is still on after a licence lapses. `TestStartWorkspaceTool_EndToEnd` now starts a workspace whose active version needs a new parameter, so we still know the whole flow works against a real `coderd`. `chatRenderTemplateParameters` keeps a direct test, it's just an internal one now, against a database instead of a whole `coderd`. It no longer checks the owner default, as that's already tested in the renderer and in the tool. The bind failure test needs a real transaction, so it moves to `chatd` and runs through the `create_workspace` tool. |
||
|
|
688a0f9b3e |
refactor: use go-jose for all JWT handling (#31931)
Closes ENG-1510. First-party code used two JWT libraries: `go-jose/v4` (workspace apps, jwtutils, tailnet resume, agent hooks, chats) and `golang-jwt/jwt/v4` (licenses, Azure OIDC PKI, test signers, and `jwt.MapClaims` in idpsync). This moves everything to go-jose and removes `golang-jwt/jwt/v4` from `go.mod`. - `enterprise/coderd/license`: verification uses `jwt.ParseSigned` with an EdDSA allowlist and `kid` lookup. Time claims are validated with zero leeway, matching golang-jwt's previous behavior instead of go-jose's 1 minute default. `ParseClaimsIgnoreNbf` still returns `ErrMultipleIssues` for any verification or time-claim failure other than `nbf`. `Claims` now embeds `jwtutils.RegisteredClaims`, so `ExpiresAt` becomes `Expiry` and `NumericDate` uses `.Time()`. - `coderd/oauthpki`: the Azure client assertion is signed with go-jose and keeps the `typ: JWT` and `x5t` headers that the existing test asserts. - Test helpers (`coderdtest`, `oidctest`, `coderdenttest`) sign with go-jose. - `jwt.MapClaims` is replaced with `map[string]any`. No callers used its methods. - A depguard rule (`single_jwt_library`) rejects new `github.com/golang-jwt/jwt` imports. `golang-jwt/jwt/v5` stays as an indirect dependency through `SherClockHolmes/webpush-go`. <details> <summary>Decision log</summary> - **Why go-jose over golang-jwt:** `coderd/jwtutils/jwe.go` needs JWE, which golang-jwt doesn't support, so only go-jose can be the single library. go-jose was already used for the more security-sensitive token paths, and `coreos/go-oidc` depends on it anyway. Its `ParseSigned` requires an explicit algorithm allowlist. Moving the golang-jwt usages, which were mostly `MapClaims`, was the smaller change. - **Expiry edge case:** golang-jwt treated a license as expired at `now >= exp`, and go-jose treats it as expired at `now > exp`. With whole-second timestamps the difference is at most one second. - **Not evaluated:** a comparison of CVE history or maintenance pace between the two libraries. </details> Validation: `make pre-commit`. Tests: `enterprise/coderd/license`, `enterprise/coderd` (license, trial, OIDC, and sync tests), `enterprise/trialer`, `enterprise/coderd/usage`, `enterprise/coderd/enidpsync`, `coderd/oauthpki`, `coderd/idpsync`, `coderd/coderdtest/oidctest`, `coderd` (OIDC, login, Google instance identity, and OAuth2 tests), `coderd/externalauth`, `coderd/provisionerdserver`, `cli`. I confirmed the depguard rule flags a `golang-jwt/jwt/v5` import. > Generated with Coder Agents on behalf of @deansheather. |
||
|
|
6993824dd1 |
feat: allow scoped tokens to manage AI resources (#32653)
Closes CORE-916
A token can only be created with scopes from a hand-kept list of
requestable names, and that list has nothing for most Coder Agents
resources. As a result, a CI job that manages AI providers, MCP servers,
models or the system prompt, or one that just starts a chat, has to hold
an unscoped token.
This PR adds the names for `chat`, `ai_provider`, `mcp_server_config`
and `deployment_config`, the rest of `chat_model_config`, plus
`organization_member:read` and `assign_role:read`, which our Terraform
jobs also need.
I've tested locally that the calls of our dogfood Terraform plan and
apply jobs, and of `triage-via-chat-api.yaml`, all work with tokens that
hold only the scopes each job needs. That caught one bug, where `GET
/api/v2/organizations/{organization}/chats/models` returned a 403 to a
`chat_model_config:*` token, as the handler only accepted the exact
`chat_model_config:read` scope. It now accepts any scope that covers it.
Whilst here, I've corrected the description of
`deployment_config:update`, which the scopes reference gave as "Updating
health information."
|
||
|
|
ac92143dbe |
refactor!: remove the AI Gateway provider list route (#32651)
Relates to AIGOV-824 Stacked on #32650. `GET /api/v2/ai-gateway/providers` was added in #28966, in September, and first shipped in v2.38.0. It was a fix for the provider filter on the AI Gateway sessions page. That filter called `GET /api/v2/ai/providers`, which only owners could read, so the dropdown was empty for auditors. Rather than open up the provider config, #28966 added a second route that returns just the `name`, `type`, `display_name` and `icon` of every provider, deleted ones included, to anyone who can read sessions, i.e. owners and auditors. Now that `GET /api/v2/ai/providers` answers every signed-in user with those same fields (#32650), the second route has no caller that it alone can serve. Jake, who added it, and I agree that we should remove it rather than keep two routes that list providers, so this PR does that. The one thing only the old route did was return deleted providers, so that sessions and spend recorded under a provider that has since been deleted keep their label. So, `GET /api/v2/ai/providers` gains an `include_deleted` query parameter. A deleted provider can share its name with a live one, so each name appears once, as its live provider if there is one, otherwise the most recently updated deleted one. Unlike the old route, any caller can pass it, so members can now see the names of deleted providers. A deleted provider comes back without its configuration, for owners too. The sessions provider filter and the Spend page now call `GET /api/v2/ai/providers?include_deleted=true`, and show the same thing as before. `codersdk.AIBridgeProvider`, `Client.AIBridgeListProviders` and the `GetAIProviderFilterOptions` query go with the route. ## For changelog - `GET /api/v2/ai-gateway/providers` has been removed (#32651) > `GET /api/v2/ai-gateway/providers` has been removed, along with `codersdk.AIBridgeProvider` and `Client.AIBridgeListProviders` in the Go SDK. It listed providers only for users who can read AI Gateway sessions, i.e. owners and auditors. `GET /api/v2/ai/providers` replaces it, and now answers every signed-in user. Owners still get each provider's full configuration from it, and everyone else gets the same list with an empty `base_url`, an empty `api_keys` array, `null` `settings` and no `status`. > > Migration: Call `GET /api/v2/ai/providers?include_deleted=true` instead. Each provider keeps its `name`, `type`, `display_name` and `icon` fields, and `display_name` now holds the provider name when no display name is set. In the Go SDK, `Client.AIProviders` now takes a `codersdk.AIProvidersFilter`. Set its `IncludeDeleted` field to list deleted providers too. An API token with an allow list needs `ai_provider` in that list to call `GET /api/v2/ai/providers`, where the removed route needed `aibridge_interception`. |
||
|
|
fd74a160ec |
feat: let all users list AI providers (#32650)
Closes AIGOV-824
`GET /api/v2/ai/providers` now answers every signed-in user. Before, it
returned a 403 to anyone who isn't an owner.
Owners get exactly what they did before. Everyone else gets the same
list without each provider's configuration, i.e. `base_url`, `api_keys`,
`settings` and `status` come back empty:
```json
[
{
"id": "90f4a82a-c945-4598-93be-be9dde57c38d",
"type": "openai",
"name": "corp-openai",
"display_name": "Corp OpenAI",
"icon": "/icon/openai.svg",
"enabled": true,
"base_url": "",
"api_keys": [],
"settings": null,
"created_at": "2026-11-24T11:56:44.789072Z",
"updated_at": "2026-11-24T11:56:44.789072Z"
}
]
```
Clients need the list to find out what a provider is called. They reach
a provider through AI Gateway at `/api/v2/ai-gateway/<provider-name>/`,
and the name is whatever an admin chose. Mux, for example, lists
providers with `GET /api/v2/ai/providers`, so a member's Mux only finds
providers that happen to have a default name.
To do this, I've split the permission in two. `ai_provider:read` now
only covers the fields that are filled in above, and every member holds
it, the same way they can read OAuth2 apps and workspace proxies. A
provider's base URL, keys and settings sit behind a new
`ai_provider:read_secret` permission, which only owners hold. `GET
/api/v2/ai/providers/{idOrName}` and the dashboard's AI settings pages
now check `ai_provider:read_secret`, so they're still owner only.
This doesn't show members much that's new. They can already read the
name, type, display name, icon and enabled state of every enabled
provider from `GET /api/v2/users/{user}/ai-provider-keys`, so the
additions are disabled providers and the two timestamps.
The next PR in the stack removes `GET /api/v2/ai-gateway/providers`,
which `GET /api/v2/ai/providers` replaces.
|
||
|
|
273adb2a2b |
chore: refresh AI model price book (#32783)
## Price book changes 28 models added, 62 models removed, 71 models changed. <details> <summary>Added</summary> - azure/fw-deepseek-v4.1-flash - azure/fw-glm-5.3 - azure/fw-glm-5.3-flash - azure/fw-kimi-k3 - azure/fw-kimi-k3.1-pro - azure/fw-nemotron-3-ultra-nvfp4 - azure/fw-nemotron-lightning-3.5-30b-a3b - azure/gpt-oss-120b - azure/grok-4.7 - azure/kimi-k3.1-pro - bedrock/ca.anthropic.claude-haiku-5-5 - bedrock/ca.anthropic.claude-sonnet-5-5 - bedrock/in.moonshotai.kimi-k3 - bedrock/in.moonshotai.kimi-k3.1 - bedrock/writer.palmyra-vision-7b - openai/gpt-6-astra-healthcare - openai/gpt-6.1-sol-healthcare - openai/gpt-6.2-astra-healthcare - openai/gpt-6.2-sol-healthcare - openrouter/mistralai/pixtral-large-2502 - openrouter/radixark/daisyrose-27b - openrouter/thinkingmachines/inkling-2-mini - openrouter/tngtech/deepseek-r1t2-chimera - openrouter/upstage/solar-mini-4-5 - openrouter/upstage/solar-pro-4-contributor - openrouter/xiaomi/mimo-v2.6-flash-mopd - vercel/google/gemini-4-neon-fast - vercel/thinkingmachines/inkling-2-mini </details> <details> <summary>Removed</summary> - azure/claude-mythos-5 - azure/codex-mini - azure/o1 - azure/o3 - azure/o3-mini - azure/o4-mini - azure/phi-4-reasoning-plus - bedrock/apac.anthropic.claude-sonnet-4-20250514-v1:0 - bedrock/eu.anthropic.claude-fable-5 - bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0 - bedrock/global.anthropic.claude-sonnet-4-20250514-v1:0 - bedrock/jp.anthropic.claude-opus-5 - bedrock/jp.anthropic.claude-sonnet-5 - bedrock/us.amazon.nova-premier-v1:0 - bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0 - copilot/claude-opus-4.7 - copilot/claude-opus-5 - copilot/gemini-3.5-flash - copilot/gemini-3.6-flash - copilot/gemini-3.7-flash - copilot/gpt-5-mini - copilot/gpt-5.4 - copilot/gpt-5.4-mini - copilot/gpt-5.5 - copilot/gpt-5.6-terra - copilot/kimi-k2.7-code - google/gemini-2.5-computer-use-preview-10-2025 - google/gemini-3.1-flash-lite-preview - google/gemini-omni-flash-preview - google/lyria-3-clip-preview - google/lyria-3-pro-preview - openai/gpt-3.5-turbo - openai/gpt-4 - openai/gpt-4-turbo - openai/gpt-4.1-nano - openai/gpt-4o-2024-05-13 - openai/gpt-5.3-codex-spark - openai/gpt-realtime-2.1 - openai/o1 - openai/o1-pro - openai/o3-mini - openai/o4-mini - openrouter/cohere/north-mini-code:free - openrouter/dots-studio/dots-3-note-preview:free - openrouter/meituan/longcat-2.0 - openrouter/meta-llama/llama-3.2-1b-instruct - openrouter/mistralai/mistral-medium-3 - openrouter/mistralai/mistral-medium-3.1 - openrouter/moonshotai/kimi-k2 - openrouter/moonshotai/kimi-k2-0905 - openrouter/moonshotai/kimi-k2-thinking - openrouter/tencent/hy3-preview - openrouter/thinkingmachines/inkling-2-small:free - openrouter/unbiased/pareto-26.10 - openrouter/unbiased/pareto-26.10-preview - openrouter/unbiased/pareto-26.9 - openrouter/x-ai/grok-build-0.1 - openrouter/xiaomi/mimo-v2.5 - openrouter/xiaomi/mimo-v2.5-pro - openrouter/~unbiased/pareto-latest - vercel/alibaba/qwen3-max-thinking - vercel/spacexai/grok-build-0.1 </details> <details> <summary>Changed</summary> - azure/deepseek-v4-flash - azure/deepseek-v4-pro - azure/grok-4-20-non-reasoning - azure/grok-4-20-reasoning - azure/kimi-k2.5 - azure/kimi-k2.6 - bedrock/amazon.nova-2-lite-v1:0 - bedrock/amazon.nova-lite-v1:0 - bedrock/amazon.nova-micro-v1:0 - bedrock/amazon.nova-pro-v1:0 - bedrock/anthropic.claude-fable-5 - bedrock/anthropic.claude-fable-5-1 - bedrock/anthropic.claude-fable-5-2 - bedrock/anthropic.claude-haiku-4-5-20251001-v1:0 - bedrock/anthropic.claude-haiku-5-5 - bedrock/anthropic.claude-opus-4-5-20251101-v1:0 - bedrock/anthropic.claude-opus-4-7 - bedrock/anthropic.claude-opus-4-8 - bedrock/anthropic.claude-opus-5 - bedrock/anthropic.claude-opus-5-5 - bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0 - bedrock/anthropic.claude-sonnet-5 - bedrock/anthropic.claude-sonnet-5-5 - bedrock/global.amazon.nova-2-lite-v1:0 - bedrock/us.amazon.nova-2-lite-v1:0 - bedrock/us.amazon.nova-lite-v1:0 - bedrock/us.amazon.nova-micro-v1:0 - bedrock/us.amazon.nova-pro-v1:0 - google/gemini-2.5-flash-image - openrouter/deepseek/deepseek-chat-v3-0324 - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4-flash-vision-exp - openrouter/deepseek/deepseek-v4-pro - openrouter/deepseek/deepseek-v4.1-flash - openrouter/deepseek/deepseek-v4.1-flash-1017 - openrouter/google/gemma-3-4b-it - openrouter/gryphe/mythomax-l2-13b - openrouter/inclusionai/ling-3.1-flash - openrouter/meta-llama/llama-3.1-8b-instruct - openrouter/meta-llama/llama-3.2-3b-instruct - openrouter/minimax/minimax-m2.5 - openrouter/minimax/minimax-m2.7 - openrouter/minimax/minimax-m3 - openrouter/minimax/minimax-m3.1-flash - openrouter/moonshotai/kimi-k2.7-code - openrouter/moonshotai/kimi-k3.1-pro - openrouter/nvidia/nemotron-3.5-super-vl - openrouter/openai/gpt-oss-120b - openrouter/openai/gpt-oss-20b - openrouter/particle-ai/particle-1 - openrouter/qwen/qwen3-coder-30b-a3b-instruct - openrouter/qwen/qwen3.5-27b - openrouter/qwen/qwen3.5-397b-a17b - openrouter/qwen/qwen3.5-9b - openrouter/qwen/qwen3.6-35b-a3b - openrouter/qwen/qwen3.8-27b - openrouter/reflection/beam-1.0-501b-a23b - openrouter/z-ai/glm-4.5-air - openrouter/z-ai/glm-4.7 - openrouter/z-ai/glm-5.1 - openrouter/z-ai/glm-5.2 - openrouter/~deepseek/deepseek-flash-latest - openrouter/~deepseek/deepseek-pro-latest - openrouter/~deepseek/deepseek-v4-flash-latest - openrouter/~z-ai/glm-flash-latest - vercel/alibaba/qwen3.8-27b - vercel/amazon/nova-lite - vercel/amazon/nova-micro - vercel/amazon/nova-pro - vercel/deepseek/deepseek-v4-pro-0813 - vercel/minimax/minimax-m2.7 </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/45808292131). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
3fea25447a | test(coderd): deflake queued reasoning effort test (#32782) | ||
|
|
856a8684cb |
fix: prevent channel shutdown send races (#29658)
Workspace update subscriptions and VPN tunnels could close a channel
while another goroutine was still sending on it, panicking with `send on
closed channel`. VPN senders could also block forever once nothing read
the channel.
- `coderd`: `sub.Close` no longer closes the updates channel, so a
pubsub callback still running cannot send on a closed channel.
- `vpn`: after Stop, the tunnel no longer closes the shared send
channel. The writer exits after writing the Stop response, so Stop is
the final frame, and its exit is what ends the senders below.
- `vpn`: a speaker send context ends when the speaker is canceled or the
writer exits, for example on a write error. RPCs, RPC replies, updates
and logs wait on it, so they return instead of blocking on a channel
nothing reads. Before, an update holding the updater mutex could block a
Stop the tunnel had already read. The updater context derives from it,
so the updater also stops after Stop when Start never succeeded.
- `vpn`: RPC response channels are buffered, so delivering a response no
longer deadlocks against a caller canceled at the same moment. That
deadlock exists on main for a canceled caller context, and the send
context adds a cancellation at shutdown. A response received before EOF
or writer exit is returned instead of an error.
<details>
<summary>Decisions and regression evidence</summary>
- Nothing observes the subscription channel closing: its only reader,
`WorkspaceUpdates` in `tailnet/service.go`, also stops on its stream
context and calls `Close` itself.
- The tunnel does not cancel its speaker after Stop. Senders return once
the writer has finished the Stop response rather than when it is handed
over, and a request the manager sends after Stop stays parked until
`Tunnel.Close`, as on main.
- `updater.stop` is unchanged: it cancels after closing the conn, so
logs the conn emits while closing reach the manager (the tunnel is the
only log sink with `UseAsLogger` on macOS).
`TestTunnel_StopForwardsCloseLogs` guards that ordering.
- RPCs wait on the send context directly instead of relying on
`recvLoopDone`. The receive loop cannot exit while it is handing a
request to a busy `requestLoop`, and closing a blocking file descriptor
may not interrupt its read. `recvFromSerdes` still delivers requests
after the writer exits, so a Stop it has already read is not dropped.
When only the writer has exited, RPCs return `io.ErrUnexpectedEOF`, as
for EOF. Every RPC return removes its response channel, so RPCs that
fail after the writer exits do not accumulate entries.
- Against main's production code:
- `TestWorkspaceUpdatesClose/{QueryInFlight,CallbackAfterClose}` and
`TestTunnel_StopConcurrentSenders` panic with `send on closed channel`.
- `TestSpeaker_ResponseDuringCancellation` deadlocks.
- `TestSerdes_StopClosesAfterResponse` receives a frame after Stop.
- `TestTunnel_StopAfterWriterExits` and
`TestSpeaker_RPCAfterWriterExits` stay blocked after the writer exits.
- `TestSpeaker_ResponseBeforeEOF`,
`TestSpeaker_ResponseBeforeWriterExits` and
`TestTunnel_StopForwardsCloseLogs` pass on main. They guard ordering the
fix depends on: each fails when that ordering is changed or the matching
part of the fix is removed.
- The regression tests pass 50 runs with `-race`. The `vpn` and
`tailnet` race suites pass.
</details>
> This PR was created with the help of Coder Agents for @mafredri and
will be reviewed by a human.
|
||
|
|
c7b144cc76 |
fix(coderd/x/chatd): prevent a chat stream relay deadlock on repeated episode selection (#31187)
Stacked on #31196, which must merge first. When a chat's worker runs on the same replica as the stream, the chat stream relay can deadlock with the in-process parts endpoint. Live model output then stops on that stream until the client reconnects, while saved messages, status and queue updates keep arriving. The stream loop configures the relay forwarder after every newer snapshot, and queueing a message, deleting or promoting a queued one, interrupting, and recording a retry keep the episode. The forwarder sent a selection each time, and the endpoint answers each one by sending the episode again from `seq` 1, so K updates on an N-part episode moved about K times N parts. While the stream loop reads slowly, the resent parts fill the buffers and the endpoint's serve loop waits to send. Three unread selections fill the pipe's one-slot channel, the endpoint's selection reader and its one-slot channel to the serve loop, and the forwarder's next `WriteControl` never returns. - The forwarder sends a selection only on a new connection or when the target changes. Before #31196, only a repeated selection restarted live output after the part buffer dropped a slow subscriber. - The endpoint's selection reader replaces an unread selection instead of waiting, so the endpoint does not depend on how a client sends selections. After the first change the forwarder cannot practically reach the cycle, since it drops other episodes' parts without waiting. Dropping one loses nothing, because every selection starts again from `seq` 1. <details> <summary>Investigation and decision log</summary> ### Evidence `TestStreamRelayForwarderSelectsOnlyChangedTargets` configures one 200-part episode 10 times: before the forwarder change it sees 10 selections and 2000 parts, after it 1 selection and 200 parts. `TestStreamPartsEndpointLatestSelectionWinsWhileBlocked` fails in 10 of 10 runs without the reader change and with a 15-slot queue that replaces nothing. `TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures` stalls the stream loop until the buffers fill, configures the same episode 1000 times, then requires a new part to arrive; it fails in 20 of 20 runs with both changes reverted and passes with either one alone. All three pass with `-race -count=20`. A goroutine dump taken with the world stopped, from a test that used the real forwarder, local dialer and part buffer with a 2000-part episode, shows the four goroutines at the waits described above and every buffer full. The deadlock formed in 20 of 20 runs under `-race`, after 4 to 384 same-episode selections. After the test read every buffered part, added live parts, configured the relay 11 more times (once for a new episode) and fired the buffer's send timeout, no part arrived. ``` F goroutine 73 [select]: streamPartsChannelClientTransport.WriteControl stream_parts_transport.go:142 <- (*streamRelayForwarder).loop.func4 stream_relay.go:148 <- loop stream_relay.go:207 R goroutine 74 [select]: streamPartsEndpoint.serve.func1() stream_parts.go:84 E goroutine 83 [select]: streamPartsChannelServerTransport.WriteEvents stream_parts_transport.go:120 <- streamPartsEndpoint.serve stream_parts.go:169 L goroutine 84 [select]: (*streamPartsTransportSession).readLoop stream_parts_transport.go:236 f.parts=128/128 s.parts=128/128 eventsCh=128/128 controlCh=1/1 SelectEpisode started=13 returned=12 ``` A test goroutine in place of the stream loop dropped repeated parts and spent a fixed sync time on each hint before it selected the same episode again (200 hints, 3 runs per row, real clock): | Sync time per hint | Hint interval | Deadlock formed | |--------------------|---------------|-----------------| | 1 ms | 1 ms | 1 of 3 | | 5 ms | 5 ms | 1 of 3 | | 1 ms | 2 ms or 5 ms | 0 of 6 | | 5 ms | 10 ms | 0 of 3 | The deadlock formed only when selections arrived about as fast as the stream loop handled them. How often that happens in production is not measured. Selecting a new episode every time under the same pressure did not deadlock in 300 of 300 iterations, because the forwarder drops parts of other episodes without waiting for the stream loop. Over the WebSocket transport with the pipeline full, 1263 selections over 2999 iterations all returned; when the stream loop then stopped reading, the server heartbeat closed the parts connection about 35 seconds after it opened, and the forwarder dialed again once the stream loop read again. ### Decisions - `WriteControl` keeps its waiting send: the reader no longer waits after reading the pipe, so the send returns, and replacing there changed no test result. - Replaced `TestStreamRelayLivePartsAfterSameEpisodeReselects`, which waited for full buffers before every selection and so relied on the replays the forwarder change removes, with a test that fills the buffers once by stalling the stream loop. - Rejected: having the serve loop read selections while it waits in `WriteEvents`. The serve loop would have to abandon a send in progress and drop its part, a larger change with the same result. </details> > 🤖 This PR was created with the help of Coder Agents. |
||
|
|
1d565409e4 |
fix(coderd/x/chatd): keep slow part subscribers attached while the episode is open (#31196)
The message part buffer dropped a subscriber of an open episode whose
send waited 10 seconds. The parts endpoint read the closed channel as
the end of the episode and kept the connection open, so live output
stopped for the rest of the model call. Only on the cross-replica
WebSocket could a longer stall end it: the endpoint's heartbeat closes
the socket 15 to 30 s after the relay stops reading, and the relay
reconnects and replays once it reads again. That path is unchanged. The
stream loop stops reading when its writes to the browser block.
The timeout keeps an unresponsive subscriber from holding an episode in
memory, but only closed episodes wait for subscribers. It now starts at
the close, also for a send already waiting then.
A drop after the close only cuts short the live preview, which the saved
message or the error event replaces. The buffer has no logger, so it is
not logged.
Cost: a subscriber that stops reading an open episode holds its
goroutine and batch until it reads, is cancelled, its context ends, the
buffer closes, or `SubscriberSendTimeout` passes after the episode
closes.
> 🤖 This PR was created with the help of Coder Agents.
|
||
|
|
b044acbe2b |
fix(coderd/database/migrations): remove lock-retry blocks from chat migrations (#31167)
Migrations 000609, 000611 and 000615 start with a lock-retry block (added in #30297 and #30412) that is meant to stop live chat traffic from deadlocking with the migration. On a release upgrade it cannot do that, and it can turn a failure into a 2-minute hang or cause a failure that would otherwise not happen. This PR removes the blocks. A release upgrade that runs 000607 to 000615 while chats are in use is unreliable with or without them, so it needs chat traffic stopped, for example by scaling the deployment to zero first. `coder server` runs all pending migrations in one transaction, so every migration's locks are held until the transaction commits. On a release upgrade (from v2.38 or earlier), 000607 and 000608 lock `chats` before any block runs. A chat request that writes `chat_messages` or `chat_queued_messages`, or that reads `users`, holds a lock that a later migration needs and then waits for `chats`. The block can release only the locks it took, so it can avoid this deadlock only when its migration takes the first chat lock of the upgrade. Postgres checks a waiting request for a deadlock once, after `deadlock_timeout` (1 second by default). The block pauses 100ms between 100ms lock attempts, so a check that lands in a pause finds no deadlock, the request keeps its lock, and the block retries until it fails the upgrade after 2 minutes, with the request stuck until then. Without the block, the outcome depends on timing. If the request's check fires after the migration starts waiting for it, Postgres cancels the request and the upgrade continues. If the request had already waited longer than `deadlock_timeout`, its check found no deadlock, so Postgres cancels the migration instead and the upgrade fails. Main does not finish those cases either: its block was still retrying after a minute, and it gives up at its 2-minute deadline. 000609 and 000611 return to their content before #30297, and 000615 loses the block in both directions. A block's migration takes the first chat lock of an upgrade only when upgrading from a build of main at 608 through 614: dogfood, where the #30297 deploy failed, or a `coder-preview` image built between 2026-10-02 and 2026-10-11. No release stops in that range, and dogfood is already past 615. v2.39 ships these migrations with the blocks. Editing them leaves every schema unchanged: databases on v2.39 or later already ran them and do not run them again, and `dump.sql` regenerates without a diff. The change affects only databases upgrading from v2.38 or earlier. WI-46 proposed the opposite direction: make the migrator survive live chat traffic. The v2.38 upgrade thread concluded instead that old replicas must be stopped before an upgrade runs migrations. So `TestMigrationChatTablesConcurrentTraffic`, which tested the blocks under chat traffic, is removed without a replacement, and its helpers `async` and `dedicatedConn` move to `migration000638_test.go`, their remaining caller. <details> <summary>Measurements</summary> Each run starts chat requests while the upgrade transaction is open, on the Postgres 13 test container with the default `deadlock_timeout`. "Request canceled" means Postgres canceled the chat request as the deadlock victim. "Stuck" means the migration was still retrying when the run was stopped, after 10 seconds unless noted. | Upgrade from | Migration | Chat requests | main | This PR | |---|---|---|---|---| | v2.38 (605) | 000609 | queued message insert | upgrade failed after 2m0s | request canceled after 1s, upgrade ok | | v2.38 (605) | 000609 | chat message insert | stuck | request canceled after 1s, upgrade ok | | v2.38 (605) | 000609 | chat message insert that waited 1.2s before 000609 started | stuck (stopped after 1 minute) | migration canceled after 1s | | v2.38 (605) | 000609 | chat message insert and queued message insert | stuck (stopped after 1 minute) | migration canceled after 2s | | v2.38 (605) | 000615 | read `users`, then `chats` | stuck | request canceled after 1s, upgrade ok | | v2.38 (605) | 000615 | read `users`, then `chats`, plus a chat message insert | stuck (stopped after 1 minute) | migration canceled after 2s | | 607 (main build) | 000609 | queued or chat message insert | stuck | request canceled after 1s, upgrade ok | | 610 (main build) | 000615 | queued message insert | stuck | request canceled after 1s, upgrade ok | | 608, 610, 614 (main build) | 000609, 000611, 000615 as the first chat lock | the four cases in `TestMigrationChatTablesConcurrentTraffic` | no deadlock | 2, 1 and 1 of 4 deadlock; in the 000615 case Postgres canceled the migration, in the others a chat request | </details> > 🤖 This PR was created with the help of Coder Agents, and has been reviewed by a human. 🏂🏻 |
||
|
|
389cfeef2f |
fix(coderd): generate chat titles for users without the owner role (#32738)
Automatic title generation only works for chats created by a user with
the Owner role. For anyone else the chat keeps its fallback title (the
first message, truncated), and the only sign is a warning in the coderd
logs:
```
[warn] coderd.chatd.processor: failed to resolve model for automatic title generation ...
error= resolve fallback chat model for title:
- get AI provider:
- unauthorized: rbac: forbidden: ...
```
`GenerateChatTitleForMessagesAsync` runs its goroutine as the user who
made the request, and resolving the title model reads the `ai_provider`
row, which only Owners can read. Setting a title generation model
override doesn't help, as resolving the override reads the provider too.
To fix, we'll run the goroutine as chatd, as `ProposeChatTitle` already
does for the same reason. The model config lookup still loads the chat
owner's subject, so the owner's access still decides which model the
title call can use. That lookup now has the owner's full scope, where
before it had the scope of the API key that made the request.
`TestPostChats_AutomaticTitleGeneration` now creates the chat as a
member and asserts on the stored title, instead of waiting for the title
request to reach the provider.
I've confirmed this on a dev server (`./scripts/develop.sh`, one OpenAI
provider, `gpt-4.1-mini` as the default model, no title generation model
override), creating chats through the API on the same database before
and after the fix:
| Commit | Chat created by | Title |
|---|---|---|
| `6603069e8b` (`main`) | `admin` (Owner) | Generated after 2s: "Why the
sky is blue" |
| `6603069e8b` (`main`) | `member` (no roles) | Still the fallback after
90s, and coderd logged `failed to resolve model for automatic title
generation` |
| `549cbdfafb` (this PR) | `member` (no roles) | Generated after 2s:
"Why the sea is salty" |
It also reproduces on dogfood, where I don't have the Owner role: a chat
I created there on `main` kept its fallback title.
|
||
|
|
d4e66907c4 |
refactor(coderd/x/chatd/chatwebhook): keep only the Standard Webhooks verifier (#32614)
--- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
39a4b4d90c |
fix(coderd/schedule/cron): compare reserved zone names without case (#32087)
--- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
13f5cc7872 |
fix(coderd/telemetry): give the reporter its own HTTP transport (#32160)
--- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
4186344631 |
test(coderd/provisionerdserver): start the MatchTags deadline after database setup (#32722)
## TL;DR `TestAcquirer_MatchTags` sometimes fails with `context deadline exceeded` before it checks anything. The test started its 10 second deadline first and created its test database second. When the database took 10 seconds or more to create, the deadline had already passed by the time the test ran its first query. This PR starts the deadline after the database exists, so slow database setup no longer fails the test. Refs https://linear.app/codercom/issue/CORE-713/flake-testacquirer-matchtagsuser-scoped-provisioner-and-user-scoped <details> <summary>How to navigate this PR</summary> - One test file, no production code. - Read `coderd/provisionerdserver/acquirer_test.go`, inside the subtest loop of `TestAcquirer_MatchTags`. One line moves below `dbtestutil.NewDB`, and a two-line comment says why. </details> <details> <summary>Implementation</summary> - `coderd/provisionerdserver/acquirer_test.go`: the `testutil.Context(t, testutil.WaitShort)` line in `TestAcquirer_MatchTags` now comes after `dbtestutil.NewDB(t)`. - Nothing between the old and the new position uses the context, so what the test checks is unchanged. - `TestAcquirer_Store` in the same file already creates its database first. - The deadline is not made longer. A longer deadline would only make the failure less likely, because database setup has no upper limit that a fixed value could cover. - Other tests in the repository create a short deadline before `dbtestutil.NewDB` in the same way. They are left for a separate change. </details> <details> <summary>Expected Output</summary> - When creating the test database takes longer than 10 seconds, every `TestAcquirer_MatchTags` subtest still passes. - The test still gives each subtest 10 seconds for the part that checks tag matching. - A subtest with a wrong expectation still fails. A provisioner that should not get a job, but is expected to, fails at the `AcquireJob` assertion when the deadline ends. </details> <details> <summary>Testing</summary> - No test was added. The change is to the test itself. - The recorded failure: `test-go-pg (windows-2022)` in the nightly workflow, [job 111783661367](https://github.com/coder/coder/actions/runs/37316261411/job/111783661367). The subtest failed at its first insert in the same millisecond the pubsub became ready, after 10 to 14.6 seconds of setup. - Reproduced on `main` on macOS with a local PostgreSQL 17. In a run of 20 repeats with `-parallel=16`, 16 subtests failed at the same line with the same message. They were exactly the 16 whose database copy took over 10 seconds. - With a temporary 10.5 second delay before database creation in every subtest (not part of this PR): - `main`: 42 of 42 database subtests failed at the same line. - This change: 44 of 44 subtests passed. - This change without the delay: 20 repeats passed, 440 of 440 subtests. - Mutation check: with the expectation of one "no match" case set to "match", that subtest failed at the `AcquireJob` assertion. - On this branch: `go test ./coderd/provisionerdserver -run '^TestAcquirer_' -count=3 -parallel=16` passes. - Not covered: the Windows and macOS lanes run only in the nightly workflow, so they have not run on this branch yet. </details> |
||
|
|
f32341ea4e |
fix(coderd/notifications): do not fetch after a graceful stop (#32627)
## TL;DR Fix a race condition where the notification sender could fetch another batch after graceful shutdown was requested, delaying shutdown and causing intermittent `TestBackpressure` failures. Refs https://linear.app/codercom/issue/CORE-718/flake-testbackpressure ## Changes - Check the graceful context before fetching a new batch. - Allow in-flight batches to complete and persist their results before shutdown. - Leave `quartz` and other `TickerFunc` callers unchanged. - Add `TestNotifier_NoFetchAfterGracefulStop` to verify that a late ticker callback does not trigger another fetch. ## Testing - New regression test fails without the fix and passes with it. - Notifier tests pass with `-race -count=5`. - `golangci-lint` reports zero issues. - Reproduced the original CI failure under high concurrency. - With an artificially widened race window: 10/10 failures before the fix, 0/20 after the fix. - Database-backed tests were validated on an earlier commit but have not been rerun on this branch. |
||
|
|
27eecbf092 |
fix(coderd): stop logging whole objects in authorization denials (#32526)
Linear: [PLE-94](https://linear.app/codercom/issue/PLE-94). Dogfood Loki holds plaintext credentials because several log call sites emit secrets. This is one of three independent PRs split out of the original masking change. ## Root cause Both "requester is not authorized to access the object" warnings in `coderd/authorize.go` logged `slog.F("object", object)`, the raw `rbac.Objecter`. When the caller passes a database row, every field is dumped, e.g. `oauth2_client_secret` on `database.MCPServerConfig`; any Objecter row with a secret field leaks. `actor_name` was also the whole `rbac.Subject` (expanded roles, groups and email), which duplicated the `roles`, `actor_id` and `scope` fields; it dates to a mechanical rename of `roles.ActorName` in #12816. ## Fix Log `object.RBACObject()` (type, id, owner, org), and log `roles.FriendlyName` (the username, or the name of an internal actor) as `actor_name`. Sibling PRs (independent, disjoint files): - https://github.com/coder/coder/pull/32532 - https://github.com/coder/coder/pull/32533 ## Follow-ups not included - AI Gateway prompt, tool and thought content logged in `aibridgedserver.go` (~511-613) and `aibridge/recorder/log_recorder.go` - `rich_parameter_values` in `runner.go` (~443) - Proxy `response_body` in `aibridgeproxyd.go` (~1102) - Terraform `TF_LOG` output relayed to logs 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
7c7dd8fb63 |
chore: remove the retention start from the AI spend users response (#32687)
## Description Only the old spend page read `retention_start` from the per-user AI spend response, to limit its date picker. That page is gone, and the AI Gateway retention endpoint now serves this purpose, so the field is removed. The server still narrows a default period to the retention and rejects an explicit one that starts before it. Related to AIGOV-729 ## Changes - Remove `RetentionStart` from `codersdk.OrganizationAISpendReport`. - Keep the retention start local to `aiSpendRetainedPeriod`, its only reader. - Regenerate the API docs and TypeScript types, and update the tests and mocks. Depends on #32686. > [!NOTE] > Generated by Coder Agents on behalf of @ssncferreira. |
||
|
|
dfe6402910 |
feat: add an AI Gateway data retention endpoint (#32659)
## Description Pages that read raw AI Gateway data and have a date picker don't handle data retention consistently. AI Sessions allows start dates whose data is already purged. AI spend only learns the retention after a request. The new AI spend page reads aggregated data, which is never purged, in some views and raw data in others. For consistency, the Overview and Detailed report tabs should accept the same date range, so both are limited to the retention. The retention is in the deployment config, but only Owners can read it. This adds an experimental endpoint that returns only the retention, so these pages can offer only retained dates. ## Changes - Add `GET /api/experimental/ai-gateway/retention`, returning `retention_ms`. Zero means data is never purged. - Any authenticated user with the AI Gateway feature can read it, since it holds no usage data. - Add `codersdk.AIGatewayRetention` and the `ExperimentalClient.AIGatewayRetention` method. > [!NOTE] > Generated by Coder Agents on behalf of @ssncferreira. |
||
|
|
74a15cbcaa |
feat: adopt OpenTelemetry GenAI semantic conventions for Coder Agents traces (#32411)
Aligns Coder Agents traces with the [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) so customers can ingest per-user model usage, spend, and tool activity without custom mapping. Scope follows the requesting team's Slack ask: agent spans, inference spans with token usage, GenAI attributes, per-user attribution, and visibility into tools that cannot be reached. Closes CODAGT-1523. ## Changes - Span names follow the conventions: `chat_turn` becomes `invoke_agent coder`, `stream` becomes `chat {model}`, and `tool_call` becomes `execute_tool {tool}`. Every stage span now carries a `stage` attribute with the old stage name, which matches the Prometheus `stage` label. Metrics are unchanged. - GenAI spans carry `gen_ai.operation.name`, `gen_ai.conversation.id` (the chat ID), `user.id` (the chat owner), and `coder.organization.id`, `coder.workspace.id`, `coder.chat.parent_id`, `coder.chat.root_id`. - `chat` spans are `CLIENT` spans with the provider, request model, and `gen_ai.request.stream` set at creation (so samplers can see them), plus requested max tokens and temperature, response ID (including OpenAI Responses metadata on non-streaming calls), the finish reason the provider reported (omitted when none, kept when Coder rejects the response), `gen_ai.output.type=json` for native OpenAI structured output, and token usage with cache read/write (only when nonzero) and reasoning breakdown. `gen_ai.usage.input_tokens` includes cached tokens, as the spec requires. Fantasy reports them separately (Google providers use the OpenAI-compatible client, which does the same). - `execute_tool` spans carry the tool name, call ID, and type (`function` for built-in tools, `extension` for MCP and caller tools), all set at creation. - Every model call records a `chat` span: assistant streams (`stage=stream`), and, as `stage=model_call`, the advisor, compaction summaries plus titles, status labels, and chat summaries (via `StageTracer.TraceModelCalls` in `resolveModelCall`). `model_call` has no histogram, so the `stream` metric is unchanged. - Failed spans get `error.type`. A tool that returns an error result, as MCP clients do for an unreachable server, ends its span with `error.type=tool_error` without recording the result text. - GenAI attributes carry metadata only; prompts, responses, and tool payloads are not recorded. The docs note that other spans and events in the trace, such as AI Gateway spans and server log events, can contain content. - Docs state known limits: Anthropic server-tool responses undercount input tokens in both spans and AI Gateway cost control (the client keeps first-iteration occupancy), the OpenAI-compatible client drops reported cache writes, request attributes are what Coder requested, and the exporter is OTLP/gRPC, plaintext unless a certificate is configured. - New docs page: `docs/coder-agents/platform-controls/opentelemetry-tracing.md`. - `coderd/x/chatd/ARCHITECTURE.md` gains a GenAI semantic conventions subsection under Lifecycle tracing. Existing attributes (`provider`, `model`, `chat_id`, `tool_name`, ...) are kept so current queries on attributes keep working. Queries on span names need to switch to the `stage` attribute or the new names. <details> <summary>Decision log</summary> - **Convention version:** semconv v1.41.0, the last core release that ships the GenAI attributes. Later releases moved them to `semantic-conventions-genai`. The PR uses the Go constants from `go.opentelemetry.io/otel/semconv/v1.41.0`, which is already in the module graph. No experiment gate: chatd is already under `x/`, and the docs page notes that the conventions may change. - **Rename vs. attributes only:** spans are renamed because the conventions define the span names. The `stage` attribute keeps lifecycle identity stable for dashboards and tests. - **Agent name:** `gen_ai.agent.name=coder` for root chats and subagents alike. `chat_kind` and `coder.chat.parent_id` tell them apart. - **Provider name mapping:** configured provider type to well-known values (`openai`, `anthropic`, `azure.ai.openai`, `aws.bedrock`, `gcp.gemini`). Anthropic providers with Bedrock settings report `aws.bedrock`. The `invoke_agent` span gets the provider after `prepare` resolves the turn's model, since the turn span starts first. Other types (`openrouter`, `openai-compat`, `vercel`, `copilot`) are passed through as-is. - **No content capture:** `gen_ai.input.messages`, `gen_ai.output.messages`, and tool arguments/results are opt-in in the conventions and not needed for usage and spend attribution, so they are left for a follow-up behind an explicit deployment flag. - **Out of scope:** GenAI metrics (`gen_ai.client.token.usage`, `gen_ai.client.operation.duration`), an aggregated token total on the `invoke_agent` span, a cost attribute, span links between subagent and parent traces, and correlation IDs with AI Gateway interceptions (an open question in the issue). Subagent turns join the parent only through `coder.chat.root_id`; a span link needs the spawning span context persisted across chats and runners. Spans carry tokens, not cost; cost stays in the existing cost API. - **Identity snapshot:** chat identity is taken when the turn opens. A workspace created mid-turn appears on spans from the next turn. </details> --- Generated by Coder Agents on behalf of @f0ssel. |
||
|
|
c484ad2be4 |
fix: keep the provisioner key secret out of request paths and logs (#32532)
Linear: [PLE-94](https://linear.app/codercom/issue/PLE-94). One of three independent PRs split out of the original masking change. ## Root cause `codersdk.Client.GetProvisionerKey` sent the real provisioner key secret in the URL path (`/api/v2/provisionerkeys/<key>`) as well as in the `Coder-Provisioner-Daemon-Key` header. The path ends up in proxy/access logs, the server request logger (`path`, `params_provisionerkey`) and the SDK's `sdk request` debug log. The server ignores the path value: the route uses `ExtractProvisionerDaemonAuthenticated` and `fetchProvisionerKey` returns the header-authenticated key. Nothing reads `{provisionerkey}` on that route (`ExtractProvisionerKeyParam` is only mounted on the org-scoped route, where the value is a key name). ## Fix - The SDK now sends a fixed placeholder segment, `/api/v2/provisionerkeys/me`; the secret travels only in the header. Old servers ignore the path, and old clients still work with new servers. - `loggermw` masks the `provisionerkey` route param (keeping at most a 4 character prefix) in `params_*` and `path` as a backstop for old clients. It only applies when the route pattern is the top-level `/provisionerkeys/{provisionerkey}`; the org-scoped `/organizations/{organization}/provisionerkeys/{provisionerkey}` carries a key name and is left alone. - Swagger annotation and generated docs now describe the path param as an ignored placeholder (edited by hand, not via `make gen`). Sibling PRs (independent, disjoint files): - https://github.com/coder/coder/pull/32526 - https://github.com/coder/coder/pull/32533 ## Follow-ups not included - AI Gateway prompt, tool and thought content logged in `aibridgedserver.go` (~511-613) and `aibridge/recorder/log_recorder.go` - `rich_parameter_values` in `runner.go` (~443) - Proxy `response_body` in `aibridgeproxyd.go` (~1102) - Terraform `TF_LOG` output relayed to logs 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
d1487f62f1 |
fix: resume workspace context push after coderd rejects it (#32534)
When coderd rejected a workspace context push, the agent kept resending the same snapshot until it restarted, so fixing the bad file on disk did not resume sync. Each retry now rebuilds the request from the newest snapshot. coderd returns `InvalidArgument` for validation failures, and the agent then waits for the next change instead of retrying. `Initial` stays set until a push succeeds. A new agent talking to an old coderd gets no code and keeps retrying, now with the newest snapshot. Fixes CODAGT-1640. Touches `agent/agentcontext/push.go`, as #31831 does. <details> <summary>Plan context</summary> This is unit A1 of the Agent Plugins plan (CODAGT-1101, parent CODAGT-1639): fix workspace-context bugs on main before adapting the plugins stack, because plugins add more ways for coderd to reject a push. - Scope: retry with the newest snapshot when files change; coderd marks validation errors as permanent so the agent waits for the next change. - Not included: showing the rejection in the chat or the context panel. - Verify: unit tests with a fake pusher and a mock clock. Revert: plain revert, no data. </details> --- Generated by Coder Agents on behalf of @f0ssel. --------- Co-authored-by: Garrett Delfosse <garrett@coder.com> |
||
|
|
52427e8fd6 |
test(coderd/x/chatd): give TestProjectSkillsFollowProjectAccess a longer context (#32276)
`TestProjectSkillsFollowProjectAccess` runs six sequential model turns on one context created with `testutil.WaitLong` (25s). In a recent CI run ([job](https://github.com/coder/coder/actions/runs/43909622615)) the turns took about 35s, so the context expired just as the last turn was sent. The chat finished normally (its final update was published about 4s later), but every `GetChatByID(ctx, …)` inside `waitForChatProcessed` then returned a deadline error, which the condition treats as not yet processed, so `require.Eventually` failed with "Condition never satisfied". Use `testutil.WaitSuperLong`, as other multi-turn chatd tests do. --- _Generated by [Claude Code](https://claude.ai/code/session_01VpiVZBgFqiSdRKrH8dPSPT)_ Co-authored-by: Garrett <garrett@coder.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
dcbe84a23b |
feat: add organization member AI spend endpoint (#32203)
Adds `GET /api/v2/organizations/{organization}/members/{user}/ai/spend`,
which returns a user's effective AI budget and current-period spend
inside one organization. Admins, and users themselves, can use it to
look up spend in a specific organization.
The endpoint resolves the budget inside that organization only, the same
way AI Gateway resolves a request made there. The response has the same
shape as the user spend endpoint, plus `organization_id`.
Users can read their own spend, and admins can read the spend of a user
whose membership in that organization they can read. The endpoint
returns 404 when the user isn't a member of the organization, or when
the caller can't read the user. It requires the AI Governance license.
Organization admins can read every user, so only the organization and
membership checks keep them out of other organizations. The tests cover
both sides: an organization admin reading a member of their own
organization (200) and of another organization (404).
Also adds `Client.OrganizationMemberAISpendStatus` to `codersdk`, and
links the endpoint from `cost-controls.md`.
Stacked on #32202, which adds `GET
/users/{user}/ai/spend/organizations`. Review only the last two commits
here.
Refs [AIGOV-766](https://linear.app/codercom/issue/AIGOV-766)
---
*Generated by Coder Agents on behalf of @SasSwart.*
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
1b9f2d8181 |
feat!: add the client to the AI spend CSV export (#32474)
## Description
Adds the client to the stable `GET
/api/v2/organizations/{organization}/ai/spend/export` CSV export, so the
Detailed report page (https://github.com/coder/coder/pull/32482) can
export the same data with the same filters.
## Changes
- `ExportOrganizationAISpend` groups rows by client as well, and takes a
`client` filter. Usage without a recorded client is reported as
`Unknown`, like `/ai/spend/users`.
- The export accepts a `client` query parameter, and adds a `client`
column at the end of the CSV, so existing columns keep their position.
- `OrganizationAISpendDetailsFilter` takes a `Client`.
- Update the Spend export docs and the query and handler tests.
## Breaking change
The AI spend CSV export (`GET
/api/v2/organizations/{organization}/ai/spend/export`) now has a
`client` column at the end, and splits rows by it.
If you rely on one row per user, group, model and provider, sum
`cost_micros` and the token columns across clients to get the previous
totals.
Closes AIGOV-733
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
|
||
|
|
c236edcb8d |
feat: add per-organization AI spend endpoint (#32202)
Adds `GET /api/v2/users/{user}/ai/spend/organizations`, which returns a
user's AI budget and current-period spend in each of their
organizations. The avatar menu uses it to show spend to users who belong
to more than one organization (#32204).
The response lists each organization the user is a current member of and
the caller can read, sorted by name. Each entry has the effective group,
budget, and spend that AI Gateway resolves for a request in that
organization. When no group budget applies, the effective group is the
organization's `Everyone` group. `organization_id` names the
organization of the user's site-wide effective group, so the menu opens
on the numbers the user sees today. It's null when that organization
isn't in the list.
`GET /users/{user}/ai/spend` is unchanged. Its API docs now say that it
resolves the site-wide effective group, and point to the new endpoint
for the per-organization breakdown.
dbauthz filters the user's organizations to those the caller can read,
so an organization-scoped admin only sees the organizations they
administer. The handler queries spend only for those organizations. A
new query, `GetUserAISpendByEffectiveGroupsSince`, reads the spend for
all of them in one call. It reads existing tables, so there's no
migration, and dbauthz checks it the same way as `GetUserAISpendSince`:
the caller must be able to read the user.
Refs [AIGOV-766](https://linear.app/codercom/issue/AIGOV-766)
<details>
<summary>Decisions</summary>
- **Separate endpoint.** An earlier version of this PR added
`organizations` and `organization_id` to `GET /users/{user}/ai/spend`.
Following review, the breakdown moved to its own route ([AIGOV-766
comment](https://linear.app/codercom/issue/AIGOV-766/show-spend-per-org-to-users-in-several-orgs#comment-6855c55c)).
Because the breakdown depends on who is asking, a dedicated route keeps
the existing endpoint's response the same for every caller.
- **`organization_id` on the new response.** The comment's schema left
it out, but its frontend notes and its test rely on it, so the response
includes it.
- **Existing endpoint left as on `main`.** An organization-scoped admin
can still see a user's site-wide effective group, budget, and spend
through `GET /users/{user}/ai/spend`, even when that group is in another
organization. The earlier version of this PR hid those fields; this
version keeps the existing behavior, as the review asked.
- **Authorization check.** dbauthz post-filters
`GetOrganizationsByUserID` with `read` on each organization. The
endpoint itself requires read on the user, as the existing spend
endpoint does.
- **Empty result.** A caller who can read the user but none of their
organizations gets `200` with an empty `organizations` list and a null
`organization_id`, so the response doesn't reveal that memberships
exist.
- **Per-organization spend.** Each entry reports spend on the user's
current effective group in that organization, which is what budget
enforcement compares.
</details>
---
*Generated by Coder Agents on behalf of @SasSwart.*
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
c5af20be31 |
test: copy test databases by file and start test deadlines after setup (#32426)
## Summary Mitigate Windows nightly timeout bursts caused by slow test database creation. Multiple tests were hitting `context deadline exceeded` because their 10-second deadlines started before database setup completed. Refs https://linear.app/codercom/issue/CORE-615 ## Changes - Use `STRATEGY FILE_COPY` for test database creation on PostgreSQL 15+, avoiding the more expensive default `WAL_LOG` strategy. PostgreSQL 13/14 remain unchanged. - Cache the PostgreSQL version lookup, preserving existing behavior if detection fails. - Log database copies exceeding 2 seconds, including duration and strategy. - Move context creation after database/server setup in affected WebPush, OIDC, notification, and prebuild tests, without changing timeout values. - Add unit tests for PostgreSQL version-based strategy selection. Test-only changes across 6 files; no production code changes. ## Validation - Local PostgreSQL 17.10 tests pass, including WebPush, prebuild reconciliation, OIDC, and notifications. - `go vet` and `golangci-lint` report no issues. - Local OIDC comparison: - Default strategy: 3–5 failures/run. - `FILE_COPY` with partial context fixes: 1–2 failures/run. - **Final implementation: 0 failures across 5 runs**, with maximum database creation time reduced from 13.3s to 8.9s. ## Remaining Work - Run `nightly-gauntlet` repeatedly to verify improvements on Windows and macOS. - Compare WAL volume, checkpoint overhead, and test durations. `FILE_COPY` increases checkpoints, though local database creation was faster. - Confirm PostgreSQL 13 and 17 Linux jobs pass. **Status:** Draft pending nightly validation. |
||
|
|
5b82b04a78 |
fix(coderd): use a port outside the OS range in the TCP dial failure test (#32541)
## Summary Fixes a flaky `TestServerTailnet_ReverseProxy_TCPDialFailure` (~2% CI failure rate) caused by a port race. Previously, `testutil.RandomPort` selected a port by briefly opening and closing a listener. Another parallel test could claim that port before the connection attempt, causing an unexpected success instead of a connection refusal. This PR introduces `closedPort`, which selects an unused port from **20000–29999**, outside the default ephemeral port ranges on Linux, macOS, and Windows. It checks both `127.0.0.1` and `::1`, since the agent may attempt either address. Refs [CORE-756](https://linear.app/codercom/issue/CORE-756/flake-testservertailnet-reverseproxy-tcpdialfailure) ## Changes - Add `closedPort` in `coderd/tailnet_test.go` and replace the `testutil.RandomPort` call. - Skip ports already accepting connections on IPv4 or IPv6. - Keep existing assertions unchanged. No production code changes. **Limitation:** This mitigates rather than eliminates the race. Another process could explicitly bind the selected port after the check, although the OS will not assign it automatically as an ephemeral port. ## Testing | Scenario | Result | |---|---| | Before fix: 9,600 parallel Linux runs | 1 failure | | After fix: 9,600 parallel Linux runs | **0 failures** | | Ports 20000 and 20001 occupied | Pass; selects 20002 | | Remove expected dial log fields | Test fails as expected | | macOS: 20 consecutive runs | Pass | | `golangci-lint` | 0 issues | Windows remains untested. ## Expected Behavior The test continues to verify that a failed TCP dial returns HTTP 502 and logs `agent_id`, `dial_phase=tcp_dial`, and `tcp_dial_after`, while reducing failures caused by port collisions. |
||
|
|
e35a124b0d |
feat: report database migration outcome (#31849)
Nothing said how a migration run ended. On failure, the CLI printed the PostgreSQL error with the failing SQL, but not which migration failed or whether anything was saved. After a failed run, the reporter asks PostgreSQL how the transaction ended (`pg_xact_status` on the captured transaction ID, plus the saved schema version). Every run logs one outcome line: committed, rolled back, committed before failure, unknown, lock timeout, dirty schema, or failed before start. Every failure line has an `error` field. The error names the failed migration and gives PostgreSQL's short message and SQLSTATE, without the SQL or detail text, which can contain row values. ``` [info] committed database migrations status=success count=2 from_version=1 final_version=3 transaction_status=committed total_duration_ms=0 [erro] migration failed, transaction rolled back, no changes saved status=failure count=1 version=3 name=step_3 final_version=1 sqlstate=23505 transaction_status=aborted total_duration_ms=0 failed_duration_ms=0 error="migration 3 (step_3): migration failed: duplicate key value violates unique constraint \"a_pkey\" (sqlstate=23505)" ``` Closes ENT-236 _Written with Claude Code and Coder Agents, reviewed and tested by @kirstaeff._ |
||
|
|
5f5c30eafb |
fix(coderd/x/chatd): prefer native subagents over ACP harnesses (#32604)
Agents sometimes call `acp_spawn_agent` when a native subagent (`spawn_agent`) could do the job, even when the requested model is available natively. This adds one line to the `<acp-subagents>` system prompt block: "Prefer using non-ACP subagents unless the user asks for an ACP harness or if the requested model is only available through ACP." Tests reference `acpSubagentPromptBlock` by constant rather than by text, so no test changes are needed. |
||
|
|
6a45e8c8d1 |
feat: log migration progress and heartbeat (#31789)
Migrations run at server startup with no output, so admins can't tell which migration is running, whether it waits on a lock, or how far it got. This adds a reporter to the migration driver. It logs: - the pending migrations, and each step with its position and duration; - the migration lock (debug level); - a heartbeat every 10s during a lock wait or a long step, with the connection state from `pg_stat_activity` and the blocking sessions. The migration transaction is named `coder-migrate/<version>`, so other instances and admins can see it. Heartbeat queries run on their own connection and never delay the migration. API: `Up(db, opts...)`, with `WithFS` (replaces `UpWithFS`) and `WithLogger`. Without a logger, nothing is logged. Server startup turns it on in #31790. ``` [info] database migration required from_version=1 target_version=3 pending=2 [info] applying database migration version=3 name=step_3 position=2 total=2 [info] still applying database migration elapsed_ms=1000 state=waiting_on_lock wait_event=relation blocked_by=[blocker] version=3 name=step_3 position=2 total=2 [info] database migration applied, pending commit version=3 name=step_3 position=2 total=2 duration_ms=1000 ``` Tests compare log output with golden files in `coderd/database/migrations/testdata/reporter`. Closes ENT-235 _Written with Claude Code and Coder Agents, reviewed and tested by @kirstaeff._ |