mirror of
https://github.com/coder/coder.git
synced 2026-11-21 18:58:17 +08:00
dependabot/github_actions/github-actions-fe5f304cd8
678
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
8705d80fe0 |
feat: add provider, model, and client spend to the AI spend users endpoint (#32330)
## Description
Extends the experimental `GET
/api/experimental/organizations/{organization}/ai/spend/users` endpoint
with the per-user details behind the AI spend overview and the detailed
report. Each user now returns their spend per provider, model, and
client, and whether each has unpriced usage.
## Changes
- Rewrite `ListOrganizationAISpendUsers` with `GROUPING SETS`, returning
one row per user and provider, model, or client:
- Adds the `user_ids` and `group_id` filters.
- Pages, counts, and totals users, not their rows.
- Reads the provider display name, icon, and type from `ai_providers`,
including deleted providers. The live provider wins when a name was
reused, like `GetAIProviderFilterOptions`.
- Update the SDK and handler:
- Each user returns `provider_spend`, `model_spend`, and `client_spend`,
most expensive first, each with `has_unpriced_usage`.
- `totals` returns `has_unpriced_usage`.
- Remove the `providers`, `clients`, and `models` name arrays and
`unpriced_usage_count`.
- Accept `user_ids` (comma-separated, maximum 100) and `group_id`.
- Return more than 100 `user_ids` on the group members AI spend endpoint
as a validation error, like `/ai/spend/users`.
- Switch the Spend page to the new fields, with no UI changes.
- Update the query and handler tests.
<details>
<summary>Dogfood performance</summary>
- Benchmarked on **dogfood**, comparing the existing query on **main**
with the updated query in **this PR**.
- Tested **1, 7, 15 and 30-day windows**, ending at **November 18, 2026,
00:00 UTC**, exclusive.
- Each query ran **five times per window**, one at a time, with query
order and window order rotated across rounds to reduce ordering bias.
The table shows PostgreSQL execution time in **seconds, average
(min-max)**.
| Days | Main | This PR |
|------|-----:|--------:|
| 1 | 0.288 (0.199-0.501) | 0.223 (0.184-0.275) |
| 7 | 11.413 (4.076-40.003) | 4.107 (3.529-4.828) |
| 15 | 9.961 (8.053-16.917) | 7.253 (6.873-7.736) |
| 30 | 14.979 (12.276-23.177) | 8.499 (7.813-9.169) |
All five runs are included. Main's first seven-day run took **40.003s**
with unusually high read I/O time, which raises its average. Cache and
concurrent load can affect these results.
</details>
Closes AIGOV-734
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
|
||
|
|
4bccdc4ed6 |
feat: show and filter by organization in AI Gateway sessions API (#32057)
Adds an `organization` filter to `GET /api/v2/ai-gateway/sessions` (and its `/api/v2/aibridge/sessions` alias) and returns the organization an interception was attributed to, and how it was chosen, on sessions, threads and agentic actions, as proposed in the surface definitions on AIGOV-754. No migration: `aibridge_interceptions.organization_id` and `organization_source` already exist (000634). The filter accepts an organization name or ID and keeps sessions with at least one interception in that organization; the count uses the same rule so pagination totals match. Each session, on the list and detail responses, lists the organizations its interceptions were attributed to, ordered by name, with the distinct sources used for each, or `[]` when none was stored. Each thread carries the organization of its root interception and each agentic action carries its own, or null when none was stored. The new filter is listed in the AI Gateway monitoring docs. Refs AIGOV-754 ## Open questions for reviewers - **Multi-org sessions** (AIGOV-776): the filter is row-level, like provider and model. A session spanning two orgs is listed under each org's filter, and with the filter on, `threads`, `started_at` and `ended_at` only cover the matching interceptions, while providers, models, tokens and `organizations` cover the whole session. Is that the desired behavior? - **Unknown org ID:** an unknown org name returns 400, but an unknown org ID returns an empty page, because `parseOrganization` does not look up UUIDs. This matches workspaces and templates, but the spec says 400. ## Notes for reviewers - `aiBridgeSessionOrganizations` returns an empty list if the organizations JSON from the query can’t be decoded, rather than failing the whole request. The field is supplementary, so a decoding problem shouldn’t take down the sessions list, but it does mean a SQL bug here would show up as empty data rather than an error. The alternative is to log the error before returning the empty list. - A thread’s organization is taken from its root interception only. If later requests in the same thread were attributed to a different organization, that shows on each agentic action’s own organization field. <details> <summary>Implementation notes</summary> - `coderd/database/queries/aibridge.sql`: - `@organization_id` filter in `CountAIBridgeSessions` and the `session_page` CTE of `ListAIBridgeSessions`. - New `sorg` lateral in `ListAIBridgeSessions` that groups the session's interceptions by organization, collects distinct sources, joins `organizations` (deleted orgs still resolve) and returns a JSON array. - `ListAIBridgeSessionThreads` resolves the organization name, display name and icon through a `LEFT JOIN LATERAL` in the final `SELECT`. A plain join on `organizations` is not safe there: the query has two `@authorize_filter` placeholders, and the injected filter can reference a bare `id`, which would be ambiguous next to `organizations.id`. The lateral only exposes the three selected columns. This answers the authorize-filter open question from the surface proposal. - `coderd/database/modelqueries.go`: the hand-written `ListAuthorizedAIBridgeSessions`, `CountAuthorizedAIBridgeSessions` and `ListAuthorizedAIBridgeSessionThreads` gain the new argument and scan columns. The compiler does not catch a mismatch here; it fails at runtime. - `enterprise/coderd/aibridge.go`: pass `OrganizationID` into `CountAIBridgeSessionsParams`, which is built field by field, and list the `organization` key in `@Param q`. - `coderd/searchquery/search.go`: `organization` key via `parseOrganization`. - `codersdk/aibridge.go`: `AIBridgeInterceptionOrganizationSource` enum, `AIBridgeInterceptionOrganization`, `AIBridgeSessionOrganization`, new response fields and `AIBridgeListSessionsFilter.Organization`, per the proposed Go definitions. - `coderd/database/db2sdk/db2sdk.go`: decode the session organizations JSON, never returning nil; `AIBridgeInterceptionOrganizationSource` converter; build one organization per interception while grouping thread rows, and use it for the thread (root interception) and each agentic action. - `site/`: add `organizations: []` to two frontend mocks, now that the field is required in the generated types. - `docs/ai-governance/ai-gateway/monitoring.md`: `organization` added to the sessions API query filters. - Tests: `TestAIBridgeSessions` (name and ID parsing), `TestAIBridgeListSessions/Filters` (by name and ID, checks count and page), `FilterErrors/UnknownOrganization`, `TestAIBridgeListSessions/Organizations` (multi-org ordering and sources, no-org session returns `[]`, filtering by either org returns the multi-org session and never the no-org one), `TestAIBridgeGetSessionThreads/Organizations` (thread uses the root's org, each action its own, null when none, session `organizations` on the detail endpoint), and `TestAIBridgeInterceptionOrganizationSource` (every database source maps to an SDK value). - Remaining files are generated by `make gen`. </details> --- Code written by @mollymaefraser, with Coder Agents used as a guide: explaining the existing code path, reviewing each step, and running tests. |
||
|
|
734a0cae07 |
feat: scope browser-only connections to a template (#30578)
Add per-template `browser_only` enforcement while preserving `CODER_BROWSER_ONLY` as a deployment-wide override. Refs #29157. Supersedes #29204 (closed by stale bot). Rebased onto current `main`, with migration renumbered to `000643`. ### Changes - Add `templates.browser_only` (default `false`) to the database, SDK, and template create/update APIs. - Require the `browser_only` entitlement to enable the setting, but allow disabling and continue enforcement after license expiry. - Reject agent coordinate connections with 409 and enforce per-template tunnel restrictions through `AuthorizeTunnel`. - Return non-fatal tunnel policy errors in both AGPL coordinator and pgcoord, preserving other active tunnels on shared connections. - Exclude browser-only workspaces from Desktop workspace updates and enforce the restriction in MCP agent connections. - Fix `TestMigration000617ConnectionLogsMethod` to use raw SQL, avoiding schema compatibility issues. ### Open questions - **Naming:** Keep `browser_only` or use `require_browser_connections`? - **Performance:** `AuthorizeTunnel` adds a database query under the coordinator mutex. Consider a narrower query if needed. - **Feature reporting:** Should the feature report as enabled when any template uses it? ### Out of scope Dashboard UI, CLI flag, and Terraform provider support (requires a separate `coder/terraform-provider-coderd` change). ### Verification - Relevant unit and integration tests passed, including coordinate rejection, tunnel isolation, workspace filtering, and non-fatal policy errors in both coordinators. - `golangci-lint` passed with no issues. - Regenerated database, SDK TypeScript, Swagger/API reference, and audit-log artifacts. - Not manually verified with Coder Desktop, multi-node deployments, workspace proxies, or UI. ### AI disclosure Most changes and the rebase were completed with Claude Code (Opus 5/5.5), following the [AI contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING). |
||
|
|
579b9995e8 |
fix: document WebSocket routes as 101 responses in the Swagger spec (#30125)
Six WebSocket routes were documented as `200` responses: `chats/watch`,
`chats/{chat}/stream`, `chats/{chat}/stream/git`,
`chats/{chat}/stream/parts`, `workspaces/{workspace}/watch-ws`, and
`workspaceagents/{workspaceagent}/watch-metadata-ws`.
Mark them `@Success 101`, matching the other WebSocket routes, and
describe each message. `chats/{chat}/stream` and `stream/parts` send a
JSON array batch of events per message, so they keep `{array}`; the
others send one event per message.
Also document that the previous template version route returns `204`
with no body when there is no previous version.
Part of DOCS-1122, split from #30121.
<details>
<summary>CI flakes unrelated to this change</summary>
On `d23267b7c3`, two checks failed in code this PR does not touch.
-
[`TestChatTurnStopsAtStepLimit/Default`](https://github.com/coder/coder/actions/runs/40809166900/job/123235512188)
in `coderd/x/chatd` (test-go-pg, ubuntu): this PR changes only Swagger
comment annotations and generated docs, and does not touch the `chatd`
package.
-
[`updateWorkspace.spec.ts:76`](https://github.com/coder/coder/actions/runs/40809166900/job/123235512158)
(test-e2e): this PR changes no UI code, and the test exercises workspace
parameter updates.
</details>
---
🤖 Built with AI assistance.
---------
Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com>
|
||
|
|
17a2b62205 |
feat: add an API to attach templates to chat projects (#30754)
Adds the API for attaching workspace templates to a chat project, on the schema and queries in #32309. A project can attach templates, turn on a limit that restricts its chats to them, and set a default template with either a default preset or default parameter values. Attaching a template never grants access to it: every reader is checked against the template's own sharing. This PR stores and returns `limit_templates`; #32310 enforces it. - The limit is opt-in. `limit_templates` is off unless a request turns it on, which is what every existing project gets. - Templates are attached and detached one at a time with `PUT` and `DELETE /chats/projects/{project}/templates/{template}`, so a caller never replaces a list they can only partly see. Attaching needs project `update` and template `use`. Detaching needs project `update` and template `read`, and a template the caller cannot read is reported as not found. `POST /chats/projects` accepts `template_ids`, `limit_templates`, and `default_template` for the new project. - `PATCH /chats/projects/{project}` sets `limit_templates` and `default_template`, and no longer changes which templates are attached. The default must be an attached template the caller can read, and its preset must belong to the template's active version. Default parameter names and values are checked against that version for templates on the classic parameter flow; dynamic parameters are checked when a workspace is built. Detaching the default template clears the default. - Project responses list only the attached templates the caller can read, as `templates`, and count the rest as `hidden_template_count`. `default_template` is omitted when the caller cannot read it. Deleted, deprecated, and agent-disabled templates are left out and are not counted as hidden. - Editing uses `chat_project:update`, which the project owner and the project `admin` ACL role have. - Attaching and detaching are audited as writes to the project, with the template list before and after, including the templates attached while creating a project. Changes to `limit_templates` and the default template are part of the project's own audit diff. Not included: showing which project members lack access to an attached template, and MCP server attachments. Stack (merge top to bottom): - #32309 - #30754 👈 - #32310 - #30755 - #32371 - #32372 - #30756 - #32373 - #32374 - #32375 - #30898 - #32376 - #32377 - #32378 - #32379 |
||
|
|
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> |
||
|
|
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.
|
||
|
|
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) | ||
|
|
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. |
||
|
|
2187ecd37e |
feat: add PubsubReport to healthsdk HealthcheckReport (#31620)
Adds pubsub to the deployment health report types in `healthsdk`:
- New top-level `pubsub` section (`PubsubReport`) in
`HealthcheckReport`. It embeds `BaseReport` and adds one field,
`backend` (string).
- New `HealthSectionPubsub` constant, added to `HealthSections` so the
section can be dismissed.
- `HealthcheckReport.Summarize` includes pubsub errors and warnings,
which `coder support bundle` prints.
This is the first PR in a stack for GRU-100. It only changes the SDK and
the files generated from it (Swagger, API docs, `typesGenerated.ts`),
plus the two frontend health mocks that need the new required field. The
server does not fill in this section yet. That comes in a follow-up PR.
<details>
<summary>Plan</summary>
- Add `PubsubReport { BaseReport; Backend string }` to
`codersdk/healthsdk`.
- Add `Pubsub PubsubReport \`json:"pubsub"\`` to `HealthcheckReport`.
- Add `HealthSectionPubsub` and include it in `HealthSections`.
- Include `Pubsub` in `HealthcheckReport.Summarize`, with test coverage.
- Regenerate TS types, Swagger and API docs.
- Follow-up PRs: populate the report in `coderd/healthcheck` (including
severity and dismissal handling) and update the health UI.
</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> |
||
|
|
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.
|
||
|
|
e307f1d5cf |
feat: add the user-scoped chat-automations experiment (#32064)
## Why The Automations RFC controls availability with one user-scoped experiment. Its text: "The user-scoped `chat-automations` experiment controls availability. Operators configure defaults with `--experiments` and can change per-user rules while Coder is running. Each surface checks the relevant caller or automation's owner, and experiment evaluation fails closed." The later backend PRs (management routes, the `manage_automations` tool, `Publish`) need that check first. This PR registers the experiment and proves the per-user, fail-closed check. Nothing consumes it yet. Part of CODAGT-1135 ## What changed - Registers `chat-automations` in `ExperimentsKnown` and `ExperimentsUserScoped`. An earlier experiment with this name was removed in #30412, and this PR restores none of its consumers. - Keeps it out of `ExperimentsSafe`, so `--experiments=*` does not turn it on. Automations act with their owner's authority, and a test pins the choice. - Adds the name to the `userScopedExperimentStaticCheck` ruleguard rule, so server code cannot decide it from the static list. `TestExperimentsUserScopedRuleguard` keeps the rule in step with `ExperimentsUserScoped`. - Regenerates the swagger files, `docs/reference/api/schemas.md` and `typesGenerated.ts`. - Adds tests for the real experiment name. The evaluator tests cover the startup default, stored `on`, `off` and condition rules for two users, and an off decision on a rules read error, a malformed rule, an unknown mode, an attribute read error, a condition error and a nil subject. A coderd test with a real database checks the same per-user behavior through `api.ExperimentEvaluator` and `GET /api/v2/experiments`. ## Scope No routes, tool, UI or chatd change. I added no helper: `Evaluator.Enabled(ctx, userID, ex)` already decides per user and fails closed, and API handlers reach it through `api.ExperimentEvaluator`. chatd has no evaluator handle on main, because #31327 removed the unused field. The first chatd consumer adds it together with its read. ## Blast radius With the experiment off, which is the default, behavior on main does not change. Two things become visible. `GET /api/experimental/experiments/rules` and `coder exp experiment-rules list` show a `chat-automations` row, and an administrator can store a rule for it. A deployment that already passes `--experiments=chat-automations` sees three small differences: the startup log reports an opted-in hidden experiment where it reported an unknown one, the deployment Overview page stops flagging the name as invalid, and the rules row shows the static default as on. Nothing reads the experiment yet, so no feature turns on. ## Live check A local `./scripts/develop.sh` deployment built from this head ran with no flag, with `--experiments=*` and with `--experiments=chat-automations`. `GET /api/v2/experiments` lists `chat-automations` for the owner and for a member only when the startup list or a rule turns it on, and `--experiments=*` does not turn it on. A condition rule `user.username == "member"` turned it on for the member and off for the owner without a restart, and `reset` restored the startup default. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_ |
||
|
|
1126533c31 |
feat: export workspace last used time to Prometheus (#31346)
Add an opt-in coderd_workspace_last_used_timestamp_seconds gauge that reports workspaces.last_used_at, the value the dormancy threshold measures inactivity from. To enable it, set --prometheus-collect-workspace-stats or CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS. A separate WorkspaceStats collector refreshes the gauge once a minute in the background from a new GetWorkspaceLastUsedForMetrics query. Each series has a workspace_id label, so a workspace that reuses a deleted workspace's name starts a new series. Workspaces owned by deleted users are excluded. Closes CLIENT-1065 |
||
|
|
0a7ef88af9 |
feat: add option to disable the embedded AI Gateway (#31967)
Adds `--ai-gateway-embedded-enabled` / `CODER_AI_GATEWAY_EMBEDDED_ENABLED` (default `true`) so standalone-only deployments can stop `coderd` from starting the in-memory AI Gateway. `CODER_AI_GATEWAY_ENABLED` stays the global switch: the AI Gateway entitlement, `/api/v2/ai-gateway/serve`, and cost-control metrics still depend only on it. The embedded daemon now starts only when both options are `true`. | `ENABLED` | `EMBEDDED_ENABLED` | Result | |---|---|---| | `true` | `true` | Unchanged | | `true` | `false` | No embedded gateway; standalone gateways keep working | | `false` | any | No AI Gateway | Refs AIGOV-514 ## Open questions for reviewers - **Coder Agents does not work with the embedded gateway disabled.** `chatd` still starts, but model calls fail with "AI Gateway transport factory is not configured" because there is no in-process transport. AIGOV-597 (routing Agents through standalone gateways) was canceled. The docs and option help state that Agents requires the embedded gateway. Is that acceptable, or should `chatd` also be turned off in this mode? - **Option name:** the ticket proposed `CODER_AI_GATEWAY_EMBEDDED_ENABLED` tentatively. OK to keep? ## Verification ``` $ go test ./cli/ -run 'TestServer_AIGateway' -count=1 ok github.com/coder/coder/v2/cli 0.518s $ go test ./enterprise/coderd/ -run 'TestAIGatewayServe' -count=1 ok github.com/coder/coder/v2/enterprise/coderd 0.755s ``` `TestServer_AIGatewayEmbedded` fails when the new check is removed. <details> <summary>Implementation notes</summary> - `codersdk/deployment.go`: new option and `AIBridgeConfig.EmbeddedEnabled` field; updated `--ai-gateway-enabled` description. - `cli/server.go`: outer `if Enabled` sets up cost-control metrics and the blocked-users collector (the standalone `/serve` endpoint uses these too). Inner `if EmbeddedEnabled` creates the daemon, registers the in-memory handler, and adds its cleanup. - `cli/server_test.go`: `TestServer_AIGatewayEmbedded` covers the three modes by checking for the embedded daemon's startup log. - `enterprise/coderd/aibridgeserve_test.go`: `TestAIGatewayServeEmbeddedDisabled` checks the entitlement and `/serve` still work with embedded disabled. - `docs/ai-governance/ai-gateway/standalone.md`: new "Disable the embedded gateway" section. - Remaining files are generated by `make gen`. - Found during review: keeping metrics inside the embedded check would have dropped cost-control metrics for standalone gateways. </details> --- Generated with Coder Agents; reviewed, revised, and verified by @mollymaefraser. |
||
|
|
fb12d6018f |
fix!: redact agent environment variable values in API responses (#31932)
Workspace, build, and agent API responses (`/workspaces`,
`/workspacebuilds/{id}`, `/workspaceagents/{id}`, and so on) returned
agent environment variable values in plain text. Template authors often
pass credentials such as API tokens through `coder_env`, so anyone who
could read the workspace could read those secrets.
`db2sdk.WorkspaceAgent` now replaces every non-empty value with
`***REDACTED***` and keeps the keys. This is the same marker the support
bundle (`sanitizeEnv`) and the agent `/debug/manifest` endpoint already
use. The agent still gets the real values through its manifest
(`db2sdk.WorkspaceAgentEnvironment`), and nothing in the CLI or frontend
reads these values from the API.
Every value is redacted because neither `coder_env` nor
`coder_agent.env` in the Terraform provider has a sensitive flag, and
`proto.Env` has no field to carry one. Selective redaction would need
changes to the provider, the proto, and the database.
## For changelog
- Agent environment variable values are redacted in API responses
(#31932)
> Workspace, workspace build, workspace agent, and template version API
responses now return `***REDACTED***` for every non-empty agent
`environment_variables` value. Keys and empty values are unchanged. The
agent still receives the real values, so workspaces behave as before.
>
> Migration: Update scripts and integrations that read agent environment
variable values from the API or from `coder list -o json`. Read the
values inside the workspace instead.
Closes ENG-1505 (coder/security#51)
<details>
<summary>Decision log</summary>
- Confirmed the leak on `main` (
|
||
|
|
7301cee2c4 |
fix: list every enum value the API can return in the Swagger spec (#30122)
The API reference is generated from Swagger comments and struct tags, and several `enums:"..."` tags narrowed a named enum type, so the docs omitted values the server returns. For example, `User.status` listed only `active` and `suspended`, not `dormant`, and `TemplateVersion.warnings` listed `DEPRECATED_PARAMETERS`, which is not a value of the type. Remove 34 `enums` tags that narrow or duplicate a named type so the referenced type's full value list is used. Tags that describe an intentional subset stay: ACL role fields (which omit the `""` deleted sentinel used only in update requests), `APIKey.scope`, and plain-string fields. `Template.provisioner` keeps its tag because `.swaggo` replaces `ProvisionerType` with `string`. Also fix enum defects that break code generators: - The provisioner jobs and daemons `status` query parameters listed their enum twice (Swagger 2.0 requires unique `enum` items) or with the wrong type. Both are now `[]codersdk.ProvisionerJobStatus` and `[]codersdk.ProvisionerDaemonStatus`, matching what each handler parses, including comma-separated values. The daemons route previously documented job statuses, which the handler rejects with a 500. - Replace the `_` zero placeholder of `WatchErrorCode` with `iota + 1`, so the spec no longer lists 0 or `x-enum-varnames: ["_", ...]`. Wire values are unchanged. Where the narrowed tag hid values the server returns, the SDK type now includes them: `LoginTypeOAuth2ProviderApp`, `BuildReasonAutodelete`, and `MissingTemplateParameter` widen the generated TypeScript unions. The dashboard attributes `autodelete` builds to Coder like other system builds. `APIKey.login_type` and `AuthorizationCheck.action` set explicit examples so the generated samples stay representative. `TestSwaggerEnumsNotNarrowed` fails when a property's enum list drops values of its named type (other than the 15 allowlisted intentional subsets), lists a value the type lacks, or repeats a value. Part of DOCS-1122, split from #30121. --- 🤖 Built with AI assistance. |
||
|
|
082668fbc1 |
feat: run computer use on OpenAI-compatible AI providers (#31895)
Computer use only ran on Anthropic and OpenAI AI providers. Chatd derives the tool flavor from the AI provider type, and `openai-compat` had no flavor, so every self-hosted model was marked unavailable for `type=computer_use`, including the model a single-provider deployment already uses for chat. Hosted computer tools are not an option on those servers: an OpenAI-compatible endpoint accepts a `computer_20250124` tool over `/v1/messages` and a `computer-use-preview` tool over `/v1/responses` and then drops both, so the model never sees a way to act. Computer use is now declared as an ordinary function tool for those providers. The model sends one action per call and every call answers with a fresh screenshot, which is the shape these models already handle through the shared action runner. The tool omits `zoom`, which the agent desktop cannot perform. The desktop clamps a point outside the screen to its edge, so the tool rejects a coordinate outside the declared screenshot with an error that states the valid range, and a model that aims off the screen learns that it missed. Media tool results reach the model because the pinned fantasy fork promotes them to user-role messages, so no dependency changed. Coder can't verify an arbitrary OpenAI-compatible model, so those models keep the unverified warning icon in the admin UI. The virtual desktop docs, the Coder Agents index, the chatd architecture doc, and the organization model settings copy now list OpenAI-compatible providers as supported, and the docs say what to check before using one. Three shared behaviors needed fixing to make this usable. A coordinate of `[0,0]` is the top-left pixel and decoded as an omitted field, so the desktop rejected those clicks with a missing-coordinate error; coordinates now decode by key presence, which also keeps an absent coordinate absent. A `scroll_amount` of zero or less, or a key `repeat` of zero, was also forwarded as omitted, so the desktop scrolled its default of three clicks or pressed the key once; the runner now rejects both, and the function tool declares a minimum of 1 for each. And because a chat completions model sends one action per call, it plans every call of a step against one screen, so a failed action now halts the later calls of that step, as it already did for Anthropic. The hosted OpenAI flavor still differs here on purpose: it delivers an array of actions in one call. Halting would strand a mouse press whose release was planned for a later call, so the function tool offers `left_click_drag` instead of separate press and release actions, and rejects any action it does not declare. Provider types that reuse the chat completions client without being OpenAI-compatible (Azure, Google, OpenRouter, Vercel, Copilot) stay unsupported until each is verified. > [!NOTE] > `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`, `docs/reference/api/schemas.md` and `site/src/api/typesGenerated.ts` are hand-edited to match the new enum value, because the environment that prepared this change had no pnpm to re-run the generators. The same environment had no node, so `pnpm run typecheck`, biome and prettier did not run locally; CI is the validator for the `site/` change and the generated files. > [!NOTE] > Prepared by Xum, Mike's coding agent, from the measurement that showed an OpenAI-compatible server dropping both hosted computer tools. --------- Co-authored-by: Ethan Dickson <ethanndickson@gmail.com> |
||
|
|
9fa68ac013 |
feat: hold every steer message while one is under edit (#31748)
Whilst a steer message is under edit, every steer message now waits, not just the one under edit and the ones behind it. Say Next step holds A, B and C, and you edit B. Before this, A went to the agent at the next model call whilst B and C waited. Now nothing goes out until the edit ends, then A, B and C go in together. If the turn ends whilst a steer message is under edit, the chat pauses, the same as it already does for a queue message. `GetChatQueuedMessageHead` now returns a steer message under edit first, so the paused check still finds it when it isn't the first row. Queue messages are unchanged: editing one holds it and the messages behind it. On the site, every other row shows "Waiting" whilst a steer message is under edit, and Enter on an empty composer won't send the first held message whilst it's waiting on an edit. The docs are updated to match. The first version of this PR refused edits on steer messages instead, following [Mathias's review of #30074](https://github.com/coder/coder/pull/30074#pullrequestreview-5352986208). Mathias has since suggested holding the whole steer lane, so the agent never starts working on part of what you sent. Part of CODAGT-1140 |
||
|
|
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
|
||
|
|
f8ab27ff7c |
feat: allow computer use on Claude models from AWS Bedrock AI providers (#31745)
Closes https://linear.app/codercom/issue/CODAGT-1525/allow-computer-use-with-claude-models-from-aws-bedrock-ai-providers Computer use was only available on models from Anthropic and OpenAI AI providers, as we decided support from the AI provider type alone, in five separate places (spawn, turn setup, override validation, telemetry and the settings UI). A Bedrock AI provider serves Claude models over the Anthropic Messages API though, and chatd already routes those through the Anthropic fantasy client, so there's no reason computer use shouldn't work on them. To fix, there's now a single rule, `chatprovider.ComputerUseProvider(providerType, model)`, derived from the client chatd builds for the model (`chatprovider.ClientProvider`, previously `aibridgeClientProvider`). If the model uses the Anthropic client, it gets the Anthropic computer use tool. The OpenAI tool is still only offered on OpenAI AI providers, as I haven't tested it against Bedrock Mantle, and I couldn't find anyone else doing it either. All five places now call this function. The UI can't re-derive Bedrock routing without duplicating the model ID heuristic, so `ChatModel` gets a read-only `computer_use_provider` field (`anthropic`, `openai`, or omitted when computer use isn't supported). The computer use model override endpoint now accepts Bedrock Claude models, and its 400 message has changed. Whilst in here I also fixed a latent bug where the default model credential check looked up the user's keys under the tool flavour (`anthropic`) instead of the provider type (`bedrock`). One caveat: on a Bedrock AI provider using InvokeModel, AI Gateway runs the provider's configured model rather than the chat model, whilst we pick the computer use tool version from the chat model ID. It's not specific to computer use, and should go away with [AIGOV-747](https://linear.app/codercom/issue/AIGOV-747/deprecate-the-bedrock-invokemodel-protocol-with-model-translation). In the meantime, #30752 warns when an InvokeModel provider ignores the chat model identifier. |
||
|
|
6de3d92883 |
fix: correct invalid and nonexistent Swagger parameters (#30124)
Several parameter annotations produced a wrong or invalid spec. - `GET /api/v2/settings/idpsync/available-fields` and `field-values` documented a required `organization` path parameter that their URLs do not contain. The annotations were copied from the organization-scoped routes. - `format(uuid)` on the `ids` array query parameter of the provisioner jobs and daemons routes put `format: uuid` on the array rather than its items. swag cannot set an item format, so the description now says the IDs are UUIDs. - Swagger 2.0 does not allow `example` on header parameters, which failed strict validation. The `Authorization` and `Content-Disposition` examples move to `x-example` vendor extensions, which Swagger 2.0 allows on parameters and the docs generator uses for the curl samples. - `TestSwaggerParametersValid` reads every path in the generated spec and fails on a non-body parameter with `example`, an array parameter with `format`, or a path parameter missing from its route. Part of DOCS-1122, split from #30121. --- 🤖 Built with AI assistance. |
||
|
|
585485c8bf |
fix: document raw JSON as objects and byte fields as base64 strings (#30123)
Swagger renders `json.RawMessage` and `[]byte` fields as integer arrays, so the API reference showed chat tool calls as `"args": [0]` even though tool arguments and results are JSON values. Render every `json.RawMessage` as an object with one `.swaggo` replace rule, and tag `[]byte` fields, which JSON-encode as base64, `swaggertype:"string" format:"byte"`. This covers `ChatMessagePart.args`, `.result`, `.data`, `ToolResult.output`, `DynamicTool.input_schema`, both workspace build `state` fields, `TemplateBuilderModuleVariable.default`, and `CreateTestAuditLogRequest.additional_fields`. `ChatMessagePart.provider_metadata` is internal only, so it is hidden with `swaggerignore:"true"` like its siblings. `ChatMessagePart.result` and `ToolResult.output` can hold any JSON value, and `TemplateBuilderModuleVariable.default` holds a string, number, or boolean, so `object` is an approximation for all three and the field comments say so. swag rejects an untyped `.swaggo` override for `json.RawMessage`. Part of DOCS-1122, split from #30121. --- 🤖 Built with AI assistance. |
||
|
|
820689dc0b |
feat: include the owner in the chat project ACL response (#31244)
The chat project ACL response now includes the project's owner, so the
project page can show who owns a project to everyone who can read it.
`GET
/api/experimental/organizations/{organization}/chats/projects/{project}/acl`
returns a new `owner` field (`MinimalUser`). The owner is never in
`users`, and `GET /api/v2/users/{id}` returns 404 to regular
organization members, so project members and project admins currently
see the owner as "Unknown". The handler loads the owner with a
system-restricted context after the existing read and sharing-disabled
checks, matching how it already loads shared users and groups.
`TestChatProjectSharing/User` and `/Admin` now check the owner as seen
by the owner, a `use` sharee and an `admin` sharee, and that both
sharees still get 404 from the users endpoint. Dogfood UAT on a dev
deployment confirmed the field for all three callers, no owner data for
callers without access (404), and the unchanged 403 when chat sharing is
disabled.
Stack (merge bottom first):
- 👉 this PR
- #31245
- #31246
- #31247
|
||
|
|
ba068876cd |
feat: register MCP OAuth2 clients when MCP server configs are updated (#31559)
Relates to CODAGT-779 We only ran Dynamic Client Registration when an MCP server config was created. If an admin later switched an existing server to OAuth2, or changed the URL of a server whose client Coder had registered, the server was left without a working client, and users couldn't connect to it. To fix, create and update now go through the same planner, which registers a client whenever a save needs one. That's when a config becomes `dynamic` (on create, when the auth type changes to OAuth2, or when `oauth2_client_registration` changes from `manual` to `dynamic`), or when the URL of a `dynamic` config changes. The update request gets an optional `oauth2_client_registration` field. When it's omitted, we use `dynamic` if the resulting config has no client ID, auth URL or token URL, and keep the stored value otherwise. Coder owns the client ID, secret, auth URL and token URL of a `dynamic` config, so we ignore them when a request leaves them empty or repeats them, and any other value fails with a 400 unless the request also sets `manual`. Updates that touch auth fields are also validated now, so a `manual` config without a client ID, auth URL or token URL is rejected. A new client replaces the client ID, so it deletes every user's stored token. If discovery or registration fails, nothing changes, and if the config changes whilst we're registering, the request fails with a `409 Conflict`. There are a few gaps I've left for now, and documented. A change to the deployment's access URL doesn't register a new client. Configs broken by the old behaviour stay `manual` until an admin switches them to `dynamic`. We also don't re-register when the provider rejects the client with `invalid_client`. |
||
|
|
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. |
||
|
|
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.
|
||
|
|
b54f7de4c6 | feat: graduate chat projects out of the chat-projects experiment (#31354) | ||
|
|
8b0c0cc35e |
fix!: validate workspace app URLs on the server (#31262)
- Reject external app URLs with javascript, vbscript, data, blob, file, or filesystem schemes, or control characters, for template and sub-agent apps. - Skip invalid sub-agent apps and log the reason; the dev container still starts. - Strip the $SESSION_TOKEN placeholder from sub-agent app URLs. - Drop app status URIs that aren't http, https, or file. |
||
|
|
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 |
||
|
|
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.
|
||
|
|
514f23979a |
feat: honor disable-model-invocation in skill frontmatter (#31147)
Extends #30882's `model_invocable` semantics to workspace skills and to stored skills created through the API. Claude Code and Xum let skill authors set `disable-model-invocation: true` in SKILL.md frontmatter, so agents never pick the skill on their own and it runs only when a person invokes it. Coder Agents honored the key only when someone imported a SKILL.md file while adding a project skill (#30884). ## What changes - **Workspace skills:** when the pinned SKILL.md sets the key to the YAML boolean `true`, chatd leaves the skill out of `<available-skills>` before merging sources, so a listed skill with the same name keeps its bare name, and `read_skill` reports it as not found. The skill stays in the `/` menu, and invoking it still loads its body. `read_skill_file` serves its supporting files under the bare name or `workspace/<name>` and refuses its `SKILL.md` (case-insensitive, after `path.Clean`). Skills without the key behave as on the base. - **Invoked workspace skills:** invoking a workspace skill now stores the pinned skill directory on the invocation part, and the prompt renders it as `dir` on `<invoked-skill>`, escaped as an attribute value. Before, only `read_skill` gave the model a skill's directory, and it refuses a hidden skill, so a hidden skill could not run the scripts it bundles. The part also stores the chat's workspace, and the prompt shows `dir` only while the chat stays bound to it, as it does for workspace file references. This changes #30861's invocation code. Hook payloads drop the directory and its workspace like the body, and API responses strip both. - **Stored skills:** a create request whose content sets the key and that omits `model_invocable` stores `model_invocable = false`. An explicit value wins, and PATCH is unchanged. This covers personal, organization, and project skills, which share `createSkill`. - `workspacesdk.SkillDisablesModelInvocation` reads the key. The `CreateSkillRequest.ModelInvocable` doc comment, the generated API docs, and `extending-agents.md` (the SKILL.md format, a new "Turn off automatic use" section, and the notes on the skill index, the skill tools, and aliases) describe the new behavior. ## Follow-ups - The personal and organization skill editors have no "Agents can use it automatically" switch yet. Only the project editor from #30884 has one. ## Testing - Go tests cover the parser, the turn's skill index and aliases, `read_skill`, `read_skill_file`, invocation of a hidden skill and the directory it carries (attribute escaping, no directory after the chat changes workspace, no directory in hook payloads), and the create default for personal and organization skills. Each new test fails when its code path is removed. - Remote dogfood UAT with a real model failed rounds 1 to 3. Rounds 1 and 2 found the hidden SKILL.md still readable through `read_skill_file` by symlinks and stale pins, plus a bare-name lookup bug and a docs gap that round 2 fixed. Round 3 found that the content check added against those bypasses refused a listed skill's file whose own frontmatter sets the key. After round 3 we narrowed the rule to the hidden skill's `SKILL.md` path. The key decides what agents are offered (the index and `read_skill`), not which files they can read: `read_file` and `execute` already open any workspace file, so a content check in `read_skill_file` protected nothing and kept producing edge cases. - Round 4 passed on `c9ff25dc29f`. Later commits added a behavior-neutral cleanup (`cd617533c2e`), one test case from the test audit (`044c1e6e23a`), and a comment fix (`9ec3768b18b`), which passed validation without another UAT round. Round 5 passed on `2b518c6c2b1`, which adds the skill directory. A real model ran hidden skills' scripts from the `dir` on `<invoked-skill>`, including directories whose paths contain `&`, `'`, `"`, `<` and `>`, and API responses carried no directory. Merging main after #30884 landed (`2d7d3cb9674`) did not change this PR's diff, so UAT was not rerun. `8f043b2a342`, which shows the directory only while the chat stays bound to the skill's workspace, has Go tests but no UAT round. - The doc-check skill ran in author self-check mode on `2d7d3cb9674`, and `27de7f5c6d7` fixes its findings: the skill index sentence said every skill is listed, the stored-skill sentence claimed any project editor import honors the key and presented the API default as fixed, the API path came before the UI path, and some wording broke the docs style rules. The fix is docs-only, so UAT was not rerun. - Polish and the test audit stayed inside the implementation diff. No new dependencies. - Codex review found no major issues on `9ec3768b18b`, then raised one P2 on the same head when the PR was marked ready: an invoked hidden skill gets no skill directory. A probe confirmed it, and `2b518c6c2b1` fixes it. Its earlier finding on that head (honor `CODER_AGENT_EXP_SKILL_META_FILE`) was refuted, because the pinned skill snapshot always reads `SKILL.md`. Both threads are resolved, and Codex found no major issues on `2b518c6c2b1` or on the merge `2d7d3cb9674`. - On `27de7f5c6d7`, Codex raised two P2s. One was confirmed: an invoked skill's directory stayed in the prompt after the chat moved to another workspace, which a prompt test showed on that head, and `8f043b2a342` fixes it. The other was declined: on Windows, `scripts\..\SKILL.md` gets past the `SKILL.md` check in `read_skill_file`, but that check is not an access boundary (`read_file` opens any path), and Windows has more aliases (`SKILL.md.`, `SKILL.md::$DATA`, `SKILL~1.MD`) that normalizing backslashes would not stop. On `8f043b2a342`, Codex asked to bind the directory to the workspace build instead. That was declined: every workspace start is a new build with new agent IDs, so the directory would drop after each stop and start, and the pinned body and the live files can diverge without a rebuild anyway, as they do for `read_skill`. A later request on that head asked to limit a hidden skill's `read_skill_file` access to invocations in the current workspace. That was declined too: `read_skill_file` resolves names against the current pin for listed skills on main as well, and the key decides which skills agents are offered, not which files they can read. All four threads are resolved. `a697dcd927f` adds the `format:"uuid"` tag that `TestSDKFieldsFormatted` requires on the new field, and Codex found no major issues on `a697dcd927f`. `ae70b2c533f` is docs-only: it applies the doc-check suggestion to say that an invoked skill's directory is included only while the chat stays in that workspace. The author doc-check self-check found no blocking findings on it, and Codex found no major issues on `ae70b2c533f`. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. --------- Co-authored-by: Jaayden Halko <jaayden.halko@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
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.
|
||
|
|
c4d76a4009 |
feat: add skill action and automatic-use settings (#30882)
Adds two per-skill settings that the project skills UI will expose next: - `action` marks a project skill to show as an action button above project chat composers. A `skills_action_project_only` check keeps it to project skills; the personal and organization routes reject `action` with 400. - `model_invocable` (default true, every stored source) controls automatic use. When it's false the skill is left out of `<available-skills>` and `read_skill` reports it as not found, but a structured skill invocation (a chip from the `/` menu or an action) still loads it, as long as the skill is enabled and the chat owner can read it. Workspace skills always count as model-invocable. Migration 000625 adds both columns with defaults, so existing skills keep today's behavior. The list, get, insert and update queries, `codersdk.SkillMetadata` and the create/update requests carry both fields, and the audit table tracks them. `coderd/x/chatd/ARCHITECTURE.md` gets TODO notes for the author. **NOTE**: the migration adds two columns with constant defaults and a CHECK constraint to `skills`. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 👈 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
9b8d880d63 |
fix: exempt service accounts from user dormancy (#30824)
Closes CODAGT-1344 The Slack bot for Coder Agents (CODAGT-1098) runs inside coderd and acts as a service account that an admin picks. It creates chats and sends messages as that account through Go calls, not HTTP requests. Two dormancy rules break it: 1. **New service accounts start dormant.** The CLI and the web "Create user" page send no status, and `InsertUser` falls back to `dormant`. So the bot's account is dormant from the start. 2. **Accounts go dormant after 90 days without a "last seen" update.** Only the API key middleware updates `last_seen_at`, and only on HTTP requests. The bot never sends any, so its account goes dormant on day 90, even if people use the bot every day. A chat owner must be active, so once the bot's account is dormant, every Slack mention fails. Any other in-process integration that acts as a service account has the same problem. Dormancy does nothing useful for service accounts: - It exists to free license seats, and service accounts never take a license seat (#24401, #27279). - It isn't a lock. Any API request activates a dormant account again. - System users already skip the dormancy job for the same reason. So this PR: - creates service accounts as active when the request doesn't set a status, - rejects an explicit dormant status for a service account with a 400, - skips service accounts in the dormancy job, the same way it already skips system users. Side effects: a service account that nobody uses for 90 days now stays active. That has no effect on license seats. If the account has ever sent traffic through AI Gateway, it also keeps its AI Governance seat until an admin suspends or deletes it. That matters less than it sounds: AI Governance is now included with Premium rather than sold per seat (#27545), so the seat only counts on a license that still has an AI Governance seat limit, and there it only feeds the seat-limit warning. The dormancy job also no longer writes "marked dormant" audit entries for service accounts. I've left existing dormant service accounts alone rather than adding a migration. An admin can activate one, and any API request from it activates it too. --- _This PR description was written by Coder Agents._ |
||
|
|
ffd24861a1 |
feat: send skill invocations as structured message parts (#30861)
Adds a structured `skill-invocation` chat part so a user message can carry an explicit skill. chatd loads that exact skill when the message is sent and puts its body into the user's prompt, so the skill always applies instead of relying on the model to notice it in `<available-skills>`. The composer chip that sends these parts comes in the next PR. - codersdk: a `skill-invocation` input part and message part with `skill_source` (`personal`, `org`, `project`, `workspace`) and `skill_name`. The resolved body is stored on the part as internal `skill_body`; it's hidden from TypeScript and stripped from every API response. - coderd rejects an unknown source or an invalid name with 400. - chatd resolves each invocation on create, send and edit with the chat owner's permissions, through the same loaders as `read_skill`: stored skills by source and name (project skills through the chat's project, with the root chat fallback for subagents) and workspace skills from the pinned context snapshot. The body is saved at send time so past turns show what the model received. A missing, disabled or unreadable skill rejects the send with 400 "Skill project/triage is not available." - The prompt renders a line saying the user invoked the skill, followed by `<invoked-skill name="project/triage">` with the sanitized body. Titles and hook prompt text show the invocation as `/project/triage`. - The site only gets no-op cases so the regenerated types compile. `coderd/x/chatd/ARCHITECTURE.md` gets a TODO for the author. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 👈 - #30880 - #30881 - #30882 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
c61d842b9c |
feat: show available ACP harnesses in chat context (#31059)
Expose discovered ACP harnesses in the chat context resource inventory when the `chat-acp-subagents` experiment is enabled, including configuration paths and resource status. Persist ACP harness resources from agent context snapshots and update the SDK and generated API types. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
f4cd0deccb |
feat!: report template insights session usage per app (#29796)
Report template insights session usage per app instead of five fixed family rows, with registry names and icons. - Add per-app rows for reported session apps (VS Code, Cursor, GoLand, Zed, etc.); unused apps are omitted - Replace `type` (`builtin`/`app`) with `method` (`ssh`, `reconnecting_pty`, `port_forwarding`, `workspace_app`); session methods are derived from the app name until #31012 stores them - Add `usage_total_seconds` to count each user's active minutes once, and use it as the UI bar denominator so overlapping apps can exceed 100% - Merge template apps sharing a slug into one row across templates, using the newest display name and icon - Rename Web Terminal slug from `reconnecting-pty` to `reconnecting_pty` - Cap the response at the 64 busiest unregistered apps and fold the rest into "Other apps", flagged with `seconds_is_upper_bound` ("Up to" in the UI) - Add `unknown` and `overflow` accounting rows with explanatory tooltips, and a fallback icon for apps without one - Remove the unused `codersdk.UnionByFamily` helper from the Go SDK BREAKING CHANGE: `report.apps_usage` in `GET /api/v2/insights/templates` no longer returns the fixed five rows, family slugs, or previous display names. Consumers must update. Part of CLIENT-642 Prometheus metrics handled separately in #29906 |
||
|
|
dfdd6a59a5 |
feat: move chats between projects through the chat update API (#30894)
`PATCH /api/v2/chats/{chat}` now takes `project_id`. A project ID moves
the chat into that project, and `uuid.Nil` removes it from its project.
**Stack** (moving chats between projects, bottom first):
1. #30893: the move in chatd
2. **This PR**: the chat update API takes `project_id`
3. #30895: **Move to project** in the chat menu
4. #30795: drag a chat onto a project folder in the sidebar
**Why:** #30893 can move a chat family, and the UI layers above need an
endpoint to call.
- A move accepts the same projects as chat creation, through
`validateChatProjectSelection()`, which this PR extracts from
`postChats()` without a change in behavior.
- A project that the chat's owner cannot use gives 404, even for an
admin. The owner must own the project or hold a grant on it
(`chatd.ChatProjectUsableBy`, the check that chat creation uses since
#30439). So an admin cannot put a member's chat into a project that the
member has no access to and expose its memory.
- A child chat, an archived chat or a disabled `chat-projects`
experiment gives 400. A family that is not idle gives 409 ("Cannot move
an active chat. Interrupt or wait for the chat to finish first."). A
project deleted between the check and the move gives 404.
- The move is the last write in `patchChat()`, so a refused move keeps
the earlier writes of the same request, as a refused archive does.
**What to scrutinize:** the access check in
`validateChatProjectSelection()` and the order of the refusals in
`patchChat()` (`coderd/exp_chats.go`).
**Architecture doc:** the `PATCH /api/v2/chats/{chat}` section of
`coderd/x/chatd/ARCHITECTURE.md` lists the `SetProject` states of a move
and its refusals, and no longer says that only an `archived` change
emits transitions.
**Generated** (`make gen`): `coderd/apidoc`,
`docs/reference/api/chats.md`, `docs/reference/api/schemas.md` and
`typesGenerated.ts` come from `UpdateChatRequest.ProjectID` in
`codersdk/chats.go`.
## Testing
- `make pre-commit` passes, and so does `go test ./coderd -run
TestPatchChatProject` (14 subtests).
- `TestPatchChatProject/AnotherOwnersProject` gets 404 for another
user's project, then moves the chat after the project is shared with the
chat's owner. It fails without the access check, and also with an
owner-only check. `MoveBackWaitsForAPendingMove` ends in the wrong
project when the handler skips the move before the lock.
`ActiveFamilyReturnsConflict` checks the 409 for a running, interrupting
or action-waiting root and for a running subagent.
`PublishesProjectChange` and `AuditsTheMove` cover the watch event and
the audit entry.
- Untested: the 404 when the project is deleted between the check and
the move.
> Xum opened this PR on behalf of @ibetitsmike.
|
||
|
|
0968f97a43 |
feat: move a chat family between projects in chatd (#30893)
chatd can now move a root chat, together with its subagent chats, into a project, to another project, or out of its project. Nothing calls this yet. #30894 adds the API. **Stack** (moving chats between projects, bottom first): 1. **This PR**: the move in chatd 2. #30894: `PATCH /api/v2/chats/{chat}` takes `project_id` 3. #30895: **Move to project** in the chat menu 4. #30795: drag a chat onto a project folder in the sidebar **Why:** today a chat keeps the project it was created with. A move must follow the family rules of archiving, because a step that runs during a move would still have the memory tools of the old project. - `chatstate.Tx.SetProject` runs only from W, E0 and E1, like `SetArchived`. `SetFamilyProject()` locks the root row before its subagents, in the same order as archiving, so a busy family gets `ErrTransitionNotAllowed` and nothing changes. - A move to the project the chat is already in changes nothing, even while the chat runs. The check reads the locked root row, so it waits for a move that is still in flight. - Only the root row stores `project_id`, and subagents use the project of the root. After the commit, chatd publishes a new `project_change` watch event for each chat of the family. The move keeps `updated_at`, so lists keep their order. - A root chat outside a project now has an empty memory index. When a chat leaves its project, or its project is deleted, its next turn start commits one memory index update that removes the memories the model saw there. **What to scrutinize:** the lock order and the same-project check under the lock in `SetFamilyProject()` (`chatstate/family.go`), the turn-start condition in `memoryIndexMessage()` (`memory.go`), and whether the `ARCHITECTURE.md` text matches them. **Generated** (`make gen`): `queries.sql.go`, `querier.go`, `dbmock` and `dbmetrics` come from `queries/chats.sql`. `coderd/apidoc`, `docs/reference/api/schemas.md` and `typesGenerated.ts` come from the new watch event kind, which is also why two `chats.test.ts` fixtures gain `project_change: false`. **Architecture doc:** `coderd/x/chatd/ARCHITECTURE.md` lists `SetProject` among the transitions and in the execution state diagram (W, E0 and E1 back to themselves). It also says that a root chat's project can change after creation, and that a moved chat's next turn starts with a memory index update from the old project to the new one. ## Testing - `make pre-commit` passes. `go test` passes for `coderd/x/chatd/chatstate`, `coderd/database/dbauthz` (`TestMethodTestSuite`) and the chatd memory tests. - `TestSetFamilyProjectLocksRootFirst` fails with 55P03 when a subagent row is locked first. `TestSetFamilyProjectKeepsTheCurrentProject` covers the same-project move during a run. The transition matrix test gains `SetProject` cases for W, E0 and E1. - `TestMovedChatUsesNewProject` runs two real turns around a move: the second turn uses the instructions and memories of the new project, and `OutOfProject` fails without the memory index removal. > Xum opened this PR on behalf of @ibetitsmike. |
||
|
|
6ebefb8325 |
feat: add chat project sharing API (#30439)
API for chat project sharing (experiment `chat-projects`). Builds on #30479 (merged). Owners share a project with users, groups, or the whole organization (the Everyone group, ID = organization ID). Chats in a shared project stay private. | Role | Project and instructions | Memories | ACL | Delete | |---------|--------------------------|------------|------|--------| | `use` | read | read/write | read | no | | `admin` | read/write | read/write | edit | no | Only the owner, and administrators whose role grants delete, can delete a project. - **API:** `GET`/`PATCH .../chats/projects/{project}/acl`, same shapes as `/chats/{chat}/acl`, plus SDK methods. Project responses include the caller's `permissions` (`update`, `delete`, `share`); the UI hides edit and delete accordingly. - **Listing:** `GET /chats/projects` returns owned and shared projects. Removes `GetChatProjectsByOwnerID`. - **Chat access:** creating a chat in a project, and loading its memory and instructions on each turn, requires the chat owner to own the project or have an ACL grant (`chatd.ChatProjectUsableBy`). Role grants don't count. If the grant is removed, existing chats lose memory and instructions on their next turn. - **Validation:** users and groups must be in the project's organization; keys must be canonical UUIDs; callers can't change their own role; the owner can't be added. Migration `000624` drops a user's grants when they leave the organization, so rejoining doesn't restore access. - **Instructions:** readers who can't edit get 403 instead of 404, and the UI hides editing. - **Agent prompt:** memories are visible to and editable by sharees, so the agent is told not to save secrets or personal details. Known gap: project deletion still detaches chats, and a sharee's open sidebar keeps showing them until reload. #30683 replaces this. Not included: share notifications, `/acl/available`, sharing UI. <details> <summary>Decision log</summary> - `use` grants memory read/write over HTTP, because agents in a sharee's chats can already write memories. Making the agent read-only for sharees was the alternative (@f0ssel chose sharees changing memories through use). - An administrator with `share` can grant themselves access and then use the project. Accepted to keep access control simple (@f0ssel). </details> > Generated by Coder Agents. |
||
|
|
a379c849da |
feat: add project skill queries and authorization (#30826)
Adds the storage and authorization layer for chat project skills. The `skills` table already allows a `project_id` owner (migration 000621); this adds the queries for it and authorizes them through the parent chat project, the same way project instructions work. - New queries in `skills.sql`: insert, get by name, list metadata, update (COALESCE on description, content and enabled), delete, and `GetProjectSkillByIDForUpdate` for the shared update lock. - dbauthz checks `chat_project:read` on the project for reads and `chat_project:update` for writes. `authorizeChatProjectInstructions` became `authorizeChatProjectConfig`, shared by instructions and skills. `Skill.RBACObject()` still denies project rows so nothing reaches them without going through the project. - Audit: new `chat_project_skill` resource type (enum-only migration 000624), `AuditableChatProjectSkill`, and the usual diff/request/table/FriendlyString/AuditFilter wiring. The API that emits these entries comes in the next PR. Stack (merge top to bottom): - #30826 👈 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 - #30884 |