mirror of
https://github.com/coder/coder.git
synced 2026-11-21 18:58:17 +08:00
feea5ab959f59cd2135443ed2a0c19bf7643db8f
1902
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7c7e2e73cf |
feat: honor disable-model-invocation in uploaded skill content (#31159)
Addresses @ethanndickson's [review comment on #30882](https://github.com/coder/coder/pull/30882#discussion_r4344815088): the same `SKILL.md` file could be manual-only in Claude Code and the project dialog but automatic in Coder, because the server and the browser each handled `disable-model-invocation` in their own way. The server now owns the key for personal, organization, and project skills: - When a create or update request leaves `model_invocable` unset, `disable-model-invocation: true` in the content turns automatic use off, and `false` turns it back on. The key is read with the function workspace skills use, so a file gets the same setting in both places. Only YAML booleans count, so a quoted `"true"` is ignored. - An explicit `model_invocable` in the request always wins. - New content without the key leaves the setting unchanged, so editing text never turns it back on. - Content is stored as uploaded. Every API response returns content whose key agrees with `model_invocable`: when the stored file says otherwise, the server replaces the value of the key or adds the key before the first one, and leaves every other byte alone. - **Download** and **Export all** save the content the API returns, so the browser no longer edits the file. `withDisabledModelInvocation` is removed. - An upload is rejected with a 400 when the key holds a value the server can't replace with a boolean, such as a list. A later change to `model_invocable` can then always reach the file. Two edges: - Adding the key makes the returned file about 30 bytes larger, so a file at the 64 KB upload limit can be too large to upload again. - A skill stored before the upload check with a value the server can't replace is returned as stored. Workspace skills already honor the key since #31147. #31160, the frontend PR on top of this one, adds the switch to the personal and organization skill editors. > Generated by an agent on behalf of the user --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
99e3bf91a7 |
fix(coderd/database/migrations): resolve duplicate version (#32329)
Main cannot initialize database migrations because #32309 reused version 000643, already taken by the skill display-name migration from #31747. Renumber the later chat-project migration and its fixture to 000644, preserving the earlier migration number. All three renames leave SQL contents unchanged. |
||
|
|
3211ca066e |
feat: add organization unpriced AI models endpoint (#31753)
## Description
Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/model-prices/unpriced`
endpoint behind the "N models not set up" warning on the organization AI
spend page
([Figma](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=70-11964&t=KQwENGjcQvVT9qkh-4)).
It lists the models used in the period that still hold no price in the
organization, using the query from this stack.
## Changes
- Add the `organizationUnpricedAIModels` handler and
`ExperimentalClient.OrganizationUnpricedAIModels`:
- Reuses `aiSpendRetainedPeriod`, since token usage is subject to data
retention.
- Returns the applied period, `count`, and `models` (provider name,
display name, icon and type, model, token count), most unpriced tokens
first.
- Requires read on the organization's model prices (owners and
organization admins), so the UI only requests it for users who can set
prices.
- Add handler tests for the response, period validation, organization
scoping and role access.
Note: pagination will be added in a follow-up.
Closes AIGOV-730
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
|
||
|
|
1f1aa6ae3c |
feat: add chat project template schema and queries (#32309)
Adds the database layer for attaching workspace templates to chat projects: the schema, the queries, their authorization, and the audit type. Nothing calls the new queries yet, and the existing create and update handlers pass the new parameters unset. The API, the limit's enforcement, and the agent tools follow in the PRs above. - Attachments live in a `chat_project_templates` table (`project_id`, `template_id`, `created_by`, `created_at`), deleted with the project or the template. `chat_projects` gains `limit_templates` (default `false`), `default_template_id`, `default_template_version_preset_id`, and `default_parameters jsonb`. A project stores a default preset or default parameter values, not both. - `InsertChatProjectTemplates` needs project `update` and `use` on every template. It skips templates that are already attached, and templates outside the project's organization, so an attachment never crosses organizations. `DeleteChatProjectTemplate` needs project `update` and template `read`, and clears the project's default when it detaches the default template. Both checks are in dbauthz. - `GetChatProjectTemplatesByProjectIDs` is authorized through the project, and leaves out deleted, deprecated, and agent-disabled templates. It does not check the caller's access to each template, so callers do that before they expose one. - `UpdateChatProjectByID` changes the template settings only when the request sets them, so an update that omits them cannot write back a stale snapshot. - `AuditableChatProjectTemplates` is the audit form of a project's attached templates, logged as a write to the project. The new `chat_projects` columns are tracked in the project's own audit diff, with the default parameter values masked because they may hold credentials. **NOTE**: the migration adds one table and four columns and changes no existing rows. Existing projects keep unlimited template access. Stack (merge top to bottom): - #32309 👈 - #30754 - #32310 - #30755 - #30756 - #30898 |
||
|
|
c3ff770e8a |
fix(coderd/database): match workspace requester by owner ID when sorting (#32188)
GetWorkspaces sorted the requester's favorite and own workspaces first by matching the owner's username. Usernames are unique only among non-deleted users, and a deleted user keeps theirs, so a user who took a deleted user's username saw that user's deleted workspaces and favorites sorted as their own when listing deleted workspaces. Match by owner_id instead, as the sort did before #22290. The username form most likely worked around the sqlc CTE bug: with the EXISTS (tasks) filter the query had then, sqlc without the coder/sqlc fix rejected the bare owner_id as ambiguous. #29085 removed that filter, so the owner_id form generates with either sqlc. |
||
|
|
4866d0fb1f |
feat: add display names to project skill actions (#31747)
closes CODAGT-1506 Project skill action chips show the skill's slug (`deploy-bot`, `security-review`), because skill names must be kebab-case. This adds an optional display name that labels the chip instead. Project skills get a `display_name` column, set through `display_name` on the create and update requests. It is limited to project skills (the same rule as `action`), trimmed, single line, and at most 64 Unicode code points. The chip, its tooltip, and the "More" menu show the display name, sort by it, and fall back to the skill name when it is empty. When a display name is set, the tooltip and the menu item also show the `/name` slash command, so actions that share a display name stay distinguishable. Clicking an action still inserts `/name`, and the `/` menu is unchanged. The project skill editor shows a **Display name** field under **Show as action** only while that switch is on. Turning the switch off hides the field but keeps its value, and saves omit `display_name` while the action is off, so the stored value stays. The display name lives in the database rather than SKILL.md frontmatter, so downloading and re-importing a skill does not carry it. To share the code-point length check with the editor, `countCharacters` and `maxCharacters` move from `ChatProjectDialog.tsx` into `site/src/utils/formUtils.ts`. <img width="637" alt="Project skill editor with the Display name field under Show as action" src="https://raw.githubusercontent.com/coder/coder/assets/pr-skill-action-display-name/pr/edit.png" /> <img width="520" alt="Action chips labeled with display names, with the tooltip open" src="https://raw.githubusercontent.com/coder/coder/assets/pr-skill-action-display-name/pr/chips.png" /> Refs CODAGT-1506 |
||
|
|
3795d72713 |
fix: search AI Gateway models and clients by substring (#32159)
Closes AIGOV-801 Typing `hai` into the model filter on the AI Gateway sessions page shows the haiku models for a moment, then "No models found". Whilst the debounced request is pending, the menu filters the options it already has by a case-insensitive substring, but `GET /api/v2/ai-gateway/models` only matched a case-sensitive prefix, and Bedrock identifiers start with `anthropic.`. The client filter matched the same way, so it had the same problem. To fix, both endpoints now match a case-insensitive substring. This needed one change to the model menu. When the page loads with a model already in the filter, the menu used to look that model up on the server, by searching for its name and taking the first result. That's the same pattern as the user filter, where the lookup fetches the avatar, but a model option needs nothing from the server, so all it did was check that the model exists. With a substring search, the first result for `claude-3-5-sonnet-20241022` can be `anthropic.claude-3-5-sonnet-20241022-v2:0`, so the check would fail for a model that does exist. The menu now skips the lookup and just shows the model from the filter as selected. The only visible difference is that a model name in the URL that doesn't exist now shows as selected, instead of "All models". The client menu has the same lookup, which still works, as no client name contains another, so I've left it alone. The prefix match was added in #22230 (models) and #22694 (clients) so the queries could use the B-tree indexes. That only works on a C collation database, and only for models, as the clients query wraps the column in `COALESCE`. On an `en_US.utf8` database it's a plain filter either way. On a C collation database a model search with no matches does get slower, from instant to a few seconds with 5M synthetic rows, but I think that's worth it for a search that works. |
||
|
|
0be6e7a034 | feat: add a setting for web terminal font size (#32027) | ||
|
|
b0ae8adab5 |
feat(coderd): protect pending jobs only while the provisioner queue is moving (#32099)
Stops the pending job reaper from failing jobs in a queue that's still moving. This is an alternative to #31469 that came out of Steven's [review](https://github.com/coder/coder/pull/31469#pullrequestreview-5847958482) asking whether 2h is enough, and it builds on George's work there. A pending job past 30m is now only protected while a matching online provisioner is making progress, meaning it finished a job in the last 30m or is running one that's still being updated. A moving queue never gets reaped and a frozen one still does at 30m like today. There's no absolute cap. No migration since it uses the existing `provisioner_jobs_worker_id_organization_id_completed_at_idx`. One tradeoff is that a stuck build whose provisioner keeps heartbeating counts as progress, so if every matching provisioner is stuck like that, the queue waits until that build is canceled. Still a draft so we can talk it through with Spike and Steven. Part of CORE-586 --------- Co-authored-by: George Katsitadze <george.katsitadze@gmail.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
4f6a56427e |
feat: report pubsub health from the pubsub backend (#31621)
Fills in the `pubsub` section of the deployment health report on the server. Stacked on #31620. - New `pubsub.ReportingPubsub` interface: `Pubsub` plus `HealthReport(ctx) healthsdk.PubsubReport`. The `Pubsub` interface itself is unchanged. - The PostgreSQL, NATS and in-memory backends implement it. Each reports its backend name (`postgres`, `nats` or `memory`) and its connection state: - **PostgreSQL:** tracks the `pq` listener's connected state from its event callback. When it's not connected, the report has severity `warning` and `EPS01`. - **NATS:** warns with `EPS02` if the embedded server isn't `Running()`, and with `EPS01` for each publish or subscribe connection whose `Status()` isn't `CONNECTED`. - **In-memory:** always `ok`. - `coderd.Options.Pubsub` is now a `ReportingPubsub`. `ReplicaSyncPubsub` stays a plain `Pubsub`. - `coderd/healthcheck` has a new `Pubsub` check, which counts toward `healthy` and the overall severity like the other sections. `formatHealthcheck` applies the dismissed setting for it. - New health codes `EPS01` (not connected) and `EPS02` (embedded NATS server not running), documented in `docs/admin/monitoring/health-check.md`. - Test helpers follow the type change: `coderdtest.Options.Pubsub` and the pubsub returned by `dbtestutil.NewDB` are now `ReportingPubsub`, and a few test wrappers embed `ReportingPubsub` instead of `Pubsub`. <details> <summary>Decision log</summary> - `HealthReport` returns a `healthsdk.PubsubReport` rather than filling one in place. This matches the `healthcheck.Checker` methods. `ctx` is unused for now. - The healthcheck layer sets `Dismissed`, so backends don't need to know about health settings. - Problems are reported as warnings, not errors, so they show on the health page without marking the deployment unhealthy. Both backends reconnect on their own. - Postgres connection state comes from the listener event callback, not from `pq.Listener.Ping`, so the health check doesn't do database I/O. Closing the pubsub also marks it disconnected. - NATS `conn` gains `Status()`, which `*natsgo.Conn` already implements. The pools are immutable after construction, so `HealthReport` reads them without locking. - The docs say the pubsub section appears in the JSON response, because the health UI doesn't show it until a later PR in this stack. - psmock is not regenerated: none of its users pass it to coderd. </details> --- Generated by Coder Agents on behalf of @spikecurtis. |
||
|
|
38e74c4506 |
feat: add agent-plugins experiment and Agent API v2.17 plugin messages (#29320)
Linear: [CODAGT-1101](https://linear.app/codercom/issue/CODAGT-1101/agent-plugins-read-only-support-behind-the-agent-plugins-experiment) **tl;dr:** Adds the `agent-plugins` experiment and the Agent API v2.17 messages that carry Agent Plugins data from the agent to coderd. First of eight stacked PRs adding read-only [Agent Plugins](https://agent-plugins.org/) v1.0.0 support. A plugin is a directory with a `plugin.json` manifest, skills under `skills/`, and an optional `mcp.json`. Across the stack, the agent discovers plugins in `plugins/` and `.agents/plugins/` under its scan roots (for example `~/.coder/plugins/<name>`), chatd lists their skills with plugin attribution, the agent runs the MCP servers of plugins in the workspace working directory, and the Agents page shows plugin attribution in the chat context. Hooks, commands, agents, install flows, and org-managed plugins are out of scope. Background: [research/agent-plugins-standard.md](https://github.com/coder/scott-misc/blob/main/research/agent-plugins-standard.md) (internal). This PR adds `codersdk.ExperimentAgentPlugins` and a `PluginBody` oneof variant on `ContextResource` (tag 18) that carries the validated manifest fields and nests the plugin's skills and MCP servers. `Manifest` gains `agent_plugins_enabled` (field 23), which coderd sets when the experiment is enabled; the agent discovers plugins only then. coderd stores each nested resource as its own row with the plugin's name in a new `plugin_name` column (migration 000642), which the hydrate, MCP sync, and re-pin queries copy. With the experiment off, `PushContextState` drops plugin resources and everything nested in them. Otherwise it rejects pushes with plugin names that fail `workspacesdk.ValidatePluginName` (the spec's name grammar, shared by agent and coderd), OK plugins without a name or with a duplicate name, a non-OK plugin that nests resources, nested entries of the wrong kind, plugin skill sources outside `<plugin source>/skills/`, and plugin MCP servers with an empty `server_name` or a source other than `<plugin name>/<server_name>`. Nested resources count toward the 1000-resource cap. Agents now dial v2.17, so a new agent needs a coderd that supports it, as with every Agent API minor. Turning the experiment off does not remove plugin data already pinned to existing chats. <!-- pr-map:start --> <details><summary>PR map</summary> `main..4b0cfc9657` | Category | Files | + | - | |---|---:|---:|---:| | prod (backend) | 15 | 342 | 78 | | test (backend) | 9 | 534 | 3 | | migrations | 2 | 14 | 0 | | generated (backend) | 7 | 1216 | 1027 | | generated (frontend) | 1 | 2 | 0 | | **Total** | 34 | 2108 | 1108 | 1. `coderd/agentapi/context.go` (+211/-51, API): drops plugin resources when the experiment is off; otherwise validates plugin names and nesting, and stores each nested skill and MCP server as its own row with the plugin's name. 2. `agent/proto/agent.proto` (+39/-9, API): `PluginBody` with nested `skills` and `mcp_servers`, and `Manifest.agent_plugins_enabled`. 3. `codersdk/workspacesdk/frontmatter.go` (+31/-0): `ValidatePluginName` and `MaxPluginNameLength` (manifest name grammar). 4. `coderd/database/queries/chats.sql`, `workspaceagentcontext.sql`, migration 000642 (+28/-7, DB): the `plugin_name` column on both context resource tables, copied by the hydrate, MCP sync, and re-pin queries. 5. `codersdk/agentsdk/agentsdk.go`, `agent/agent.go` (+18/-4, API): `Manifest.AgentPluginsEnabled` and `ConnectRPC217WithRole`; the agent dials v2.17. 6. `coderd/agentapi/api.go`, `manifest.go` (+4): the manifest flag follows the experiment. 7. `tailnet/proto/version.go` (+8/-1, API): Agent API v2.17. 8. `codersdk/deployment.go` (+4, API): the `agent-plugins` experiment. </details> <!-- pr-map:end --> --- This PR was generated by Coder Agents on behalf of @jscottmiller. Co-authored-by: Garrett Delfosse <delfossegarrett@gmail.com> |
||
|
|
d611c60a9a |
feat: scope unpriced AI models to an organization and its prices (#31752)
## Description Scopes `GetUnpricedAIModels` to an optional organization and checks organization prices, so the unpriced models endpoint can list what an organization still needs to price. Usage is attributed to an organization through its token usage's effective group, the same as spend. ## Changes - Optional `organization_id`: when set, only that organization's usage counts, and when null (the notification), all usage counts. - A model still holds a price if it has a site-wide price for the provider type, or an organization price (`ai_model_configs`, live and with a price) for the provider in the usage's organization. - dbauthz reads `ResourceAiModelPrice`, scoped to the organization when one is given, like `GetAIModelPriceForProvider`. - Table-driven query tests run every case for all organizations, org A and org B. <details> <summary>Cases</summary> Model X is on `anthropic-prod`. Y is the model the provider reports serving for X. "Notif" is the deployment-wide notification, "UI A/B" is the endpoint for org A/B. | # | Prices | Usage | Notif before | Notif after | UI A | UI B | |---|---|---|---|---|---|---| | 1 | No price for X anywhere | A uses X, unpriced | ✅ | ✅ | ✅ | ❌ (B didn't use X) | | 2 | Site-wide price for X | A and B use X, priced | ❌ | ❌ | ❌ | ❌ | | 3 | A priced X before the usage | Only A uses X, priced | ❌ | ❌ | ❌ | ❌ | | 4 | A priced X after the usage | Only A uses X, unpriced when recorded | ✅ (wrong) | ❌ | ❌ | ❌ | | 5 | A priced X, B has none | A uses X (priced), B uses X (unpriced) | ✅ (because of B) | ✅ (because of B) | ❌ | ✅ | | 6a | No price for X or Y when recorded, then Y priced site-wide | Only A uses X, unpriced when recorded | ✅ | ✅ | ✅ | ❌ | | 6b | Same as 6a | A and B use X, unpriced when recorded | ✅ | ✅ | ✅ | ✅ | | 7a | No price for X, but a site-wide price for Y | A uses X, priced through Y | ❌ | ❌ | ❌ | ❌ | | 7b | No price for X, A priced Y, and B has none | A and B use X: A priced through Y, B unpriced | ✅ (because of B) | ✅ (because of B) | ❌ | ✅ | </details> Note: pagination will be added in a follow-up. Related to AIGOV-730 > [!NOTE] > Generated by Coder Agents on behalf of @ssncferreira. |
||
|
|
8c5921db5e |
fix: count unpriced AI model usage by when it was recorded (#31751)
## Description Updates the unpriced AI models query behind the weekly owner notification to count token usage by when it was recorded (`token_usages.created_at`) in a `[period_start, period_end)` window, consistent with the other AI spend queries. It also returns one row per provider name and model instead of per provider type, so the unpriced models endpoint later in this stack can reuse it. The notification payload keeps the same format. ## Changes - Rename `GetUnpricedAIModelsSince` to `GetUnpricedAIModels`. It used `interceptions.started_at` with no end. - Treat usage as unpriced only when no price was found (`cost_micros IS NULL AND priced_model IS NULL`), so usage whose price was found but whose cost could not be computed is not reported. - Return one row per live provider name and model, with the provider's display name, icon and type. - The notification passes the last 7 days and merges rows by provider type, since site-wide prices are keyed by type, so its payload keeps the same shape. - Table-driven query tests and a notification test for providers sharing a type. Related to AIGOV-730 > [!NOTE] > Generated by Coder Agents on behalf of @ssncferreira. |
||
|
|
d639ced1e0 |
fix: send only changed chat history over the stream (#29662)
A client could resume the chat stream only with after_id, a message ID. A message ID does not identify what a client has received. A reconnect could skip a message that another client sent, send no history_reset for an edit the client missed, or resend the whole history. A client can now resume with the chat's snapshot_version, which the newest messages page returns and the stream's events then include. The stream sends what changed at that version or later. For an edit it sends the ID of the edited message and the messages written since, not the whole history. A stream opened without snapshot_version sends the same events as before. A write outside a chat state transition does not increase snapshot_version, and a stream can miss it. The queries that only tests used for such writes are removed. When the stream cannot be set up, the server now returns 500 before the WebSocket upgrade. It used to upgrade and send an error event, which the web client shows as a chat error. The Tasks to Chats migration guide told clients to reconnect with after_id. It now describes snapshot_version. |
||
|
|
30abd0593c |
feat: add organization AI spend overview endpoint (#31709)
## Description
Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/spend` endpoint that
backs the new Overview tab of the organization AI spend page ([Figma
design](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=12-5152&t=YlCC7RGSMNrzMxVo-4)).
It returns the organization's spend summary, daily spend, and a page of
users with their per-group spend, using the queries from #31711.
## Changes
- Add the `organizationAISpend` handler and
`ExperimentalClient.OrganizationAISpend`:
- Reuses the period handling of `/ai/spend/users`: `period_start` and
`period_end` must be provided together and span at most 31 days, and the
default is the current budget period.
- Also requires both bounds at 00:00:00 UTC, since the daily spend
aggregate holds whole UTC days.
- Is not limited by the AI Gateway data retention window, since the
daily spend aggregate is not purged. `/ai/spend/users` and the export
keep the retention check, now in `aiSpendRetainedPeriod`.
- Returns `count`, `totals` (`spend_micros`, `median_spend_micros`),
`intervals` (daily spend, one interval per UTC day, zeros included), and
`users` (paginated with `limit`/`offset`, most spend first, with
per-group spend).
- Echoes the applied period, and reads every value in one read-only
repeatable-read transaction so the values agree.
- Extract `parseOrganizationAISpendPage`, shared with `/ai/spend/users`.
- Add handler tests.
Closes AIGOV-728
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
|
||
|
|
7db53f3b47 |
feat: add organization AI spend overview queries (#31711)
## Description Adds 3 database queries for the organization AI spend overview. They read the daily spend aggregate (`ai_user_daily_spend`), scoped to the organization through each spend row's effective group, over a `[period_start, period_end)` range of UTC days. 1. `GetOrganizationAISpendTotals`: the number of users with spend, the total spend, and the median of the users' total spend. 2. `ListOrganizationAISpendPerUser`: paginated users, most spend first, with one row for each group their spend was attributed to. 3. `GetOrganizationAISpendPerDay`: the spend for every UTC day in the range, including days without spend. Note: Only users with spend above zero are included, so users with only unpriced usage are not listed. ## Changes - dbauthz checks matching `/ai/spend/users` (read on organization group members). - Querier and dbauthz tests. Related to AIGOV-728 > [!NOTE] > Generated by Coder Agents on behalf of @ssncferreira. |
||
|
|
c303114fae |
perf(coderd/database): batch chat authz fetch in GetChatDiffStatusesByChatIDs (#31880)
> Generated by Coder Agents on behalf of @cstyan. |
||
|
|
1126533c31 |
feat: export workspace last used time to Prometheus (#31346)
Add an opt-in coderd_workspace_last_used_timestamp_seconds gauge that reports workspaces.last_used_at, the value the dormancy threshold measures inactivity from. To enable it, set --prometheus-collect-workspace-stats or CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS. A separate WorkspaceStats collector refreshes the gauge once a minute in the background from a new GetWorkspaceLastUsedForMetrics query. Each series has a workspace_id label, so a workspace that reuses a deleted workspace's name starts a new series. Workspaces owned by deleted users are excluded. Closes CLIENT-1065 |
||
|
|
fb12d6018f |
fix!: redact agent environment variable values in API responses (#31932)
Workspace, build, and agent API responses (`/workspaces`,
`/workspacebuilds/{id}`, `/workspaceagents/{id}`, and so on) returned
agent environment variable values in plain text. Template authors often
pass credentials such as API tokens through `coder_env`, so anyone who
could read the workspace could read those secrets.
`db2sdk.WorkspaceAgent` now replaces every non-empty value with
`***REDACTED***` and keeps the keys. This is the same marker the support
bundle (`sanitizeEnv`) and the agent `/debug/manifest` endpoint already
use. The agent still gets the real values through its manifest
(`db2sdk.WorkspaceAgentEnvironment`), and nothing in the CLI or frontend
reads these values from the API.
Every value is redacted because neither `coder_env` nor
`coder_agent.env` in the Terraform provider has a sensitive flag, and
`proto.Env` has no field to carry one. Selective redaction would need
changes to the provider, the proto, and the database.
## For changelog
- Agent environment variable values are redacted in API responses
(#31932)
> Workspace, workspace build, workspace agent, and template version API
responses now return `***REDACTED***` for every non-empty agent
`environment_variables` value. Keys and empty values are unchanged. The
agent still receives the real values, so workspaces behave as before.
>
> Migration: Update scripts and integrations that read agent environment
variable values from the API or from `coder list -o json`. Read the
values inside the workspace instead.
Closes ENG-1505 (coder/security#51)
<details>
<summary>Decision log</summary>
- Confirmed the leak on `main` (
|
||
|
|
3728e7a4e1 |
perf: use the build parameter index in GetTemplateParameterInsights (#31765)
Speeds up `GetTemplateParameterInsights`, which the insights collector runs every 5 minutes on every replica. The `@>` array join could only hash on `name`, so every run scanned all of `workspace_build_parameters`. Unnesting the build IDs and joining on `(workspace_build_id, name)` lets the existing unique index serve it, and the results don't change since each build ID shows up at most once per group. On 8.4M synthetic build parameters the collector's 5 minute window went from 5,193 ms to about 31 ms. `TestGetTemplateParameterInsights` is new and passes on both the old and new SQL. This also fixes the Prometheus docs example, which summed per-replica copies of the same metric. I split the `workspace_app_stats` index into #31766 so this one has no migration and can be backported to 2.34 through 2.39 (2.34 to 2.38 without the docs hunk). The pre-push hook skipped tests on this push because of a stale `origin/main` in my checkout. An earlier full run only failed in `agent/` and `site/`. Part of [CORE-439](https://linear.app/codercom/issue/CORE-439). |
||
|
|
66dca90c91 |
fix(coderd/database/migrations): renumber the workspace_app_stats index migration to 000641 (#31997)
#31766 and #31748 both added a `000640` migration and both merged, so main currently has two migrations with the same number. Migrations fail to load with `duplicate migration file: 000640_workspace_app_stats_session_ended_at_idx.down.sql`, which breaks every test that sets up a database. This moves the `workspace_app_stats` index to `000641`. It's a rename only and `dump.sql` regenerates unchanged. `go test ./coderd/database/migrations/...` and the insights and dbrollup tests pass with it. Part of [CORE-439](https://linear.app/codercom/issue/CORE-439). |
||
|
|
78e1b280d1 |
perf(coderd/database): index workspace_app_stats by session_ended_at (#31766)
Adds an index on `workspace_app_stats(session_ended_at)`. The table had
no time index and is never purged, so the insights collector's app usage
query scanned all of it every 5 minutes on every replica. On 3M
synthetic rows that query went from 124 ms to 19 ms.
**NOTE**: the index build holds a lock that blocks app stat writes until
the migration batch commits (about 1.4 to 3.4 s per 3M rows in testing),
and active session upserts stop being HOT updates.
This is separate from #31765 so that one can be backported without a
migration. dbrollup's `UpsertTemplateUsageStats` still needs its own
query change to use this index on Postgres 17+ (noted on
[CORE-776](https://linear.app/codercom/issue/CORE-776)). The migration
number may need a bump at merge time.
I skipped the pre-push hook for this push since `make pre-push` also
fails on clean `main` in my workspace. This branch only failed in tests
it doesn't touch.
<details><summary>Failing pre-push tests</summary>
Clean `main` (
|
||
|
|
5563b7444d |
fix: keep in-flight builds from blocking the prebuild hard limit (#30060)
Fixes #30058. Fixes an issue where in-flight prebuilds prevent presets from reaching their failure hard limit. `GetPresetsAtFailureLimit` now considers only completed builds (`succeeded`, `failed`, `canceled`) when evaluating consecutive failures. Pending and running builds no longer mask earlier failures, while successful and canceled builds still break the failure streak. ### Tests - Added query tests covering in-flight builds with and without a reached failure limit. - Added a reconciler test confirming hard-limited presets do not create additional prebuilds. - Fixed the test helper to properly mark successful jobs as completed. - Verified the new tests fail before the fix and pass afterward. - All relevant tests and `golangci-lint` pass. **Live validation:** A preset with builds failing after 90s (longer than the 60s reconcile interval) stopped after 4 failures, with no additional builds during a 20-minute observation. Previously, the same scenario produced 156 failed builds in approximately 2 hours. ### AI disclosure Written with AI assistance (Claude Code). I reviewed the changes, ran the tests, and verified the fix on a live deployment. Co-authored-by: Bryson Henneberger <591079+PushTheLimit@users.noreply.github.com> Co-authored-by: Bobby Ho <bobby@coder.com> |
||
|
|
9fa68ac013 |
feat: hold every steer message while one is under edit (#31748)
Whilst a steer message is under edit, every steer message now waits, not just the one under edit and the ones behind it. Say Next step holds A, B and C, and you edit B. Before this, A went to the agent at the next model call whilst B and C waited. Now nothing goes out until the edit ends, then A, B and C go in together. If the turn ends whilst a steer message is under edit, the chat pauses, the same as it already does for a queue message. `GetChatQueuedMessageHead` now returns a steer message under edit first, so the paused check still finds it when it isn't the first row. Queue messages are unchanged: editing one holds it and the messages behind it. On the site, every other row shows "Waiting" whilst a steer message is under edit, and Enter on an empty composer won't send the first held message whilst it's waiting on an edit. The docs are updated to match. The first version of this PR refused edits on steer messages instead, following [Mathias's review of #30074](https://github.com/coder/coder/pull/30074#pullrequestreview-5352986208). Mathias has since suggested holding the whole steer lane, so the agent never starts working on part of what you sent. Part of CODAGT-1140 |
||
|
|
a40ff12c8c |
feat!: steer chat messages by default and remove the interrupt busy behavior (#31174)
Breaking API Change for changelog:
> `POST /api/v2/chats/{chat}/messages` now steers by default. If the
chat is busy, the message is delivered before the agent's next model
call, instead of after the turn ends. `busy_behavior` accepts `steer` or
`queue`, and `interrupt` now returns a 400. To redirect the agent, just
send a message, and only call `POST /api/v2/chats/{chat}/interrupt` to
stop it. Queued messages now include their `busy_behavior`.
This is where steering becomes the default for API clients. A send
without a `busy_behavior` used to wait for the turn to end, and now it
goes in the steer lane, so the agent sees it before its next model call
and keeps going. `queue` still waits for the turn to end.
Interrupt isn't a busy behaviour any more. Since #31155 it just meant
"interrupt, then steer", so the API now returns a 400 for it, and
`codersdk.ChatBusyBehaviorInterrupt` is gone. `coder_send_chat_message`
in the MCP server gets the same default and enum. A steer message
already corrects a busy agent, and combining it with an interrupt goes
wrong in either order, so the docs and the MCP tool descriptions now say
to send a message to redirect the agent, and to interrupt only to stop
it.
Queued messages now report their `busy_behavior`, and the queue lists
the steer lane first, so clients can show which messages go in at the
next step and which wait for the turn to end. A message moved with Send
now reports `steer`.
The site doesn't send a `busy_behavior`, so its sends start steering
with this PR, but its queue UI doesn't know about the steer lane until
#31173. chatd still accepts `interrupt` internally, as `message_agent`
uses it, and #31175 removes both.
Part of CODAGT-1140
|
||
|
|
63e08e231e |
feat(coderd): steer queued messages on Send now (#31156)
"Send now" on a queued message (`POST
/api/v2/chats/{chat}/queue/{queuedMessage}/promote`) now just moves it
to the end of the steer lane. It never interrupts the chat, so it can't
cancel the step that would have answered it. The endpoint's request
doesn't change. Before, it moved the message to the head of the queue
with `MIN(position) - 1`, so if you pressed "Send now" on two messages,
the second one went first. With a queue of `Q1 Q2 Q3 S4`, "Send now" on
`Q1` then `Q3` now delivers `S4 Q1 Q3`, and `Q2` keeps waiting.
If the chat has errored or is paused, the steer lane goes in straight
away, like a send. Otherwise it goes in at the next delivery point:
before the next model call, when the turn ends, or when an interrupt
finishes. Stop is the only thing that interrupts.
"Send now" and "Remove" on a message that's already been delivered now
return a 404 instead of a 409, the same as editing one, and "Remove" on
an archived chat returns a 400.
In chatstate, `SteerQueuedMessage` replaces `PromoteQueuedMessage`. It
moves the message to the end of the steer lane, and on an errored or
paused chat it also delivers the steer lane and resumes the chat, like a
send does. The `SteerChatQueuedMessage` query sets `position =
nextval(...)` and replaces `ReorderChatQueuedMessageToHead`. Most of the
diff is tests.
#31174 then makes `steer` the API default and removes `interrupt` as a
busy behaviour, #31175 makes `message_agent` always steer, and #31173
updates the site.
Part of CODAGT-1140
|
||
|
|
0616658cb5 |
feat(coderd): add a steer lane to queued chat messages (#31154)
As suggested on #30074, steer messages are now their own lane, rather than queue rows that jump ahead with a lower position. chatstate uses a queued message's `busy_behavior` as its lane, and the steer lane always goes first. `GetChatQueuedMessages` lists the steer lane first, so the queue is shown in the order it'll actually be delivered. At turn end, when an interruption finishes, and on a send to an errored chat, the whole steer lane goes in. If there aren't any steer messages, the queue head goes in like it does today. So with a queue of `Q1 S1 Q2 S2`, turn end delivers `S1 S2`, and `Q1` waits for the next turn end. chatstate accepts `steer` here, but nothing sends it yet, so users won't see a change. Until later in the stack, a few things still ignore the steer lane: - An interrupt send goes to the head of the queue lane, so it waits behind any steer messages. #31155 moves it to the end of the steer lane. - "Send now" on a running or interrupting chat only moves the message to the head of its own lane, so when the interruption finishes, the steer lane goes in instead of it. - "Send now" on an errored chat, or one waiting on tool results, puts the message into history straight away, ahead of any queued steer messages. #31156 fixes both "Send now" cases by making it steer. None of these can happen yet, as there are no steer messages to get in the way. I've added a "Queued message lanes" section to the chatd architecture doc. Most of the diff is new cases in the transition matrix tests. Since the first review, lane rule 3 in the architecture doc also says that delivery stops at a message under edit, and which model and reasoning effort a batch of delivered messages uses. Part of CODAGT-1140 |
||
|
|
8230004d73 |
chore(coderd): store a delivery mode on queued chat messages (#30073)
Queued chat messages now store a delivery mode. Later in this stack, `steer` messages go in before the next model call instead of at turn end, so chatd needs to know which queued rows are steer rows. The migration adds the enum `chat_busy_behavior` (`queue`, `steer`) and the column `chat_queued_messages.busy_behavior`. It's `NOT NULL DEFAULT 'queue'`, so existing rows get `queue`, and chatstate still passes `queue` on every insert for now, so this doesn't change behaviour. The old `InsertChatQueuedMessage` query doesn't set the column and just gets the default, but only tests use it. There's no `interrupt` value on purpose. An interrupt isn't a delivery mode, it's something that happens to the chat, and #31174 stops the API accepting it as a busy behaviour. This supersedes #29783. Part of CODAGT-1140 |
||
|
|
b0fe0ba261 |
fix(coderd): tighten up database connection errors (#31850)
Tightens up database connection errors so they stay concise, and logs internal error details server-side instead of returning them in API responses. Adds tests covering the error output. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
bc5dd20a05 |
feat: report Agent Relay builds in telemetry (#31407)
Telemetry builds now report whether Agent Relay created them. Before this, relay workspaces looked like any other build. A start build counts as a relay build when it has the `agent_relay_session_id` parameter. Stop and delete builds never get the field. For those builds, the new `agent_relay` field on `WorkspaceBuild` reports: - `provider`: `claude_code`, `cursor`, `ambiguous`, or `unknown` - `client_platform`: Claude Code only. Lowercased, characters outside `[a-z0-9_]` become `_`, and cut to 15 characters - `attempt`: omitted when missing or not an integer, so `0` is sent - `session_id_hash` and `pool_hash`: SHA-256 hashes No other parameter values are sent. Other builds leave the field out. The snapshot fetches these parameters with one new batch query. The workspace-create event reads the stored parameters with one extra query, only when telemetry is enabled, so it reports the same data as the snapshot. `docs/admin/setup/telemetry.md` lists the parameters that are read. The collector side is [coder/coder-telemetry-server#56](https://github.com/coder/coder-telemetry-server/pull/56). Merge this PR first. Refs [RELAY-9](https://linear.app/codercom/issue/RELAY-9/telemetry-report-agent-relay-usage-from-codercoder) <details> <summary>Decision log</summary> - **Detect relay builds from parameters.** This needs no relay changes. Relay registration or [CORE-426](https://linear.app/codercom/issue/CORE-426) provenance metadata can come later. - **Builds only, not workspaces.** `GetWorkspaces` doesn't return the latest build's parameters, so a workspace field would cost another query. The collector can join on `workspace_id`. - **Provider comes from parameter names only.** `agent_relay_claude_code_*` means Claude Code and `agent_relay_cursor_*` means Cursor. A build with both reports `ambiguous`; a build with neither reports `unknown`. coderd stores every declared parameter on every build (ephemeral ones with their default), so a Claude Code start after a stop still reports `claude_code`. - **Start builds only.** Stop and delete builds of a relay workspace carry the same parameters but are not dispatches, so the snapshot skips them before querying parameters. - **Hash session ID and pool.** Pool names are user content, and sessions only need counting. - **Known gaps.** Cursor has no client platform. Relay version and health would need relay registration. - **Parameter names are shared with coder/agent-relay.** If agent-relay renames one, telemetry silently stops reading it. </details> <details> <summary>Manual test on <code>develop.sh</code></summary> Ran on `8ad7cd491f` with `CODER_TELEMETRY_ENABLE=true CODER_TELEMETRY_URL=http://127.0.0.1:8081` and `go run ./scripts/telemetry-server --port 8081` as the collector. Pushed three templates with no infrastructure, each declaring the same parameters as the real modules: - `relay-claude`: `agent_relay_session_id`, `_delivery_id`, `_pool`, `_client_platform`, plus ephemeral `agent_relay_attempt` and `agent_relay_claude_code_lock_to_account` - `relay-cursor`: `agent_relay_session_id`, `_delivery_id`, `_pool`, `agent_relay_cursor_pool_name`, `_idle_release_timeout`, `_repo_url` - `relay-plain`: `region` Created workspaces with `POST /api/v2/users/me/workspaces` and `rich_parameter_values`, the same call the relay makes. Then ran stop and start builds on the relay workspaces, and restarted coderd to get a periodic snapshot. | Workspace | Build 1 (create event and snapshot) | Builds 2 and 3 (stop, start) | |---|---|---| | Claude (`claude_in_slack`, attempt 1) | `claude_code`, platform, attempt 1 | `claude_code`, platform, no attempt | | Cursor | `cursor` | `cursor` | | Plain | field omitted | n/a | | Claude template, no session ID | field omitted | n/a | - Stop and start builds keep `agent_relay_claude_code_lock_to_account`, with an empty value, so Claude Code rebuilds still report `claude_code`. - No session ID, pool name, or `region` value appears in the captured telemetry. The hashes match `sha256` of the inputs. - Fed the captured snapshot through the conversion code in coder/coder-telemetry-server#56: all 8 builds converted, 6 of them with `agent_relay` set. - No telemetry errors or panics in the coderd logs. This run predates the start-only change: build 2 (stop) carried the field then. Stop and delete builds are now omitted, which `TestTelemetry_WorkspaceBuildAgentRelay` covers. </details> --- *Generated by Coder Agents on behalf of @Emyrk.* |
||
|
|
d70ce38559 |
feat: record the OAuth2 client registration method of MCP server configs (#31558)
Relates to CODAGT-779 Currently we can't tell whether the OAuth2 client of an MCP server config was entered by an admin, or registered by Coder with Dynamic Client Registration (RFC 7591). The next PR in the stack needs to know this, so it can register a new client when a config is updated. This PR adds `mcp_server_configs.oauth2_client_registration` (`manual` or `dynamic`) and returns it to admins on the API. Create stores `dynamic` when it registers the client, and `manual` otherwise. An update resets it to `manual` when it switches away from the `oauth2` auth type, or when it changes the client ID, secret, auth URL or token URL of a `dynamic` config, since the admin has replaced Coder's client. Existing rows default to `manual`, as there's nothing in the data that tells us which clients came from Dynamic Client Registration. |
||
|
|
55573833d0 |
fix(coderd/database): lock the workspaces row when claiming a prebuild (#31518)
`ClaimPrebuiltWorkspace` locked the `workspace_prebuilds` view with `FOR UPDATE ... SKIP LOCKED`, but the view is built from CTEs, so nothing got locked. Concurrent claims picked the same prebuild and the losers got a 409 (a customer saw 28 of 30 fail). This locks the `workspaces` row directly (`FOR NO KEY UPDATE SKIP LOCKED`), rechecks owner and deleted on it, and checks eligibility with per-workspace index lookups instead of the views. It uses `=` instead of `IN` so one claim can't take two prebuilds, filters on the preset's template so other templates' prebuilds aren't scanned, and claims oldest first so prebuilds are used before they hit the preset TTL. Query-only, no migration, applies cleanly to release/2.38. Builds on #31468 by Kevin Ha (Canva). Benchmarks (Postgres 17, 20k users, 320k builds, 600 ready prebuilds): ~12 ms per claim (was ~640 ms), and 500 concurrent claims got distinct prebuilds in ~1.5 s. Known limitations: - Each claim still checks every prebuild of the preset's template (other presets included) before sorting. That's a few ms at hundreds of prebuilds per template. - Pre-existing: a reconciler delete during a claim can still 409. Follow-up is a `deleting_at` marker the claim skips. --------- Co-authored-by: Kevin Ha <kevinh@canva.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c0f7663e95 |
feat: support editing queued chat messages (#29215)
The owner of a chat can edit a queued message through
`PATCH /api/v2/chats/{chat}/queue/{queuedMessage}`. chatd never sends
a row under edit (`editing_since`): rows ahead of it still send in
order, and a turn that ends at it puts the chat in the new `paused`
status. Ending the head's edit, deleting it, or promoting a queued row
continues the chat. Interrupting sends still run ahead of the queue.
The chat state machine classifies a queue whose head is under edit as
its own sub-state (R1P, I1P, A1P, E1P, XE1P, P), so every path to
`paused` is in the transition matrix. A chat whose family has a paused
member cannot be archived, and auto-archive skips that family. Queue
edit and delete are owner-only, because both can send the next message
with the owner's credentials.
`ChatQueuedMessage` gains `editing_since` and `reasoning_effort`, and
`ChatStatus` gains `paused`.
Closes CODAGT-1028
Refs CODAGT-971
|
||
|
|
31b8fd1b88 | feat: graduate the chat advisor from experiments (#31414) | ||
|
|
1acacc9c30 | feat: graduate MCP tool search from experiments (#31327) | ||
|
|
d1f308d9f3 |
feat: let organization members turn off organization skills in chats (#31134)
## Stack Organization skills load into every member's Coder Agents chats in their organization, with no way for a member to opt out. This stack adds a per-organization setting that lets members turn them off for their own chats, bottom to top: 1. **#31134** data model, API, and chatd (this PR) 2. #31135 admin and member controls in the dashboard, the `/` menu, and docs ## What changes Organizations get `members_can_disable_skills`, off by default. Users who can update organization skills change it with `PUT /api/experimental/organizations/{organization}/skill-settings`, which writes an organization audit entry. Anyone who can read the organization can `GET` it. While the setting is on, each member saves their own choices with `PATCH /api/experimental/organizations/{organization}/members/{user}/skill-preferences`: `all_skills_disabled` (a master switch that also covers skills created later) and `skills`, a sparse map from skill ID to on or off. `GET` returns the setting, the master switch, and `disabled_skill_ids`. The routes follow the personal-settings rules: without `read_personal` or `update_personal` on that user the caller gets 404, a PATCH while the setting is off gets 403, and a key that is not an organization skill that member can read gets a 400 that names the key. The check runs as the member, not the caller, so an owner or user admin editing someone else's choices is held to that member's skills. Turning the setting off keeps the choices but ignores them. Migration 000636 adds the column and two tables keyed by organization membership. Both cascade when the membership goes away, and the per-skill table also cascades when the skill is deleted, so a recreated skill loads by default. chatd reads the preferences as the chat owner when it builds the skill index and when it loads a body for `read_skill` or for a structured skill invocation (#30861). A skill the member turned off is left out of the index, and both loads report it as not found, including later in a running chat. If the preferences cannot be read, turn preparation fails, as it already does when the skill metadata cannot be read. Older migration tests created organizations with `dbgen.Organization` and `GetDefaultOrganization`, which now select the new column before it exists, so they insert organizations with raw SQL instead. ## Review focus - Authorization in `coderd/organizationskillpreferences.go` and the five new dbauthz methods (`read_personal` and `update_personal` on the user, `organization_skill` update for the setting). - `GetOrganizationSkillMemberPreferencesRow.Excludes` is the one rule chatd applies; #31135 mirrors it in `activeOrganizationSkills`. ## Testing - Go tests cover the queries and cascades, dbauthz, both routes (including the audit diff and each 400 case), and chatd (index, `read_skill`, skill invocations, master switch, a change during a chat). Each new test fails with its code path removed. - Remote dogfood UAT (10 scenarios, real model) passed on the pre-split branch head `186c28d81ab`, which has the same code except the fix below. It found one issue: two spellings of one skill ID with opposite values stored a random result. The PATCH now rejects every aliased key with a 400. A second run on the stack's top head at the time, `718dd6d1bd1`, passed: every aliased form returns 400 and stores nothing, and chats leave out a skill the member turned off, including in `read_skill`. - Polish and the test audit stayed inside the implementation diff. No new dependencies. - Rebased on main as one commit. The migration is now 000636, after main's 000634 and 000635. Every organization skill load passes the chat owner, including main's skill invocation path, so `/skill` invocations honor the opt-out too. The model's skill index leaves out a skill that is not model-invocable or that the member turned off. Apart from that, the diff is unchanged. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
3697bb38ce |
feat!: choose the computer use model per organization (#31300)
> [!NOTE]
> Xum opened this PR for Mike (Coder agent). Mike reviews it before
merge.
Fixes CODAGT-1472.
Computer use now runs on a chat model that each organization picks.
Before, it ran a fixed model on the first enabled AI provider of a
deployment-wide provider type, sorted by name. On dogfood that
provider's key is rejected, so every computer use subagent failed.
## What changed
- **Setting.** A new `computer_use` organization model override, set in
the **Computer use** row of **Organization settings** on the Coder
Agents admin page. Without an override, computer use runs on the
organization's default model. If the chosen model is disabled, deleted,
or unusable for the chat owner, computer use falls back to the default
model, as other overrides do. It also falls back when the chosen model
moves to an AI provider that is not Anthropic or OpenAI, and the row
then says that the saved model is ignored.
- **API.** `PUT
/api/v2/organizations/{organization}/chats/model-overrides/computer_use`
returns 404 while the `chat-virtual-desktop` experiment is off, and 400
unless the model's AI provider type is Anthropic or OpenAI.
- **chatd.** The `computer_use` subagent runs on that model, and the
computer tool flavor follows the model's provider type. OpenAI computer
use always uses the Responses API, so a model that sets
`use_responses_api: false` gets a configuration error. When no usable
model exists, `computer_use` is unavailable, and the reason says whether
a saved computer use model was skipped and why the default model cannot
be used. The default model is read under the chat owner's model ACLs, as
chat turns do.
- **UI.** The row lists only enabled Anthropic and OpenAI models. A
warning icon with the tooltip "Make sure that the selected model
supports computer use." appears when the model in effect (the selected
one, or the default) is not on a curated list of canonical model IDs
known to accept the computer tool (`knownComputerUseModels` in
`knownModels/catalog.ts`, exact match only). It also appears when the
model's AI provider type is OpenAI and its **Use Responses API**
override is Off, because OpenAI computer use needs the Responses API.
The warning does not block saving. I built the list from a live probe on
2026-10-26 that sent each Anthropic and OpenAI model one request with
the computer tool.
- **Docs.** `virtual-desktop.md`, `models.md`, `organizations.md`, and
`architecture.md` describe the new setting, and chatd's
`ARCHITECTURE.md` describes the computer use model routing.


## Breaking change
This removes the deployment-wide computer use provider setting
(`agents_computer_use_provider`), its experimental `GET`/`PUT
/api/experimental/chats/config/computer-use-provider` endpoints (shipped
since v2.35), the Virtual desktop settings card, and its audit field.
Migration 000635 deletes the stored value. After the upgrade, computer
use runs on each organization's default model until an admin picks a
computer use model. Computer use subagents created before the upgrade
keep the model they inherited from their parent chat, so a follow-up
message to one of them can fail; a new computer use subagent uses the
organization's computer use model. Telemetry now reports the
per-organization overrides instead of the provider, and `null` when it
cannot read them.
## Testing
- `make pre-commit` passes. `go test` passes for `./coderd/x/chatd/...`,
`./coderd/database/migrations/`, and the targeted coderd, telemetry,
dbauthz, enterprise audit, and codersdk tests. Vitest and the touched
Storybook stories pass.
- Each new Go test fails when its target behavior is removed from
production code.
- Remote dogfood UAT ran on an isolated Coder instance built from the PR
head, with real Anthropic and OpenAI models:
- 110234e: the row with the experiment on and off, the picker, the
warning icon cases, save and clear, the 400 for other provider types,
which model and computer tool each computer use subagent used
(Anthropic, OpenAI, default, and disabled override), a real desktop
session on an Anthropic and an OpenAI model, the unavailable reasons,
the upgrade through migration 000634, and the removed endpoints.
- 09ce818: an override whose model moved to an unsupported AI provider.
- 7925be9: the alert for a moved and a disabled override, and a computer
use subagent on an Anthropic model.
- 2a01eaf: the row, and computer use subagents on the override and on
the default model.
- 47f5bd1: the warning icon for an OpenAI model with **Use Responses
API** set to Off, On, and Default. With Off, a computer use subagent on
that model fails with a configuration error before any provider request.
With Default, it runs with the computer tool through the Responses API.
- 81d33b4: the unavailable reasons for a disabled override, a cleared
override, and missing credentials, and a computer use subagent on an
Anthropic override. This round found that the docs named the wrong
section of the model form for **Use Responses API**. aeb3d02 fixes that
step, and a re-read of the docs against the recorded UI passed.
|
||
|
|
eb38759fda |
feat: limit effective group resolution to an organization (#31119)
AI budget resolution searches all of a user's groups across every organization. Whichever group wins determines the organization. #31120 needs to resolve inside a known organization, and it needs to know which organization site-wide resolution picked. Add an `organizationID uuid.NullUUID` argument to `budget.ResolveUserAIBudget` and `budget.ResolveUserEffectiveGroup`. When it is set, count only that organization's override, group budgets and Everyone group. An organization that is unknown, deleted or that the user is not a member of resolves to nothing. When it is null, resolve exactly as before. Return the winning group's organization in `budget.EffectiveGroup.OrganizationID`. Read the override through a new resolution-only query, `GetUserAIBudgetOverrideWithOrganization`, so that the CRUD query `GetUserAIBudgetOverride` and the admin endpoints stay untouched. Add a nullable `organization_id` filter to `GetHighestGroupAIBudgetByUser` and `GetUserEveryoneFallbackGroup`. Every caller passes null, so behaviour is unchanged. There is no migration and no proto change. Scoping to an organization can lift a limit: a user capped in org B has no limit in org A if A has no budgets. AIGOV-711 intends this, and it takes effect in #31120. Part of AIGOV-715. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
7f6ce9c8ab |
test(coderd): stamp chat message fixtures with the current content version (#30996)
Chat prompt tests built most of their stored-message fixtures in the legacy content format (`content_version` 0), so they exercised the legacy decoder instead of the current one. This PR changes tests only: it stamps those fixtures with `ContentVersionV1` and builds them with `MarshalParts`, so they keep passing after the legacy decoder is removed later in this stack. Tests of the version 0 decoder itself keep their version 0 rows until the layers above remove that decoder. **Why it is safe** - `mustMarshalContent` and `mustMarshalToolResult` now build current parts (`PartFromContent`, `ChatMessageToolResult`) and encode them with `MarshalParts`, the production write path. - `TestMixedFormatConversation` becomes `TestConvertMessagesWithFiles_Conversation` and uses current-format rows only. - `TestParseContent_BackwardCompat` does not change. Migration 000434 stamped every existing row with version 0, so its six cases of current-format parts in version 0 rows still cover the version 0 heuristics. #30998 moves those six cases to version 1 rows when it removes that decoder. - `TestProviderExecutedResult_LegacyToolRow` calls the legacy writers (`MarshalContent`, `MarshalToolResult`) directly, so its provider-executed tool row still goes through the legacy tool-row decoder. - `TestParseContent_ErrorPaths` runs its malformed-input cases on version 1 rows, and runs the same input on version 0 rows of each role (`v0/<role>/malformed_json`), so a version 0 parser that accepts malformed content still fails the suite. #30998 deletes the version 0 cases with that decoder. - I ran the 17 mutants listed below, each a `go test -overlay` edit of the current decode and prompt-conversion code in `chatprompt.go`, against the `chatprompt` and `db2sdk` tests on `main` and on this branch. Every mutant `main` catches is still caught. Two more are caught here: mutant 3, because `TestParseContent_ErrorPaths/system/malformed_json` used to hit the legacy system decoder, and mutant 14, by the new JSON `null` case of `TestConvertMessagesWithFiles_NormalizesAssistantToolCallInput`. Mutants 4 and 8 survive those tests on both. The `chatd` test `TestOrganizationSkillsFollowChatOwnerAccess` catches mutant 4, so 8 is an existing gap. - Mutants of the version 0 decoder fail on `main` and on this branch: version 0 assistant or user rows always take the envelope path, their current-format parts are dropped, legacy tool rows lose `provider_executed`, or a version 0 parser accepts malformed JSON. - With the version 0 case removed from `ParseContent` by an overlay, only tests of version 0 rows fail. #30997 deletes them, except the six `TestParseContent_BackwardCompat` cases, which #30998 moves, and the version 0 cases of `TestParseContent_ErrorPaths`, which #30998 deletes. <details> <summary>The 17 mutants</summary> 1. `ParseContent` returns no parts for a V1 row. 2. V1 decoding skips NUL restoration (`decodeNulInParts`). 3. The V1 parse error says "decode" instead of "parse". 4. Tool error string extraction is off (`toolResultPartToMessagePart`). Only a `chatd` test catches it. 5. Tool call input is dropped. 6. Tool call `ProviderExecuted` is dropped when reading. 7. Resolved file data is dropped. 8. The file media type fallback is dropped (`partsToMessageParts`). Survives. 9. User file IDs are not collected for resolution. 10. Text provider metadata is dropped. 11. File reference text is replaced by the raw content. 12. System messages are dropped. 13. Tool call `ProviderExecuted` is dropped when writing (`PartFromContent`). 14. `normalizeToolCallInput` keeps a JSON `null` input instead of `{}`. Survives on `main` only. 15. Text tool result `ProviderExecuted` is dropped. 16. Tool result IDs are dropped. 17. Assistant file IDs are resolved like user file IDs. </details> **Review focus** The rewritten conversation test in `chatprompt_test.go`. It checks the same prompt shape as before, but every row is in the current format. In the same file, `TestProviderExecutedResult_LegacyToolRow` keeps its legacy rows, `TestParseContent_ErrorPaths` checks malformed input on both content versions, and the input normalization table gains a JSON `null` case. The other changed test files only switch fixtures to the current format: `coderd/x/chatd/chatprompt/file_inline_test.go` (+4/-16), `coderd/database/db2sdk/db2sdk_test.go` (+11/-13), `coderd/x/chatd/message_conversion_test.go` (+3/-2) and `coderd/x/chatd/quickgen_internal_test.go` (+1). **Validation** - `go test ./coderd/x/chatd/... ./coderd/database/db2sdk/ -count=1 -p 4 -parallel 4`: ok - `go vet` on the touched packages and `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: clean - pre-commit hook: passed **Stack** This stack retires chatd compatibility paths for chat data that older Coder versions stored. 1. #30996 stamp chat message fixtures with the current content version (this PR) 2. #30997 drop tests of the legacy content codec 3. #30998 retire the V0 chat message content decoder 4. #31000 inline the model config provider identity 5. #31005 retire the `close_agent` tool alias > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
161b7233d9 |
feat(coderd): store the organization on AI Gateway interceptions (#31118)
Adds `organization_id` (FK to `organizations`, `ON DELETE RESTRICT`) and `organization_source` (new enum: `workspace`, `chatd`, `effective_group`) to `aibridge_interceptions`, with a check constraint that keeps them set or unset together. Cost and pricing run later, in `RecordTokenUsage`, so they need the organization that AIGOV-716a resolves once per request stored on the interception row. `RecordInterceptionRequest` gains `organization_id` (18) and `organization_source` (19), and the aibridged API moves to v1.5. `RecordInterception` stores a valid pair; any other combination is logged as a warning and stored as NULLs, so a gateway bug never turns into an HTTP 500 for the user. A well-formed ID for an organization that does not exist fails on the FK, like an unknown `initiator_id`. Nothing sends the fields yet, so behaviour is unchanged until AIGOV-716a. **Malformed values are stored as empty, not rejected.** A failed `RecordInterception` returns HTTP 500 to the user, so the server logs a warning and stores NULLs instead. The one exception is a well-formed ID for an organization that does not exist: the foreign key rejects it, the same as an unknown `initiator_id` today. Part of AIGOV-712 *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
7283fff69f | fix(coderd/database/pubsub): close listener before waiting on latency probe (#31317) | ||
|
|
1a9d5b28ba |
fix: keep ACP harness context synchronized (#31351)
ACP harness resources bypass context drift detection, but only MCP resources were live-synced into bound chats. Later ACP discoveries, capability updates, probe errors, and removals could therefore leave chat context stale without offering a refresh. Extend the existing live-sync query to include ACP harnesses and publish context updates for affected chats while keeping instructions and skills pinned. Depends on #31350. This PR contains the ongoing synchronization change; #31350 fixes initial probe ordering. |
||
|
|
0d1cba2def |
feat: expose connection duration and client session ID in connection logs (#30759)
Show how long each SSH and reconnecting PTY connection lasted, and let users find connections that share a client session ID. No schema changes. API (ssh_info): - Add client_session_id, the ID supplied by the client (the Coder CLI or a tool that launches it), if any. - Add a client_session_id:<32 hex chars> filter. UI: - Each row shows the connect → disconnect time range and the duration as badges. A connection with no disconnect shows "Ongoing", equal timestamps show an "Unknown" start, and a disconnect recorded before its connect is labeled as such. - The info icon opens a details popover instead of a hover tooltip. It uses the default popover styling and sentence-case labels, and lets users copy the client session ID and open "View related connections" for the same workspace. Closes CLIENT-1010 |
||
|
|
28192213ab |
feat!: label the VS Code family and report built-in app usage per app (#29906)
The session banner now labels the VS Code family "VS Code Family", so it isn't confused with the VS Code editor. coderd_insights_applications_usage_seconds now reports built-in apps per app instead of per family. - Generate the frontend's family labels from the Go table in codersdk. - Add the connection_method label: workspace_app for template apps, and ssh, reconnecting_pty, or port_forwarding for built-in apps. - Rename the application_name label to display_name. For built-in apps it holds the registry name, "Unknown" for unknown, and "Other apps" for overflow. - Built-in apps get one series per app name, only for apps used in the window. The series limit and the fold rule are shared with the template insights API. - Breaking: selectors with a value for application_name, or with slug="", match nothing. The Prometheus docs map each old series to its new one. Closes #29940 Closes CLIENT-1034 Closes CLIENT-1036 |
||
|
|
3f055e7a56 |
feat: list every chat attachment in the Summary panel (#31140)
In long chats, the Summary panel's **Attachments** section only listed
agent files from the messages already loaded in the transcript. It
showed "No attachments in the loaded messages." and a **Load earlier
messages** button, so finding a chat's files meant paging through its
history.
## What changes
- **API:** `GET /api/v2/chats/{chat}/attachments` returns every file
part in the chat's user-visible user and assistant messages, newest
first, as `{message_id, part_index, role, file}`, where `role` is `user`
or `assistant`. An optional `before_id` limits it to older messages.
Parts go through the same conversion as `GET /messages`, so `part_index`
matches that endpoint. `file` is a `ChatAttachmentFile`, a file-only
type, so the OpenAPI schema, the API reference, and the generated
TypeScript all describe a file part. An inline file omits `file_id` and
carries its bytes in `data` as a base64 string. It needs the same
permission as reading the chat. A new sqlc query,
`GetChatMessagesWithFilePartsByChatID`, backs it; there is no migration.
- **Panel:** attachments from the loaded messages stay live. While older
history is not loaded, the panel fetches the attachments before the
oldest loaded message and lists them with the rest. It sends no request
when every message is loaded or the Summary tab is hidden. Loading
earlier transcript pages reuses the list it already fetched instead of
sending another request, and does not blank, duplicate, or reorder it,
including while the last page moves into the chat store.
- **Groups:** files the agent attached are listed under "From the
agent", then uploads and pasted text under "From you".
- **Cards:** selecting a card previews the file. Images open in the
image lightbox and show their thumbnail on the card. Text, Markdown,
CSV, and JSON files open in the text preview, which opens at once with a
spinner while a stored file's text loads on its first view, and reuses
the text until the cache frees it, five minutes after nothing on the
page reads it. An icon on the card downloads the file. Other files keep
the download card. Closing a preview returns focus to its card, and an
image whose thumbnail fails to load becomes a download card that takes
focus, even if its preview was open.
- **Dialogs:** `Lightbox` now passes Radix's close event to
`onCloseAutoFocus` instead of always calling `preventDefault`, so a card
hands it to `useDialogFocusReturn().restoreFocus`, which prevents the
default only when it can focus a target. `MermaidDiagram`, the only
other caller that passes the prop, now calls `preventDefault` itself, so
its focus return is unchanged. `ImageLightbox` and `TextPreviewDialog`
take the same optional prop.
- **Transcript focus:** closing the preview of an attachment in the
transcript (the image lightbox or the text preview) or of a tool result
image returns keyboard focus to the attachment that opened it instead of
the page body. Each attachment button passes itself to the opener,
because a stored text file opens its preview only after its download
finishes, when the click event no longer holds the button.
- **States:** the header count shows once the list is complete and
leaves out expired files. An empty list says "No attachments yet." While
the earlier request is pending, the loaded attachments stay, with a
spinner below them. If the request fails, they stay and the section
shows the server's error in an alert with Retry, which stays while the
retry runs or waits offline. The load-earlier button is gone.
- **Expired files:** files the chat no longer has fold into a closed "N
expired attachments" list that names each one and explains why files
expire. A file from unloaded history counts as expired when the chat's
file list no longer has it. If the cached chat record is older than
those messages (a revisit after more than a page of new messages), a new
file can show as expired until the chat refetch returns. A stored text
file whose preview finds it deleted stays in place as "Attachment
expired", keeps focus, and leaves the count.
| Cards grouped by who attached them | Earlier attachments in the
Summary panel | Expired files, listed by name |
| --- | --- | --- |
| 
| 
| 
|
| Text file found deleted | Earlier request failed | Image preview |
| --- | --- | --- |
| 
| 
| 
|
Closes CODAGT-1436.
## Testing
`TestGetChatAttachments` checks the order and the filtering (deleted,
model-only, and tool messages are left out, and `part_index` skips a
stripped hook-context part as `GET /messages` does), compares every
returned file with its part from `GET /messages`, including an inline
paste's `data`, and covers `before_id`, a 400 for an invalid
`before_id`, a 404 for another user, and the raw JSON of an inline file,
which has no `file_id` key and a base64 `data` string. The dbauthz suite
asserts chat read. Vitest covers the panel's request gating and Retry,
seeding an earlier boundary from a cached list, the attachment helpers
(including earlier files the chat no longer lists), and the cards'
previews (including a text preview that opens before its text loads),
download link (including the share sheet it opens in an installed iOS
app), and focus, including a thumbnail that fails to load, also with its
preview open, and a text file that returns 404, and that a viewed text
file's text leaves the cache once nothing shows it. Vitest also opens a
transcript image, an inline text file, a stored text file whose download
finishes after focus has moved on, and a tool result image with Enter,
closes each with Escape, and checks that focus is back on the
attachment. Stories cover the new states, including a retry in flight, a
retry paused offline, and a reconnect after a failed retry. Two existing
stories now import the shared 1x1 PNG fixture instead of keeping their
own copies. Each new test fails when its code path is broken. No new
dependencies.
## Review record
- mafredri's review: grouping by role, the expired list, and keeping the
loaded attachments visible while the earlier request loads are in
`5cf0757b1d8`. The previews and the download icon that @ibetitsmike
asked for in the same round are in `6ae8719d6a0`.
- Frontend review (8 reviewer roles): 4 rounds before the first UAT, 3
delta rounds on the Codex fixes, then 12 rounds on mafredri's review and
the preview cards, with an FE1 to FE10 audit in rounds 2 to 10 (rounds
11 and 12 re-checked comments only), then 3 delta rounds on the
download-link test in `868d42430f0`, 4 on the fixes for Codex's fifth
run, 1 on its sixth, 7 on its seventh, and 4 on its eighth. The last of
those four passed every role it ran, and so did its FE1 to FE10 audit.
Every blocking and should-fix finding is fixed or declined with a
reason. Declined: the alert's title is an h2 under the section's h3,
because the shared `AlertTitle` always renders an h2, as in every
`ErrorAlert`; Retry does not move focus after a successful retry removes
it, which matches the other `RetryButton` callers and would need a focus
effect; the endpoint and panel ship together because the panel is the
endpoint's only consumer; a chat record without `files` is not read as
an empty file list, because the server also omits `files` when its
best-effort metadata query fails, which would show every earlier file as
expired; the header count does not subtract a deleted image or an
unopened text file, because the panel learns of a deletion only from the
chat record or a preview's 404; a card whose file a chat refetch reports
deleted moves into the expired list, which closes its open preview, as
the transcript swaps an evicted file's card for the expired tile; if the
transcript's last page arrives while the earlier request is still
loading, the header count briefly leaves out that page's files, because
only a rerender test reading the header could hold a fix, which FE1
keeps out of Vitest; a text file found deleted counts again once the
cache frees its 404, five minutes after nothing on the page reads it,
because keeping that 404 until reload would need a cache entry per
deleted file that is never freed, and the transcript on `main` forgets
the same 404 as soon as the chat closes; and AttachmentBlocks.tsx is at
719 lines (699 on `main`), because moving its file cards out would
create an import cycle.
- Remote dogfood UAT passed on `c1af9dd7cbc` and again on `d11c699cd0d`.
The second round ran `d11c699cd0d` and the `c1af9dd7cbc` frontend
against the same backend: an evicted earlier upload shows as expired on
`d11c699cd0d` and as a download card that returns 404 on `c1af9dd7cbc`,
and loading earlier pages sends no further attachments requests on
`d11c699cd0d`, while `c1af9dd7cbc` sent one per new page boundary. One
issue also reproduces on `main` and is unchanged here: after a live
attach evicts an older file, the panel and the transcript keep its
download card until the page reloads. The changes since `66e92f09064`
(mafredri's review, the preview cards, and the fixes for Codex's third
to eighth runs) were checked in Storybook and Vitest, and on dogfood
only through the keyboard round below, which also opened the Summary
panel's image and text cards; the screenshots above are Storybook
renders.
- Codex review: round 1 raised 4 findings, all fixed (see the resolved
threads). Round 2 found no issues on `d11c699cd0d`. A third run on
`d11c699cd0d` raised 2 findings, both fixed in `db0109d1120`. A fourth
run on `6ae8719d6a0` raised 1 finding (the download-link test read only
the link's attributes), fixed in `868d42430f0`. A fifth run on
`868d42430f0` raised 4 findings. Three are fixed in `e924d0595d9`: an
open image preview lost focus when its thumbnail failed, a slow text
load let a second preview open, and the earlier attachments dropped for
a render when the last page loaded. The fourth (paginate or cap the
endpoint) is left open for a product decision. A sixth run on
`e924d0595d9` raised 1 finding (the expired list's button did not say
what expired), fixed in `661db9b52af`. A seventh run on `661db9b52af`
raised 4 findings, all fixed: an inline file's `file_id` came back as
`null` and the schema described `data` as integers (`5fb4a047e39`), and
viewed text stayed cached until reload and the card's doc comment
restated its code (`51c5c98feb8`). An eighth run on `51c5c98feb8` raised
3 findings. Two are fixed: the attachment role allowed `system` and
`tool` (`2ed84cd882f`), and the error line hid the server's message
(`ce4e79593f6`). The third, that Testing Library cannot find the
decorative thumbnail by its `img` role, does not reproduce and is
declined in its thread.
- @jaaydenh's approval note, that keyboard focus was lost after closing
the preview of an attachment in the transcript, is fixed in
`b37b9952898` and `484e010dd25`; `359dd039b78`, `277b89ba1e2` and
`606b601c445` only refactor the hook, tighten the tests, and reword a
comment. Frontend review ran 5 rounds on the fix; the last passed, and
every blocking and should-fix finding is fixed or declined. Declined:
the composer's pending-attachment previews, the recording preview, and
the Instructions page's text preview also drop focus when they close,
but they predate this PR and are outside the transcript, so they are a
follow-up; if a stored text file finishes downloading while the same
message's image preview is open, closing the image returns focus to the
text file, because a message row remembers one opener, so focus still
stays in that message; and the fix grows ConversationTimeline.tsx from
812 to 827 lines, which was already over the 500-line guideline. Remote
dogfood UAT passed on `484e010dd25` with real key presses: after Enter
or Space opens the preview of a user's image, text file (also when its
download is slowed and the user presses Tab while it loads), or pasted
text, of an assistant's attachments, of one of three attachments in one
message, or of a tool result image, Escape returns focus to the same
attachment, so Tab continues from there. On `bac7cb055ce` focus fell to
the page body and the next Tab went to the Coder logo, so a keyboard
user needed 130 Tabs to get back to the composer instead of 44. Summary
panel cards returned focus before the fix and still do. The image,
slowed text file, and Summary panel cases passed again on `277b89ba1e2`;
`606b601c445` changes only a comment.
- Rebased onto `main` after those reviews. The added and removed lines
are unchanged; only the path of `AgentChatPageView.tsx` changed, because
`main` moved it into `AgentChatPage/`. After the eighth Codex run,
`main` was merged in, with one conflict in `coderd/chat_routes.go`,
where both sides added a route. On 2026-10-26 the branch was rebased
onto `main` (`aa9b0a950ad`) again, with conflicts in the same route list
and in the generated `site/src/api/typesGenerated.ts`, where both sides
added a type; the added and removed lines are unchanged.
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
1e0a481a60 |
fix: retry workspace quota commits with jittered backoff (#31207)
Bursts of builds for the same user and org (usually autostarts) can hit serialization failures in `CommitQuota`. `InTx` only retried those 3 times back-to-back, so once retries ran out the build failed outright. `CommitQuota` stays `SERIALIZABLE` and now gets up to 10 retries with full-jitter exponential backoff (50ms base, 2s cap, about 11s of backoff at most). These builds aren't interactive, so a longer wait is a better trade than a failed build. The wait respects the request context and happens between transactions, so nothing holds a connection while it sleeps. Each attempt also resets its results now, so a rolled-back attempt can't leak `Ok: true` into the response. The retry settings are opt-in fields on `database.TxOptions` (`SerialMaxAttempts` and `BeforeSerialRetry`). Every other `InTx` caller keeps the default 3 attempts with no delay. Since this touches `coderd/database/db.go`, it'll need a look from a `coderd/database` owner. This replaces #30126 with the simpler approach Spike and I landed on. If we still see failures after this ships, the next step is making autostart replica-aware so a single replica handles each user, rather than adding locking here. Fixes [CORE-198](https://linear.app/codercom/issue/CORE-198) |
||
|
|
4e4a56b665 |
fix: show configured provider icons and names in AI settings (#31033)
Admin-configured provider icons were ignored on the AI Settings Models
page (model rows, Add model menu, provider filter, model form header and
provider select) and in Agents compaction settings. These views derived
the icon only from the provider type, so a provider like DeepSeek on an
OpenAI-compatible type showed a generic icon even though the Providers
page and chat model selector showed the configured one. They now pass
the configured icon to `ProviderIcon`, which falls back to the type
icon.
The Spend page showed provider types (OpenAI) instead of configured
providers (DeepSeek) because `ListOrganizationAISpendUsers` aggregated
`ai.provider` while its filter matched `ai.provider_name`. It now
aggregates `provider_name`, and the page resolves names to display names
and icons from the AI Gateway providers list, which it shares with the
provider filter through one query. `OrganizationAISpendUser.providers`
now holds provider names; records from before configured names existed
have the type as their name, so they render as before.
AI Gateway Sessions views have the same type-versus-name issue and are
left for a separate fix.
**Note:** the Spend page resolves provider display names and icons from
`/aibridge/providers`, which requires deployment-wide read access
(`viewAnyAIBridgeInterception`). Owners and Auditors see the custom
display name and icon; Template Admins, User Admins, Org Admins, Org
Auditors and Org User Admins see the provider name rendered as a type
without the icon. Revisiting that endpoint's permissions is tracked in
AIGOV-726.
Refs CODAGT-1421
<details>
<summary>Decision log</summary>
- Root cause: callers rendered `<ProviderIcon provider={type} />`
without the descriptor's `icon`; nothing was stale.
- Spend page provider metadata is fetched only for viewers who can
already use the provider filter (`viewAnyAIBridgeInterception`); other
viewers see names formatted like provider types.
- Extended `ProvidersBadge` with an optional `providersByName` map
instead of adding a Spend-specific badge, so the Sessions fix can reuse
it.
- Removed `providerTypeByIDFromUserConfigs`, which became unused once
compaction settings used `providerInfoByIDFromUserConfigs`.
- Visual coverage is in Storybook stories (ModelRow, ModelForm,
UserCompactionThresholdSettings, SpendPage) per the repo's FE1 rule.
</details>
---
_Generated by Coder Agents on behalf of @tracyjohnsonux._
|
||
|
|
15a5844253 |
feat: add cost to AI Gateway session threads API (#30509)
## Description
Exposes cost data on the AI Gateway session threads endpoint (`GET
/api/v2/aibridge/sessions/{session_id}`), so the session page can show
cost alongside token usage. Backend only, the UI changes for AIGOV-600
will follow separately.
## Changes
- Add `cost_micros` and `has_unpriced_usage` to
`AIBridgeSessionThreadsTokenUsage`, populated for the session summary,
each thread, and each agentic action.
- Compute the session summary cost in `ListAIBridgeSessions`, next to
the existing session token sums, so tokens and cost come from the same
rows.
- Add `priced_model`, the model and per-token prices used for pricing,
to `AIBridgeThread` for the root interception (the prompt) and to each
`AIBridgeAgenticAction` for that interception, since requests in a
thread may be priced as different models. Nil when not priced.
- Update frontend mocks for the new required fields.
Related to AIGOV-600
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
|
||
|
|
946c2f0e04 |
feat: resolve orgs from workspace session tokens in AI Gateway requests (#30902)
Add an AI Gateway org resolver at the coderd IsAuthorized boundary, detect workspace session tokens, load the workspace org, validate the user is still a member of that org, reject missing workspaces or invalid membership, and return the resolved org in IsAuthorizedResponse while leaving it unused by downstream policy. Include tests for successful workspace-token resolution, missing workspace rejection, invalid org membership rejection, and compatibility with the existing ServeHTTP flow. Fixes AIGOV-714 |
||
|
|
9edb2e388d |
feat: enable Coder.USSpelling Vale rule (#30790)
Depends on #30782. Adds `Coder.USSpelling` at `warning` severity. The rule flags an `-ise` family (`organise`, `initialise`, `authorisation`) and a list of British spellings (`behaviour`, `labelled`, `cancelled`, `analogue`, `whilst`, and others) and suggests the US form. It covers `docs/**` except `docs/.style/style-guide/**` and the generated `docs/reference/{api,cli}/*.md` pages. Baseline: 13 findings before cleanup, 0 after. The first commit fixes 11 of them: 10 in hand-written pages and 1 in the Prometheus metrics table, which comes from metric help text. Two findings sit in generated reference pages, which `.vale.ini` excludes for this rule: the CLI alias `favourite` and `amongst` in a Go comment from a vendored dependency (the DERP map schema). The metric help text comes from `querymetrics.go`, so the fix lands there and in `generated_metrics` and `prometheus.md`. Known false positive: Vale doesn't skip bold text, so a UI label in bold that keeps British spelling is flagged. The rule comment and the guide footer say to use a code span for such a label. Linear: DOCS-1280 <details> <summary>Decision log</summary> - **Rule type**: `substitution`, so each message names the US form. The `-ise` family can't name a specific replacement, so it suggests "the -ize form". - **`cancelled`**: the guide's "Use US spelling" section lists `canceled` and `canceling`. The rule flags the double-l verb forms and leaves `cancellation` alone, which Merriam-Webster spells with one `l`. - **Exceptions**: Vale applies an exception to the matched word, so each is anchored with `^` and `$` and case-insensitive. The list covers `-wise` words and stems for `advise`, `advertise`, `exercise`, `promise`, `premise`, `compromise`, `surprise`, `comprise`, `concise`, `precise`, `revise`, `supervise`, `televise`, `devise`, `improvise`, `franchise`, `merchandise`, `disguise`, `despise`, `paradise`, `cruise`, `noise`, `raise`, `rise`, `wise`, and others, each with the endings `e`, `es`, `ed`, `ing`, `er`, and `ers`. The `mise` tool is excepted by name. - **Extra British spellings** beyond the guide table: other doubled-`l` verbs (`signalled`, `levelled`), `metre`, `litre`, `fibre`, `theatre`, `calibre`, `offence`, `pretence`, `analyse`, `judgement`, `acknowledgement`, `ageing`, `artefact`, `sceptic`, `aluminium`, `practise`, `enrol`, `fulfil`, `instil`, `skilful`. None appears in the corpus today. - **Generated pages**: excluded for `docs/reference/{api,cli}/*.md`, as `Coder.UnitSpacing` does. Changing the `favourite` alias would change CLI behavior, and the `amongst` comment isn't ours to edit. - **Prometheus doc**: edited by hand with matching table padding because `go run ./scripts/metricsdocgen` already rewrites the whole table on the base branch, independent of this change. Test cases, run with `vale --config` against fixtures that are not committed, in LF and CRLF: - Positive: `organise`, `initialise`, `authorise`, `customisation`, `authorisation`, `organisations`, `Organised`, `initialising`, `recogniser`, `customisable`, every explicit list entry, and capitalized forms. - Negative: `advise`, `exercise`, `otherwise`, `Enterprise`, `premise`, `compromise`, `promise`, `surprise`, `precise`, `concise`, `expertise`, `revising`, `supervising`, `improvising`, `raise`, `noise`, `cruise`, `franchise`, `merchandise`, `disguise`, `despise`, `paradise`, `appraise`, `sunrise`, `arise`, `liaise`, `clockwise`, `cancellation`, `canceled`, `mise`. - Skipped: words in code spans and fenced code blocks, such as `cancelled`. - LF and CRLF results are identical. Checks: `vale --output=line docs/` reports 0 `Coder.USSpelling` findings, `make lint/style-claims` passes, and the pre-commit hooks pass on both commits. </details> *Generated by [Coder Agents](https://coder.com/docs/ai-coder/agents) on behalf of @nickvigilante.* |