mirror of
https://github.com/coder/coder.git
synced 2026-11-21 18:58:17 +08:00
90948802e2439d2641f392e6229dd058a1dcafe3
4777
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
50ecadf953 |
fix: scope the MCP OAuth2 resource help text to auto-discovery
An empty resource sends none unless auto-discovery fills it while registering the client, so say that instead of promising none. Shorten the create request doc to match, drop a class that has no effect on the single-field row, and use an example.com resource in the form test. |
||
|
|
b1bf4afd74 |
fix: align and clarify the MCP OAuth2 resource field
Label the form input "Resource URL" like its sibling endpoint fields, say that an empty value sends no resource parameter, and match the sibling row grid so the field lines up with the column above. Describe the API field's discovery and clear semantics precisely, and cover clearing a stored resource from the edit form. |
||
|
|
b23e377218 |
fix(coderd): reject MCP OAuth2 callbacks whose resource changed since connect
RFC 8707 binds an authorization code to the resource named in the authorization request. Record that resource in a callback-scoped cookie at connect, and fail the callback with the existing 409 before the code exchange when an admin changed oauth2_resource in between, so the code is never redeemed for a resource the user did not authorize. |
||
|
|
f4516862df |
test(coderd): tighten MCP OAuth2 resource indicator coverage
Assert invalid resources are rejected before auto-discovery, cover clearing on every non-oauth2 auth type, check whitespace trimming on update, and restore the bodyclose directive on TestMCPServerOAuth2PKCE. |
||
|
|
8d02836295 | refactor(coderd): reuse parsed resource indicator in MCP OAuth2 discovery | ||
|
|
2b875068e0 |
feat: send RFC 8707 resource parameter on MCP server OAuth2 flows
Store an oauth2_resource indicator on MCP server configs. Auto-discovery fills it from the Protected Resource Metadata entry that covers the server URL (else the canonical server URL); admins can set or clear it. When set, Coder sends it as the resource parameter on authorization, code exchange, and refresh requests. Manual configs without it send no resource parameter, so providers that reject it keep working. |
||
|
|
4afd834ad2 |
fix(coderd/x/chatd): return database errors from turn preparation (#30492)
Relates to CODAGT-1330 When chatd prepares a turn, it reads a bunch of things from the database: the user's custom prompt, plan mode instructions, personal skills, the advisor config, the user's compaction threshold override, MCP server configs, inline MCP servers, MCP user tokens and the pinned workspace MCP tools. If any of those reads failed, we'd log a warning and run the turn without them, so the model would quietly ignore the user's instructions or be missing tools for that turn. To fix, we'll just return the error instead, so the prepare retry runs, and the chat shows an error if the reads keep failing. The provider switch history sanitizer and the cancel of deleted tool calls also return their database errors now. A model config that's unavailable, e.g. deleted, is still treated as foreign by the sanitizer like it is today. An inline MCP server with invalid stored headers still shows up as a failed connect in the chat debug panel, but a failed read of the inline MCP servers themselves now fails the turn. This PR is in a stack on top of #30449. |
||
|
|
807878c1ab |
fix(coderd): return database errors at chat create and subagent spawn (#30449)
Relates to CODAGT-1330 chatd stores the deployment and organization system prompts in a chat when it's created. If either read failed, we'd log it and use the built-in default, or skip the organization prompt, so the chat ignored the admin's instructions for its whole life. The subagent model override had the same problem, and the compaction and advisor overrides quietly fell back to the chat model for that turn. To fix, we'll just return the database error instead. Overrides that can't be used, e.g. the model was deleted or the user has no API key for its provider, still fall back like they do today. |
||
|
|
f923f4a525 |
chore!: remove the chat automations experiment (#30412)
Removes the experimental Chat Automations feature (`chat-automations` experiment) from main. This reverts the 16-PR stack that added it and adds two forward migrations that undo its schema and credential changes.
> [!WARNING]
> **Upgrade consequences**
>
> - **Automation data is deleted.** Migration 000615 drops the `chat_automations` table and deletes every queued message an automation delivered. Chats, their messages and ordinary queued messages stay. Messages lose their automation provenance (`automation_id`, `input_id`).
> - **Automation-only credentials are revoked.** Migration 000616 deletes API keys, OAuth2 codes and OAuth2 tokens whose only scopes (or allow-list entries) were `chat_automation:*`. Mixed credentials keep their other scopes. Custom roles lose their `chat_automation` permissions. OAuth2 apps that allowed only `chat_automation` scopes get the whitespace allowlist that grants nothing, as in 000595.
> - **A coordinated restart is required.** Stop all old replicas before the new version runs the migrations. Old replicas read the dropped table and columns, so a rolling deploy is not supported.
> - **Remove `--chat-max-automations-per-owner` before upgrading.** The flag, the YAML key `chat.maxAutomationsPerOwner` and the env var `CODER_CHAT_MAX_AUTOMATIONS_PER_OWNER` are removed. A deployment that still sets the flag or the YAML key will not start (`unknown flag` / `unknown option`). The env var is ignored. This includes dogfood. No release or tag contains the flag.
> - **Down migrations restore the schema only.** 000616 down and 000615 down recreate the 000611 schema with empty tables. They do not restore deleted automations, webhook secrets, provenance, queued deliveries, revoked credentials, stripped permissions or the deleted experiment rule.
## What is removed
- The `chat-automations` experiment and its stored runtime rule (`experiment_rule:chat-automations`).
- The `--chat-max-automations-per-owner` deployment option.
- The `chat_automation` RBAC resource, its member and chatd grants, and the `chat_automation:*` API key scopes.
- The automation sqlc queries, dbauthz wrappers and audit table entries.
- The management routes under `/api/experimental/organizations/{organization}/chat-automations`, and the webhook route `POST /api/experimental/chat-automations/{automation}/events` with its rate limiter.
- The chatd management service, webhook publish, schedule loop, the `manage_automations` tool, and the chatstate admission seam and queue promotion guard that only automations used.
- The Agents Automations page, editor, nav entry, chat labels, the Manage automations toggle and the API client.
- The `archived:any` chat search value that the automations "View chats" dialog added.
- `docs/ai-coder/agents/automations.md`, its manifest entry, the glossary entry and the related rows.
Reverted PRs: #30085, #30096, #30112, #30117, #30127, #30134, #30160, #30166, #30167, #30171, #30187, #30207, #30214, #30217, #30219, #30220.
## What stays, and why
- Migrations 000609, 000610 and 000611, their fixture, and the #30297 lock fix with `migration000609_test.go` stay unchanged. Deployments such as dogfood already ran them.
- New migration **000615** reverses the schema changes of 000609 and 000611 against the current schema. It uses the same short-wait lock-and-retry block as 000609, and it rebuilds `chats_expanded` from main's current definition minus the two automation columns. New migration **000616** follows the 000595 Tasks removal for credentials and recreates `api_key_scope` without the five `chat_automation:*` values. It keeps the `chat_project_memory:*` values from 000612.
- The `chat_automation` value stays in the `resource_type` enum, and `codersdk.ResourceTypeChatAutomation` stays. Old audit log rows stay readable, as with `task` after the Tasks removal.
- The 000615 delete fires the existing queue-version trigger, so `queue_version` moves to `snapshot_version` for each affected chat. `snapshot_version` is not bumped: the coordinated restart restarts every stream loop from an empty state, and the site does not read the version fields.
- `coderd/x/chatd/ARCHITECTURE.md` drops the sections the stack added and gets back its pre-stack wording, merged with the later main edits to the same file.
## Notes for reviewers
- #30379 (chat project page) merged while this PR was in progress. It passed `manageAutomationsEnabled` in `AgentCreatePage.test.tsx` and listed an `automations` route in `AgentsPageLayout.test.tsx`. Later main commits also added automation props in `ConversationTimeline.test.tsx` and `ConversationTimelineWorkingBlocks.stories.tsx`. This PR removes all of them.
- Remaining `automation` matches under `coderd`, `codersdk`, `enterprise`, `site/src` and `docs` are intended:
- migrations 000609 to 000611, their fixture and `migration000609_test.go`;
- the new 000615 and 000616 migrations and `migration000615_test.go`;
- the `chat_automation` resource type in `dump.sql`, `models.go`, `codersdk/audit.go`, the generated API docs, `swagger.json` and `typesGenerated.ts`;
- unrelated uses of the word "automation" (docs, `chatlabels_test.go`, `ratelimit.go`, `autostop.go`, `subagent_catalog.go`, `WorkspaceSharingSection.tsx`, `AgentChatPage.stories.tsx`).
Remote UAT on an isolated dev deployment passed. It upgraded a populated pre-removal database, then checked chats, queued messages, tokens, the 404 routes, the removed page and nav entry, and the experiments list.
---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_

|
||
|
|
c28ae0dc9b |
feat: trigger compaction independently for the chat and compaction models (#28568)
> [!NOTE]
> Xum (an AI agent) authored this pull request on Mike's behalf.
## Summary
Automatic compaction now fires at whichever of two independent triggers
is reached first, and the UI shows when the organization override's
trigger applies.
- **Chat trigger**: the chat owner's personal threshold (or the chat
model's) against the chat model's window. A threshold of 100 turns off
only this trigger.
- **Organization trigger**: a fixed 80% of the organization compaction
override model's window. The override model's own compression threshold
is ignored. The other 20% is a target margin for the summary prompt and
the summary, not a guarantee, because the trigger reads the previous
step's prompt size.
On main, the chat threshold was applied to the smaller of the two
windows, and nothing in the UI showed it. Example: with a 20K chat model
at 70% and an 8K override, main compacts at 5,600 tokens; this PR
compacts at 6,400 (80% of 8K, shown as 32%).
## Changes
Backend (`coderd/x/chatd`):
- The trigger with the lower token point binds (ties go to the chat
trigger). It drives the automatic compaction gate and the
still-over-limit check, and every summary, automatic or manual, records
it.
- An override that is unset, deleted, disabled, on a disabled provider,
or without credentials for the chat owner is treated as absent: the chat
model summarizes and only the chat trigger applies.
- The summary's output cap is bounded by the summarizer's own window,
not the trigger's.
- The still-over-limit error names what can clear it: the compaction
threshold (chat trigger), an override model with a larger window
(organization trigger), or both when usage is over both points.
- The still-over-limit check compacts once more when the latest summary
was recorded under a different threshold or trigger window. The
`chat_summarized` result gains `trigger_context_limit_tokens`, and
`context_limit_tokens` now records the chat model's window (main
recorded the smaller window). On main, lowering a threshold after a
compaction ended every later turn with the error.
- The still-over-limit check skips a 0% threshold ("always compact"),
which on main ended the run with the error after every compaction.
- `ARCHITECTURE.md` documents the two triggers, the summary cap, and the
still-over-limit rules.
Frontend (`site`), through a shared `compactionTriggers` helper that
mirrors the backend rules (no new API):
- Coder Agents settings: the compaction override row warns when the
organization trigger undercuts chat models' default triggers ("the
organization override compacts chats at 80% of {model}'s {N}-token
window").
- Personal thresholds page: an Effective column shows the trigger that
applies, with a popover when the organization override binds. "Compacts
at" follows the same trigger, and a point the chat model's window cannot
reach shows as Off. The header's 100% sentence, and the row warning when
a member types 100, say an organization override may still compact chats
when one is set or its organization's overrides failed to load (the
header also while they load).
- Chat context gauge: the compact-at percent follows the binding trigger
and is annotated when the organization override binds. If the overrides
request fails, it shows the chat-only value with "(organization override
not loaded)", or "Compaction off (organization override not loaded)"
when the chat trigger is off.
- An override whose provider the user cannot use is ignored on the gauge
and the personal page, matching chatd.
- The shared `formatContextLimit` prints counts below 1,000 exactly (an
800-token compaction point showed "~1K") and 999,500 to 999,999 as
"1.0M" instead of "1000K". It also labels the model pickers; their other
values are unchanged.
- `HelpPopoverIconTrigger` lets callers set their own `aria-label`; only
the Effective column's popover does.
Known v1 limits: the Coder Agents settings alert is organization-scoped,
so it can warn about an override that some members fall back from for
lack of provider credentials. The gauge checks the viewer's provider
access, so on a shared chat its label can differ from the owner's
runtime trigger (Codex P2, declined). Compaction itself is unaffected.
## Screenshots
From remote UAT round 13 on
|
||
|
|
86ebc72236 | chore: remove unused autofill-parameters endpoint and experiment (#30525) | ||
|
|
d28a433b23 |
perf(coderd/database): index chat message pagination (#30562)
Loading a chat's history can take seconds when its messages sit far from the end of the `chat_messages` id space, because no index returns one chat's live messages in id order. Given the `LIMIT`, the planner chooses `chat_messages_pkey` instead and filters by `chat_id`, so it reads other chats' messages until it reaches this chat's. On dogfood, the newest page of one idle long chat took 21 s: `Index Scan Backward using chat_messages_pkey` discarded 614,776 rows and did 78,749 disk reads. Over the past 7 days, 108 of 33,745 `GetChatMessagesByChatIDDescPaginated` calls took more than 1 s, and 10 took more than 10 s. `GetChatMessagesByChatIDAscPaginated` has the same problem in the other direction: for `after_id = 0, limit 1`, which chatd uses as a first-turn probe, dogfood's plan scans forward from the table's oldest row. 305 of its 2,863 calls took more than 1 s. This PR adds migration 000614: `CREATE INDEX idx_chat_messages_chat_id ON chat_messages (chat_id, id DESC) WHERE deleted = false`. No queries change. **Migration cost:** a plain `CREATE INDEX` inside the migration transaction, which blocks writes to `chat_messages` until the upgrade commits. Reads continue. On a 1.01M-row fixture (641 MB heap) the build took 0.8 s and the index is 39 MB. Dogfood has 5.85M rows and a 5.7 GB heap, so expect seconds and about 230 MB. ## Testing Remote UAT through Coder Agents (round 1 PASS) on the 1.01M-row fixture, Postgres 13.21. It ran base |
||
|
|
782fb30f09 |
feat: load whole chat turns per history page (#30524)
Closes [CODAGT-1372](https://linear.app/codercom/issue/CODAGT-1372/load-whole-turns-per-history-page-so-collapsed-working-blocks-fill-in). With collapsed working blocks, a long agent turn renders as one row, but chat history pages hold a fixed 50 messages. A 400-step turn took about eight sequential page loads to fill, and its block showed partial labels ("at least", "or more") until then. `GET /api/v2/chats/{chat}/messages` now returns `turn_start_id` on newest-first pages: the ID of the user prompt that starts the turn containing the page's oldest message. It comes from a new `GetChatTurnStartID` query on the existing `idx_chat_messages_user_prompts` index, so there is no migration. Soft-deleted prompts and model-only user rows never start a turn. The history query then fills each page back to that prompt with requests of up to 200 messages, capped at 1000 messages per page, so a page holds whole turns and a complete block renders without partial labels. Past the cap, or when a fill request fails or returns no messages, the page keeps what loaded and ends mid-turn, and the next page continues it, as before. Because the fill runs inside the page fetch, a chat now waits for its fill requests (one to five) before it first renders: with an injected 500 ms per-request delay, a chat whose newest turn hits the cap appeared after 3.8 s instead of 1.1 s. ## Screenshots From the dogfood UAT, the same 200-step turn with its next history request held, so each label shows only what loaded before it: **Before**, on the base commit `29e876df4da`, after two 50-message pages: "Worked for at least 1m 35s (48 steps or more)", partly hidden by the loading indicator.  **After**, on `186a9b053a0`, after the first page: "Worked for 6m 39s (200 steps)".  A 750-step turn, larger than one 1000-message page, is exact once the next page loads:  A malformed fill response keeps the loaded messages and the partial label instead of showing "Failed to load chat", as `ecdfb27ec29` did:  ## Testing - Go: `TestGetChatMessages_TurnStartID` (pages spanning turns, deleted prompts, model-only user rows, polling and empty pages) and the dbauthz suite entry. - Vitest: fill request parameters, the 1000-message cap, failed, malformed, and empty fill responses, and servers without `turn_start_id`. - Dogfood UAT through Coder Agents: PASS on `186a9b053a0` (round 4): whole-turn first pages, the 1000-message cap and its continuation, fill failures, a live turn, and API checks for deleted prompts and model-only user rows. Round 3 on `ecdfb27ec29` failed: a malformed fill failed the chat load, and an empty fill reporting `has_more` repeated forever. `7266f468290` fixes both, with regression tests. ## Review record - Test audit with mutation checks: the Go test now covers a page spanning two turns, which catches a lookup keyed on the newest message. A re-audit of later test changes changed nothing; the one surviving mutation drops the `!older.has_more` stop, costing one extra request when the prompt is deleted mid-fill. - Frontend review (8 roles, 5 rounds): fixed doc, naming, loose-type, and test findings. Its suggestions to catch only the fill request (DF5) and drop the empty-page stop (SD4) caused the round 3 failures and are reverted. Kept: SD1 (`MAX_MESSAGES_PER_REQUEST` is used once, named like `MESSAGES_PAGE_SIZE`) and round 5 SD4 (`!older.has_more` is the endpoint's pagination signal). Declined DF6: the `queued_messages` refetch race predates this change, and a failed refetch fill only unloads older history that reloads on scroll. - Codex: no findings on `186a9b053a0`. - Known: a hung fill delays the first render (no client timeout); fills are not cancelled when the user leaves; the top of history costs one extra empty request; injected malformed fill rows break the page as they do on the first page. > Xum opened this PR on behalf of @ibetitsmike. |
||
|
|
befda9b29f |
docs: mention chat reasoning_tokens is part of output_tokens (#30500)
Document that reasoning_tokens is included in the output_tokens on ChatMssageUsage, which is the case for all known providers. Refs CODAGT-1350 |
||
|
|
261269aff0 |
fix: support path-aware OAuth discovery for remote MCP (#30168)
## Problem VS Code discovers Coder's MCP endpoint as a path-qualified OAuth resource, but Coder advertises the deployment root. Accepting MCP-bound tokens also requires keeping REST-backed tool calls within the originating MCP resource rather than granting those tokens direct REST access. ## Fix - Publish path-aware protected resource metadata and authentication challenges; keep authorization-server metadata at the root. - Validate the MCP audience and delegate tool requests through a private in-process transport that retains identity, scopes, expiry, revocation, and streaming cancellation. - Reject unsupported MCP path aliases and validate SDK path components before URL resolution. - Add discovery, audience, authorization, endpoint-isolation, and transport lifecycle regression tests and update integration docs. ## Validation VS Code completed OAuth and returned the authenticated user through a real MCP tool. Official MCP SDK 1.30.1 completed discovery, registration, PKCE, tool execution, and refresh. These live checks preceded the final path hardening; the hardened paths are covered by automated regressions. Affected Go package tests, targeted race tests, backend/SDK lint, and targeted documentation checks passed during self-review. The exact PR commit was also checked separately from the uncommitted consent-scope fix. > [!NOTE] > Tokens are MCP-audience-bound, but grants still include `coder:all`; least-privilege scopes remain a separate requirement ([PLAT-639](https://linear.app/codercom/issue/PLAT-639)). Preview: https://coder.com/docs/@fix/mcp-internal-delegation/ai-coder/mcp-server <details> <summary>Implementation decisions and review context</summary> 1. Treat `/api/experimental/mcp/http` and its single-trailing-slash form as supported MCP resource paths; reject other aliases and descendants before route authentication. 2. Preserve deployment-root discovery and authorization-server metadata for existing REST integrations. 3. Bind private delegation to the authenticated API-key ID. Revalidate the original credential and enforce normal RBAC/scopes on every internal REST request; do not derive delegation from HTTP headers. 4. Keep internal HTTP, streaming, and WebSocket traffic in-process with no network fallback. Close the transport on outer-request cancellation and normal completion. 5. Validate workspace owner/name path segments before SDK URL construction, including tool-level tests that malformed arguments cannot select a different REST endpoint. 6. Keep compatibility and delegated tool execution together: discovery-only changes would allow authentication while leaving real MCP tool calls broken. </details> > 🤖 This PR was created with the help of Coder Agents, and needs a human review. 🧑💻 |
||
|
|
315789c6bf |
chore: refresh AI model price book (#30498)
## Price book changes 27 models added, 8 models removed, 46 models changed. <details> <summary>Added</summary> - anthropic/claude-haiku-5-5 - azure/claude-haiku-5-5 - azure/grok-4.6 - bedrock/anthropic.claude-haiku-5-5 - bedrock/au.anthropic.claude-haiku-5-5 - bedrock/eu.anthropic.claude-haiku-5-5 - bedrock/eu.anthropic.claude-sonnet-5-5 - bedrock/global.anthropic.claude-haiku-5-5 - bedrock/global.zai.glm-5.3 - bedrock/in.anthropic.claude-haiku-4-5-20251001-v1:0 - bedrock/in.anthropic.claude-opus-5 - bedrock/in.anthropic.claude-sonnet-5 - bedrock/jp.anthropic.claude-haiku-5-5 - bedrock/us.anthropic.claude-haiku-5-5 - bedrock/us.anthropic.claude-sonnet-5-5 - bedrock/us.zai.glm-5.3 - copilot/claude-haiku-5.5 - openrouter/anthropic/claude-haiku-5.5 - openrouter/apodex/apodex-1.1-mini:free - openrouter/google/gemini-nano-banana-2.1 - openrouter/inclusionai/ling-3.1-flash - openrouter/mistralai/mistral-large-4-0 - openrouter/unbiased/pareto-26.10-preview - vercel/anthropic/claude-haiku-5.5 - vercel/google/gemini-nano-banana-2.1 - vercel/mistral/mistral-large-4 - vercel/stealth/glyph-cluster </details> <details> <summary>Removed</summary> - openrouter/kwaipilot/kat-coder-pro-v2.5 - openrouter/qwen/qwen3.8-27b:free - openrouter/stealth/space-bunny-alpha - vercel/deepseek/deepseek-v3.1-terminus - vercel/inclusionai/ling-3.0-flash-sante-free - vercel/liquid/d1 - vercel/moonshotai/kimi-k2-thinking - vercel/stepfun/step-3.5-flash </details> <details> <summary>Changed</summary> - anthropic/claude-sonnet-5-5 - bedrock/anthropic.claude-sonnet-5-5 - bedrock/global.anthropic.claude-sonnet-5-5 - copilot/claude-sonnet-5.5 - openrouter/anthropic/claude-sonnet-5.5 - openrouter/deepseek/deepseek-v3.1-terminus - openrouter/deepseek/deepseek-v3.2 - openrouter/deepseek/deepseek-v4-flash - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4-pro - openrouter/deepseek/deepseek-v4.1-flash - openrouter/inclusionai/ling-3.0-flash-fin - openrouter/meta-llama/llama-4-maverick - openrouter/meta/muse-glimmer-30b - openrouter/moonshotai/kimi-k2.6 - openrouter/moonshotai/kimi-k3 - openrouter/nvidia/nemotron-3-nano-30b-a3b - openrouter/nvidia/nemotron-3-super-120b-a12b - openrouter/nvidia/nemotron-3-ultra-550b-a55b - openrouter/nvidia/nemotron-3.5-lightning - openrouter/openai/gpt-5.6-sol-pro - openrouter/qwen/qwen3-235b-a22b-2507 - openrouter/qwen/qwen3-next-80b-a3b-instruct - openrouter/qwen/qwen3.5-27b - openrouter/qwen/qwen3.5-35b-a3b - openrouter/qwen/qwen3.5-397b-a17b - openrouter/qwen/qwen3.6-27b - openrouter/qwen/qwen3.8-27b - openrouter/z-ai/glm-5.1 - openrouter/z-ai/glm-5.2 - openrouter/z-ai/glm-5.3 - openrouter/~anthropic/claude-haiku-latest - openrouter/~anthropic/claude-sonnet-latest - openrouter/~deepseek/deepseek-flash-latest - openrouter/~deepseek/deepseek-pro-latest - openrouter/~deepseek/deepseek-v4-flash-latest - openrouter/~moonshotai/kimi-latest - openrouter/~z-ai/glm-flash-latest - openrouter/~z-ai/glm-latest - vercel/anthropic/claude-sonnet-5.5 - vercel/arcee-ai/trinity-large-thinking - vercel/google/gemini-3.8-flash-lite-tts - vercel/google/gemini-3.8-flash-tts - vercel/inclusionai/ling-3.0-flash-sante - vercel/poolside/laguna-s-2.1 - vercel/xiaomi/mimo-v2.6-flash </details> ## Review notes Regenerated by `make gen/aibridge-prices` from the live [models.dev](https://models.dev) catalog. Both artifacts come from one snapshot, so they ship together: - `coderd/aibridge/prices/data/prices.json` - `site/src/modules/aiModels/knownModels/knownModelsGenerated.json` These are customer-visible cost numbers taken from upstream data, so this PR is never merged automatically. The summary above lists what moved; check the diff for exact figures before approving. Opened automatically by the [aigateway-prices-refresh workflow](https://github.com/coder/coder/actions/runs/37754651010). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
788a8bc1ba |
test: skip agent tool call tests until netstack TIME_WAIT fix (#30465)
Skip `TestAgent_ToolCall` and `TestEditMessageCancelsToolCallsOnAgent` until the agent netstack fix in PLAT-717 lands. The agent's gVisor netstack accepts connections through `tcp.Forwarder` and has no listening endpoint, so it drops a SYN that reuses a source port it still holds in TIME_WAIT (google/gvisor#15013). Agent API requests open a new connection each and the agent closes first, so a client that reuses a port within 60s hangs for about 63s. Both tests make enough requests to one agent to hit it (CODAGT-1336, CODAGT-1331). The same stall was reproduced against a production agent on dogfood, so this is a product bug, tracked in PLAT-717. |
||
|
|
ef590afda7 |
fix: coalesce AI session metadata in list query (#30351)
Update `ListAIBridgeSessions` to return `{}` when selected
session/interception metadata is SQL NULL, regenerate database code, and
add a regression test that inserts an interception with NULL metadata
and verifies the sessions list succeeds with empty metadata. No schema
migration is included; existing insert-path normalization remains
unchanged.
Fixes AIGOV-694
|
||
|
|
b4d51012da |
feat: allow template version selection for workspace builds (#30199)
Add named template version selection to `coder start` and `coder stop`, and independent stop/start selection to `coder update` with `--stop-template-version` and `--template-version`. Stop still defaults to the workspace's current version, and update starts with the active version by default. Explicit selections use the selected version for parameter preparation and builds, keep server permissions authoritative, and never silently fall back to the active version. Classic stop builds retain previous parameter values omitted by the selected stop version, so a later start can reuse them across separate commands or an interrupted update. Declared parameters still follow normal validation, and start builds still discard removed parameters. Update now returns an error and retry guidance when a start apply fails after stopping, including unflagged updates that previously returned success. Closes #29100 [PLAT-616](https://linear.app/codercom/issue/PLAT-616/cli-allow-specifying-a-template-version-for-stopstart-builds-and-both) --------- Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
b4fb7901e6 |
docs: clarify that disable-password-auth also applies to owners (#30362)
The `--disable-password-auth` help text says owners can still sign in with a password "to avoid potential lock out", and a comment in `coderd/userauth.go` says the same. Neither is true. #6193 removed the owner bypass on purpose, so the flag blocks password login for everyone. The recovery advice was also wrong. It named a command that doesn't exist (`create-admin`), and any admin that `create-admin-user` creates while the flag is on still can't sign in. This PR changes docs and comments only: - Rewrites the flag description to say it applies to owners too and how to recover access. Regenerated the CLI and config reference docs and the golden files. - Fixes the misleading comment in `coderd/userauth.go`. - Adds the same warning and recovery steps to `docs/admin/users/password-auth.md`. > [!NOTE] > Generated by Coder Agents on behalf of @jdomeracki-coder. |
||
|
|
f08bfddfa7 |
feat: validate AI Gateway actor and credentials in proxy mode (#30225)
Extends the AI Gateway `forwardingHandler` with actor check, provider credential resolution, and initial interception metadata. Missing provider credentials return 403 Credential resolution failures return 500 with details kept in logs. AWS-signed bridged credentials remain unsupported. Generated by Coder Agents on behalf of @pawbana. |
||
|
|
28fe61ffa1 |
feat(coderd): evaluate read_template parameters for the chat owner (#29561)
The chat `read_template` tool returned the parameter defaults recorded at template import. Defaults that depend on the workspace owner, such as a region chosen from the owner's groups, were therefore wrong for many users, and an agent that omitted the parameter in `create_workspace` built a workspace with a different value than the tool had shown. `read_template` now evaluates the active version's parameters for the chat owner with no inputs, through `dynamicparameters.Prepare` and the same `Render` call `wsbuilder` makes for a first build, via a `RenderTemplateParametersFn` hook wired from coderd like the other chat hooks. The result carries a `parameters_note` naming the source: owner-evaluated build values, import rows for templates on the classic parameter flow (which `wsbuilder` also builds from), a retry note while the version is still importing, or import rows with a warning when evaluation fails. A parameter whose evaluated default fails its own validation is reported as `error` instead of a usable `default`. Only an evaluated default is checked: without one, preview and the static renderer validate an empty value, so required parameters and unevaluated defaults are never reported as broken, and their remaining errors surface at build time. Fields preview cannot evaluate before the build are shown as evaluated rather than filled from the import row, because preview's output does not distinguish a default, option set, or validation bound that is unknown (it depends on `data.coder_provisioner`) from one that is null for this owner: an unevaluated default carries a `default_note` saying so, an option with an unknown value is omitted, with preview's invalid-options error surfaced as `error` when the parameter has an evaluated default, and bounds appear exactly as rendered. The one import-row fill is for parameters a `module_not_loaded` render dropped, keyed on the same diagnostic code `wsbuilder` uses. Import rows carry no module provenance, so that fill also restores root-level rows the render omitted for this owner; every restored row carries a `note` marking it an import-time estimate. The build-values note is scoped to a request that omits every parameter and matches no preset, since a default that depends on another parameter is re-evaluated against the values `create_workspace` passes, a preset can match without a `preset_id`, and a claimed prebuilt workspace can keep its own values. When evaluation falls back, the warning logs only diagnostic codes, because diagnostic text can quote owner attributes. Measured on dogfood, evaluation adds about 4 ms for a two-parameter template and about 70 ms for the 6-parameter, 19-module `coder` template per `read_template` call, matching the workspace create form's evaluate endpoint, with no file cache growth across repeated calls. > Xum acted for Mike on this pull request. |
||
|
|
9cfe27063d |
test(coderd): reduce chat test fixture and timer waits (#29523)
Reduce repeated database/server fixtures and fixed timer waits in chat tests without changing production code or assertions. `TestTransitionMatrix_AllCombinations` shares one database and seeded dependencies across 272 leaves, with a unique chat and recording publisher per leaf. `TestPostChatFile` shares one authenticated client across 20 upload leaves. `TestResolveFallbackModelConfigID` shares one database with independently seeded model configurations. The requires-action test closes its server after the expected state persists; the stopped-workspace test advances a trapped Quartz validation timer; two tool-filtering tests no longer start unused workspace agents. | Test | Before | After | |---|---|---| | `chatstate/TestTransitionMatrix_AllCombinations` (272 leaves) | 94.06s | 16.86s | | `coderd/TestPostChatFile` (20 leaves) | 31.23s | 0.95s | | `chatd/TestRequiresActionChatPersistsWaitingStatusLabel` | 11.21s | 1.25s | | `chatd/TestSubagentChatExcludesWorkspaceProvisioningTools` | 7.90s | 2.84s | | `chatd/TestPlanModeSubagentChatExcludesAskUserQuestion` | 8.25s | 3.00s | | `chatd/TestStoppedWorkspaceWithPersistedAgentBindingDoesNotBlockChat` | 6.91s | 1.91s | | `chatd/TestResolveFallbackModelConfigID` (12 leaves) | 7.58s | 0.34s | Independent review measurements on September 18, 2026: median summed leaf time from two runs per side in A/B/B/A order, comparing base `0ea777a341` with head `e378f9e936`. Every run used `-tags=testsmallbatch -count=1 -v -p 1 -parallel 8`, PostgreSQL 17, and the same test selection per package. Other agents shared the host, so absolute times varied. The speedups reproduced, but not the original ratios: the matrix improved 5.58x and uploads 32.87x. Summed leaf time excludes shared parent fixture setup and cleanup; it is not package wall time. Median package elapsed was 19.26s to 9.76s for the full `chatstate` package, 4.47s to 1.28s for `coderd` with only `TestPostChatFile`, and 11.43s to 3.36s for the five targeted `chatd` tests. Compilation time is excluded. <details> <summary>Investigation notes</summary> - Transition matrix: the shared user, organization, membership, provider, and model are not mutated by any leaf. Each leaf seeds its own chat, messages, and queue, and copies the fixture with a new recording publisher (`transitions_matrix_test.go:617,728,762`). `ChatMachine.Update` still opens real transactions on the shared database store; no outer transaction masks rollback assertions (`chatstate/machine.go:161`, `transitions_helpers_test.go:891`). Parent cleanup runs after every leaf. - Requires-action: the old idle hook reached its 10s timeout because the runner remains active while awaiting dynamic-tool results (`testhooks.go:14`, `worker.go:114`). The test now waits for the persisted status and label, closes and drains the server, and retains the no-web-push assertion (`chatd_test.go:3072`). - Stale binding: the test injects a new Quartz mock, traps the 5s validation timer, waits for `MustRelease` to finish timer registration and for the dial to start, then advances the clock (`chatd_test.go:4907`). The one-dial, model-call, and unavailable-workspace tool-result assertions remain intact. - Tool filtering: both tests create templates but no workspace, and their mocked model only invokes `spawn_agent` before returning text. The removed workspace agents could not authenticate and were never used by the tested flow; their shutdown added about 5s (`chatd_test.go:229,384`). - Fallback models: configurations and providers are independently inserted. Most leaves use unique organizations; the two default-organization cases insert distinct models, and only one inserts a default. No leaf mutates another leaf's model or provider (`chatd_internal_test.go:3512`). Validation: all changed tests passed with `-count=5` and `-race -count=2`; the full `chatstate` package passed both checks (2,350 and 940 test executions, including parents). All 272 matrix, 20 upload, and 12 fallback leaves remain present. `gofmt -l`, `git diff --check`, and `golangci-lint run` on the three changed packages were clean. The full `coderd` package was not run. No correctness changes were needed during review. `ARCHITECTURE.md` was read; this test-only PR does not affect the documented architecture, so no TODO or architecture edit is needed. </details> _Investigated, implemented, and validated by Coder Agents on behalf of @ibetitsmike._ |
||
|
|
fc01bee831 |
fix: keep new API keys within the caller's scopes and allow list (#30256)
A scoped key holding api_key:create could mint a broader key, e.g. a token scoped to [api_key:create user:read] could mint coder:all.
- New keys must be covered by the caller's scopes and allow list, and inherit them when none are requested
- Requests beyond the caller return 403
- New key expiry is capped at the caller's
- Covers POST /users/{user}/keys/tokens, POST /users/{user}/keys, app auth-redirect, and /oauth2/authorize (invalid_scope on excess grants or a restricted session allow list)
- coder:all sessions, including browser logins, behave as before
- Not addressed: workspace start still mints a coder:all key for the owner
|
||
|
|
67a781ce1d |
feat: remove model_intent from the execute, process_output, and advisor tools (#30397)
The built-in `execute`, `process_output`, and `advisor` tools offered an
optional `model_intent` argument whose text replaced the tool row's
default label. Models fill it inconsistently, so most chats mixed intent
labels with plain command labels. On dogfood over three days, Claude
Opus 5.5 sent it on 17% of `execute` calls through Bedrock and 30%
through the Anthropic API. The rate follows reasoning effort: the few
chats at max or xhigh effort sent it on every call, while chats at high,
medium, or default effort sent it on about a third of calls or fewer.
This removes the argument from the three tool schemas and always renders
the command-based labels ("Ran ...", "Started ... in the background",
"Checked ...", "Consulted the advisor"). It also deletes the frontend
helpers, tests, and stories that existed only for the intent labels.
- Old chats keep working. chatd's decoders and its tool input check
ignore undeclared keys, so calls that still carry `model_intent` run as
before and their rows show the default label.
- The per-server `model_intent` option for MCP tools is unchanged. That
field is required in the schema, and Opus 5.5 fills it on 96 to 99.7% of
those calls.
- The MCP workspace `execute` and `process_output` tools now match the
Coder Agents contract apart from their `workspace` argument, so the
golden test drops its Agents-only exception.
- Pixel diffs from this change: the deleted intent stories and the new
default labels in `AllToolIconsTranscript`,
`PolicyBadgeCoversEveryRenderer`, and
`StreamedAdvisorResultOverlaysDurableCall`.
## Testing
- `go test` for `chattool`, `chatadvisor`, `toolschema`, `coderd/mcp`,
and `coderd/x/chatd -run Advisor`; `go vet ./coderd/x/chatd/...
./coderd/mcp/...`.
- Red check: re-adding the field to `ExecuteArgs` fails
`TestWorkspaceToolsGolden`.
- Vitest unit tests for the tool utils, the generic tool row, and chat
parsing (5 files) and the affected Storybook files (4 files); `biome`,
`oxlint`, and `tsc`.
- `make pre-commit` passed on the rebased head. The pre-push hook was
skipped per the maintainer's standing preference; CI covers it.
## Review record
- `frontend-review` (FE1 to FE10): all PASS or N/A.
- `coder-frontend-review` (8 parallel reviewer roles): no findings. Two
optional side notes were declined: a nested ternary for `ExecuteTool`'s
label (SD3 discourages them) and a story for an old call that still
carries `model_intent` (TS7: it shows the same state as the existing
default-label stories).
> Xum opened this PR on behalf of @ibetitsmike.
|
||
|
|
e4682343e6 |
feat: match PR number prefixes in chat search (#30404)
Chat search now matches PR numbers by prefix, so typing `3028` already finds the chat for PR `30281` instead of showing zero results mid-typing. The free-text `search:` branch in `GetChats` switches from `pr_number = @search::bigint` to `pr_number::text LIKE @search || '%'`, still guarded by a digits-only regex so the value can never carry LIKE wildcards. The lookup stays a correlated per-chat EXISTS on the `chat_diff_statuses` primary key, which leads with `chat_id`, so the cost is the same as before and no new index is needed. The explicit `pr:` filter stays exact, and ordering is unchanged (no exact-match ranking) so cursor pagination is unaffected. Behavior note: values with leading zeros (`030281`) no longer match PR `30281`, since the old bigint cast normalized them. PR numbers never have leading zeros, so this seemed fine. Closes CODAGT-1342 ## Testing - `TestGetChatsSearch` gains prefix (`4` -> PR 42), no-infix (`2` -> none), and LIKE-wildcard (`4%` -> none) cases; the prefix case fails on the old predicate. - Dogfood UAT through Coder Agents on the branch: searching `3`, `302`, `3028`, `30281` all surface the PR-linked chat; `0281` and `302810` do not; `pr:3028` stays exact. > [!NOTE] > This PR was created by Xum acting on behalf of @ibetitsmike. |
||
|
|
02a12fefa8 |
chore: remove the Coder Agents chat board prototype (#30394)
Prototypes shouldn't be on main, so this removes the Coder Agents chat board. It removes the board added in #29425 and extended in #29472, #30094, #30103, #30231 and #30332, plus the hidden `chat-board` experiment from #30084. With them go the route, the sidebar entry and grouping, the settings toggle, the sidebar row trailing slot, and the `chatId` prop on `AgentChatPage`. The abort signal on `getChats` stays, because #30079 uses it outside the board. The board continues in the experimental PR #30395, which is not for merging. |
||
|
|
f0e2fce326 |
fix: let scoped tokens list and mark inbox notifications read (#30176)
`inbox_notification:read` and `inbox_notification:update` existed but weren't in the public scope catalog, so only `coder:all` tokens could use the inbox. The inbox endpoints also returned 500s or a clean socket close when a scope was missing, instead of a 403. - Add `inbox_notification:read` and `inbox_notification:update` to the public scope catalog. `create` stays internal, so there is no `inbox_notification:*`. No migration is needed. - Every inbox endpoint checks scopes up front and returns 403 naming the missing scope. The watch endpoint checks before the websocket upgrade. - `read-status` requires both `read` and `update`. It returns 404 unless the notification belongs to the caller, so an owner can no longer mark another user's notification read. |
||
|
|
7993c73c87 |
feat: add organization-scoped Coder Agents instructions (#30272)
Adds organization-scoped Coder Agents instructions. Organization admins
set them in **Admin settings** > **AI** > **Coder Agents** >
**Organization settings**, or with `GET`/`PUT
/api/v2/organizations/{organization}/chats/config/system-prompt`.
Implements [CODAGT-984](https://linear.app/codercom/issue/CODAGT-984).
The instructions add to the deployment system prompt and never replace
it. When a chat is created, chatd stores the organization prompt as its
own system row right after the deployment row, only for chats in that
organization. Subagents resolve their parent organization's current
prompt when they spawn, and existing chats keep their stored rows.
Access reuses the organization `chat_model_config` permission: owners
and organization admins edit, auditors read, members get 404 on read and
403 on write. Writes reuse the deployment prompt's sanitization, size
limit (128 KiB by default), and audit behavior, with a new
`chat_organization_system_prompt` audit resource type. Migration
`000613` (the next number after `000612` on `main`) adds the
`chat_organization_system_prompts` table.
## Testing
- Go: enterprise authorization (including an update-only custom role),
validation, and audit tests; chatd row order and subagent tests.
- Frontend: Vitest interaction tests and stories for the card (loading,
load error, refetch error over the cached value, save error, read-only).
- Remote dogfood UAT, [evidence
chat](https://dogfood.cdr.dev/agents/b595a709-0709-44e6-9535-96a922974d61):
round 1 **PASS** on `b027cb5ca67` (permission matrix, validation, UI,
row order, cross-organization isolation, audit, subagents, regression).
Round 2 **PASS** on `618bff67c75` (loading and load-error states,
refetch error over the cached value with unsaved edits kept, update-only
custom role saves over the API, row order, the documented size limit,
rapid organization switching, double-click save).
- CI: rebased onto `main` (`98332c739b0`) as `3850fbaa922`; other commit
SHAs in this description are from before the rebase. Every check passed
on `3850fbaa922`, with `test-go-pg` green on the first attempt. After
the review fixes in item 7, `main` was merged in as `006c4951749` to
resolve new conflicts in generated files and renumber the migration to
`000613`. Every check passes on `006c4951749`. Before the rebase, every
check passed on `b4e76543df2`. `test-go-pg (ubuntu-latest)` passed on
its fourth attempt; the first three failed only the `cli` package
goroutine leak check, with every test passing. Two of those leaked a
coderd instance, which also happens intermittently on `main`:
`TestServer/Logging` cancels `coder server` during startup, and an early
return in `cli/server.go` skips closing coderd. That fix is in #30280.
The first attempt leaked an idle HTTP connection instead (not
investigated).
## Screenshots
From remote UAT on a test deployment (test data only).
| Organization admin saves instructions (`b027cb5ca67`) | Auditor sees
read-only instructions, no save actions (`b027cb5ca67`) |
|---|---|
| 
| 
|
| **Loading state while the first fetch is pending (`618bff67c75`)** |
**Refetch error shown above the field; the unsaved edit is kept and Save
stays enabled (`618bff67c75`)** |
| 
| 
|
## Review record
1. Codex,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5387245297)
on `c42b5f9e05c`: 6 findings. Fixed the missing loading state, refetch
failures hiding cached instructions, and two docs style issues
(`58eab5603a4`, `cc73b714630`). Two were first declined in error, then
corrected: the read-only test now checks that typing leaves the value
unchanged (`cc73b714630`), and update-only custom roles no longer get a
500 on save (`618bff67c75`).
2. Independent security review by a clean-context agent,
[comment](https://github.com/coder/coder/pull/30272#issuecomment-5943505041)
on `c42b5f9e05c`: no P0 to P2 findings. A stale P3 comment was fixed in
`34c17aadb7f`; returning `err.Error()` in 500 details was kept to match
the deployment prompt handlers.
3. Codex,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5387323380)
on `58eab5603a4`: 2 findings (refetch errors not surfaced, docs line
breaks), both fixed in `cc73b714630`.
4. Codex, blockers only,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5387462070)
on `618bff67c75`: 1 P2 (a failed refresh right after a successful save
shows the previous value). Not a blocker, deferred.
5. Final fresh advisory by a clean-context agent,
[comment](https://github.com/coder/coder/pull/30272#issuecomment-5944285083)
on `618bff67c75`: **READY**, no blockers and nothing to cut. It
independently checked authorization, audit, the migration, chatd row
insertion and subagent inheritance, the tests, and soft-deleted
organization handling, and agreed with every deferral. No code changes
followed: the snapshot behavior it suggested documenting is already
documented, and its docs wording note joins the deferred docs item.
6. Codex,
[comment](https://github.com/coder/coder/pull/30272#issuecomment-5952100918)
on `b4e76543df2` (the docs-only follow-up below): no major issues. Mike
asked for a passing Codex review loop after item 5, so this review goes
past the planned stop at the final advisory. No code changes followed.
7. ethanndickson,
[review](https://github.com/coder/coder/pull/30272#pullrequestreview-5409332502)
on `3850fbaa922`: approved with 4 comments. Fixed 3: the audit target is
now empty (`91e77d3fa8c`), the docs no longer re-explain audit logs
(`a0fb6891af5`), and the organization instructions stories went from 9
to 5 (`e836097f93f`). Not fixed: the organization prompt read fails open
on a database error, like the deployment prompt, and ethanndickson is
changing both after merge
([thread](https://github.com/coder/coder/pull/30272#discussion_r4180191267)).
UAT did not rerun for these changes.
Not counted as reviews: the pre-PR frontend self-review, simplify pass,
and test audit (`de8377e94e1`), and a second test audit of
`de8377e94e1..cc73b714630` (pass with nits; the update-only test case
was added after it).
Docs-only follow-up after the advisory, requested by Mike: `b4e76543df2`
adds audit log guidance for prompt changes to the platform controls page
and an update-only custom role note to the organizations page. Codex
reviewed it (item 6). No UAT covers it, and the code is unchanged since
`618bff67c75`. The deferred claim that the Instructions page path is
outdated was wrong, so it's dropped. Item 7 removed the audit log
guidance again; the custom role note stays.
## Soft-deleted organizations
UAT found that a soft-deleted organization's prompt stays readable and
writable by UUID. This is inherited behavior, not new exposure:
`ExtractOrganizationParam` resolves UUIDs without a deleted filter, so
the sibling organization chat routes (MCP servers, model overrides,
models) behave the same. The same `chat_model_config` RBAC still
applies, nobody gains access to another organization, and writes are
audited.
## Deferred (owner: Mike)
- A failed refresh right after a successful save shows the previous
value with an error alert, so a further edit from that view starts from
the old text (Codex round 4, UAT round 2). Trigger: reports of stale
values after saving on unreliable networks.
- Update-only custom roles can save over the API, but the card stays
hidden without read access. Trigger: a customer uses such a role.
- Soft-deleted organization access by UUID, above. Trigger: the platform
starts rejecting deleted organizations in `ExtractOrganizationParam` or
purging their configuration.
- A contrived "code word" instruction was refused as possible prompt
injection; neutral instructions work. Trigger: reports of ignored
organization instructions.
- UX polish: there is no retry action after a failed first load, the
save toast can cover Cancel, there is no unsaved-changes guard, the
oversize error omits the limit, and whitespace-only text clears the
prompt without notice. Trigger: the next settings UX pass.
- Docs: the 413 response and organization name paths are undocumented.
Trigger: the next Coder Agents docs pass.
- Test audit nits: a redundant `waitFor` and an optional read-only plus
refetch story. Trigger: the next change to these tests.
> Xum, an AI coding agent, implemented, tested, and opened this PR on
behalf of @ibetitsmike.
|
||
|
|
49b1a2cf5d |
feat: expose per-ref diff statuses (#29082)
Part 2 of 6. Depends on #29081. The API now exposes every ref a chat tracks. All API changes are additive. - `Chat.diff_statuses` lists every ref on the chat GET and in chat lists (including child chats). The order is stable: refs are listed by first report, so the list does not change order when a ref gets a new git report. - `Chat.diff_status` is the primary: the ref with the most recent git report. It is the same rule as before. Use it to find the primary, not the list position. - `ChatDiffStatus` gains `remote_origin` and `git_branch`. - `diff_status_change` watch events carry `changed_diff_status` (`{ref, status}`) naming the ref that changed. If that ref's row is gone, `status` contains only `chat_id`. - `GET /chats/{chat}/diff` accepts optional `origin` and `branch` query parameters. Set both or omit both (otherwise 400). A selector that matches no stored ref returns 404. Without a selector the endpoint returns the primary, as before. The Go SDK adds `WithChatDiffStatusRef` for this. - A git report without a chat ID (for example, from a terminal or an agent older than v2.32) now refreshes only the chats that already track that ref. It does not add the ref to other chats. Such a report can no longer give a chat its first ref. Generated by Coder Agents. |
||
|
|
f85f194849 |
test(coderd/x/chatd): check tool call cancels through the agent API (#30346)
TestEditMessageCancelsToolCallsOnAgent checked the canceled process with signal 0, which os.Process.Signal does not support on Windows, so the test timed out in the nightly gauntlet. The check also tested the agent's kill rather than chatd. Both cancel tests now read the chat's process from the agent API. The edit test requires the deleted call's process to have exited with Canceled set when the edited turn calls the model, which also checks the tool call ID chatd cancels. Closes CODAGT-1331 |
||
|
|
15616728d5 | refactor: move coderd/x/nats to coderd/nats | ||
|
|
28cf704f27 |
chore: update references to the relocated install docs paths (#30380)
The Install docs moved into the five-phase spine in #29304, but several references outside `docs/` still point at the pre-move URLs. `docs/redirects.json` is empty, so those URLs 404 rather than forwarding. The release note generators are the user-visible ones: every generated release note links `coder.com/docs/install/releases` and `coder.com/docs/install/upgrade`. | Reference | Was | Now | |---|---|---| | Release schedule links in release notes | `/docs/install/releases` | `/docs/reference/releases` | | Upgrade link in release notes | `/docs/install/upgrade` | `/docs/install/operate/upgrade` | | README sizing link | `/docs/admin/infrastructure/validated-architectures` | `/docs/install/plan/sizing` | | Provisioner tag table comments | `docs/admin/provisioners/index.md` | `docs/install/operate/provisioners/index.md` | | FAQ provenance comment | `docs/admin/licensing/index.md` | `docs/install/prepare/licensing.md` | | ESR 2.24-2.29 upgrade table | `/docs/admin/provisioners` | `/docs/install/operate/provisioners` | | Helm provisioner README, `NOTES.txt`, and `values.yaml` | `/docs/admin/provisioners` | `/docs/install/operate/provisioners` | | Helm Coder chart README | `/docs/install/kubernetes` | `/docs/install/server/kubernetes` | | `workspace-tags` example README | `/docs/admin/provisioners#external-provisioners` | `/docs/install/operate/provisioners#types-of-provisioners` | | `kubernetes-envbox` example README | `/docs/admin/infrastructure/architecture#agents` | `/docs/install/plan/architecture#agents` | `scripts/releaser/docs.go` was already updated in #29304; this covers what that pass missed. Two notes on anchors: - The `#external-provisioners` anchor was already dead before #29304, so it now points at `#types-of-provisioners`, the section covering external, organization-scoped, and user-scoped provisioners. - Every other anchor was verified to still exist on its new page. One link left alone: `provisionerd/provisionerd.go` references `docs/admin/provisioners.md` through a pinned-commit GitHub permalink, which still resolves and shouldn't be rewritten. ## Verification - `go test ./scripts/release/...` passes, including the release note golden strings. - `go build ./scripts/releaser/` succeeds. - `make pre-commit` passes. - Markdown table padding reflowed with `markdown-table-formatter`; `markdownlint` reports no new findings. <sub>Opened by Coder Agents on behalf of @nickvigilante.</sub> |
||
|
|
1a96da2b6a | perf(coderd/x/chatd): make chat stream reads lock-free (#30266) | ||
|
|
7cfc38d0e7 |
feat: wire AI Gateway proxy routing and recorder dependencies (#29725)
Adds `forwardingHandler` for "bridged" routes in proxy mode. Wires provider snapshots to a shared mux and recorder, tracing, circuit breakers, and the server-owned inflight gate. Generated by Coder Agents on behalf of @pawbana. |
||
|
|
a08ba6a70c |
feat: add shared project memory API for chats in a project (#29301)
- Experiment, stacked on #29242. UI is in #29583. - Adds **project memory**: `chat_project_memories` rows with a name (lowercase slug, unique per project), a one-line description (150 characters) and a body (8KB). Up to 200 per project, shared by every root chat in the project. Chats outside a project and subagents have no memory. - Memories are immutable: they are created and deleted, never edited. Agent tools are `read_memory`, `save_memory`, `delete_memory` and `consolidate_memory`. Saving an existing name fails and points the agent at `consolidate_memory` to replace it. - **Consolidation is agent-driven, in the turn**, modeled on how Claude Code compacts its memory index when warned it is near its limit. From 160 memories (80%), save results ask the agent to get under 140 (70%) with `consolidate_memory`, choosing what to merge and drop. That tool deletes and saves memories in one transaction under the per-project advisory lock, and rolls back entirely if a delete is missing, a name is taken, or the result exceeds 200. There is no background extraction or consolidation. - **The memory index reaches the model as model-only conversation messages**, not in a tool description or the system prompt. At turn start the chat gets a full `<project-memory-index>` snapshot when its prompt has none (first turn, or after compaction), otherwise a `<project-memory-index-update>` listing only what changed. Tool definitions and the system prompt carry no memory state, so memory writes never invalidate the provider's cached prompt prefix. Writes by other chats, or by this chat mid-turn, reach the model at its next turn. - REST API (create, list, get, delete) under `/api/experimental/organizations/{organization}/chats/projects/{project}/memories`. Memory permissions follow projects onto the `agents-access` role. - **Every memory change is audited** as `ChatProjectMemory` create or delete. REST changes are attributed to the caller. Tool changes (`save_memory`, `delete_memory`, `consolidate_memory`) are attributed to the chat owner, carry the `chat_id`, and record one entry per memory after the change commits, so a rolled-back consolidation records nothing. ### Examples **What the model sees.** The system prompt gets a fixed guidance block with no memory state: ```text <memory> Memory is durable context shared by every chat in the project "platform". Save facts that will matter in future chats: … The memory index is in the conversation: a <project-memory-index> message lists every saved memory, and <project-memory-index-update> messages at the start of later turns list what changed. Changes made during a turn, including your own, appear in the next turn's update. … Memories cannot be edited: replace one that no longer holds with consolidate_memory, or delete it. </memory> ``` On the first turn, after the user's message, the chat gets a model-only row with the full index (hidden in the UI): ```text <project-memory-index> - deploy-day: Deploys happen on Tuesdays - release-owner: Alice owns releases; ping her before tagging </project-memory-index> ``` On a later turn where memories changed, it gets only the difference: ```text <project-memory-index-update> Added or changed: - deploy-day: Deploys happen on Wednesdays (changed 2026-09-30) - staging-url: Staging lives at staging.example.com Removed: - old-ci-notes </project-memory-index-update> ``` Resulting request layout, with the provider's cached prefix unchanged by memory writes: ```text [tools: fixed] [system: fixed <memory> guidance] [turn 1 user] [index snapshot] [assistant/tools …] [turn 2 user] [index update] [assistant …] ``` **Tool calls and results** (produced by the tools in this PR): ```text save_memory {"name":"staging-url","description":"Staging lives at staging.example.com","body":"Staging is https://staging.example.com; deploys from main."} → {"count":3,"saved":"staging-url"} save_memory {"name":"deploy-day", …} // name already exists → error: a memory named "deploy-day" already exists; read it, then replace it with consolidate_memory by deleting "deploy-day" and saving the new version in one call consolidate_memory {"delete":["deploy-day"],"save":[{"name":"deploy-day","description":"Deploys happen on Wednesdays (changed 2026-09-30)","body":"The team deploys every Wednesday since 2026-09-30."}]} → {"count":3,"deleted":["deploy-day"],"saved":["deploy-day"]} read_memory {"name":"deploy-day"} → {"name":"deploy-day","description":"…","body":"…","created_at":"2026-09-30T15:04:05Z","created_by":"alice"} ``` Near and at the cap: ```text save_memory … → {"count":160,"saved":"one-more","warning":"memory is 160/200, approaching the limit. Consolidate it to under 140 memories now with consolidate_memory: merge overlapping memories into one, and drop stale, wrong, or superseded ones."} save_memory … → error: memory is full (200/200); use consolidate_memory to merge overlapping memories and drop stale ones, and include this memory in its save list ``` **REST memory object** (`GET .../chats/projects/{project}/memories`): ```json { "id": "59500000-0000-4000-8000-000000000001", "project_id": "7c0e4a3e-5b1f-4f7d-9a51-2f3c8f6d2b10", "organization_id": "bb640d07-ca8a-4869-b6bc-ae61ebb2fda1", "name": "deploy-day", "description": "Deploys happen on Wednesdays (changed 2026-09-30)", "body": "The team deploys every Wednesday since 2026-09-30.", "created_by": "0ed9befc-4911-4ccf-a8e2-559bf72daa94", "created_by_username": "alice", "created_at": "2026-09-30T15:04:05Z" } ``` Create takes `{"name", "description", "body"}` and answers 409 on a duplicate name or at the cap. <details> <summary>Screenshots (predate the immutable-memory rework; tool output shape has since changed)</summary>    </details> --- Generated with Coder Agents on behalf of @f0ssel. --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
3f444d9528 |
fix: accept 128-character template descriptions on creation (#30348)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.
Template creation rejected descriptions of exactly 128 characters even
though the forms allow them and the database supports them. Change both
the standard and template-builder creation request validators to accept
up to 128 Unicode code points, and regenerate the API schema and
reference.
<details>
<summary>Investigation and scope</summary>
The validator counts Unicode code points, not bytes; the SDK comment is
corrected accordingly. The existing forms remain unchanged: their UTF-16
length checks are conservative for supplementary characters such as
emoji. This fixes the creation off-by-one without broadening frontend
character-count behavior.
</details>
|
||
|
|
ffc7dadfe2 |
refactor: use typed AI Gateway actor identity (#30258)
Adds typed AI Gateway actor identity, including the API key ID used by recording. Recorders now read the authenticated API key ID from each call context instead of capturing request identity at construction time. This allows one recorder to be reused safely across sequential and concurrent requests. Includes context helper coverage and recorder regression tests. Generated by Coder Agents on behalf of @pawbana. |
||
|
|
bf3db74b83 |
fix: reject encoded path traversal in ai gateway before forwarding upstream (#30178)
AI Gateway passthrough forwards the client's escaped path upstream unchanged. `http.ServeMux` only cleans literal dot segments, so a percent-encoded dot segment (for example `/openai/v1/models/%2e%2e/files`) matched an allowlisted passthrough route here, while the upstream decoded it and served a different endpoint with the centralized key attached. This adds `xurl.ContainsEncodedPath` in `coderd/util/xurl` so other forwarding code can reuse it. It is applied at the gateway entrypoint (`NewRequestBridge`, via `routing.RejectInvalidForwardPath`) and in the experimental `x/proxy.Router`, before routing. Requests get a 400 `invalid request path` if any path segment, after decoding once: - contains a `.` or `..` element, including behind an escaped `/` or `\`, - still contains `%`, which only arises from multiple encoding, - contains control characters. Escaped separators in ordinary segments such as `/models/org%2Fmodel` keep forwarding unchanged. Fixes AIGOV-678 <details> <summary>Decisions</summary> - **Validate once at the entrypoint instead of per handler.** One check covers every provider and route, including the reverse-proxy handler that will mount behind `x/proxy.Router`. - **Shared helper in `coderd/util/xurl`.** Per review, the check is a generic `func ContainsEncodedPath(*url.URL) bool` so other proxies can reuse a single implementation. - **Reject rather than normalize.** Legitimate clients have no reason to send dot segments to these APIs, and rejecting avoids authorizing a path the upstream interprets differently. - **Decode exactly once, and reject leftover `%`.** One decode matches RFC 3986 section 2.4. Rejecting a remaining `%` means further decoding by any downstream component cannot produce a dot segment. - **Split decoded segments on `/` and `\`.** Guards against components that decode reserved characters. `org%2Fmodel` still passes. - **Literal `..` now returns 400** instead of the ServeMux 307 redirect, because the check runs before the mux. - **Out of scope:** tightening passthrough route patterns and key-pool hardening. Both are separate follow-ups. </details> --- _Generated by Coder Agents on behalf of @SasSwart._ |
||
|
|
939d05b906 |
fix(coderd): never dial the embedded DERP region over the network (#30221)
Fixes CLI-9 The `goleak` check in `cli` has been flaking on an idle HTTP connection. It turns out that's coming from `coder server` shutting down, not the OIDC links command. `API.Close` cancels the API context well before it closes the server tailnet, and since #14680 the embedded DERP region dialer returns `nil` once that context is done. Unfortunately, `nil` tells `derphttp` to dial the region over the network instead. So the server dials its own access URL (`example.com` in tests), gets a 404, falls back to WebSocket, and our tailscale fork leaves that failed WebSocket connection open forever. This has only been flaking since #29462, which has the server tailnet fetch the DERP map straight away rather than after the first 5 second tick. Before that, most server tests had finished before the tailnet ever connected to DERP, so there was nothing to reconnect on shutdown. To fix, the embedded region now gets an already closed conn once shutdown starts, so the DERP handshake fails and magicsock just backs off until the tailnet closes. I reproduced the leak by pointing a server tailnet's embedded region at `example.com` and cancelling the context; it fails `goleak` without this change and passes with it. |
||
|
|
bb9f31d94b |
fix: apply Anthropic prompt caching through OpenRouter and OpenAI-compatible gateways (#29563)
Anthropic models configured through an `openrouter` provider (and, by
the same code path, `vercel` and generic `openai-compat` providers)
never got prompt caching. Two independent gaps: chatd only emitted
`cache_control` breakpoints when the fantasy client was `anthropic`, and
even when a client sent them, the AI Gateway chat-completions
interceptor rebuilt the upstream body from typed
`openai.ChatCompletionNewParams` and silently dropped the unknown key.
Dogfood UAT on main @
|
||
|
|
98332c739b |
feat: align MCP workspace tools with Coder Agents and add execute tools (#30275)
The control-plane MCP server's workspace tools now share their
arguments, behavior, and result formats with the Coder Agents tools. The
MCP server also exposes the Coder Agents execute and process tools.
The shared logic lives in a new `codersdk/toolsdk/workspacetools`
package that both `coderd/x/chatd/chattool` and `codersdk/toolsdk` call.
The Coder Agents tool schemas, descriptions, and JSON responses are
unchanged and the existing chattool tests pass unmodified. The one
exception is the missing-shell guidance, which now reads "Workspace
commands run with `sh -c`" instead of naming Coder Agents. Golden files
in `coderd/mcp/testdata/workspace_tools` hold the shared contract for
each tool, and a test checks both the Coder Agents and MCP tools against
them, so contract changes show up in review. The test also fails if MCP
text names a tool that only exists in Coder Agents.
The MCP versions differ from Coder Agents in four ways:
- Each tool takes a `workspace` argument.
- Invalid arguments and agent API errors come back as MCP tool errors.
- A single call waits at most 5 minutes, matching the agent's maximum
blocking wait. Longer timeouts are rejected with a pointer to
`run_in_background`.
- There is no `model_intent` argument.
**Breaking changes to `/api/experimental/mcp/http` and `coder exp
mcp`:**
| Before | After |
|---|---|
| `coder_workspace_read_file`: byte offset/limit, base64 `content` +
`mimeType`, binary-safe | Line-based `offset`/`limit`, text only,
returns `{content, file_size, lines_read, total_lines}` |
| `coder_workspace_write_file`: base64 `content`, binary-safe |
Plain-text `content`, returns `{ok: true}` |
| `coder_workspace_edit_file` + `coder_workspace_edit_files` |
`coder_workspace_edit_files` only, returns `{files: [{path, diff}], ok}`
|
| `coder_workspace_bash` over SSH: `timeout_ms` (default 60s, 5m cap),
kills the command on timeout (exit 124), trims output |
`coder_workspace_execute`: `timeout` (default 10s, 5m cap), `workdir`,
`run_in_background`. On timeout the command keeps running and the result
has `background_process_id`. Output is untrimmed and capped at 32KB. |
| None | `coder_workspace_process_output`,
`coder_workspace_process_list`, `coder_workspace_process_signal` |
`--allowed-tools` lists and templates that name the removed tools will
need updating. A code search found `coder_workspace_bash` in a couple of
demo templates (`coder/demo-env-templates`, partner demos).
<details>
<summary>Decision log</summary>
- **Shared core vs. duplication.** The execute lifecycle has the most
logic that could drift: waiting in the foreground, handing off to the
background on timeout, recovering a snapshot after transport errors, and
truncating output. It's extracted rather than copied, along with
edit-file validation, read-file handling, and result types. Each surface
keeps its own protocol handling: fantasy and MCP response envelopes,
plan-turn restrictions, `model_intent`, and workspace resolution and
authorization. Struct-tag descriptions must be literals, so the
golden-file test is what keeps them in sync with the shared constants.
Shared result structs keep their fields in alphabetical order so the
JSON matches what Coder Agents produced from maps before.
- **Replace instead of add alongside.** Keeping `coder_workspace_bash`
next to `coder_workspace_execute` would give models two overlapping ways
to run commands. The read and write contracts change anyway, so keeping
the old names wouldn't preserve compatibility. The endpoint and CLI
command are both experimental.
- **5-minute cap on MCP calls.** Each stateless MCP request has to
return before the client gives up. Otherwise the `background_process_id`
needed to follow up is lost and the command keeps running with no ID the
model knows about. Coder Agents has no cap, so its behavior is
unchanged.
- **No SSH fallback.** `execute` doesn't fall back to SSH on older
agents, because SSH can't support the process management contract. The
agent process API and line-based reads shipped in February 2026.
- **Process scoping.** The agent scopes processes by chat ID, which
coderd sets only for Coder Agents connections. MCP calls carry no chat
ID, so they can't see or signal Coder Agents chat processes. All MCP
callers share one process namespace per workspace, which means anyone
with SSH access can list and signal processes another MCP user started.
That matches what SSH access already allows. The existing `ActionSSH`
check in `coderd/mcp_http.go` still runs before every agent connection.
Nothing reaps MCP processes; they run until they exit, are signaled, or
the agent stops.
- **Errors.** As in Coder Agents, command failures and timeouts come
back as result JSON (`success: false`, `background_process_id`). Agent
API errors have transport metadata removed, the same way Coder Agents
formats them.
</details>
---
🤖 Generated by Coder Agents on behalf of @kylecarbs.
|
||
|
|
cc0c868c55 |
feat: add client_session_id to ssh connections (#29701)
Add a new /tcp endpoint on the agent that is used to pass along the client session ID (with the existing baggage mechanisms). The agent then can upgrade that into the desired connection type, based on the port. For now that is only the standard SSH port and reconnecting pty. The `ssh`, `ssh --stdio`, `ssh --stdio` over Coder Connect, `exp rpty`, and web terminal paths are all updated to use this new endpoint, and fall back to the old method when the endpoint is not available. That ID is added to the log context, and is also used to populate the session ID column in the connection logs table. There are some logs related to a connection that will not be tagged with the ID (like the "accepted connection" line) because they happen before the http handler gets to run. |
||
|
|
0f78361750 |
fix(coderd): cancel tool calls in messages deleted on edit (#30194)
Editing a message removes it and every later message from the chat. Before, a tool call in those messages kept going in the workspace: a foreground command ran to completion, and a file edit or write could still apply, while the model no longer knew about it. Now chatd sends the workspace agent a cancel request for each such call before the new turn's first model call. Calls that already returned, such as background processes the model was told about, keep running. Fixes CODAGT-1222 |
||
|
|
122757d1d2 | fix(coderd/database/migrations): lock chat tables before 000609 alters them (#30297) | ||
|
|
a3b6881aea |
feat: add the manage automations toggle, tool rendering and CODAGT-1217 tests (#30219)
Adds the "Manage automations" toggle to the composer's tools menu, so
the interim `manage_automations_enabled` switch can be set from the UI,
and gives the `manage_automations` tool a readable rendering.
Closes CODAGT-1212 (slice 12c of 3). Part of CODAGT-1135.
## What changes
- **Toggle.** A "Manage automations" checkbox item in the composer's +
menu, next to "Plan first". It shows for new chats and for existing root
chats the viewer owns, and only when the `chat-automations` experiment
is on for the viewer. Existing chats update through an optimistic PATCH
(`updateChatManageAutomations`) with rollback and an error toast; new
chats send `manage_automations_enabled` in the create request. The
optimistic single-field update is shared with `updateChatPlanMode`.
- **Tool rendering.** `manage_automations` calls get a label and icon
that name the action (for example "Created automation ..."), with the
generic fallback for unknown actions.
- **Invalidation.** After a successful write action (create, update,
enable, disable, delete, run_now) the automation queries are
invalidated, so the Automations page reflects agent changes; `run_now`
also refreshes chat lists.
## CODAGT-1217 acceptance tests
Adds the remaining CODAGT-1217 acceptance tests (tests only; no bug
found):
- `TestAutomationQueuedInputRunsAfterExperimentOff` (chatd): a webhook
input queued into a busy chat still runs after a stored rule turns the
experiment off for the owner (no restart); new inputs are refused.
- `TestChatAutomationEvents/ExperimentOffForOwner` now also asserts that
refused events for an existing-chat and a new-chat webhook create no
messages, queued inputs or chats.
- `TestChatAutomationEvents/SingleUseExperimentOff`: with the owner's
experiment off, a single-use webhook delivery is refused (404) and
`webhook_consumed_at` stays NULL; after the rule is back to inherit, the
same secret delivers once and then gets 409.
## Validation
- Vitest tests assert the PATCH body, optimistic update and rollback,
the create request field, the owner, sub-agent and experiment rule, and
the invalidations. Stories cover the checked menu state and three tool
renderings for Pixel. Full `make pre-push` passed before push.
- Frontend self-review with `coder-frontend-review` (8 roles) and the
project `frontend-review` (FE1 to FE10) ran before this PR; all blocking
and should-fix findings were fixed. A second `coder-frontend-review`
pass (8 roles) on the final slice, after the Codex fixes, raised
comment, type and readability items; the should-fix ones were fixed in
|
||
|
|
20ff7f1715 |
feat(coderd): add manage_automations write actions (#30217)
Adds the write actions of the `manage_automations` chat tool: `create`, `update`, `enable`, and `run_now`. They call the same management methods as the API (`CreateAutomation`, `UpdateAutomation`, `RunAutomation`) with the chat owner as the actor, so owner-only checks stay in the service. Part of CODAGT-1212 (slice 12b of 3). Part of CODAGT-1135. ## Rules - **Target containment.** An `existing_chat` automation must target the calling chat: `create` defaults `target_chat_id` to it (a heartbeat) and refuses any other chat, even another root chat of the same owner. A `new_chat` automation may not give new chats more tools than the calling chat has. Until tool sets land, the only tools that differ between such a chat and the calling chat are the model config's provider tools, so `new_chat_model_config_id` defaults to the calling chat's config and any other config is accepted only when it has no provider tools. Force On MCP servers apply to both chats because the tool is offered only in root, non-explore chats. `update` and `enable` check containment on the stored automation and on the result; `run_now` checks the stored automation. - **Automation-reached turns.** `create`, `update`, `enable`, and `run_now` are refused before any other work. - **Secrets.** The tool never returns a webhook secret, single-use or multi-use: tool results stay in the chat, where read-shared users, the model provider and compaction can see them. `create` of a webhook returns a note that the owner rotates the secret in the automations UI to get one. - **Audit.** `create`, `update`, and `enable` write the automation audit entry with `chat_id`. `run_now` records what the run endpoint records: nothing for `existing_chat` (a run changes no configuration), and for `new_chat` the same chat-create entry with `automation_id` and `input_id`, plus `created_by_chat_id`. - **Locked-row recheck.** The tool's containment check runs again inside the service on the locked automation row (`UpdateAutomation` before the write, `RunAutomation` at admission), so a concurrent owner edit between the tool's read and the write cannot slip past it. - **Known limitation.** Containment holds for tool-initiated operations. Later scheduled and webhook runs use the current model configuration, so a later admin change that enables provider tools on that config is not rechecked. Tracked in CODAGT-1271. - **Schedule interval.** Like the API, the tool accepts any cron expression, including every minute. A minimum interval is tracked in CODAGT-1272. - **Deferred review nits.** Codex round 4: the update audit diff uses the pre-lock row as its before-image (CODAGT-1273); `list` ignores `automation_id` and `run_now` reports a full message queue as a generic error (CODAGT-1274). - `create` records the calling chat as `created_by_chat_id`. `kind`, `target_mode`, and `webhook_use` cannot be updated, like the API. Fields that do not apply to an action are rejected instead of dropped. Lower-layer changes: `auditAutomationCreatedChat` (scheduler, 1211) takes an optional map of extra audit fields, and `UpdateAutomation` and `RunAutomation` (1209/1211) take an optional `AutomationGuard`. The scheduler and the HTTP handlers pass `nil`, so their behavior is unchanged. ## Size About 780 hand-written lines (about 380 production, 390 tests, docs). No generated changes. ## Validation - Tests cover each rule: heartbeat create, cross-chat create refused, model-config containment, before and after refusals for update and enable leaving the row unchanged, run_now containment, reached-turn refusals with no side effects, the secret matrix, audit fields, field rejection, and the org-admin owner case. Separate test audit (code-removal checks) passed. Full `make pre-push` passed before push. - Remote dogfood UAT passed: a heartbeat created by asking the agent to "check back every five minutes" appeared in the automation list and kept firing every five minutes with the browser closed; automation-started turns could not create, update, enable or run; creating an automation aimed at another chat was refused; no multi-use secret appeared in any tool output; `new_chat` containment behaved as above. Audit entries are verified in Go tests only. > [!NOTE] > ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. ## Stack On top of slice 12a. Next: slice 12c (composer toggle). --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
fb0951b850 |
feat: add the manage_automations chat tool switch and read actions (#30214)
Adds the `manage_automations` chat tool with its read and stop actions
(`list`, `get`, `disable`, `delete`), gated by an interim per-chat
switch. Tool sets have not landed, so this ships
`chats.manage_automations_enabled` as the RFC describes for that case;
tool sets later replace it and migrate its values.
Part of CODAGT-1212 (slice 12a of 3). Part of CODAGT-1135.
## What changes
- **Switch.** Migration `000611` adds `chats.manage_automations_enabled`
(default off). It is set through `POST /api/v2/chats` and `PATCH
/api/v2/chats/{chat}`. After creation only the chat owner may send the
field (403 otherwise). Turning it on returns 400 when the
`chat-automations` experiment is off for the chat owner (POST checks the
resolved `owner_id`, not the caller) or when the chat is a sub-agent
chat. Turning it off is always accepted. The audit table tracks it.
- **Offering.** The tool is offered only in root chats, outside plan
mode and explore mode, with the switch on, and with the experiment on
for the chat owner (decided once per turn, like `mcp-tool-search`). It
is not on the plan-mode or explore allowlists, and sub-agent chats are
created with the switch off.
- **Per-call recheck.** Every call reloads the chat and checks all rules
again, with a fresh experiment evaluation, before doing anything.
- **Scoping.** Owner and organization come from the chat, never from
arguments. Reads run as the owner through a new query that filters on
organization and owner. Other members' automations are "not found", even
when the chat owner is an organization admin.
- **Automation-reached turns.** Detected at call time from the full
history (compaction replays user rows without `automation_id`, so the
prompt window is not enough). In such turns only automations that target
the chat or created it (`chats.automation_id`) are visible.
- **Visibility of prompts and deletes.** `list` leaves out prompts (tool
results stay in the chat, which may be shared); `get` returns the prompt
of the automation it names. In a turn an automation reached, `delete`
only removes the triggering automation; the others can still be
disabled.
- **Audit.** `disable` and `delete` go through the management service
and write a background audit entry with `chat_id`, plus the triggering
`automation_id` and `input_id` in reached turns. Results use the API
shape and never contain a secret or secret hash.
`create`, `update`, `enable`, and `run_now` come in the next PR and
return "not available in this version" here.
Follow-up: CODAGT-1270 (bound the history read that reached-turn
detection does on each call).
## Size
About 1,380 hand-written lines: about 460 production, 680 tests, and 240
SQL that has to be there (the `chats_expanded` view rebuilt in both
migrations and the 17 inline column lists). Generated: +649/-280 (sqlc,
dbmock, dbmetrics, dump.sql, apidoc, API and audit docs,
`typesGenerated.ts`).
## Validation
- Unit and DB tests for every rule above (switch 403/400 cases, offering
rules, per-call recheck, owner/org scoping with an org-admin owner,
reached-turn detection including compaction replay, audit fields, secret
scan), plus a separate test audit. Full `make pre-push` passed before
push.
- Remote dogfood UAT passed on this slice: switch API cases, tool absent
with the switch off, in plan mode, in sub-agents and with the experiment
off for the owner (checked in the server's per-step tool lists),
list/get/disable/delete, and a secret scan of all tool output. Audit
entries are verified in Go tests only.
> [!NOTE]
> ARCHITECTURE.md prose was drafted by an agent at the user's request;
the user will review it.
## Stack
Stacked on the Automations for Coder Agents stack (30085 ... 1214b).
Next: slice 12b (write actions), then 12c (composer toggle).
---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
|
||
|
|
a0ef149ace |
feat: add webhook automations to the automation editor (#30207)
Closes CODAGT-1214
Part of CODAGT-1135
> Stack: part 11b of "Automations for Coder Agents", on top of #30187
(11a, the schedule editor). Review only the diff against
`tk/codagt-1214-automations-editor`.
Adds webhook automations to the Agents automation editor. This finishes
the webhook half of CODAGT-1214; the schedule half is #30187.
## What changes
1. **Create a webhook.** New automations get a **Trigger** choice
(Schedule or Webhook). Webhooks get a **Use** choice (Single-use or
Multi-use, default Multi-use). A webhook create request sends `kind:
"webhook"`, `webhook_use`, and the shared and target fields, and never
schedule fields. When busy defaults to Queue for webhooks and Skip for
schedules, unless the user picked a value.
2. **Secret shown once.** After a create or a rotate, a dialog shows the
publish endpoint, the secret, and a `curl` example, with "You will not
see this secret again." The secret lives only in page component state
while the dialog is open. The mutation functions hand the secret to page
state and return the response without it, so it never reaches a React
Query cache, the mutation cache, browser storage, the URL, or logs.
Outside clicks do not close the dialog; Done and Escape do.
3. **Edit a webhook.** Trigger and Use are read-only. The editor shows
the **Publish endpoint** with a copy button, "Used on <date>" for a
consumed single-use webhook, and **Rotate secret** behind a
confirmation. Owners and non-owners both see Save and Rotate secret; the
server decides, and its 403 message is shown next to the button. The
editor cannot close while a save or rotation is in flight, so a rotated
secret cannot be lost.
4. **List copy** mentions webhooks.
5. **Backend prerequisite (small).** Rotating the secret of a used
single-use webhook used to succeed and show a secret that every delivery
rejects. `RotateAutomationSecret` in chatd now refuses it inside its
locked transaction with the existing `ErrAutomationWebhookConsumed`, and
the rotate endpoint returns 409 ("This single-use webhook was already
used."). The editor shows that error and no secret. No SQL, migration,
or dbauthz changes; the swagger failure codes for the rotate endpoint
are regenerated.
Not in this release (per the RFC): the Workspace field, the Tools list,
target locking. The client never evaluates cron.
## Implementation notes
- `rotateChatAutomationSecret` API method and mutation factory. The
create and rotate factories take an `onWebhookSecret` callback and strip
`webhook_secret` from the result. `webhookPublishEndpoint` builds
`{origin}/api/experimental/chat-automations/{id}/events` from the
configured dashboard URL.
- While a rotation or a webhook create is in flight, the page uses the
shared `useUnsavedChangesPrompt` (browser prompt on reload, Leave/Stay
dialog on in-app navigation). The hook now also clears a blocked
navigation once its reason is gone.
- New `AutomationWebhookFields`, `AutomationWebhookSecretDialog`, and a
small `RadioOption` shared by the three radio groups in the editor.
`CodeExample` gains an optional `copyLabel` so the copy buttons have
distinct names.
- `validateOnBlur: false` in the editor: dogfood found that a blur error
shifted the Trigger radios between pointerdown and pointerup, which
swallowed the click.
## Validation
- Go: chatd `TestRotateAutomationSecret` (unused single-use and
multi-use rotate; a used one returns the error with the hash and version
unchanged and no plaintext; a consume holding the row lock makes a
concurrent rotate fail after commit) and the handler's 409 case.
- Vitest (`AgentAutomationsPage.test.tsx`): webhook create body shape
and default use, the secret gone from the document, every query cache
entry, and local/session storage after the dialog closes; rotate
confirm, cancel (no request), 403 message, and no close mid-rotation;
trigger switch body shape and When busy default; webhook edit body.
- Storybook: webhook create, webhook edit, used single-use webhook,
rotating, and the secret dialog.
- `tsc`, `pnpm lint`, Biome, and the pre-commit hook pass. Frontend
self-review (coder-frontend-review, 8 roles, plus FE1 to FE10) ran
twice; blocking and should-fix findings are fixed.
- Remote dogfood UAT (three rounds; round 3 on
|
||
|
|
a3fbd2384d |
feat: add the Agents automations list page and chat-list automation filter (#30171)
Closes CODAGT-1213. Part of CODAGT-1135 (Automations for Coder Agents,
RFC step 7).
Adds an Automations list to the Agents UI and an `automation_id` filter
on the chat list, so users can see their automations and find the chats
an automation created or wrote to.
## Changes
- **Chat-list filter:** `GET /api/v2/chats?automation_id=<uuid>` returns
root chats whose `chats.automation_id` matches (chats the automation
created) and chats with a non-deleted message whose
`chat_messages.automation_id` matches (chats it wrote to). The nil UUID
is rejected, because the query uses it as "no filter". It is honored
only when the `chat-automations` experiment is on for the caller;
otherwise it is ignored, as the RFC says, and the evaluator runs only
when the parameter is present. Chat authorization is unchanged. Swagger
documents the parameter, and `codersdk.ListChatsOptions` gains
`AutomationID`. The existing partial indexes back the filter.
- **List page:** `/agents/automations`, with an **Automations** sidebar
entry. Both are hidden when the experiment is off for the viewer
(per-user experiment list). The page lists the automations of the
organization selected in the Agents organization picker; it shares the
stored selection with the new-chat form and has its own picker. Columns:
name (with the creating chat for agent-created automations), trigger
(cron and time zone, or webhook single or multi use), target (chat link,
"New chat each run", or a **Missing target** badge for a deleted or
archived target), next run from the server's `next_run_times`, an
enabled switch (PATCH; a non-owner cannot re-enable), **Run now** (owner
only, schedules only, disabled for a missing target and while another
run is pending), and **View chats** (owner only; a paged dialog backed
by the new filter). Chat titles are looked up only for the viewer's own
automations. The list refetches every minute so the next run stays
current. On mobile, the chats header links to the page, which opens full
width with a back link. A Run now failure, such as `409` for a busy chat
with skip or `429` for a full queue or share, shows the server message
in an alert above the table.
- Out of scope, per the ticket: the **Last skipped run** column, and the
editor (CODAGT-1214). The empty state points to the API because the
`manage_automations` tool is not in this stack yet.
## Validation
- Go: `TestListChats/AutomationFilter` covers:
- created and written-to chats, deleted messages, and another user's
chat;
- an unknown id, a malformed id (`400`), and the nil UUID (`400`);
- the experiment turned off by a per-user rule, where the parameter is
ignored, including a malformed id.
- Vitest (`AgentAutomationsPage.test.tsx`), all asserting requests:
- the selected organization's list is requested, and switching the
picker refetches and stores the choice;
- the switch sends `PATCH {enabled:false}`;
- Run now sends its POST when the server answers `409` or `429`;
- View chats requests `?automation_id=`, and Load more requests the next
page;
- nothing is requested with the experiment off.
- Storybook (Pixel): `WithAutomations`, `OtherOwner`, `Empty`,
`MissingTarget`, `RunNowError`, `ChatsDialog`,
`ChatsDialogLoadMoreError`, `Loading`, `RefetchError`, `ListError`, and
`ChatsSidebar/MobileWithAutomations`.
- Remote dogfood UAT: PASS in round 1 (`fa60a15767`) and round 2 on the
current head `b37e9d99d0`. Round 2 repeated every criterion and verified
the review fixes. Screenshots are in the comments below.
- `coder-frontend-review` self-review: every role passes after fixes on
each update, except two items:
- the experiment-off test waits for the not-found page only as a sync
point before asserting that no request was sent;
- there is no story for a chat-title lookup error, because the Storybook
query helper cannot inject errors.
- Codex review: 4 rounds (8, 4, 4 and 6 P2 findings, no P0 or P1).
- Rounds 1 to 3 were fixed, except the model-availability item
(CODAGT-1244).
- Round 4 found no blocker and is tracked in CODAGT-1246, together with
the minor UAT round 2 findings.
- All threads are resolved. There is no clean Codex verdict on the
current head. Further rounds were not requested because findings were
not converging and none was a blocker; the stack orchestrator accepted
stopping at round 4.
- CI: `ci` run 36703512580, started with workflow_dispatch, is green on
the current head `b37e9d99d0`. Pushes to existing stacked PRs did not
start the pull_request `ci` run (noted in the comments). The earlier
head `8f2ee30d8f` was green through a normal pull_request run.
Size: about 1,370 hand-written lines (about 560 of them tests and
stories), plus generated code. This is over the 1,000-line guideline,
mostly from review fixes.
## Stack
Stacked on #30085, #30096, #30112, #30117, #30127, #30134, #30160,
#30166 and #30167 (CODAGT-1215). Base:
`tk/codagt-1215-automations-chat-labels`, merged in (not rebased).
Follow-ups: CODAGT-1244, CODAGT-1246.
---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
|