mirror of
https://github.com/coder/coder.git
synced 2026-11-23 04:09:07 +08:00
90948802e2439d2641f392e6229dd058a1dcafe3
517
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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
|
||
|
|
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. |
||
|
|
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._ |
||
|
|
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.
|
||
|
|
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 |
||
|
|
1a96da2b6a | perf(coderd/x/chatd): make chat stream reads lock-free (#30266) | ||
|
|
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> |
||
|
|
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.
|
||
|
|
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 |
||
|
|
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
|
||
|
|
b25f8859f2 |
feat: add Run now for schedule chat automations (#30166)
Closes CODAGT-1211. Part of CODAGT-1135. > Stack: PR 7b of "Automations for Coder Agents", on top of 7a (#30160, the schedule scanner), which sits on 1210 5b (#30134). Adds Run now for schedule automations: `POST /api/experimental/organizations/{organization}/chat-automations/{automation}/runs` publishes the saved prompt at once through the existing `Publish` path, with no occurrence. It never writes the automation row, so the schedule cursor and revision stay unchanged. - **Owner-only.** `chatd.RunAutomation(ctx, actorID, id)` compares the caller with the automation owner before anything else, so org admins and site owners get 403 even though dbauthz lets them read and write the row (CODAGT-1226). A user who cannot read the automation gets 404, and the route sits behind the experiment gate, so a caller with `chat-automations` off gets 404. `Publish` also checks the owner's experiment again. - **Statuses.** 202 with `input_id` and `chat_id`; 400 for a non-schedule automation; 409 for a disabled schedule, a busy chat with When busy `skip`, or an unavailable target or model; 429 when the chat queue or the automations' share of it is full; hook denials use the same response as chat messages. - **new_chat.** A Run now of a new_chat schedule creates a chat titled with the run time in the schedule's time zone and records the same audit entry as webhook-created chats. ## Tests `coderd/exp_chat_automation_runs_test.go` runs against a real coderdtest server: the owner's run saves one message with the returned input id and leaves the whole automation row byte-equal; org admin and site owner get 403 (also on a webhook automation, proving the owner check comes first) and a non-reader gets 404, with nothing saved; webhook 400, disabled 409, busy `skip` 409, queue share 429; new_chat title, owner, and audit entry. The experiment gate test covers the new route. Dogfood UAT ran on a real dev instance through Coder Agents and passed: immediate publish with the cursor and revision unchanged, 409/429 refusals, 403 for an org admin and the site owner, 404 with the experiment off, and a one-minute schedule that kept one message per minute around a Run now. ## Size About 325 hand-written lines (about 190 of them tests). Generated: `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`, `docs/reference/api/schemas.md`, `site/src/api/typesGenerated.ts` (213 lines). ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. Also replaces the CODAGT-1209 ARCHITECTURE.md TODO from #30117; the prose was drafted by an agent at the user's request, and the user will review it. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
8620361fcc |
feat(coderd): run chat automation schedules (#30160)
Part of CODAGT-1211. Part of CODAGT-1135. > Stack: PR 7a of "Automations for Coder Agents", on top of 1210 5b (#30134, `tk/codagt-1210b-automations-new-chat`). Run now (`POST .../runs`) is split into PR 7b (#30166) on top of this one, which closes CODAGT-1211. Schedule automations now run. Every coderd instance scans for due schedules at start and every 30 seconds, and publishes each occurrence through the existing `Publish` paths (existing_chat `SendMessage(queue)` and new_chat `Create`, with their `AdmitInTx` callbacks). There is no second admission path. ## How a scan works 1. An unlocked read returns enabled schedule automations whose cursor (`schedule_next_run_at`) is due, in pages of 500 by (cursor, id) until a short page. It leaves out inactive or deleted owners and existing_chat targets that are gone or archived. 2. The `chat-automations` experiment is evaluated once per owner per tick, outside any callback. Owners with it off are dropped without a cursor write. `Publish` checks the experiment for the owner again before the transaction (webhooks map that refusal to 404, like the handler's own check). 3. A cursor more than 60 seconds (the grace window) old is missed: a guarded write moves it to the next future time, nothing is published, and nothing is replayed. 4. Otherwise `Publish` runs (up to eight occurrences at once, so one slow hook or lock wait does not hold back the rest) with the observed revision and cursor. The pre-check refuses a stale or expired occurrence before any hook runs. Under the chat and automation locks, the callback requires the same revision and cursor, reads the clock after the locks, requires the occurrence to be due and within grace, and moves the cursor to the first cron time after that read in the same transaction. 5. A busy chat with `skip`, a full queue or automation share, a hook denial, lost permission, or an occurrence that expired while waiting for a lock skips the occurrence with the same guarded write and an info log. A stale, disabled, or deleted automation is left alone. Other errors keep the cursor, so the next scan retries within grace. That includes an experiment-off refusal from `Publish`, because the evaluator also reports a failed read as off. New chats created by a schedule are titled with the occurrence's scheduled time in the schedule's time zone, for example `Tokyo digest 2026-09-30 08:14 JST` (the ticket says acceptance time; the two differ by at most the grace window, and the scheduled time cannot drift across a minute while hooks or locks run). Webhook titles stay in UTC. Each such chat gets an audit entry as created by the automation owner, with the automation and input ids, like the chats the webhook endpoint creates. ## Decisions reviewers should check - **Clock (deviates from the ticket's "fresh database clock").** The callback reads the injected quartz clock after the chat and automation locks are held, not transaction-start `now()`. The ticket also requires fake-clock tests, and the lower layers already read the clock after locks. Exactly-once rests on the revision and cursor tuple, not on time. Inter-instance clock skew cannot cause a double acceptance or a replay: an acceptance commits only together with the conditional cursor write under the automation lock, and every cursor write moves the cursor strictly forward (`advanceAutomationSchedule` refuses a next run at or before the cursor). A clock that is off by `d` only shifts the acceptance window to `[cursor-d, cursor+grace+d]` in true time; a clock that runs ahead can skip occurrences within `d`. See the comment on `checkAutomationOccurrence` and the `CursorOnlyMovesForward` test. Swapping in `clock_timestamp()` later is a one-line change. - **Authorization of the cursor write.** `AdvanceChatAutomationScheduleCursor` follows the object pattern of `ConsumeChatAutomationWebhookByID` and `UpdateChatAutomationByID`: the dbauthz wrapper loads the automation and authorizes `update` on it. The scanner and the callback call it as chatd, so the chatd subject gains `update` on `chat_automation` (it already had `read`). This is the smallest grant; chatd still cannot create or delete automations (pinned in `TestAsChatd`), and owner-only changes stay in the chatd automation service. No 1207 migration is touched. - **Narrow write.** The query sets only `schedule_next_run_at` and `updated_at`, guarded by `id`, `kind = 'schedule'`, `enabled`, the observed `schedule_revision`, and the observed cursor. It never touches owner-controlled fields or the revision. - **Known limitation (CODAGT-1234).** Two replicas that read the same due row can both reach the `user_prompt_submit` hook before one loses under the lock; only one message or chat commits. This matches the lower layer's best-effort unlocked pre-check for webhooks. A claim-first cursor move would break the ticket's retry-within-grace rule or the forward-only cursor, so a lease column is proposed as a follow-up. - The schedule tests run their servers through dbauthz, so they use the chatd subject's real permissions (they fail without the grant). ## Tests `coderd/x/chatd/automation_schedules_internal_test.go` uses a mock clock, real Postgres, and a second connection that holds row locks (waiting on `pg_stat_activity`): two instances accept one occurrence (existing_chat, and new_chat with no orphan chat); busy `skip`, automation share full, and queue full each advance the cursor once; a cron edit rolls back an in-flight acceptance; restart after missed intervals publishes nothing, restart within grace accepts once; previews match accepted runs; an occurrence that expires while waiting for a lock is not accepted; a DST change keeps 09:00 wall-clock time; the experiment off gets no run (scan and Publish); the cursor only moves forward; the loop scans at start. Dogfood UAT ran on a real dev instance through Coder Agents and passed: a one-minute schedule delivered one message per minute with no browser open, a busy chat skipped its occurrence, disable stopped runs and re-enable did not replay, new_chat titles used Asia/Tokyo, two coderd instances produced no duplicates, and downtime was not replayed. ## Size About 994 hand-written lines (about 560 of them tests). Generated: `queries.sql.go`, `querier.go`, `dbmetrics`, `dbmock` (181 lines). ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
1e1e884c25 |
feat(coderd): create a chat for each webhook event of a new_chat automation (#30134)
Closes CODAGT-1210. Part of CODAGT-1135. > Stack: PR 6 of "Automations for Coder Agents", on top of #30127 (CODAGT-1210 part 1, webhook events for `existing_chat`). This PR delivers webhook events to `new_chat` automations and replaces part 1's `501` for them. ## What this adds - A webhook event for a `new_chat` automation creates a new chat as the automation owner through chatd `CreateChat` with an `AdmitInTx` callback, and the endpoint answers `202` with the new `chat_id`. - The chat uses the automation's model config and reasoning effort and client type `api`, and selects no MCP servers (the organization's Force On servers still apply). Its title is set explicitly to the automation name plus the acceptance time in UTC (`<name> 2006-01-02 15:04 UTC`), so automatic title generation does not run and event data never becomes the title. - Before the create, the same input checks as part 1 run (enabled, secret version, single-use unused), plus: the owner may create a chat in the organization (`403`), and the owner can read the automation's model config, which must be enabled and in the same organization (`409`). A `user_prompt_submit` denial creates no chat. - Under the automation lock, the callback rechecks all of that, sets `chats.automation_id` on the new chat (new query `UpdateChatAutomationIDByID`, dbauthz: update on the chat), consumes a single-use webhook, and returns the provenance. A refusal rolls back the whole creation. - The events endpoint records an audit entry for each created chat (action create, user = the automation owner, with `automation_id` and `input_id` in the additional fields), as chat creation through the chat API does. - Part 1's lock and consumption code is shared by both target modes. ## Notes for reviewers - ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. - Size: about 600 hand-written lines (about 380 of them tests). Generated: about 65 lines (`coderd/apidoc`, `dbmock`, `dbmetrics`, `querier.go`, `queries.sql.go`). - Dogfood UAT ran through Coder Agents on a real dev deployment: curl deliveries created chats with the explicit UTC title, client type `api`, two message parts, and `automation_id` set; single-use concurrency created exactly one chat; a disabled model config gave `409` with no chat. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ --------- Signed-off-by: Thomas Kosiewski <tk@coder.com> |
||
|
|
b517db4beb |
feat: deliver webhook events to existing chats through chat automations (#30127)
Part of CODAGT-1210 (1 of 2). Part of CODAGT-1135. > Stack: PR 5 of "Automations for Coder Agents", on top of #30117. The ticket is split in two by operation: this PR delivers webhook events to `existing_chat` targets; the stacked follow-up delivers them to `new_chat` targets and closes CODAGT-1210. Until then a `new_chat` automation's events endpoint answers `501`. ## What this adds - `POST /api/experimental/chat-automations/{automation}/events`. External systems send the automation's webhook secret as `Authorization: Bearer <secret>` and a JSON body of at most 256 KiB. The route has no API key middleware and sits outside the `/api/experimental` group, behind its own rate limiter keyed by caller and a fixed endpoint key (IP address for unauthenticated callers), so varying the automation id does not reset the budget. - Secret check: SHA-256 of the bearer value, compared in constant time. Unknown ids, other kinds, and wrong secrets all get the same `401`. The `chat-automations` experiment is checked for the automation owner only after the secret matches (`404` when off). The body is then read: over the limit `413`, not JSON `400`. - `chatd.PublishAutomationWebhook` sends as the owner (`dbauthz.As` with the owner's subject) through `SendMessage` with the `queue` busy behavior set explicitly, so automations never interrupt or steer. `user_prompt_submit` hooks run first: a denial is `403`, an unreachable hook service `502`. - One admission check runs before the send (so refused events never reach hooks) and again in the `AdmitInTx` callback, which locks the automation together with the chat's queued automations in one ascending-order call. Under the lock it rechecks: enabled, secret version (a request verified before a rotation but committed after it gets `401`), single-use state, target chat (root chat of the owner, same org, not archived), owner status, and the owner's `chat:update` permission. It then applies **When busy**: `skip` refuses a busy chat (`409`), `queue` refuses input beyond the automations' share, half the chat queue cap rounded down and at least 1 (`429`); busy and the share count only queued rows that promotion would still deliver. It marks a single-use webhook consumed and returns the provenance. - The message has two parts: the saved prompt, and a labeled part with the body as untrusted event data inside `<automation_event_data>` tags. `json.HTMLEscape` escapes `<`, `>`, and `&` in the body, which keeps the JSON value and makes the closing tag impossible to forge. - `chatd.Config.Authorizer` (wired from `options.Authorizer`) for the explicit owner checks; publishing fails closed without one. - New query `ConsumeChatAutomationWebhookByID` with a dbauthz wrapper. Status codes follow the RFC's failure outcomes table; the chat-without-a-model case returns the same `400` as a person's message. ## Notes for reviewers - Single-use consumption runs from the chatd publish code as the owner, because the chatd role only reads `chat_automation`. No lower-layer RBAC change. - ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. - Size: about 1,460 hand-written lines after review fixes (about 770 of them tests), over the ~1,000 budget because of the review hardening. Generated: about 360 lines (`coderd/apidoc`, `dbmock`, `dbmetrics`, `querier.go`, `queries.sql.go`, `docs/reference/api/schemas.md`, `typesGenerated.ts`). - Dogfood UAT ran through Coder Agents on a real dev deployment with curl deliveries. Round 1 found error-mapping defects, fixed here; rounds 2 and 3 passed, the last on the final code (the head after it changes only ARCHITECTURE.md). - Deferred: CODAGT-1233 (stale automation rows filling the physical queue cap; lower-layer `SendMessage` path). --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
5c1662ea4c |
feat: disable, re-enable, and rotate chat automations with schedule preview (#30117)
Completes the chat automations management API from RFC step 3: disable and re-enable, delete that disables first, webhook secret rotation, and a server-side schedule preview. Stacked on #30112. - **Disable** (`PATCH` with `{"enabled": false}`) runs in two steps. A short transaction that touches only the automation row sets `enabled = false` and increments `queue_generation`, the cutoff. After it commits, the automation's queued rows below the cutoff are deleted one chat at a time through chatd's existing `DeleteQueued` transition, run as chatd, so queue versions and stream updates match a manual delete. If a row is missed, for example after a crash between the steps, the queue promotion guard from #30096 discards it, because its generation is stale. Running turns are not interrupted. - **Delete** deletes the row and then removes all of the automation's queued rows the same way. Deleting the row is itself the cutoff, because the promotion guard discards rows whose automation no longer exists. So delete needs only delete permission, not update. This differs from the RFC's "disable, then delete" order, with the same outcome. - **Re-enable** (`{"enabled": true}`) moves a schedule's cursor to the next future cron time, so the disabled period is not replayed. The generation never resets. - **Permissions:** only the owner can enable, edit, or rotate. Organization admins and site owners can send exactly `{"enabled": false}` (anything combined with it is 403), and can still list, read, and delete. - **Rotation:** `POST .../chat-automations/{automation}/secret/rotate` (owner only, webhooks only) returns the new secret once and increments `webhook_secret_version`. Only the SHA-256 hash is stored, and the rotation is audited with the hash redacted. - **Preview:** `POST .../chat-automations/schedule-preview` evaluates an unsaved cron expression and time zone with create's rules and returns the next five run times, or 400. - `coderd/x/chatd/ARCHITECTURE.md` gets a `TODO (CODAGT-1209)` note about disable using the delete-queued transition. **Author action before merge:** replace that TODO with the architecture prose (agents do not write that document). Known gap, tracked in CODAGT-1227: when the target chat is archived, disable and delete cannot remove its queued automation rows, because `DeleteQueuedMessage` is not allowed from archived states. The rows never run, since the promotion guard discards them, but they stay visible after the chat is unarchived. The fix needs a chatstate transition from the lower layer. Dogfood UAT ran on a real dev instance and passed. It covered disable removing only that automation's queued rows (the chat API agreed), delete, re-enable without replay, the permission matrix for an organization admin and the site owner, rotation (the stored hash matches the new secret, and neither secret appears in get or list), preview, and a runtime experiment rule. It also checked that a leftover row is discarded on promotion. Closes CODAGT-1209 Part of CODAGT-1135 Refs CODAGT-1217 Stack: PR 3b of the Automations for Coder Agents stack, on top of #30112 (PR 3a), #30096, and #30085. > This PR was written by an AI agent (xum) and reviewed by the agent's own test audit and UAT. A human has not reviewed it yet. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ --------- Signed-off-by: Thomas Kosiewski <tk@coder.com> |
||
|
|
9316d67440 |
feat: add chat automations management API behind chat-automations (#30112)
Adds the management API for chat automations under
`/api/experimental/organizations/{organization}/chat-automations`,
behind the new user-scoped `chat-automations` experiment. This is the
first of two PRs for RFC step 3; nothing publishes automation messages
yet.
- **Experiment:** `chat-automations` is in `ExperimentsKnown`,
`ExperimentsUserScoped`, and the ruleguard list in `scripts/rules.go`.
Every route asks `chatd.AutomationsEnabled(ctx, api.ExperimentEvaluator,
callerID)`, which fails closed on a missing subject or evaluator; the
routes stay mounted and return 404 when the experiment is off for the
caller, so a runtime rule for one user applies on the next request
without a restart. There is no `/api/v2` alias.
- **Routes:** list, create (201), get, `PATCH`, delete (204), with
Swagger annotations and audit entries. List returns the automations in
the organization the caller can read (members see their own,
organization admins see all).
- **Service** (`coderd/x/chatd/automations.go`): create validates kind
and target shape, a non-empty prompt, a five-field cron and IANA time
zone, model access, and that an `existing_chat` target is a root chat of
the owner in the same organization. It defaults `when_busy` to `skip`
for schedules and `queue` for webhooks and computes the first schedule
cursor. `PATCH` runs the same per-field validation on each changed
field, rejects `kind` and `target_mode`, bumps `schedule_revision` on
prompt, cron, or time zone changes, and recomputes the cursor on cron or
time zone changes.
- **Owner-only:** only the owner can `PATCH` an automation, even with
organization-admin or site-owner roles (403); admins can list, read, and
delete.
- **Secrets:** a webhook's secret (`coder_automation_` prefix) is
returned once in the create response. Only its SHA-256 is stored, and it
appears in no list, get, audit, or log output.
- **Cap:** new option `--chat-max-automations-per-owner` (default 50)
caps automations per owner across all organizations; creating one more
returns 409. Creates serialize on a per-owner advisory lock.
- **Cron:** `cron.Standard(spec, timeZone)` accepts any standard
five-field expression (the existing `Weekly` rejects day-of-month and
month restrictions). Responses include the next five run times of an
enabled schedule.
PR 3b (stacked on this one) adds disable and re-enable with the queue
cutoff, makes delete run disable first, and adds secret rotation and the
schedule preview route. Until then, the queue promotion guard from
#30096 discards queued rows whose automation was deleted.
Dogfood UAT ran on a real dev instance and passed:
create/list/get/patch/delete via curl, owner-only 403s for an
organization admin and the site owner, the cap (including concurrent
creates and cross-organization counting), a runtime rule turning the
experiment off for one user without a restart, and `/api/v2` 404s.
Part of CODAGT-1209 (PR 3b closes it)
Part of CODAGT-1135
Refs CODAGT-1217
Stack: PR 3 of the Automations for Coder Agents stack, on top of #30096
(which is on top of #30085).
> This PR was written by an AI agent (xum) and reviewed by the agent's
own test audit and UAT. A human has not reviewed it yet.
---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
---------
Signed-off-by: Thomas Kosiewski <tk@coder.com>
|
||
|
|
eaca2290b0 |
feat(coderd): add chatd automation admission seam and queue promotion guard (#30096)
Adds the backend-only seam that lets a later `Publish` operation admit an automation message inside chatd's existing create-chat and send-message transactions, and the guard that drops stale automation input when the queue promotes it. Only Go test callbacks use the seam in this PR, so ordinary chat behavior does not change. Closes CODAGT-1208 Part of CODAGT-1135 > Stack: PR 2, on top of #30085 (schema, RBAC resource, and audit entries). No migration changes; this PR adds and extends sqlc queries only. ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. ## Changes - **Admission seam.** `chatstate.AdmitFunc` is a nil-default `AdmitInTx` field on `chatd.CreateOptions`, `chatd.SendMessageOptions`, `chatstate.CreateChatInput`, and `chatstate.SendMessageInput`. `CreateChat` runs it after inserting the chat and before the initial history, and requires exactly one initial user message. `SendMessage` runs it on the locked chat before any write. The callback returns an `AutomationProvenance` (automation ID, input ID, queue generation), which is validated and stamped on the message. A callback error rolls back the whole transaction, so no chat, message, or queue row survives. `Server.CreateChat` and `Server.SendMessage` keep their signatures. - **Provenance.** `chatstate.Message.Automation` is written to queued rows (`automation_id`, `input_id`, `queue_generation`) and history rows (`automation_id`, `input_id`). `InsertChatMessages` and `InsertChatQueuedMessageWithCreator` gain the matching parameters, and `messageFromQueuedRow` copies them on promotion. - **Promotion guard.** `chatstate.LockAutomations` is the only way to lock automation rows: it locks them `FOR UPDATE` in ascending ID order, running as chatd. The chatd subject gains read on `chat_automation`. A queued automation row passes only if its automation exists, is enabled, and has the row's `queue_generation`. Two helpers apply the check: - `nextPromotableQueueHead` serves `sendMessageE1`, `FinishTurn`, and `FinishInterruption`. A head without an automation costs no extra query. Otherwise it locks every automation in the queue up front, deletes failing heads until one passes, and leaves rows behind that head alone. If the queue empties, `FinishTurn` and `FinishInterruption` land in `waiting`, as from `R0` and `I0`. - `guardQueuedRows` serves explicit `PromoteQueuedMessage`. A failing row is deleted and the transition returns `Rejected` without an error, so the delete commits. `Server.PromoteQueued` then returns `ErrQueuedMessageNotFound` (HTTP 404) without reordering, substituting a message, or changing status. - The steer paths (`DeliverSteerMessages` and the steer batches from #30073/#30074) add one `guardQueuedRows` call each, whichever PR lands second. - **Deadlocks.** `database.IsDeadlockError` is new. `ChatMachine.Update` reruns the transaction, at most 3 attempts with a fresh publish buffer each, only when an attempt that took automation locks hit a deadlock abort. Attempts without automation locks, and nested Updates, never retry. The `SendMessage` and `PromoteQueued` closures reset their results so a rerun is safe. - **Transition matrix.** Adds the outputs the guard can produce, such as `R1 -> FinishTurn -> W` and `E1 -> SendMessage -> R0`. - **`ARCHITECTURE.md`.** Describes the admission seam, provenance, the queue promotion guard, the lock order, and the deadlock retry, and adds the guard's outcomes to the state diagram. ## Validation - Go tests on real PostgreSQL cover the ticket's checks: - A callback error leaves no chat, message, or queue row. - A guard rejection deletes only the rejected heads, on every promotion path and for each failure reason (missing, disabled, disabled with the same generation, generation mismatch). - Explicit promotion of a failing row returns not found, and the delete is committed. - Provenance round-trips through queue and history. - `LockAutomations` works through dbauthz. - `Update` retries only when an attempt that took automation locks hits a deadlock. - A concurrency test of acceptance, promotion, and disable across mixed automation IDs sees zero deadlock aborts. - Mutation checks confirmed that the guard, retry, and permission tests fail when their behavior is removed. - Remote dogfood UAT passed on a real dev instance: sending, queueing, head and explicit promotion, interrupting, and deleting queued messages all behaved as before. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
ff158c0589 |
feat: preserve user-supplied chat titles (#29486)
Chats created through the API or MCP couldn't be given a title, and automatic title generation could overwrite a title the user had set, at creation or by renaming during generation. #30254 tried to keep renames by comparing title text, but text can't tell a user title from a generated one that has the same text. Chat creation over the API and MCP now accepts a title. Each chat records where its title came from: fallback (derived from the prompt), generated, or user. A title can only be replaced by a title from the same source or a higher one, so automatic generation never overwrites a user's title. Title changes no longer reorder the chat list, and clients apply them in the order they were written. Chats created before this change are treated as having fallback titles. Closes CODAGT-1047 Reverts #30254 |
||
|
|
e3446c9c21 |
fix(coderd/x/chatd): drop late preview parts after a chat error (#30279)
When a generation attempt fails without a retry (`FinishError`), the chat moves to `error` but keeps its `history_version` and `generation_attempt`, and `retry_state` stays null. The stream loop therefore did not retire the attempt, and a part of the failed attempt that the relay delivered after the `error` event was still forwarded. The frontend clears its preview on `error` (`useChatStore.ts`), so the user saw a mid-message fragment appear under the error. This is the error-path variant of the issue fixed in #30241 for retries. The stream loop now also retires the current attempt when a sync observes `status = error`, so its late parts are dropped. Every generation attempt increments `generation_attempt` before it creates its part episode (`beginGenerationAttempt`), so the next run after an error starts a fresh preview as before. Other statuses that leave `running` (`interrupting`, `requires_action`, `waiting`) are unchanged: the frontend does not clear the preview for them. The frontend contract is unchanged. `TestStreamLoopLatePartAfterError` fails on main and passes with the fix; its subtests also cover the next attempt after an error and an interrupt that keeps streaming. A separate docs commit updates step 7 of the sync algorithm in `ARCHITECTURE.md` and corrects the `preview_reset` description, which said it is emitted when the LLM call fails mid-way. The code emits it only when the history version changes or a new generation attempt starts. The bug was found by a TLA+ model of the chat stream and confirmed with a Go reproduction. Refs #30241 --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
15382ebd5d |
fix(coderd/x/chatd): finish interruption inline for unowned interrupting chats (#30259)
Interrupt and SendMessage(busy_behavior=interrupt) now finish the interruption in the same transaction for an unowned chat that is already interrupting, as they already did for an unowned running chat. Interrupt on an unowned interrupting chat was previously rejected with 409. Inline finishes now also run the post-interruption side effects a worker runs (clearing the cached turn summary) and record the promoted head's queue wait. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
bb31a19e5b |
fix(coderd): return queued chat messages in promotion order (#30255)
Clients read the chat queue through GetChatQueuedMessages, which ordered by created_at, while chatstate promotes by position. Promoting a queued message changes only its position, and concurrent senders can commit with created_at and position in opposite orders, so clients showed the wrong next message. Order GetChatQueuedMessages by position, id. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
7cd1b2040b |
feat: add chat projects API (#29242)
- Experiment, behind `chat-projects` (off by default). First of three stacked PRs: #29301 (memory), #29583 (UI). This PR is API only; the screenshots below are from the UI in #29583. - CRUD under `/api/experimental/organizations/{organization}/chats/projects/{project}`. `GET /api/experimental/chats/projects` lists the caller's projects across all organizations. - `project_id` on chat create and as a chat list filter. A chat joins a project only at creation; there is no move. - Projects are identified by ID. Names are display labels (64 characters, description 1024) with no uniqueness constraint. An optional `icon` URL (usually an emoji image under `/emojis`) is capped at 256 characters and audited. - A user can own at most 100 projects across all organizations; creating another answers 409. Creates count and insert under a per-owner advisory lock so concurrent requests cannot overshoot. - Projects are private to their `owner_id`. Members may only create their own, and a chat can only be bound to a project its owner owns. An unreadable or foreign project on chat create answers 404 so IDs cannot be probed; a project from another organization answers 400. - Permissions ride on the `agents-access` role next to chats (after #30004), so whoever can use Coder Agents can use projects. Owners and org admins reach every project. ### Examples Create a project in an organization: ```http POST /api/experimental/organizations/{organization}/chats/projects {"name": "Platform", "description": "Infra and deploy work", "icon": "/emojis/1f680.png"} ``` ```json { "id": "7c0e4a3e-5b1f-4f7d-9a51-2f3c8f6d2b10", "organization_id": "bb640d07-ca8a-4869-b6bc-ae61ebb2fda1", "owner_id": "0ed9befc-4911-4ccf-a8e2-559bf72daa94", "name": "Platform", "description": "Infra and deploy work", "icon": "/emojis/1f680.png", "created_at": "2026-09-30T15:04:05Z", "updated_at": "2026-09-30T15:04:05Z" } ``` List the caller's projects across organizations with `GET /api/experimental/chats/projects` (an array of the object above). Update with `PATCH .../chats/projects/{project}` and any of `name`, `description`, `icon`; delete with `DELETE`, which detaches its chats. Create a chat in the project, and list only its chats: ```http POST /api/v2/chats {"organization_id": "bb640d07-…", "project_id": "7c0e4a3e-…", "content": [{"type": "text", "text": "Plan the deploy"}]} GET /api/v2/chats?project_id=7c0e4a3e-… ``` At the limit: ```json 409 {"message": "You can have at most 100 chat projects. Delete a project to create another."} ``` <details> <summary>Screenshots (UI from #29583)</summary>      </details> --- Generated with Coder Agents on behalf of @f0ssel. --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
7b40aa7fa6 |
fix(coderd): keep user chat renames made during title generation (#30254)
Automatic title generation captured the chat title when it was scheduled, ran the model call, then wrote the generated title with an unconditional UPDATE. A rename that landed while the model call ran was silently overwritten. Add UpdateChatTitleByIDIfTitle, a compare-and-set variant that only writes when the stored title still equals the title generation started from. When it matches no rows, generation keeps the current title and skips recording and publishing the generated one. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
d11809f095 |
fix(coderd): enforce chatd concurrent-agent capacity on every path into running (#30243)
## Problem
The concurrent-agent cap (5 root chats and 10 subagent chats per
deployment by default) could be exceeded. Three paths put more chats in
`running` with a fresh lease than the pool allows:
1. **Interrupting a waiting chat.** A user sends a message with
`busy_behavior=interrupt` to a chat that is waiting for capacity. The
chat becomes `interrupting` while unowned, a worker acquires it without
admission, and `FinishInterruption` promotes the queued message into a
running turn under that ownership.
2. **Taking over an orphaned `requires_action` chat.** A replica dies
while its chat is in `requires_action`, its lease goes stale and another
chat takes the slot. A worker acquires the `requires_action` chat
without admission, and a tool result, an interrupt or the action
deadline returns it to `running` under that ownership.
3. **Heartbeat reviving a stale lease.** A replica loses the database
for longer than the 30 second stale threshold and another replica admits
a second chat into the slot. When the first replica comes back, its
heartbeat upsert renews the stale lease unconditionally, and its runner
keeps generating until the turn ends.
## Root cause
`agentCapacityLimiter.Admit` returned `true` without taking the
admission lock or counting for every status other than `running`. The
count query already treats every owned chat with a fresh lease as
holding a slot, so the shortcut let chats acquire a slot uncounted and
later move back to `running` under that ownership. Separately,
`BatchUpsertChatHeartbeats` had no freshness or ownership condition.
## Fix
- **Admission for every runnable status.** `Admit` now counts for
`running`, `interrupting` and `requires_action`, and a refused pool
skips the rest of its candidates in the pass regardless of status. An
owned chat holds its slot until it releases ownership, so every later
transition back to `running` stays within capacity.
- **Fenced heartbeat renewal.** `BatchUpsertChatHeartbeats` is replaced
by `RenewChatHeartbeats`, which only extends rows that are still fresh
and still own their chat, using `statement_timestamp()` read after the
capacity admission lock is granted. The renewal runs under that lock
with a `lock_timeout` (`HeartbeatLockTimeout`) and a per-tick timeout
(`HeartbeatRenewalTimeout`, a third of the stale threshold). Admission
also waits at most 5 seconds for the lock.
- **Stop runners that lost their lease.** `heartbeatOnce` requests
cleanup of every runner whose lease was not renewed, which cancels its
generation. The chat stays owned by the stale lease until an admitted
worker takes it over. A tick that fails or times out cleans up no
runners and retries on the next tick.
- **Instant Stop on a queued chat.** Requiring admission for
`interrupting` would have made Stop on a chat waiting for capacity hang
until a slot frees. When `Interrupt`, or `SendMessage` with
`busy_behavior=interrupt`, runs on a running chat with no owner, the
transition now applies `FinishInterruption` in the same transaction and
cancels orphaned tool calls. An empty queue lands in `waiting`;
otherwise the queue head is promoted into `running`, still unowned, so
it goes through admission.
- **Queued metric.** `CountChatCapacityQueuedByPool` (behind
`coderd_chatd_agents_queued_for_capacity`) now also counts
`interrupting` and `requires_action` chats without a fresh lease, since
they also wait for admission.
## How it was found
A TLA+ model of capacity admission found a counterexample for each path.
Go tests reproduced all three against the previous code (each failed
with `"2" is not less than or equal to "1"` for a root pool of capacity
1), and the model with the fix enabled passes the safety invariant and
the liveness properties. The model itself is not part of this PR.
## Tests
The three reproductions are kept as regression tests in
`coderd/x/chatd/agentcapacity_regression_internal_test.go`:
`TestAdmission_InterruptWithMessageOnWaitingChatStaysWithinCapacity`,
`TestAdmission_RequiresActionTakeoverStaysWithinCapacity` and
`TestRunnerManager_HeartbeatDoesNotReviveStaleLease`. The original
reproductions failed on the base commit. Restoring the admission
shortcut makes the `requires_action` test fail, and restoring the
unconditional heartbeat upsert, or dropping the runner cleanup, makes
the heartbeat test fail. New coverage also includes
`TestAdmission_StopWaitingChatNeedsNoCapacity`,
`TestRenewChatHeartbeats_OnlyRenewsFreshOwnedLeases`,
`TestRunnerManager_FailedHeartbeatTickKeepsRunners`, and chatstate tests
for the unowned interrupt paths. Existing tests that encoded the old
behavior (`requires_action` chats holding no slot, interrupting chats
always acquirable, unconditional heartbeat renewal) were updated.
## Behavior / API change
- `POST /api/v2/chats/{chat}/messages` with `busy_behavior=interrupt` on
a chat that no worker owns (for example one waiting for capacity) now
returns the promoted message with `queued=false` instead of a queued
message, and the chat stays in `running` instead of `interrupting`. If
the chat already had queued messages, the queue head is promoted and the
new message stays queued.
- `POST /api/v2/chats/{chat}/interrupt` on such a chat lands it in
`waiting` immediately (or in `running` with the queue head promoted)
instead of `interrupting`.
- An unowned `interrupting` or `requires_action` chat (for example after
its replica died) now waits for a free slot before its runner starts,
which also delays enforcing its action deadline while the pool is full.
- New internal chat worker settings `HeartbeatRenewalTimeout` and
`HeartbeatLockTimeout`, defaulting to a third of the stale threshold and
half of that.
- Heartbeat ticks now take the capacity admission advisory lock briefly
on each replica.
## Out of scope / follow-ups
- Interrupting a chat still owned by a dead runner (stale lease,
`worker_id` set) still waits for a slot.
- An admission lock timeout should end the acquisition pass instead of
logging a warning per candidate.
- The per-chat `queued_for_capacity` flag in the chat API still reports
only `running` chats.
- Alert on failed heartbeat ticks.
`coderd/x/chatd/ARCHITECTURE.md` gains TODO lines for the affected
sections; the prose is left for the owner.
---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
|
||
|
|
cdc87ee047 |
fix(coderd): recheck auto-archive candidates under the family lock (#30242)
Auto-archive read its candidates without locks and then archived each family without rechecking, so a chat that became active after selection (a new message in the root or a child, a pin, a status change) could still be archived. SetFamilyArchivedInput gains an optional Precondition that runs after the root and every family member row are locked root-first; auto-archive uses it to rerun the candidate filters for that root through the new GetAutoArchiveInactiveChatCandidateByID query and skips chats that no longer qualify. A parity test keeps the batch and by-ID queries in sync, regression tests cover root, pin and child activity races, and ARCHITECTURE.md describes the recheck. Builds on #30240. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
303b822a85 |
fix(coderd/x/chatd): refuse to create a child chat under an archived root (#30240)
A late spawn_agent call, for example from a runner that lost its lease, could create a running, unarchived subagent under an archived root, breaking the family archive invariant. chatstate.CreateChat now locks the family root FOR SHARE in the insert transaction and returns ErrChatFamilyArchived when the root is archived, which serializes child creation with SetFamilyArchived (both lock the root first). spawn_agent also refuses an archived parent before prompt hooks run, and ARCHITECTURE.md documents the behavior. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
9ac4628947 |
fix(coderd): stop announcing stale chat retries and fence retried attempts (#30241)
Stop announcing a pending chat retry once the chat leaves running, and stop streaming preview parts of a failed generation attempt after its retry is recorded. UpdateChatExecutionState now clears retry_state on every non-running status write (the trigger advances retry_state_version), the stream loop only emits retry while the chat is running, and it retires the current attempt once it observes a retry payload or an advanced retry_state_version within an unchanged episode. Regression tests cover the error, interrupt and requires_action exits, late parts after a retry, and a retry cleared before the stream syncs; ARCHITECTURE.md documents the new rules. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ |
||
|
|
63a95d87f3 |
feat(coderd): key chat diff statuses by ref (#29081)
Part 1 of 6. `chat_diff_statuses` had one row per chat, so a chat could only track one PR, and switching branches overwrote the old branch's PR data. The primary key is now `(chat_id, git_remote_origin, git_branch)`, so each ref the agent reports gets its own row. The API still returns a single `diff_status`: the first row of the chat's statuses, ordered by `updated_at`, newest report first. The primary ref changes only when the agent reports a ref: refreshes, claims, backoffs and URL writes do not advance `updated_at`, so they cannot reorder the primary. The gitsync worker now claims, backs off and clears rows by the full key, not the whole chat. When the diff GET discovers a PR URL, it updates the existing ref row and no longer inserts one. Telemetry picks one row per chat. **NOTE**: Migration `000606` swaps the primary key under an ACCESS EXCLUSIVE lock. The table is small. Existing rows already fit the new key, so no data is rewritten. The down migration keeps only the primary row per chat. Stop old coderd instances before migrating: their `ON CONFLICT (chat_id)` upserts fail once the old key is gone. Generated by Coder Agents. |
||
|
|
8e323e435c |
fix(coderd/x/chatd): accept ambient-credential providers in model overrides (#30205)
Model overrides (title generation, advisor, compaction, subagents) run a credential pre-check through `userCanUseProviderKeys`. That check, together with `setResolvedProviderAPIKey`, treated only the `bedrock` provider name as keyless. An anthropic-type provider with Claude Platform on AWS settings is marked available by `ResolveUserProviderKeys` through `SupportsAmbientCredentials`, but it got no `ByProvider` entry. The override then failed with `model override credentials are unavailable for provider "anthropic"`. Title generation and advisor treat this as a hard error, so titles were skipped on dogfood. Compaction and subagent overrides were silently ignored. Chat turns were unaffected because they route through the AI Gateway without the pre-check. The empty-key `ByProvider` entry is now recorded whenever a provider resolves as available, and `userCanUseProviderKeys` accepts `APIKey != "" || HasProvider(name)`. Bedrock behaviour is unchanged, and ambient providers whose policy requires a user key stay unavailable. If the AWS environment is misconfigured, such an override now fails at request time instead of at the pre-check, which matches bedrock today. Tests: a regression test for the title override on a Claude Platform on AWS provider (it fails on main with the dogfood error), new `ResolveUserProviderKeys` cases for ambient anthropic with and without a required user key, and extra `userCanUseProviderKeys` cases. > This PR was generated by Coder Agents on behalf of @jscottmiller. |
||
|
|
fc0af7fbd8 |
feat: open a chat_turn span per prompt (#29771)
**TL;DR:** Wraps each prompt in a `chat_turn` root span with every lifecycle stage parented under it. The span records one outcome per turn (`completed`, `interrupted`, `error`, `abandoned`), and the new `coderd_chatd_turn_outcomes_total` counter counts those outcomes. Turns stay correct when tasks are canceled, replaced, or retried. Each prompt runs inside a `chat_turn` root span owned by the runner (`runnerTurnSpan`). The generation step, prepare, MCP connect, stream, TTFT, provider attempt, commit, thinking, tool call, compaction, and retry backoff stages are parented under it, activating the stages from #29770. `chat_turn` spans are standalone roots: the turn runs on a worker, often on another replica, and no trace context is persisted. **Lifecycle** - **Start.** Each generation loop iteration calls `Ensure`, which opens the turn if none is open and returns a `turnToken`. The span is backdated to the trigger: the latest of the last user prompt, a dynamic tool's result message after it, and a pending compaction request. An `acquisition` stage covers trigger to pickup. - **Stale trigger / takeover.** A trigger at or before the previous anchor opens the turn at now with no `acquisition` and counts `stale_anchor`. A runner that took the chat over from an owner with a stale heartbeat (`TakenOver`, from acquisition) opens its first turn at now with no `acquisition`, so the dead owner's run is not reported as pickup delay. - **Newer prompt.** `Ensure` on the current turn with a newer trigger closes it and opens a new one. The closed turn is `abandoned` unless the task that ran it records an outcome before releasing it. - **Finish.** After `FinishTurn` or `EnterRequiresAction` commits, the step calls `Complete`; `Settle` closes the span after the step's own stage ends, so the finishing step is inside the turn. A chat waiting in `requires_action` is outside any turn; the generation resumed by its tool results opens a new one. - **Emission.** Closing a turn fixes its end time; its span is emitted once every task that joined it (`Ensure` takes the task ID) has called `Release`, which `runTask` does after the task returns. A finishing task whose `FinishTurn` promoted a queued prompt therefore still counts its turn as `completed` even when the promoted task's `Ensure` runs before its `Complete`. `End` at runner exit emits whatever is left. - **Failure.** A step that commits `FinishError`, or fails closed, invalidates the turn as `error` after the commit. Errors the task runner retries, including task timeouts, keep the same turn open; an expected, non-retryable exit records no outcome and leaves the turn open until the interrupt task, a newer prompt, or runner exit closes it. A canceled generation task records no outcome and cannot obtain a turn token, so a replaced task never touches its successor's turn. - **Interrupt.** The interrupt task marks the open turn `interrupted` before `FinishInterruption` commits and closes it after. Only a stop (by the user or a parent agent) is `interrupted`; it ends with unset span status, since error status is reserved for `error` turns. runner shutdown, loss of ownership, and message edits close the turn as `abandoned` with unset status. - **Promotion.** Every promoting transition (`FinishTurn`, `FinishInterruption`, a send to an errored chat, `PromoteQueued`) returns the promoted message's queued time in its result, and one `recordQueueWait` helper records a standalone `queue_wait` to the promotion. The promoted turn opens at the promotion time. `chat_turn` is observed on `coderd_chatd_stage_duration_seconds` only for completed turns, so the histogram is completed-turn latency; every turn still emits its span. `coderd_chatd_turn_outcomes_total{outcome, chat_kind}` counts every closed turn exactly once (`completed`, `interrupted`, `error`, `abandoned`), matching the span's `turn_outcome`, under the `chat-stage-metrics` experiment. Turn time accounting is in draft #29772. **Stages and identity** - `tool_call` is a live stage around each local tool call in `chatloop`; the tool runs on its context, and it ends errored only when the tool fails to execute. Calls that never run (inactive, unknown, or rejected by policy) record no stage. - `mcp_connect` carries connected and failed server counts and ends errored only when servers were configured and none connected. - The compaction stage carries the model that runs the summary. - `withStageIdentity` puts scope and chat kind on the turn context. Detached background work runs in `background` scope as its own trace roots. - The `advisor` tool's nested model call appears only as its enclosing `tool_call`. ARCHITECTURE.md gains a "Lifecycle tracing" section. <details> <summary>Review decisions</summary> - Turn identity stays timestamp-based with targeted fixes (clamped acquisition, rotation on a newer trigger, invalidate after commit, fail-closed invalidation, settle closing invalidated turns) plus a takeover flag; keying turns on message IDs would not detect takeover and cannot express interrupted/abandoned outcomes. - Outcome classification: the interrupt task owns `interrupted`, and cancellation or a fence mismatch alone never records an outcome, so shutdown, ownership loss, and edits are `abandoned`. Only `error` turns set error span status. Remaining ordering races between a step and an interrupt are documented as known limitations in ARCHITECTURE.md. - Turns are emitted after the tasks that ran them return, not when they close, so an outcome a replaced task records while unwinding reaches its own turn; the successor task is not delayed. Chosen over an after-commit, pre-publish hook on `ChatMachine.Update`, which would fix only the `FinishTurn` ordering. - `requires_action` ends the turn rather than pausing it, so `chat_turn` measures chatd time; a prompt with client tools counts as several turns. - Promoted turns anchor at promotion time and `queue_wait` is always standalone, so `chat_turn` never includes time spent queued behind another turn. - The former `capacity_wait` stage (#29805) was dropped: it was a per-worker lower bound, excluded from accounting, and needed its own SQL and bookkeeping. #29805's remaining helpers are folded into this PR. </details> Supersedes #28972, #28973, and #29805. 🤖 This PR was generated by Coder Agents on behalf of @jscottmiller. |
||
|
|
e988ddb11d |
feat: trace chatd provider stages and count only output parts as first token (#29770)
**TL;DR:** Traces the model provider call: a `stream` stage, a nested `time_to_first_token` stage, and one `provider_attempt` per HTTP round trip, labelled with provider type and model. Behavior change: `coderd_chatd_ttft_seconds` now counts only a real output part as the first token, so error, warning, and finish parts no longer count. Instruments the provider call. **Stream and time to first token.** `GenerateAssistant` records a `stream` stage from stream open to close and a nested `time_to_first_token` stage. The TTFT window closes once, on the first streamed output part: any part other than warnings, finish, or error, including start markers such as `text_start`. A closed window observes the stage and the pre-existing `coderd_chatd_ttft_seconds` with the same elapsed time. A failed open, an error part, or a release without an output part ends the TTFT span with the error (a silence timeout is classified as such) and observes nothing. The `stream` span ends once, with the error `GenerateAssistant` returns, so content-filter and no-output attempts end errored. Failed `stream` windows are observed like successful ones. The attempt is released before the stream span ends, so the TTFT window always falls inside its stream. The compaction summary stream passes a nil tracer, so it records neither. Without #29771, production emits only `provider_attempt`; #29771 passes the tracer to `GenerateAssistant`. **Provider attempts.** The provider HTTP transport is wrapped in `stageSpanRoundTripper`, which emits one `provider_attempt` stage per round trip, so retries each get a span. The span closes on response headers; a status >= 400 marks it errored without changing what the client sees. `resolveModelCall` resolves the `StageModel` (wire provider, configured `provider_type`, model, effective reasoning effort) and threads it to the transport, so span attributes and labels match the call. `provider_type` is read from `ai_providers.type`, so types outside the fantasy set (copilot) keep their configured name. `chatd.New` builds the tracer with the server clock. **Behavior change to `coderd_chatd_ttft_seconds`:** only an output part counts as a first token. Error parts no longer close the window as a success, and warnings and finish parts are skipped; the help text says so. `StageSpan.End` returns the span's elapsed window, which `ttft_seconds` observes. Callers pass `Stages` and `StageModel` through `GenerateAssistantOptions`; a nil tracer discards (TTFT still records `ttft_seconds`). `Server` gains the `stages` tracer and a `TracerProvider` option, wired from `coderd`. <details> <summary>Review decisions</summary> - Start markers close the TTFT window: they are the first sign the model is producing output, and waiting for a delta would fold hidden reasoning time into TTFT. - Failed `stream` and `provider_attempt` windows are observed: that time was spent. TTFT is the exception because a first token that never arrived has no duration. - `http_host` was dropped from `provider_attempt`; every request goes through the local AI Gateway transport, so it was constant. - The advisor tool's nested model call is intentionally not instrumented as `stream`/TTFT. </details> Supersedes #28970 and #28971. 🤖 This PR was generated by Coder Agents on behalf of @jscottmiller. |
||
|
|
7a9442014e |
feat: add chatd lifecycle stage tracer (#29769)
**TL;DR:** Adds a stage tracer that turns each chat lifecycle stage into
both an OpenTelemetry span and a Prometheus histogram observation, so
traces and metrics always agree. The metrics are only registered with
the `chat-stage-metrics` experiment. Nothing calls the tracer until the
next PRs.
Adds `chatloop.StageTracer`, which emits each chat lifecycle stage as an
OpenTelemetry span and a `coderd_chatd_stage_duration_seconds{stage,
scope, chat_kind}` observation from one `End` call, so trace and metric
durations cannot disagree. The provider-bound stages (`stream`,
`provider_attempt`) are also observed on
`coderd_chatd_model_stage_duration_seconds{stage, provider_type,
chat_kind, model}`, the only family carrying `provider_type` and
`model`, and only for turn-scoped stages. Time to first token per model
stays on the existing `coderd_chatd_ttft_seconds`. Nothing calls the
tracer yet; the next PRs instrument the provider call and the runner.
- The families are registered only when the `chat-stage-metrics`
experiment is enabled (safe and known, so
`--experiments=chat-stage-metrics` or `--experiments=*` turns it on).
Spans are emitted regardless. `NewMetrics` leaves the families off;
`chatd.New` opts in from the experiment, and a test asserts the
experiment decides whether they reach the server's registry.
- `Stage`, `Scope`, `ChatKind`, and `StageAnomaly` are typed string
constants. `scope` separates latency attributable to a prompt (`turn`)
from detached `background` work; `chat_kind` is `root` or `subagent`,
empty without a known chat.
- `StageModel` carries the wire `provider`, `provider_type`, `model`,
and `reasoning_effort`. All are span attributes; only `provider_type`
and `model` are metric labels, on the model family. No family carries an
organization label.
- Observed stages: `chat_turn`, `queue_wait`, `acquisition`,
`mcp_connect`, `stream`, `time_to_first_token`, `provider_attempt`,
`tool_call`, `commit`, `retry_backoff`. `generation_step`, `prepare`,
`thinking`, and `compaction` are span-only. A test keeps the stage sets
and help text consistent.
- API: `Start` / `StartRootAt` for live spans (span timestamps come from
the tracer clock), `Record` for stages reconstructed from timestamps
(the scope comes from the context). `End` is idempotent;
`EndWithoutObservation` ends the span without a sample. A nil tracer,
provider, or metrics discards.
- `coderd_chatd_stage_anomalies_total{reason}` counts observations
dropped, adjusted, or inconsistent (`negative_elapsed`,
`inverted_window`, `missing_timestamp`, `future_start`, `stale_anchor`).
Span-only stages never feed it.
- Buckets are 12 round edges (`0.1 0.25 0.5 1 2.5 5 10 30 60 300 1800
3600`).
- Moves the body of the `for` loop in `StartGeneration` into
`runGenerationStep` so the step has a function boundary for a deferred
stage end. Control flow and error wrapping are unchanged.
<details>
<summary>Series cost (approximate, whole stack)</summary>
A histogram label set is 12 edges + `+Inf` + `_sum` + `_count`: 15
series. Per replica, each `chat_kind` costs about 150 stage series and 4
turn outcome counters; each `(chat_kind, model)` costs 30 (2 stages x
15). Both chat kinds on `M` models: about `308 + 60*M` per replica, plus
background-scope stage series.
Dogfood `main`, 3 replicas: ~3.4k `coderd_*` series per replica (~10.1k
total).
| Models used per replica | Added series (3 replicas) | vs. baseline |
|---:|---:|---:|
| 1 | ~1.1k | +11% |
| 5 | ~1.8k | +18% |
| 10 | ~2.7k | +27% |
| 35 | ~7.2k | +72% |
Most deployments run four or fewer models, so a typical replica adds
roughly 370 to 550 series. The experimental turn accounting in #29772
would add 88 more per replica (11 categories x 4 outcomes x 2 chat
kinds). Series appear lazily and do not grow with organizations.
</details>
<details>
<summary>Review decisions</summary>
- Experiment gate only; no deployment flag or metric levels. If the
experiment graduates, the families become always on like the other chatd
families; a flag is added then only if dogfood shows a cardinality
problem.
- Organization is on neither metrics nor spans, and `effort` is
span-only; `provider_type` (configured type), not the wire `provider`,
is the model-family label.
- `time_to_first_token` is not on the model family; per-model TTFT is
`ttft_seconds`, which observes the same measured window.
- The model family records only turn-scoped stages.
- Nil guards are kept so a nil or zero tracer is always safe to call.
- HTTP attribute keys stay snake_case like the rest of the chatd span
attributes.
</details>
Supersedes #28968 and #28969.
🤖 This PR was generated by Coder Agents on behalf of @jscottmiller.
|
||
|
|
fa5bac6e77 |
feat: send tool call IDs and cancel unresolved calls on interrupt (#29954)
Retries and replica takeovers ran tool calls again, and an interrupt recorded the same generic result whether a call had finished, was still running, or never started. chatd now derives a tool call ID from the chat, the committed assistant message, and the provider tool call ID, and sends it with execute starts, edit_files, and write_file. Every replica and retry computes the same ID, so the agent returns the first result instead of running the tool again, and a retried foreground execute waits only for the rest of its timeout. On interrupt, chatd cancels the unresolved calls of those tools on the agent before committing, within 30 seconds, and records what happened: "tool call was canceled before it ran; no changes were made", the output of a command canceled while running, or the real result. The UI shows a canceled command with the existing killed marker. If the cancel fails, including an old agent's 404, the result stays the generic interrupted text. Calls whose provider tool call ID is empty or repeats in the message get no ID and behave as before. Fixes CODAGT-757 |
||
|
|
5a997c471a |
fix(coderd/x/chatd): tell the model when output hit the token limit mid tool call (#30120)
When an Anthropic response hits the output token limit while the model
is writing a tool call's input, chatd gets `FinishReasonLength` with a
cut-off call. It handled both shapes of that call badly:
- If the provider closed the `tool_use` block, the call carried
truncated JSON and got the generic malformed-input result, which invites
the model to resend the same oversized input and hit the limit again.
- If the block never closed, fantasy emitted no tool call, chatloop
discarded the dangling tool input, and the turn ended with only
reasoning and no explanation.
On a length finish, `GenerateAssistant` now gives each cut-off local
call an error result: "This tool call was not executed because the
response reached the output token limit (N tokens) while writing its
input. Split the content into smaller tool calls." The token count is
included when the call has a configured output limit. A tool input that
started streaming but never became a call first gets a stand-in call
with empty input. The call persists with nil args and replays as `{}`,
so the provider receives a valid `tool_use` and `tool_result` pair, and
generation continues with another step.
With lifecycle hooks enabled, `pre_tool_use` admission skips calls the
step already resolved, so the hook is not dispatched for them and no
second result is added. The duplicate tool ID check still runs on the
full batch, because a resolved call still occupies its ID.
Independent of #30119, which stops the AI Gateway from failing these
streams before chatd sees them.
## Testing
-
`TestGenerateAssistant_SilentNoOutputFinish/LengthFinishResolvesTruncatedToolCalls`
(truncated tool call, dangling tool input): no error, reasoning kept,
and each call paired with the output-limit result.
- `TestPreToolUseHookOutputLimitTruncatedToolCallResolvedOnce` with
hooks enabled, for truncated and unfinished input: no hook dispatch, one
stored error result per call, a second model request, and a replayed
request that pairs `tool_use` input `{}` with its `tool_result`.
`DuplicateIDFailsClosed` checks that a reused ID still fails the chat
with `duplicate tool use ID`.
- Red-green: with `chatloop.go` and `generation.go` restored to the base
code, all four truncation cases fail. `DuplicateIDFailsClosed` passes on
the base code by design and fails on `d02bf4aa89b`, which dropped
resolved calls before the duplicate check.
- `go test ./coderd/x/chatd/... -count=1` passes, and lint on the
touched packages reports no issues. Local pre-push checks were skipped
per standing preference; PR CI covers them.
- Remote UAT: not run yet.
## Review record
- Parent review (Xum) of `d02bf4aa89b`: skipping resolved calls inside
`chathooks.PendingToolCalls` hid them from the duplicate tool ID check
in `admitStepToolCalls`. Fixed in `745f722165b`.
- Codex: not requested yet.
> Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike.
|
||
|
|
1e9dd0abbc |
feat: add Claude Sonnet 5.5 and GPT-6.1 Sol to Agents and AI Gateway (#30159)
Add Claude Sonnet 5.5 and GPT-6.1 Sol to the Agents known models
catalog, so they appear as suggestions when an admin adds a chat model,
and regenerate the AI Gateway price book from models.dev.
| Model | Added to |
|---|---|
| Claude Sonnet 5.5 | anthropic (`reasoningEffort: high`), azure,
bedrock (`global.anthropic.claude-sonnet-5-5`), openrouter, vercel |
| GPT-6.1 Sol | openai (`reasoningEffort: medium`), azure, openrouter,
vercel |
**Bedrock.** bedrock-runtime serves Sonnet 5.5 only through its global
inference profile, so the catalog curates the `global.` ID without a
bare alias: fantasy's Bedrock client prefixes a bare `anthropic.*` ID
with a regional profile (`us.`, `eu.`, `apac.`) that this model lacks.
bedrock-mantle takes the bare ID and the gateway looks prices up by
exact provider and model, so `overrides.jq` injects the bare ID as a
copy of the global price entry. The two GPT Daybreak alias injections
are gone: models.dev now lists both aliases, and their guards error out
once it does.
**Reasoning effort.** Sonnet 5.5 rejects the `thinking: {"type":
"disabled"}` that fantasy sends for effort `none`, and GPT-6.1 Sol
rejects `none` outright, both with HTTP 400. `applyReasoningEffort` now
maps `none` to `low` for Sonnet 5.5 on the Anthropic and Bedrock
providers, next to the Opus 5.5 clamp, and maps `none` and `minimal` to
`low` for GPT-6.1 Sol on OpenAI and Azure through a new
`chatopenai.IsGPT61Sol`, next to the GPT-6 Astra clamp. GPT-6 Sol
accepts `none` and stays unclamped; the test pins that. AI Gateway's
Bedrock adaptive-thinking allowlist already matched Sonnet 5.5 through
its `anthropic.claude-sonnet-5` substring; a table case now covers it.
**Price book drift.** `prices.json` includes every model of its 8
providers, so the regeneration also brings in upstream changes since the
last refresh: 28 new entries (such as Grok 4.7 on Bedrock and Mistral
Large 2512 on OpenRouter), 7 entries models.dev delisted (mostly free
variants on OpenRouter and Vercel), and 49 price changes (39 OpenRouter,
10 Vercel). Other uncurated upstream models, such as `-pro` and `-fast`
variants and `openai.*` on Bedrock, stay out of the catalog, matching
how earlier releases were curated.
The Reasoning effort section of `coderd/x/chatd/ARCHITECTURE.md`
documents only the GPT-6 Astra clamp and should gain Sonnet 5.5 and
GPT-6.1 Sol. That doc edit is left to a human author.
Validation: regenerating from a fresh models.dev fetch reproduces both
generated files byte for byte. Go tests pass for
`scripts/aibridgepricesgen`, `coderd/aibridge/prices`,
`coderd/x/chatd/chatprovider`, `coderd/x/chatd/chatopenai`, and
`aibridge/intercept/messages`. Removing either clamp with `go test
-overlay` fails the new cases on exactly the Sonnet 5.5 and GPT-6.1 Sol
inputs. Vitest passes for `src/modules/aiModels` (176 tests) and the
Models and Coder Agents settings pages (24 tests). The pre-commit hook
passed; local pre-push checks were skipped, so CI is the first full run.
Review record: no reviews yet. No remote UAT was run; the tested head is
`78abe17e69d`.
> Xum opened this PR on behalf of @ibetitsmike.
|
||
|
|
9aa7130e01 |
feat: evaluate experiment rules per user in discovery and chatd (#29964)
Slice 3 of 4 for runtime experiment rules: evaluate stored rules per user in discovery, the frontend experiments query, and the pilot `mcp-tool-search` gate in chatd. There is still no way to edit rules through the product; that comes in slice 4. With no rules stored and a healthy database, backend decisions match today. This PR deliberately changes three things: 1. **Fail closed on rule reads.** If the rules read fails, `mcp-tool-search` is off, even when it is enabled at startup. 2. **Frontend freshness.** The experiments query now refetches. 3. **Caching.** `/api/v2/experiments` and rendered HTML are sent with `Cache-Control: no-store`. Static assets keep their long-lived caching. ## What's in it - **coderd** builds `api.ExperimentEvaluator` from `experiments.NewDBStore` plus the startup `--experiments` list. - **Discovery:** `GET /api/v2/experiments` and the `<meta property="experiments">` tag both use `EnabledExperiments(ctx, caller)`. - **chatd:** `mcp-tool-search` is now user-scoped. `chatd.Config.ExperimentEvaluator` is required, so `chatd.New` returns an error without it. `prepareGeneration` decides once per turn for the chat owner (`chat.OwnerID`); child chats inherit the owner. - **Ruleguard** (`userScopedExperimentStaticCheck` in `scripts/rules.go`): rejects static `Experiments.Enabled(...)` and `httpmw.RequireExperiment*(...)` checks of user-scoped experiments in server packages. A codersdk test keeps its list equal to `codersdk.ExperimentsUserScoped`. - **Frontend:** the experiments query is keyed by user ID and seeded from the meta tag only when the embedded user matches. It is stale 60 s after page load and refetches on mount, window focus and reconnect. Logout also clears the experiments metadata. The dashboard keeps the last loaded list when a background refetch fails, instead of replacing the page with an error. - **Once per turn:** chatd decides `mcp-tool-search` on a turn's first step and reuses that decision for the turn's later steps, so a rule change applies from the next turn and never withdraws a `find_tools` call the model already made. The decision lives on the chat runner, keyed by the turn's prompt row, like the stop-nudge tracker. A runner handoff in the middle of a turn evaluates again. - **Reference audit:** the only non-test server check of `mcp-tool-search` is in `generation_preparer.go`, and it now goes through the evaluator. ## Testing - **Go:** per-user results and `no-store` on `/api/v2/experiments`; the per-user meta tag and the HTML cache headers in `site`; group and org conditions end to end in enterprise; chatd owner eligibility, on → off → on across turns including a child chat, and a failed rules read. - **Vitest:** user-keyed seeding, staleness from page load after a remount, refetch on focus, logout clearing, and the dashboard surviving a failed refetch. Remote dogfood UAT through Coder Agents passed on a licensed test deployment: - per-user discovery in both the API and the meta tag; - widening a rule, and turning it off, with no restart; - `off` beating a startup default, and `inherit` restoring it; - fail closed on malformed JSON and on an unknown mode, with no condition text in the logs; - the `no-store` headers; - real-model chatd enforcement: `find_tools` offered on turn 1, gone after `off`, back on turn 3. That round tested `b57207d4ee`. The later commits change only tests, and a follow-up round will cover the final head. **For the author:** `coderd/x/chatd/ARCHITECTURE.md`'s list of the runner's local state doesn't mention the per-turn trackers (debug turn, session start, stop nudges, and now this experiment decision). I did not edit that document. **Known behavior:** a broken rule logs one error line per evaluation (per request or turn), with only the experiment, revision, category and position. ## Stack 1. #29869: evaluator library 2. #29898: storage and audit types 3. **This PR:** enforcement and discovery 4. Control plane (experimental API, `coder exp experiment-rules` CLI, docs) > [!NOTE] > This PR was written by an AI agent (Xum). --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ --------- Signed-off-by: Thomas Kosiewski <tk@coder.com> |
||
|
|
faa9815cd6 |
feat: configure Claude Platform for AWS on Anthropic providers (#29049)
This PR adds configuration plumbing for Claude Platform on AWS ## Summary Makes Claude Platform for AWS configurable as a settings variant of `type=anthropic`, discriminated by `_type: "claude_platform_aws"`. Settings contain only `region` and `workspace_id`, plus the schema version. No new provider type or database enum is introduced. The API persists and projects those settings to the gateway. Provider keys can be added or removed independently: allowed BYOK takes precedence, followed by stored keys, then ambient SigV4 when neither key source applies. Model-availability hints and keyless provider construction reflect that ambient capability. Rejected or exhausted keys do not fall back to IAM. Removes Claude Platform-specific AWS identity fields, secret redaction/merge behavior, external-ID handling, and mode/key consistency checks. Bedrock configuration remains intact. Environment-based provider seeding was removed upstream and is not restored. The Claude Platform form and Experimental label remain follow-up work in #29050. ## Authentication limitation Each Claude Platform provider uses either the gateway's ambient AWS credentials when no provider keys are stored, or its stored API-key pool. In either case, a client credential takes precedence when BYOK is enabled. Rejected BYOK or an exhausted provider key pool does not fall back to ambient IAM. There is no per-provider AWS identity selection: keyless providers on the same gateway share its ambient AWS credential chain and cannot configure separate AWS access keys or assumed roles. Each provider still has its own Claude Platform workspace ID and separate provider attribution in Coder's usage/cost records; this does not imply separate AWS billing accounts. ## Validation - Race tests passed for SDK, daemon projection, db2sdk, chatprovider, and targeted CLI/API configuration tests. - Installed pre-commit hook passed, including generation, frontend/Go lint, and build. - Tests cover settings round trips, validation, adding/removing the last key without settings changes, keyless construction, model availability, and Bedrock regressions. Generated by Coder Agents on behalf of @johnstcn and @Shelnutt2 Co-authored-by: Cian Johnston <cian@coder.com> |
||
|
|
e0dce46087 |
test: fix TestConnectInline_RedactsSensitiveValues on Windows (#30028)
Closes https://linear.app/codercom/issue/CODAGT-1203 `TestConnectInline_RedactsSensitiveValues` fails every time on Windows in the [nightly gauntlet](https://github.com/coder/coder/actions/runs/36376854646/job/108784351863). It asserted on `connection refused`, but Windows words a refused dial differently. PR CI only runs the `cli` and `agent` packages on Windows, so we didn't catch it there. To fix, the test now uses a private IP that the dial guard rejects before dialling, so the error is the same on every OS and there's no closed port for another test to grab. Whilst here, I made production build the persisted connect error through the same function the truncation test uses, rather than its own copy. |
||
|
|
f5092aaa4a |
feat: make chat limits configurable deployment options (#28927)
Adds deployment options for the chat limits that shape turn behavior and API acceptance, replacing hardcoded constants in `coderd/x/chatd` and the chat API. Defaults are unchanged. | Option | Default | Limit | |---|---|---| | `CODER_CHAT_MAX_STEPS_PER_TURN` | 1200 | steps (model responses) in a chat turn | | `CODER_CHAT_MAX_GENERATION_RETRIES` | 25 | consecutive retries after a model generation fails with a transient error | | `CODER_CHAT_MAX_QUEUED_MESSAGES_PER_CHAT` | 20 | messages that can be queued in a chat | | `CODER_CHAT_MAX_ATTACHMENTS_PER_CHAT` | 50 | files linked to a chat; linking more deletes the earliest uploads | | `CODER_CHAT_MAX_PROMPT_BYTES` | 131072 | system prompt, plan mode instructions, and each user's custom prompt | | `CODER_CHAT_MAX_CONCURRENT_RECORDING_UPLOADS` | 25 | desktop recordings each server stores at the same time | `codersdk.DefaultChat*` constants remain the single source of truth. Values below 1 fail startup validation, and each option's description ends with "Must be at least 1." `chatd.New` fills any zero field in `chatd.Config.Limits` with its default once, `LimitsFromConfig` is a plain conversion, and the code that receives a limit as a parameter (the `chatstate` queue and file link checks, the turn step check, `chatretry.Retry`, and `chatadvisor.NewRuntime`) returns an error for a limit below 1 instead of choosing a default or disabling the limit. The options are documented in the generated configuration reference and in the platform controls docs. `CODER_CHAT_MAX_GENERATION_RETRIES` counts consecutive retries, and the count resets after each successful step. The default allows 25 retries (26 attempts) where the old constants allowed 24. The same limit now applies to each nested advisor model call and to background title, summary, and turn status label generation, which previously used fixed `chatretry` budgets. Chat creation and tool result bodies keep the fixed 256 KiB limit from main. The prompt-saving endpoints accept bodies up to twice the prompt limit, for JSON escaping and characters that sanitization removes, but never less than 256 KiB, so small prompt limits still return the 400 length error. At the default this equals the 256 KiB limit on main. Four settings from earlier revisions were removed, and the fixed limits from main are back: - `CODER_CHAT_MAX_TOOL_OUTPUT_BYTES`: the agent already keeps a 16 KiB head and a 16 KiB tail of command output, so raising it had no effect and lowering it cut the tail. - `CODER_CHAT_MAX_DYNAMIC_TOOLS_PER_CHAT`: tool definitions share the 256 KiB chat creation body limit, so raising the count did little. - `CODER_CHAT_DEBUG_MAX_BODY_BYTES`: one setting covered two unrelated debug caps. - `CODER_CHAT_DEBUG_MAX_TEXT_RUNES`: the name did not say what it applied to. Root and subagent concurrency caps stay fixed because they are licensing behavior, and `MaxChatFileSizeBytes` stays fixed because the web UI hardcodes the generated constant for client-side checks. `codersdk.MaxChatFileIDs` is removed; the web UI's "Attachment expired" tooltip no longer quotes the number because the cap is now per deployment, and it says that attaching a file beyond the limit permanently deletes the chat's earliest-uploaded attachments. ## Review record | Round | Reviewed head | Result | Disposition | |---|---|---|---| | Codex 1 and 2 (Sep 2 to 3) | `7f10a1572f8`, `8ee09f8fa3b`, `197bb78d5b` | 10 findings, then OK on `197bb78d5b` | all threads resolved | | Codex 3 (Sep 17) | `e4efac249a5` (pre-rebase) | 4 findings | advisor retry limit confirmed and fixed in `9e462b7b3d0` (rebased from `67341e458e8`); ARCHITECTURE.md TODOs added; JSON-escaping body sizing and streamed-argument rune cap declined as pre-existing design (evidence in threads) | | Codex 4 (Sep 18) | `9e462b7b3d0` | 6 findings | recording evicted at attachment cap 1 confirmed and fixed in `5b61895decb`; `Limits` field docs and zero-value fallback documented; prompt retro-enforcement, generated multi-sentence lines, and tool-output truncation metadata declined as pre-existing design (evidence in threads) | | Codex 5 (Sep 18) | `5b61895decb` | 1 finding | over-cap batch of already-linked files accepted after lowering the cap: confirmed and fixed in `f44063e74e5` | | mafredri (Sep 23) | `f44063e74e5` | 24 threads, changes requested | all fixed in `05e3e3d622a`, `c1f78e09e8b`, `709ddb67977`, `d0587a49829`, `ca4347b24de`, and `1f6c9e2a46f`, then answered and resolved; the ARCHITECTURE.md text was written at the author's direction and approved by the author | | Sibling sweep (Sep 24) | `1f6c9e2a46f` | author-requested audit of all 24 mafredri threads for sibling issues, plus a test refactor | fixed in `37eaf07d34d` through `1f14ac041b7`: the advisor retry limit, `chatretry.Retry`, and the turn step check reject values below 1 instead of disabling retries or the limit; limit tests run against both the default and configured values set through `chatd.Config` or `DeploymentValues`; the expired-attachment tooltip is concrete. A required coder-frontend-review run (8 roles in one agent, CD re-run once) found a stale story comment, removed. | | Codex 6 (Sep 27) | `a71383e3a31` | OK, no findings | requested after the rebase at the author's direction, past the six-pass review budget | The branch was rebased onto main `4851c7b60c8` on Sep 27; the previous head was `91b84000adb`, and the earlier SHAs in the review record predate the rebase. Conflicts in the `chatstate` transitions and `CreateChat` keep both main's `InitialStatus` and this PR's `MaxFileLinks`, and main's rewrite of `advisor_internal_test.go` in #28754 keeps main's version plus this PR's limit tests. Two tests added on main needed the new retry arguments: `TestGenerateStructuredTitleWithUsage_FallsBackToTextWhenToolChoiceRejected` and `TestAdvisorRunStreamsReasoningDeltasSeparatelyFromAdvice`. Validation on `a71383e3a31`: the pre-commit hook (generation, golangci-lint, build), the full `coderd/x/chatd/...` suite (20 packages), the chat tests in `codersdk`, `coderd`, and `enterprise/coderd`, the CLI help tests, race-detector runs of the `chatd`, `chatstate`, `chatadvisor`, and `chatretry` packages, and `go build` plus `go vet` on each of the 27 commits. No remote UAT was run. > Xum acted on behalf of @ibetitsmike for this pull request. |