Commit Graph
499 Commits
Author SHA1 Message Date
Jaayden Halko 1f1aa6ae3c feat: add chat project template schema and queries (#32309)
Adds the database layer for attaching workspace templates to chat
projects: the schema, the queries, their authorization, and the audit
type. Nothing calls the new queries yet, and the existing create and
update handlers pass the new parameters unset. The API, the limit's
enforcement, and the agent tools follow in the PRs above.

- Attachments live in a `chat_project_templates` table (`project_id`,
`template_id`, `created_by`, `created_at`), deleted with the project or
the template. `chat_projects` gains `limit_templates` (default `false`),
`default_template_id`, `default_template_version_preset_id`, and
`default_parameters jsonb`. A project stores a default preset or default
parameter values, not both.
- `InsertChatProjectTemplates` needs project `update` and `use` on every
template. It skips templates that are already attached, and templates
outside the project's organization, so an attachment never crosses
organizations. `DeleteChatProjectTemplate` needs project `update` and
template `read`, and clears the project's default when it detaches the
default template. Both checks are in dbauthz.
- `GetChatProjectTemplatesByProjectIDs` is authorized through the
project, and leaves out deleted, deprecated, and agent-disabled
templates. It does not check the caller's access to each template, so
callers do that before they expose one.
- `UpdateChatProjectByID` changes the template settings only when the
request sets them, so an update that omits them cannot write back a
stale snapshot.
- `AuditableChatProjectTemplates` is the audit form of a project's
attached templates, logged as a write to the project. The new
`chat_projects` columns are tracked in the project's own audit diff,
with the default parameter values masked because they may hold
credentials.

**NOTE**: the migration adds one table and four columns and changes no
existing rows. Existing projects keep unlimited template access.

Stack (merge top to bottom):
- #32309 👈
- #30754
- #32310
- #30755
- #30756
- #30898
2026-11-17 21:59:01 +07:00
McKayla はな 0be6e7a034 feat: add a setting for web terminal font size (#32027) 2026-11-16 15:03:30 -07:00
b0ae8adab5 feat(coderd): protect pending jobs only while the provisioner queue is moving (#32099)
Stops the pending job reaper from failing jobs in a queue that's still
moving. This is an alternative to #31469 that came out of Steven's
[review](https://github.com/coder/coder/pull/31469#pullrequestreview-5847958482)
asking whether 2h is enough, and it builds on George's work there.

A pending job past 30m is now only protected while a matching online
provisioner is making progress, meaning it finished a job in the last
30m or is running one that's still being updated. A moving queue never
gets reaped and a frozen one still does at 30m like today. There's no
absolute cap.

No migration since it uses the existing
`provisioner_jobs_worker_id_organization_id_completed_at_idx`. One
tradeoff is that a stuck build whose provisioner keeps heartbeating
counts as progress, so if every matching provisioner is stuck like that,
the queue waits until that build is canceled.

Still a draft so we can talk it through with Spike and Steven.

Part of CORE-586

---------

Co-authored-by: George Katsitadze <george.katsitadze@gmail.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 07:45:24 -06:00
Susana Ferreira 8c5921db5e fix: count unpriced AI model usage by when it was recorded (#31751)
## Description

Updates the unpriced AI models query behind the weekly owner
notification to count token usage by when it was recorded
(`token_usages.created_at`) in a `[period_start, period_end)` window,
consistent with the other AI spend queries. It also returns one row per
provider name and model instead of per provider type, so the unpriced
models endpoint later in this stack can reuse it. The notification
payload keeps the same format.

## Changes

- Rename `GetUnpricedAIModelsSince` to `GetUnpricedAIModels`. It used
`interceptions.started_at` with no end.
- Treat usage as unpriced only when no price was found (`cost_micros IS
NULL AND priced_model IS NULL`), so usage whose price was found but
whose cost could not be computed is not reported.
- Return one row per live provider name and model, with the provider's
display name, icon and type.
- The notification passes the last 7 days and merges rows by provider
type, since site-wide prices are keyed by type, so its payload keeps the
same shape.
- Table-driven query tests and a notification test for providers sharing
a type.

Related to AIGOV-730

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 13:21:32 +00:00
Mathias Fredriksson d639ced1e0 fix: send only changed chat history over the stream (#29662)
A client could resume the chat stream only with after_id, a message
ID. A message ID does not identify what a client has received. A
reconnect could skip a message that another client sent, send no
history_reset for an edit the client missed, or resend the whole
history.

A client can now resume with the chat's snapshot_version, which the
newest messages page returns and the stream's events then include.
The stream sends what changed at that version or later. For an edit
it sends the ID of the edited message and the messages written
since, not the whole history. A stream opened without
snapshot_version sends the same events as before.

A write outside a chat state transition does not increase
snapshot_version, and a stream can miss it. The queries that only
tests used for such writes are removed.

When the stream cannot be set up, the server now returns 500 before
the WebSocket upgrade. It used to upgrade and send an error event,
which the web client shows as a chat error.

The Tasks to Chats migration guide told clients to reconnect with
after_id. It now describes snapshot_version.
2026-11-13 13:02:38 +02:00
Susana Ferreira 7db53f3b47 feat: add organization AI spend overview queries (#31711)
## Description

Adds 3 database queries for the organization AI spend overview. They
read the daily spend aggregate (`ai_user_daily_spend`), scoped to the
organization through each spend row's effective group, over a
`[period_start, period_end)` range of UTC days.

1. `GetOrganizationAISpendTotals`: the number of users with spend, the
total spend, and the median of the users' total spend.
2. `ListOrganizationAISpendPerUser`: paginated users, most spend first,
with one row for each group their spend was attributed to.
3. `GetOrganizationAISpendPerDay`: the spend for every UTC day in the
range, including days without spend.

Note: Only users with spend above zero are included, so users with only
unpriced usage are not listed.

## Changes

- dbauthz checks matching `/ai/spend/users` (read on organization group
members).
- Querier and dbauthz tests.

Related to AIGOV-728

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 10:02:58 +00:00
Callum Styan c303114fae perf(coderd/database): batch chat authz fetch in GetChatDiffStatusesByChatIDs (#31880)
> Generated by Coder Agents on behalf of @cstyan.
2026-11-12 15:14:26 -07:00
Ehab Younes 1126533c31 feat: export workspace last used time to Prometheus (#31346)
Add an opt-in coderd_workspace_last_used_timestamp_seconds gauge that
reports workspaces.last_used_at, the value the dormancy threshold
measures inactivity from. To enable it, set
--prometheus-collect-workspace-stats or
CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS.

A separate WorkspaceStats collector refreshes the gauge once a minute
in the background from a new GetWorkspaceLastUsedForMetrics query. Each
series has a workspace_id label, so a workspace that reuses a deleted
workspace's name starts a new series. Workspaces owned by deleted users
are excluded.

Closes CLIENT-1065
2026-11-11 15:02:18 +00:00
Ethan 63e08e231e feat(coderd): steer queued messages on Send now (#31156)
"Send now" on a queued message (`POST
/api/v2/chats/{chat}/queue/{queuedMessage}/promote`) now just moves it
to the end of the steer lane. It never interrupts the chat, so it can't
cancel the step that would have answered it. The endpoint's request
doesn't change. Before, it moved the message to the head of the queue
with `MIN(position) - 1`, so if you pressed "Send now" on two messages,
the second one went first. With a queue of `Q1 Q2 Q3 S4`, "Send now" on
`Q1` then `Q3` now delivers `S4 Q1 Q3`, and `Q2` keeps waiting.

If the chat has errored or is paused, the steer lane goes in straight
away, like a send. Otherwise it goes in at the next delivery point:
before the next model call, when the turn ends, or when an interrupt
finishes. Stop is the only thing that interrupts.

"Send now" and "Remove" on a message that's already been delivered now
return a 404 instead of a 409, the same as editing one, and "Remove" on
an archived chat returns a 400.

In chatstate, `SteerQueuedMessage` replaces `PromoteQueuedMessage`. It
moves the message to the end of the steer lane, and on an errored or
paused chat it also delivers the steer lane and resumes the chat, like a
send does. The `SteerChatQueuedMessage` query sets `position =
nextval(...)` and replaces `ReorderChatQueuedMessageToHead`. Most of the
diff is tests.

#31174 then makes `steer` the API default and removes `interrupt` as a
busy behaviour, #31175 makes `message_agent` always steer, and #31173
updates the site.

Part of CODAGT-1140
2026-11-09 15:55:16 +11:00
Steven Masley bc5dd20a05 feat: report Agent Relay builds in telemetry (#31407)
Telemetry builds now report whether Agent Relay created them. Before
this, relay workspaces looked like any other build.

A start build counts as a relay build when it has the
`agent_relay_session_id` parameter. Stop and delete builds never get the
field. For those builds, the new `agent_relay` field on `WorkspaceBuild`
reports:

- `provider`: `claude_code`, `cursor`, `ambiguous`, or `unknown`
- `client_platform`: Claude Code only. Lowercased, characters outside
`[a-z0-9_]` become `_`, and cut to 15 characters
- `attempt`: omitted when missing or not an integer, so `0` is sent
- `session_id_hash` and `pool_hash`: SHA-256 hashes

No other parameter values are sent. Other builds leave the field out.

The snapshot fetches these parameters with one new batch query. The
workspace-create event reads the stored parameters with one extra query,
only when telemetry is enabled, so it reports the same data as the
snapshot. `docs/admin/setup/telemetry.md` lists the parameters that are
read.

The collector side is
[coder/coder-telemetry-server#56](https://github.com/coder/coder-telemetry-server/pull/56).
Merge this PR first.

Refs
[RELAY-9](https://linear.app/codercom/issue/RELAY-9/telemetry-report-agent-relay-usage-from-codercoder)

<details>
<summary>Decision log</summary>

- **Detect relay builds from parameters.** This needs no relay changes.
Relay registration or
[CORE-426](https://linear.app/codercom/issue/CORE-426) provenance
metadata can come later.
- **Builds only, not workspaces.** `GetWorkspaces` doesn't return the
latest build's parameters, so a workspace field would cost another
query. The collector can join on `workspace_id`.
- **Provider comes from parameter names only.**
`agent_relay_claude_code_*` means Claude Code and `agent_relay_cursor_*`
means Cursor. A build with both reports `ambiguous`; a build with
neither reports `unknown`. coderd stores every declared parameter on
every build (ephemeral ones with their default), so a Claude Code start
after a stop still reports `claude_code`.
- **Start builds only.** Stop and delete builds of a relay workspace
carry the same parameters but are not dispatches, so the snapshot skips
them before querying parameters.
- **Hash session ID and pool.** Pool names are user content, and
sessions only need counting.
- **Known gaps.** Cursor has no client platform. Relay version and
health would need relay registration.
- **Parameter names are shared with coder/agent-relay.** If agent-relay
renames one, telemetry silently stops reading it.

</details>

<details>
<summary>Manual test on <code>develop.sh</code></summary>

Ran on `8ad7cd491f` with `CODER_TELEMETRY_ENABLE=true
CODER_TELEMETRY_URL=http://127.0.0.1:8081` and `go run
./scripts/telemetry-server --port 8081` as the collector.

Pushed three templates with no infrastructure, each declaring the same
parameters as the real modules:

- `relay-claude`: `agent_relay_session_id`, `_delivery_id`, `_pool`,
`_client_platform`, plus ephemeral `agent_relay_attempt` and
`agent_relay_claude_code_lock_to_account`
- `relay-cursor`: `agent_relay_session_id`, `_delivery_id`, `_pool`,
`agent_relay_cursor_pool_name`, `_idle_release_timeout`, `_repo_url`
- `relay-plain`: `region`

Created workspaces with `POST /api/v2/users/me/workspaces` and
`rich_parameter_values`, the same call the relay makes. Then ran stop
and start builds on the relay workspaces, and restarted coderd to get a
periodic snapshot.

| Workspace | Build 1 (create event and snapshot) | Builds 2 and 3
(stop, start) |
|---|---|---|
| Claude (`claude_in_slack`, attempt 1) | `claude_code`, platform,
attempt 1 | `claude_code`, platform, no attempt |
| Cursor | `cursor` | `cursor` |
| Plain | field omitted | n/a |
| Claude template, no session ID | field omitted | n/a |

- Stop and start builds keep `agent_relay_claude_code_lock_to_account`,
with an empty value, so Claude Code rebuilds still report `claude_code`.
- No session ID, pool name, or `region` value appears in the captured
telemetry. The hashes match `sha256` of the inputs.
- Fed the captured snapshot through the conversion code in
coder/coder-telemetry-server#56: all 8 builds converted, 6 of them with
`agent_relay` set.
- No telemetry errors or panics in the coderd logs.

This run predates the start-only change: build 2 (stop) carried the
field then. Stop and delete builds are now omitted, which
`TestTelemetry_WorkspaceBuildAgentRelay` covers.

</details>


---

*Generated by Coder Agents on behalf of @Emyrk.*
2026-11-03 15:48:10 -06:00
Mathias Fredriksson c0f7663e95 feat: support editing queued chat messages (#29215)
The owner of a chat can edit a queued message through
`PATCH /api/v2/chats/{chat}/queue/{queuedMessage}`. chatd never sends
a row under edit (`editing_since`): rows ahead of it still send in
order, and a turn that ends at it puts the chat in the new `paused`
status. Ending the head's edit, deleting it, or promoting a queued row
continues the chat. Interrupting sends still run ahead of the queue.

The chat state machine classifies a queue whose head is under edit as
its own sub-state (R1P, I1P, A1P, E1P, XE1P, P), so every path to
`paused` is in the transition matrix. A chat whose family has a paused
member cannot be archived, and auto-archive skips that family. Queue
edit and delete are owner-only, because both can send the next message
with the owner's credentials.

`ChatQueuedMessage` gains `editing_since` and `reasoning_effort`, and
`ChatStatus` gains `paused`.

Closes CODAGT-1028
Refs CODAGT-971
2026-10-30 15:52:22 +02:00
Michael Suchacz d1f308d9f3 feat: let organization members turn off organization skills in chats (#31134)
## Stack

Organization skills load into every member's Coder Agents chats in their
organization, with no way for a member to opt out. This stack adds a
per-organization setting that lets members turn them off for their own
chats, bottom to top:

1. **#31134** data model, API, and chatd (this PR)
2. #31135 admin and member controls in the dashboard, the `/` menu, and
docs

## What changes

Organizations get `members_can_disable_skills`, off by default. Users
who can update organization skills change it with `PUT
/api/experimental/organizations/{organization}/skill-settings`, which
writes an organization audit entry. Anyone who can read the organization
can `GET` it.

While the setting is on, each member saves their own choices with `PATCH
/api/experimental/organizations/{organization}/members/{user}/skill-preferences`:
`all_skills_disabled` (a master switch that also covers skills created
later) and `skills`, a sparse map from skill ID to on or off. `GET`
returns the setting, the master switch, and `disabled_skill_ids`. The
routes follow the personal-settings rules: without `read_personal` or
`update_personal` on that user the caller gets 404, a PATCH while the
setting is off gets 403, and a key that is not an organization skill
that member can read gets a 400 that names the key. The check runs as
the member, not the caller, so an owner or user admin editing someone
else's choices is held to that member's skills. Turning the setting off
keeps the choices but ignores them.

Migration 000636 adds the column and two tables keyed by organization
membership. Both cascade when the membership goes away, and the
per-skill table also cascades when the skill is deleted, so a recreated
skill loads by default.

chatd reads the preferences as the chat owner when it builds the skill
index and when it loads a body for `read_skill` or for a structured
skill invocation (#30861). A skill the member turned off is left out of
the index, and both loads report it as not found, including later in a
running chat. If the preferences cannot be read, turn preparation fails,
as it already does when the skill metadata cannot be read.

Older migration tests created organizations with `dbgen.Organization`
and `GetDefaultOrganization`, which now select the new column before it
exists, so they insert organizations with raw SQL instead.

## Review focus

- Authorization in `coderd/organizationskillpreferences.go` and the five
new dbauthz methods (`read_personal` and `update_personal` on the user,
`organization_skill` update for the setting).
- `GetOrganizationSkillMemberPreferencesRow.Excludes` is the one rule
chatd applies; #31135 mirrors it in `activeOrganizationSkills`.

## Testing

- Go tests cover the queries and cascades, dbauthz, both routes
(including the audit diff and each 400 case), and chatd (index,
`read_skill`, skill invocations, master switch, a change during a chat).
Each new test fails with its code path removed.
- Remote dogfood UAT (10 scenarios, real model) passed on the pre-split
branch head `186c28d81ab`, which has the same code except the fix below.
It found one issue: two spellings of one skill ID with opposite values
stored a random result. The PATCH now rejects every aliased key with a
400. A second run on the stack's top head at the time, `718dd6d1bd1`,
passed: every aliased form returns 400 and stores nothing, and chats
leave out a skill the member turned off, including in `read_skill`.
- Polish and the test audit stayed inside the implementation diff. No
new dependencies.
- Rebased on main as one commit. The migration is now 000636, after
main's 000634 and 000635. Every organization skill load passes the chat
owner, including main's skill invocation path, so `/skill` invocations
honor the opt-out too. The model's skill index leaves out a skill that
is not model-invocable or that the member turned off. Apart from that,
the diff is unchanged.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-29 12:53:50 +00:00
Michael Suchacz 3697bb38ce feat!: choose the computer use model per organization (#31300)
> [!NOTE]
> Xum opened this PR for Mike (Coder agent). Mike reviews it before
merge.

Fixes CODAGT-1472.

Computer use now runs on a chat model that each organization picks.
Before, it ran a fixed model on the first enabled AI provider of a
deployment-wide provider type, sorted by name. On dogfood that
provider's key is rejected, so every computer use subagent failed.

## What changed

- **Setting.** A new `computer_use` organization model override, set in
the **Computer use** row of **Organization settings** on the Coder
Agents admin page. Without an override, computer use runs on the
organization's default model. If the chosen model is disabled, deleted,
or unusable for the chat owner, computer use falls back to the default
model, as other overrides do. It also falls back when the chosen model
moves to an AI provider that is not Anthropic or OpenAI, and the row
then says that the saved model is ignored.
- **API.** `PUT
/api/v2/organizations/{organization}/chats/model-overrides/computer_use`
returns 404 while the `chat-virtual-desktop` experiment is off, and 400
unless the model's AI provider type is Anthropic or OpenAI.
- **chatd.** The `computer_use` subagent runs on that model, and the
computer tool flavor follows the model's provider type. OpenAI computer
use always uses the Responses API, so a model that sets
`use_responses_api: false` gets a configuration error. When no usable
model exists, `computer_use` is unavailable, and the reason says whether
a saved computer use model was skipped and why the default model cannot
be used. The default model is read under the chat owner's model ACLs, as
chat turns do.
- **UI.** The row lists only enabled Anthropic and OpenAI models. A
warning icon with the tooltip "Make sure that the selected model
supports computer use." appears when the model in effect (the selected
one, or the default) is not on a curated list of canonical model IDs
known to accept the computer tool (`knownComputerUseModels` in
`knownModels/catalog.ts`, exact match only). It also appears when the
model's AI provider type is OpenAI and its **Use Responses API**
override is Off, because OpenAI computer use needs the Responses API.
The warning does not block saving. I built the list from a live probe on
2026-10-26 that sent each Anthropic and OpenAI model one request with
the computer tool.
- **Docs.** `virtual-desktop.md`, `models.md`, `organizations.md`, and
`architecture.md` describe the new setting, and chatd's
`ARCHITECTURE.md` describes the computer use model routing.

![The Computer use row with an uncurated model selected shows the
warning icon and its
tooltip](https://github.com/user-attachments/assets/3948d936-5d8f-4ff9-a6de-14094c154dc8)

![The Computer use model picker lists only Anthropic and OpenAI
models](https://github.com/user-attachments/assets/913cd4a0-3cdf-4e5d-b2f9-582b9fca999c)

## Breaking change

This removes the deployment-wide computer use provider setting
(`agents_computer_use_provider`), its experimental `GET`/`PUT
/api/experimental/chats/config/computer-use-provider` endpoints (shipped
since v2.35), the Virtual desktop settings card, and its audit field.
Migration 000635 deletes the stored value. After the upgrade, computer
use runs on each organization's default model until an admin picks a
computer use model. Computer use subagents created before the upgrade
keep the model they inherited from their parent chat, so a follow-up
message to one of them can fail; a new computer use subagent uses the
organization's computer use model. Telemetry now reports the
per-organization overrides instead of the provider, and `null` when it
cannot read them.

## Testing

- `make pre-commit` passes. `go test` passes for `./coderd/x/chatd/...`,
`./coderd/database/migrations/`, and the targeted coderd, telemetry,
dbauthz, enterprise audit, and codersdk tests. Vitest and the touched
Storybook stories pass.
- Each new Go test fails when its target behavior is removed from
production code.
- Remote dogfood UAT ran on an isolated Coder instance built from the PR
head, with real Anthropic and OpenAI models:
- 110234e: the row with the experiment on and off, the picker, the
warning icon cases, save and clear, the 400 for other provider types,
which model and computer tool each computer use subagent used
(Anthropic, OpenAI, default, and disabled override), a real desktop
session on an Anthropic and an OpenAI model, the unavailable reasons,
the upgrade through migration 000634, and the removed endpoints.
- 09ce818: an override whose model moved to an unsupported AI provider.
- 7925be9: the alert for a moved and a disabled override, and a computer
use subagent on an Anthropic model.
- 2a01eaf: the row, and computer use subagents on the override and on
the default model.
- 47f5bd1: the warning icon for an OpenAI model with **Use Responses
API** set to Off, On, and Default. With Off, a computer use subagent on
that model fails with a configuration error before any provider request.
With Default, it runs with the computer tool through the Responses API.
- 81d33b4: the unavailable reasons for a disabled override, a cleared
override, and missing credentials, and a computer use subagent on an
Anthropic override. This round found that the docs named the wrong
section of the model form for **Use Responses API**. aeb3d02 fixes that
step, and a re-read of the docs against the recorded UI passed.
2026-10-29 13:00:05 +01:00
Sas Swart eb38759fda feat: limit effective group resolution to an organization (#31119)
AI budget resolution searches all of a user's groups across every
organization. Whichever group wins determines the organization. #31120
needs to resolve inside a known organization, and it needs to know which
organization site-wide resolution picked.

Add an `organizationID uuid.NullUUID` argument to
`budget.ResolveUserAIBudget` and `budget.ResolveUserEffectiveGroup`.
When it is set, count only that organization's override, group budgets
and Everyone group. An organization that is unknown, deleted or that the
user is not a member of resolves to nothing. When it is null, resolve
exactly as before. Return the winning group's organization in
`budget.EffectiveGroup.OrganizationID`.

Read the override through a new resolution-only query,
`GetUserAIBudgetOverrideWithOrganization`, so that the CRUD query
`GetUserAIBudgetOverride` and the admin endpoints stay untouched. Add a
nullable `organization_id` filter to `GetHighestGroupAIBudgetByUser` and
`GetUserEveryoneFallbackGroup`.

Every caller passes null, so behaviour is unchanged. There is no
migration and no proto change.

Scoping to an organization can lift a limit: a user capped in org B has
no limit in org A if A has no budgets. AIGOV-711 intends this, and it
takes effect in #31120.

Part of AIGOV-715.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-29 12:14:34 +02:00
Hugo Dutka 1a9d5b28ba fix: keep ACP harness context synchronized (#31351)
ACP harness resources bypass context drift detection, but only MCP
resources were live-synced into bound chats. Later ACP discoveries,
capability updates, probe errors, and removals could therefore leave
chat context stale without offering a refresh. Extend the existing
live-sync query to include ACP harnesses and publish context updates for
affected chats while keeping instructions and skills pinned.

Depends on #31350. This PR contains the ongoing synchronization change;
#31350 fixes initial probe ordering.
2026-10-27 18:28:16 +00:00
Michael Suchacz 3f055e7a56 feat: list every chat attachment in the Summary panel (#31140)
In long chats, the Summary panel's **Attachments** section only listed
agent files from the messages already loaded in the transcript. It
showed "No attachments in the loaded messages." and a **Load earlier
messages** button, so finding a chat's files meant paging through its
history.

## What changes

- **API:** `GET /api/v2/chats/{chat}/attachments` returns every file
part in the chat's user-visible user and assistant messages, newest
first, as `{message_id, part_index, role, file}`, where `role` is `user`
or `assistant`. An optional `before_id` limits it to older messages.
Parts go through the same conversion as `GET /messages`, so `part_index`
matches that endpoint. `file` is a `ChatAttachmentFile`, a file-only
type, so the OpenAPI schema, the API reference, and the generated
TypeScript all describe a file part. An inline file omits `file_id` and
carries its bytes in `data` as a base64 string. It needs the same
permission as reading the chat. A new sqlc query,
`GetChatMessagesWithFilePartsByChatID`, backs it; there is no migration.
- **Panel:** attachments from the loaded messages stay live. While older
history is not loaded, the panel fetches the attachments before the
oldest loaded message and lists them with the rest. It sends no request
when every message is loaded or the Summary tab is hidden. Loading
earlier transcript pages reuses the list it already fetched instead of
sending another request, and does not blank, duplicate, or reorder it,
including while the last page moves into the chat store.
- **Groups:** files the agent attached are listed under "From the
agent", then uploads and pasted text under "From you".
- **Cards:** selecting a card previews the file. Images open in the
image lightbox and show their thumbnail on the card. Text, Markdown,
CSV, and JSON files open in the text preview, which opens at once with a
spinner while a stored file's text loads on its first view, and reuses
the text until the cache frees it, five minutes after nothing on the
page reads it. An icon on the card downloads the file. Other files keep
the download card. Closing a preview returns focus to its card, and an
image whose thumbnail fails to load becomes a download card that takes
focus, even if its preview was open.
- **Dialogs:** `Lightbox` now passes Radix's close event to
`onCloseAutoFocus` instead of always calling `preventDefault`, so a card
hands it to `useDialogFocusReturn().restoreFocus`, which prevents the
default only when it can focus a target. `MermaidDiagram`, the only
other caller that passes the prop, now calls `preventDefault` itself, so
its focus return is unchanged. `ImageLightbox` and `TextPreviewDialog`
take the same optional prop.
- **Transcript focus:** closing the preview of an attachment in the
transcript (the image lightbox or the text preview) or of a tool result
image returns keyboard focus to the attachment that opened it instead of
the page body. Each attachment button passes itself to the opener,
because a stored text file opens its preview only after its download
finishes, when the click event no longer holds the button.
- **States:** the header count shows once the list is complete and
leaves out expired files. An empty list says "No attachments yet." While
the earlier request is pending, the loaded attachments stay, with a
spinner below them. If the request fails, they stay and the section
shows the server's error in an alert with Retry, which stays while the
retry runs or waits offline. The load-earlier button is gone.
- **Expired files:** files the chat no longer has fold into a closed "N
expired attachments" list that names each one and explains why files
expire. A file from unloaded history counts as expired when the chat's
file list no longer has it. If the cached chat record is older than
those messages (a revisit after more than a page of new messages), a new
file can show as expired until the chat refetch returns. A stored text
file whose preview finds it deleted stays in place as "Attachment
expired", keeps focus, and leaves the count.

| Cards grouped by who attached them | Earlier attachments in the
Summary panel | Expired files, listed by name |
| --- | --- | --- |
| ![Agent files under From the agent and an upload under From you, with
an image thumbnail and a download icon on each
card](https://github.com/user-attachments/assets/02683b78-5547-409e-ad02-d9a28eb8787c)
| ![Summary panel listing a file from a loaded message and two files
from messages that are not
loaded](https://github.com/user-attachments/assets/5e8c8916-a5ff-4af4-be62-1048ff557461)
| ![Opened 3 expired attachments list naming each expired file under an
explanation of why files
expire](https://github.com/user-attachments/assets/88ba6b37-4fc6-489e-9347-28b4b7dbe79f)
|

| Text file found deleted | Earlier request failed | Image preview |
| --- | --- | --- |
| ![PLAN.md card in place with a warning tile and Attachment expired,
and the header count down to
5](https://github.com/user-attachments/assets/7005bf19-f889-46a6-9e2a-78daa6c3be0c)
| ![A loaded attachment still listed above an alert with the server's
error and a Retry
button](https://github.com/user-attachments/assets/0348c762-5042-4b1d-97bc-64328334f4b0)
| ![Image lightbox open over the panel after selecting the image
card](https://github.com/user-attachments/assets/4af74d45-b1fc-4f2f-a275-0eb0c00da977)
|

Closes CODAGT-1436.

## Testing

`TestGetChatAttachments` checks the order and the filtering (deleted,
model-only, and tool messages are left out, and `part_index` skips a
stripped hook-context part as `GET /messages` does), compares every
returned file with its part from `GET /messages`, including an inline
paste's `data`, and covers `before_id`, a 400 for an invalid
`before_id`, a 404 for another user, and the raw JSON of an inline file,
which has no `file_id` key and a base64 `data` string. The dbauthz suite
asserts chat read. Vitest covers the panel's request gating and Retry,
seeding an earlier boundary from a cached list, the attachment helpers
(including earlier files the chat no longer lists), and the cards'
previews (including a text preview that opens before its text loads),
download link (including the share sheet it opens in an installed iOS
app), and focus, including a thumbnail that fails to load, also with its
preview open, and a text file that returns 404, and that a viewed text
file's text leaves the cache once nothing shows it. Vitest also opens a
transcript image, an inline text file, a stored text file whose download
finishes after focus has moved on, and a tool result image with Enter,
closes each with Escape, and checks that focus is back on the
attachment. Stories cover the new states, including a retry in flight, a
retry paused offline, and a reconnect after a failed retry. Two existing
stories now import the shared 1x1 PNG fixture instead of keeping their
own copies. Each new test fails when its code path is broken. No new
dependencies.

## Review record

- mafredri's review: grouping by role, the expired list, and keeping the
loaded attachments visible while the earlier request loads are in
`5cf0757b1d8`. The previews and the download icon that @ibetitsmike
asked for in the same round are in `6ae8719d6a0`.
- Frontend review (8 reviewer roles): 4 rounds before the first UAT, 3
delta rounds on the Codex fixes, then 12 rounds on mafredri's review and
the preview cards, with an FE1 to FE10 audit in rounds 2 to 10 (rounds
11 and 12 re-checked comments only), then 3 delta rounds on the
download-link test in `868d42430f0`, 4 on the fixes for Codex's fifth
run, 1 on its sixth, 7 on its seventh, and 4 on its eighth. The last of
those four passed every role it ran, and so did its FE1 to FE10 audit.
Every blocking and should-fix finding is fixed or declined with a
reason. Declined: the alert's title is an h2 under the section's h3,
because the shared `AlertTitle` always renders an h2, as in every
`ErrorAlert`; Retry does not move focus after a successful retry removes
it, which matches the other `RetryButton` callers and would need a focus
effect; the endpoint and panel ship together because the panel is the
endpoint's only consumer; a chat record without `files` is not read as
an empty file list, because the server also omits `files` when its
best-effort metadata query fails, which would show every earlier file as
expired; the header count does not subtract a deleted image or an
unopened text file, because the panel learns of a deletion only from the
chat record or a preview's 404; a card whose file a chat refetch reports
deleted moves into the expired list, which closes its open preview, as
the transcript swaps an evicted file's card for the expired tile; if the
transcript's last page arrives while the earlier request is still
loading, the header count briefly leaves out that page's files, because
only a rerender test reading the header could hold a fix, which FE1
keeps out of Vitest; a text file found deleted counts again once the
cache frees its 404, five minutes after nothing on the page reads it,
because keeping that 404 until reload would need a cache entry per
deleted file that is never freed, and the transcript on `main` forgets
the same 404 as soon as the chat closes; and AttachmentBlocks.tsx is at
719 lines (699 on `main`), because moving its file cards out would
create an import cycle.
- Remote dogfood UAT passed on `c1af9dd7cbc` and again on `d11c699cd0d`.
The second round ran `d11c699cd0d` and the `c1af9dd7cbc` frontend
against the same backend: an evicted earlier upload shows as expired on
`d11c699cd0d` and as a download card that returns 404 on `c1af9dd7cbc`,
and loading earlier pages sends no further attachments requests on
`d11c699cd0d`, while `c1af9dd7cbc` sent one per new page boundary. One
issue also reproduces on `main` and is unchanged here: after a live
attach evicts an older file, the panel and the transcript keep its
download card until the page reloads. The changes since `66e92f09064`
(mafredri's review, the preview cards, and the fixes for Codex's third
to eighth runs) were checked in Storybook and Vitest, and on dogfood
only through the keyboard round below, which also opened the Summary
panel's image and text cards; the screenshots above are Storybook
renders.
- Codex review: round 1 raised 4 findings, all fixed (see the resolved
threads). Round 2 found no issues on `d11c699cd0d`. A third run on
`d11c699cd0d` raised 2 findings, both fixed in `db0109d1120`. A fourth
run on `6ae8719d6a0` raised 1 finding (the download-link test read only
the link's attributes), fixed in `868d42430f0`. A fifth run on
`868d42430f0` raised 4 findings. Three are fixed in `e924d0595d9`: an
open image preview lost focus when its thumbnail failed, a slow text
load let a second preview open, and the earlier attachments dropped for
a render when the last page loaded. The fourth (paginate or cap the
endpoint) is left open for a product decision. A sixth run on
`e924d0595d9` raised 1 finding (the expired list's button did not say
what expired), fixed in `661db9b52af`. A seventh run on `661db9b52af`
raised 4 findings, all fixed: an inline file's `file_id` came back as
`null` and the schema described `data` as integers (`5fb4a047e39`), and
viewed text stayed cached until reload and the card's doc comment
restated its code (`51c5c98feb8`). An eighth run on `51c5c98feb8` raised
3 findings. Two are fixed: the attachment role allowed `system` and
`tool` (`2ed84cd882f`), and the error line hid the server's message
(`ce4e79593f6`). The third, that Testing Library cannot find the
decorative thumbnail by its `img` role, does not reproduce and is
declined in its thread.
- @jaaydenh's approval note, that keyboard focus was lost after closing
the preview of an attachment in the transcript, is fixed in
`b37b9952898` and `484e010dd25`; `359dd039b78`, `277b89ba1e2` and
`606b601c445` only refactor the hook, tighten the tests, and reword a
comment. Frontend review ran 5 rounds on the fix; the last passed, and
every blocking and should-fix finding is fixed or declined. Declined:
the composer's pending-attachment previews, the recording preview, and
the Instructions page's text preview also drop focus when they close,
but they predate this PR and are outside the transcript, so they are a
follow-up; if a stored text file finishes downloading while the same
message's image preview is open, closing the image returns focus to the
text file, because a message row remembers one opener, so focus still
stays in that message; and the fix grows ConversationTimeline.tsx from
812 to 827 lines, which was already over the 500-line guideline. Remote
dogfood UAT passed on `484e010dd25` with real key presses: after Enter
or Space opens the preview of a user's image, text file (also when its
download is slowed and the user presses Tab while it loads), or pasted
text, of an assistant's attachments, of one of three attachments in one
message, or of a tool result image, Escape returns focus to the same
attachment, so Tab continues from there. On `bac7cb055ce` focus fell to
the page body and the next Tab went to the Coder logo, so a keyboard
user needed 130 Tabs to get back to the composer instead of 44. Summary
panel cards returned focus before the fix and still do. The image,
slowed text file, and Summary panel cases passed again on `277b89ba1e2`;
`606b601c445` changes only a comment.
- Rebased onto `main` after those reviews. The added and removed lines
are unchanged; only the path of `AgentChatPageView.tsx` changed, because
`main` moved it into `AgentChatPage/`. After the eighth Codex run,
`main` was merged in, with one conflict in `coderd/chat_routes.go`,
where both sides added a route. On 2026-10-26 the branch was rebased
onto `main` (`aa9b0a950ad`) again, with conflicts in the same route list
and in the generated `site/src/api/typesGenerated.ts`, where both sides
added a type; the added and removed lines are unchanged.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 03:13:52 +01:00
Sas Swart 837c2e1af1 feat(coderd): price token usage with organization prices (#30719)
Prices token usage by the most specific match: the organization's price
for the configured provider, then a site-wide custom price, then the
price book. The requested model is still preferred over the model the
provider reports.

- `GetAIModelPriceForProvider` replaces
`GetAIModelPriceByProviderModel`, which is removed. It is one `UNION
ALL` of primary-key lookups, ordered by requested model first, then by
specificity. dbauthz checks `ResourceAiModelPrice`, scoped to the org
when one is given.
- `coderd/aibridge/prices` tests read seeded prices through
`GetAIModelPrices`.

Interceptions don't carry an organization yet, so
`resolveTokenUsageCost` passes none and only site-wide prices apply at
runtime for now (AIGOV-716). Org matching is covered by database tests
with explicit org IDs. For the same reason, the unpriced-models report
still counts only site-wide prices.

**Used later:** prices set through the API in #30720 take effect here
once interceptions carry an organization.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-22 15:13:24 +00:00
Sas Swart da78c88100 feat(coderd): add queries for organization AI model prices (#30718)
Adds the store queries for organization AI model prices in
`ai_model_configs`, with authorization. They cover basic CRUD on one
price, keyed by `(organization_id, provider_id, model)`.

- `GetOrganizationAIProviderModelPrice` reads one price.
- `UpsertOrganizationAIProviderModelPrice` sets one price, with typed
params. It rewrites an existing row only when a price differs, so
`updated_at` records the last change.
- `DeleteOrganizationAIProviderModelPrice` soft deletes one price. Reads
and upserts only match live rows, so setting a price after a delete
inserts a new live row.

All three authorize against `ResourceAiModelPrice.InOrg(org)`. The new
`AiModelPriceInOrg` case in `TestRolePermissions` pins that only owners
and org admins pass. A TODO in dbauthz notes that this should become a
resource for AI Governance model config.

Each query has its own test. The upsert tests cover that identical
prices leave `updated_at` unchanged, that changed prices advance it, and
that an empty model is rejected.

**Used later:** #30719 seeds its lookup tests with the upsert. #30720
serves all three through the org price API.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-22 13:58:42 +00:00
Michael Suchacz 8b6f209e8f refactor: delete the FinalizeStaleChatDebugRows query (#30995)
Deletes the `FinalizeStaleChatDebugRows` query. #30989 deleted
`chatdebug.Service.FinalizeStale`, its only caller. This is the last of
three PRs that delete the stale debug-run sweep.

- Deletes the query from `chatdebug.sql` and regenerates the querier,
dbmock and dbmetrics code. `make gen/db` leaves the dbmetrics wrapper of
a deleted query behind, so I removed it by hand.
- Deletes the dbauthz wrapper and its `TestMethodTestSuite` case, and
`TestFinalizeStaleChatDebugRows` from `querier_test.go`.
- The `codersdk.ChatDebugStatus` comment no longer names the query.

**Why it is safe:** nothing calls the query after #30989. #30988
explains why no reader of the debug `updated_at` columns needs the sweep
and why dbpurge cannot delete a live run.

**Review focus:** the partial indexes `idx_chat_debug_runs_stale` and
`idx_chat_debug_steps_stale` from migration 000468 served only this
query. They stay in this PR; #31009, at the top of this stack, drops
them in a migration.

Validation: `make gen/db` and `go build ./...`. `go test -count=1`
passes for `./coderd/database/dbauthz/ -run TestMethodTestSuite`,
`./coderd/database/ -run ChatDebug`, `./codersdk/` and
`./coderd/database/dbpurge/`. The pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. #30988 Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. This PR: Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. #30934 Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. #30981 Share one finalize-once lifecycle between the stream wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. #31010 Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 21:10:40 +00:00
Michael Suchacz 2397f3953a refactor(coderd): delete the chat debug run and step heartbeats (#30988)
Deletes the chat debug heartbeats. Model calls and streams started a
goroutine that touched the step and its run on a ticker, and runner
debug turns started a second one that touched the run. Both existed so
that `FinalizeStale` would not mark a live run as interrupted, but
nothing in production calls `FinalizeStale` since #26270. Mike chose to
delete the stale sweep as dead code. This PR is the first of three that
do it.

- `chatdebug/model.go`: `Generate`, `GenerateObject` and both stream
wrappers no longer start `launchHeartbeat`.
- `active_turn_debug.go`: the runner debug turn no longer starts
`LaunchRunHeartbeat`.
- `chatdebug/service.go`: deletes `TouchStep`, `TouchRun`,
`LaunchRunHeartbeat`, `heartbeatInterval`, and the channel that
`SetStaleAfter` closed to wake the heartbeats. The `WithClock` doc no
longer names the heartbeat tickers.
- Deletes the `TouchChatDebugStepAndRun` and
`TouchChatDebugRunUpdatedAt` queries with their dbauthz wrappers and
tests, and `TestLaunchHeartbeat`. `TestFinalizeStaleChatDebugRows` now
backdates its run with `UpdateChatDebugRun` instead of the deleted
test-only query.

**Why it is safe:** the heartbeats wrote only `updated_at` on
`chat_debug_runs` and `chat_debug_steps`. These read it:

| Reader | Why it does not need the heartbeat |
|---|---|
| `FinalizeStaleChatDebugRows` and the partial indexes
`idx_chat_debug_runs_stale` and `idx_chat_debug_steps_stale` | No
production caller. The next two PRs delete the query, and #31009 drops
the indexes in a migration. |
| `DeleteOldChatDebugRuns` (dbpurge) | See the next paragraph. |
| `DebugPanel.tsx` run sort | Sorts by `started_at \|\| updated_at`, and
`started_at` is `NOT NULL`, so it never falls back to `updated_at`. |
| Debug run and step API responses | Return `updated_at` as data.
Nothing uses it to decide whether a run is alive. |

dbpurge deletes runs whose `updated_at` is older than the debug
retention window, whatever their status, and their steps cascade. The
window is `agents_chat_debug_retention_days`: 30 days by default, and 0
turns the purge off, so dbpurge never deletes a run that was written in
the last day. A run's `updated_at` still moves when the run is created,
when each step is inserted (the `InsertChatDebugStep` CTE), and on every
run update and finalize. So dbpurge could only delete a live run if one
model call plus the tool calls after it ran for more than a day. The
runner finalizes its debug run when the runner context ends, a
`requires_action` wait times out after 5 minutes (the case `TouchRun`
covered), and chatloop aborts a stream that is silent for
`--chat-stream-silence-timeout`, 10 minutes by default (0 turns that
guard off).

Mike accepted the cost: a run or step orphaned by a crashed replica
stays `in_progress` until dbpurge deletes it. That is already true on
`main`, because nothing runs the sweep.

This does not touch the chat worker's `chat_heartbeats` loop that
ARCHITECTURE.md describes, and no ARCHITECTURE.md sentence about debug
runs becomes false.

**Review focus:** nothing uses `WithClock` after this PR, but deleting
it here would take this PR past 500 changed lines, so it goes with
`FinalizeStale` in the next PR.

Validation: `make gen/db`, `go build ./coderd/...`, and `golangci-lint
run` on the touched packages (0 issues). `go test -count=1` passes for
`./coderd/x/chatd/chatdebug/...`, `./coderd/database/dbauthz/ -run
TestMethodTestSuite`, `./coderd/database/ -run ChatDebug`,
`./coderd/x/chatd/ -run Debug` and `./coderd/database/dbpurge/`. The
pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. This PR: Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. #30995 Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. #30934 Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. #30981 Share one finalize-once lifecycle between the stream wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. #31010 Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 20:32:25 +00:00
Michael Suchacz 200fa7dea7 perf(coderd): bound the initial chat stream snapshot to the client cursor (#29761)
Opening a chat on the Agents page loads its transcript over REST and
then connects the chat stream with `after_id` set to the newest loaded
message. The first sync of the stream ignores that cursor when it
queries the database: it fetches every row of the chat on each
connection, and then sends only the rows above `after_id`.

The first sync now resolves `after_id` to that message's revision and
fetches only rows changed at or after it. The history reset rule is the
one on `main` (#29808): the stream resets only when message `after_id`
is deleted or missing. A deleted cursor still produces one
`history_reset` with the surviving history, because the bounded query
includes the cursor row. An unknown ID keeps the full query. A message
ID from another chat, live or deleted, is ignored, so the client
receives the full history. Live updates after the first sync are
unchanged.

## Performance

Measured on dogfood's database, which runs `main`, with `EXPLAIN
(ANALYZE, BUFFERS, SERIALIZE BINARY)` of the first-sync query. The chats
are the 554 chats updated in the past day, picked by row count. `main`
starts at revision 0. This PR starts at the revision of the newest live
message, which is the `after_id` the web client sends.

| Chat (rows) | `main` output | `main` first / repeat run | This PR
output | This PR time |
|---|---|---|---|---|
| p50 (41) | 189 kB | 21.5 ms / 0.6 ms | 1 kB | 0.1 ms |
| p90 (351) | 2.0 MB | 163 ms / 7.9 ms | 10 kB | 0.5 ms |
| p99 (2,200) | 7.1 MB | 425 ms / 25 ms | 14 kB | 3.0 ms |
| Largest (14,746) | 64.9 MB | 4.8 s / 193 ms | 6 kB | 17.6 ms |

- Across the 554 chats, the bounded query returns 1 row up to p99 and 5
rows at most.
- Both queries visit the same heap pages, because no index covers
`revision`. The saving is the TOAST reads, serialization, transfer, and
decoding of rows that `main` then discards. Most of `main`'s time is
serialization: 153 ms of 193 ms for the largest chat.
- The cursor lookup is one primary-key read of about 0.4 ms, so a median
chat gains almost no latency. The gain grows with chat size.
- Deleted rows are about 0.1% of rows, so they do not change the cost.

## Not changed

A tab whose stream was down can miss an edit, then send a message and
store the response, so its newest ID is above the edit. On reconnect,
message `after_id` is live and the stream sends no reset, so the tab
keeps the deleted messages. `main` has done the same since #29808, and
this PR does not change it (mafredri's reproduction gives `expected [5 6
7 8], actual [3 4 7 8]` on both). An ID cannot show which edits the
client applied. #29662 adds a client-reported version for that.

<details>
<summary>Delivery record</summary>

- Rebased on `main` at `6ebefb83254`, keeping the #29808 reset rule and
#30266 read-only snapshot reads. The cursor-bound mock test is part of
`TestStreamLoopInitialSyncTombstones`.
- Assumption checked on dogfood: no live message has a higher revision
than a later message. Messages are only updated to soft-delete them or
to set search columns, which the revision trigger ignores. 2,861 rows in
29 recently active chats break it, all created between 2026-06-26 and
2026-07-16 and none since. A client cursor cannot sit before them,
because the client sends its newest message.
- Local: `go test ./coderd/x/chatd/...`, `go test ./coderd -run
'^TestStreamChat$'`, `go test ./coderd/database/dbauthz -run
'^TestMethodTestSuite$'`. Mutants of the cursor bound (no `- 1`, no
bound, cursor from another chat kept) each fail `TestStreamLoop*`.
- Remote UAT before the rebase covered deleted, foreign, and unknown
cursors, edits, grouped commits, and reconnects. On a synthetic
5,000-message chat, dial to first snapshot went from 129.6 ms to 15.0
ms.
- Codex: [round
1](https://github.com/coder/coder/pull/29761#pullrequestreview-5284702021)
and [round
2](https://github.com/coder/coder/pull/29761#pullrequestreview-5284855535)
found cross-chat cursor bugs, fixed. Round 3 and the round on
`7bed7855e41` found nothing.

</details>

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-19 19:15:56 +02:00
Michael Suchacz 0968f97a43 feat: move a chat family between projects in chatd (#30893)
chatd can now move a root chat, together with its subagent chats, into a
project, to another project, or out of its project. Nothing calls this
yet. #30894 adds the API.

**Stack** (moving chats between projects, bottom first):
1. **This PR**: the move in chatd
2. #30894: `PATCH /api/v2/chats/{chat}` takes `project_id`
3. #30895: **Move to project** in the chat menu
4. #30795: drag a chat onto a project folder in the sidebar

**Why:** today a chat keeps the project it was created with. A move must
follow the family rules of archiving, because a step that runs during a
move would still have the memory tools of the old project.

- `chatstate.Tx.SetProject` runs only from W, E0 and E1, like
`SetArchived`. `SetFamilyProject()` locks the root row before its
subagents, in the same order as archiving, so a busy family gets
`ErrTransitionNotAllowed` and nothing changes.
- A move to the project the chat is already in changes nothing, even
while the chat runs. The check reads the locked root row, so it waits
for a move that is still in flight.
- Only the root row stores `project_id`, and subagents use the project
of the root. After the commit, chatd publishes a new `project_change`
watch event for each chat of the family. The move keeps `updated_at`, so
lists keep their order.
- A root chat outside a project now has an empty memory index. When a
chat leaves its project, or its project is deleted, its next turn start
commits one memory index update that removes the memories the model saw
there.

**What to scrutinize:** the lock order and the same-project check under
the lock in `SetFamilyProject()` (`chatstate/family.go`), the turn-start
condition in `memoryIndexMessage()` (`memory.go`), and whether the
`ARCHITECTURE.md` text matches them.

**Generated** (`make gen`): `queries.sql.go`, `querier.go`, `dbmock` and
`dbmetrics` come from `queries/chats.sql`. `coderd/apidoc`,
`docs/reference/api/schemas.md` and `typesGenerated.ts` come from the
new watch event kind, which is also why two `chats.test.ts` fixtures
gain `project_change: false`.

**Architecture doc:** `coderd/x/chatd/ARCHITECTURE.md` lists
`SetProject` among the transitions and in the execution state diagram
(W, E0 and E1 back to themselves). It also says that a root chat's
project can change after creation, and that a moved chat's next turn
starts with a memory index update from the old project to the new one.

## Testing

- `make pre-commit` passes. `go test` passes for
`coderd/x/chatd/chatstate`, `coderd/database/dbauthz`
(`TestMethodTestSuite`) and the chatd memory tests.
- `TestSetFamilyProjectLocksRootFirst` fails with 55P03 when a subagent
row is locked first. `TestSetFamilyProjectKeepsTheCurrentProject` covers
the same-project move during a run. The transition matrix test gains
`SetProject` cases for W, E0 and E1.
- `TestMovedChatUsesNewProject` runs two real turns around a move: the
second turn uses the instructions and memories of the new project, and
`OutOfProject` fails without the memory index removal.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-19 12:38:17 +00:00
Garrett Delfosse 6ebefb8325 feat: add chat project sharing API (#30439)
API for chat project sharing (experiment `chat-projects`). Builds on
#30479 (merged).

Owners share a project with users, groups, or the whole organization
(the Everyone group, ID = organization ID). Chats in a shared project
stay private.

| Role    | Project and instructions | Memories   | ACL  | Delete |
|---------|--------------------------|------------|------|--------|
| `use`   | read                     | read/write | read | no     |
| `admin` | read/write               | read/write | edit | no     |

Only the owner, and administrators whose role grants delete, can delete
a project.

- **API:** `GET`/`PATCH .../chats/projects/{project}/acl`, same shapes
as `/chats/{chat}/acl`, plus SDK methods. Project responses include the
caller's `permissions` (`update`, `delete`, `share`); the UI hides edit
and delete accordingly.
- **Listing:** `GET /chats/projects` returns owned and shared projects.
Removes `GetChatProjectsByOwnerID`.
- **Chat access:** creating a chat in a project, and loading its memory
and instructions on each turn, requires the chat owner to own the
project or have an ACL grant (`chatd.ChatProjectUsableBy`). Role grants
don't count. If the grant is removed, existing chats lose memory and
instructions on their next turn.
- **Validation:** users and groups must be in the project's
organization; keys must be canonical UUIDs; callers can't change their
own role; the owner can't be added. Migration `000624` drops a user's
grants when they leave the organization, so rejoining doesn't restore
access.
- **Instructions:** readers who can't edit get 403 instead of 404, and
the UI hides editing.
- **Agent prompt:** memories are visible to and editable by sharees, so
the agent is told not to save secrets or personal details.

Known gap: project deletion still detaches chats, and a sharee's open
sidebar keeps showing them until reload. #30683 replaces this.

Not included: share notifications, `/acl/available`, sharing UI.

<details>
<summary>Decision log</summary>

- `use` grants memory read/write over HTTP, because agents in a sharee's
chats can already write memories. Making the agent read-only for sharees
was the alternative (@f0ssel chose sharees changing memories through
use).
- An administrator with `share` can grant themselves access and then use
the project. Accepted to keep access control simple (@f0ssel).
</details>

> Generated by Coder Agents.
2026-10-19 11:32:26 +00:00
Jaayden Halko a379c849da feat: add project skill queries and authorization (#30826)
Adds the storage and authorization layer for chat project skills. The
`skills` table already allows a `project_id` owner (migration 000621);
this adds the queries for it and authorizes them through the parent chat
project, the same way project instructions work.

- New queries in `skills.sql`: insert, get by name, list metadata,
update (COALESCE on description, content and enabled), delete, and
`GetProjectSkillByIDForUpdate` for the shared update lock.
- dbauthz checks `chat_project:read` on the project for reads and
`chat_project:update` for writes. `authorizeChatProjectInstructions`
became `authorizeChatProjectConfig`, shared by instructions and skills.
`Skill.RBACObject()` still denies project rows so nothing reaches them
without going through the project.
- Audit: new `chat_project_skill` resource type (enum-only migration
000624), `AuditableChatProjectSkill`, and the usual
diff/request/table/FriendlyString/AuditFilter wiring. The API that emits
these entries comes in the next PR.

Stack (merge top to bottom):
- #30826 👈
- #30827
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882
- #30884
2026-10-18 12:58:39 +07:00
George K 6d34557d74 feat: add script ordering adoption telemetry (#30860)
Count `coder_script_order` declarations and literal `rule` blocks in
coderd from the existing START plan in
`CompletedJob.TemplateImport.Plan`,
including child modules, without multiplying counts by resource or
module instances. Persist these counts per template version on
successful import after START plan graph validation, without changing
the provisioner API.

Report a deployment-wide `script_order_summary` with the number of
templates using script ordering and total declaration and rule
counts. Include only active, successfully imported versions of
non-deleted templates so repeated imports do not inflate
adoption. Elect one reporting replica per snapshot period and report
explicit zeros when no templates use ordering.

The summary contains only aggregate counts, without template
identifiers or rule contents. Dynamic rule blocks are not counted
because Terraform omits them from configuration JSON.

Configuration-decoding failures are logged and skip updating the
counts without independently failing the import. Script-order summary
collection failures are logged and omit that summary while allowing
the rest of the snapshot to proceed.

Refs: https://linear.app/codercom/issue/PLAT-551
2026-10-15 15:42:33 -07:00
Steven Masley 03cba25a63 feat: list a workspace build's secrets in coder secret list (#30388)
`coder secret list` now shows the current workspace build's secrets next to your user secrets, and which user secrets they replace. Part of [RELAY-7](https://linear.app/codercom/issue/RELAY-7/agent-relay-deliver-provider-credentials-via-coder-secrets-instead-of).

**Stack** (design decisions in #30248)
1. #30248 Database schema, queries, and RBAC
2. #30249 Encryption at rest
3. #30250 Set secrets on workspace builds
4. #30251 Deliver secrets to the agent
5. #30252 Docs
6. **#30388 List a build's secrets (this PR)**
7. #30459 Audit a build's secrets

- New `GET /workspacebuilds/{workspacebuild}/secrets` lists a build's secrets (metadata only, never values) and which user secret each one replaces.
- Inside a workspace, `coder secret list` includes the current build's secrets. Outside a workspace, use `--workspace` or `--build-id`.
- The agent now exposes `CODER_WORKSPACE_BUILD_ID`, so the CLI knows which build it is running in.
- The agent manifest and the new endpoint use one shared resolver, so they always agree on which secret wins.
- The user secret API is unchanged.

<details>
<summary>Implementation details</summary>

- The manifest carries `workspace_build_id`; the agent sets it as `CODER_WORKSPACE_BUILD_ID`.
- `coderd/workspacesecrets.Resolve(user, build, policy)` decides which secret is delivered on each env var and file. The manifest no longer relies on entry order.
- `codersdk.WorkspaceSecret` embeds `UserSecret` and adds `workspace_build_id`, `ephemeral`, `cleared_at`, `env_replaces`, and `file_replaces`. Secrets whose values a later build cleared are still listed, with `cleared_at` set.
- CLI columns: `source` and `replaced by` are shown by default only when a build is included; `ephemeral` is opt-in. The CLI makes two requests: user secrets, then build secrets.
- Agents that predate the build ID fall back to `CODER_WORKSPACE_ID` and its latest build.

</details>

<details>
<summary>Decision log</summary>

(existing decision log, unchanged)

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 17:40:00 -05:00
Steven Masley 7aef110ca2 feat: add workspace secrets table, queries, and RBAC (#30248)
Adds the database table, queries, and permissions for workspace secrets: secrets set on a workspace build and delivered to the agent, never to Terraform. 

Each secret belongs to one workspace build. A new build copies the previous build's secrets, then the old copies lose their values but stay as history.
2026-10-15 13:32:40 -05:00
Garrett Delfosse 2b9fad8bba feat: add chat project sharing database layer (#30479)
Database and authorization layer for chat project sharing (experiment
`chat-projects`), part 1 of 2. #30439 adds the API on top of it. Nothing
here changes behavior: projects start with empty ACLs, no endpoint
writes them yet, and deleting a project still detaches its chats.
Project deletion is in #30683.

- **Schema:** migration `000621` adds `user_acl` and `group_acl` jsonb
columns to `chat_projects`, typed as `ChatACL` like chats, with GIN
indexes. It also adds the `chat_project:share` API key scope.
- **Queries:**
- `GetChatProjectsOwnedOrSharedWithUserID`: owned projects plus projects
with an ACL entry for the user directly, through a group, or through the
Everyone group (whose ID is the organization ID). Entries count only for
members of the project's organization. Keys match regardless of actions,
so dbauthz filters the rows.
- `IsChatProjectAccessibleByUserID`: whether a user owns a project or
holds a `read` or `*` grant on it, for code running under a system
subject. With sharing disabled, dbauthz answers owner-only.
- `GetChatProjectByIDForUpdate`: lets the ACL update read, modify, and
write in one transaction.
  - `UpdateChatProjectACLByID`.
- **RBAC:**
- New `share` action on `chat_project`. dbauthz requires it to update
the ACL.
- `ChatProject.RBACObject` attaches the project ACL. Memory objects get
a derived ACL: project `read` grants memory read, and `read` with
`update` grants memory create and delete. Wildcard grants count. Read
sharees change memories through their chats' agents, which #30439 gates.
Project instructions authorize through the same object, so a `read`
grant reads them and an `update` grant edits them.
- `--disable-chat-sharing` also covers projects: ACLs are ignored, the
ACL update is rejected, and roles deny `chat_project:share`. The help
text and chat sharing docs say so.
- **Audit:** `user_acl` and `group_acl` changes are tracked.
- **Tests:**
- Querier tests run the access queries both raw and through dbauthz
(owner, direct user, group, Everyone, wildcard grants, a member of
another org, grants without read).
- RBAC object and memory ACL tests, with an authorizer check, in both
sharing modes.
- dbauthz cases including the disabled guards, and the
`chat_project:share` negation in the roles test.

The generated TypeScript changes only add the new scope value.

> Generated by Coder Agents.
2026-10-14 10:42:00 -04:00
Michael Suchacz 2c432a12a3 feat: add organization skill sharing ACL routes (#30611)
## Stack

Part of
[CODAGT-1341](https://linear.app/codercom/issue/CODAGT-1341/support-organization-level-skills-in-coder-agents).
This stack adds organization skills to Coder Agents: admins publish a
skill once per organization, share it with groups or members, and chats
in that organization load it next to personal and workspace skills. It
replaces the 21-PR draft stack #30584 to #30604 with five PRs, bottom to
top:

1. #30609 data model: one migration, queries, RBAC and dbauthz
2. #30610 organization skill API routes and the scope-neutral SDK
3. **#30611** sharing ACL routes (this PR)
4. #30612 settings UI: shared skills table, admin page, member section
5. #30613 chats: chatd loading, `/` menu, docs

## What changes

This PR adds the routes that let admins choose who can read an
organization skill. It reuses the MCP server ACL machinery rather than
adding a second implementation.

Routes under
`/api/experimental/organizations/{organization}/skills/{skillName}`, all
behind `httpmw.ExtractOrganizationSkillParam` with `share`, so a caller
without share gets 404:

- `GET /acl` returns the resolved user and group grants.
- `GET /acl/available` returns the organization's users and groups that
can be granted, with the same `q`, `after_id`, `limit` and `offset`
paging as the MCP endpoint.
- `PATCH /acl` takes a sparse `UpdateOrganizationSkillACLRequest`: only
the listed principals change, `read` grants and `""` removes. It returns
204 and writes a `write` audit entry with the old and new ACL.

**Concurrency (please review closely):** the PATCH transaction first
locks the granted users' `organization_members` rows `FOR KEY SHARE`
(new query `LockOrganizationMembersByUserIDsForShare`, run as system),
then locks the skill row `FOR UPDATE`, then validates the update on the
transaction handle. Member removal takes the same locks in the same
order (its membership row, then the skill rows through the #30609
trigger), so the two can't deadlock, and a removal can't miss a grant
written by a concurrent PATCH. A skill deleted between the middleware
read and the row lock stays a 404.

Grants are users and groups, the same as MCP server configs (Mike's
decision, for parity). Only the `read` role exists; any other role is a
validation error, as are users or groups outside the organization.

Supporting changes:

- `coderd/mcp_acl.go`: the MCP ACL handlers' resolution, candidate
listing and validation move into generic helpers
(`writeOrganizationACLAvailable`, `validateOrganizationACLUpdate`,
`resolveACLUsers`, `resolveACLGroups`) shared by both resources;
`acl.Validate` accepts a named `acl.Role` constraint that now includes
`codersdk.OrganizationSkillRole`.
- `codersdk/skills.go`: `OrganizationSkillRole`, `OrganizationSkillACL`
with its user and group entries, `UpdateOrganizationSkillACLRequest`,
and client methods.
- New sqlc query `UpdateOrganizationSkillACLByID` with its dbauthz
wrapper (requires `share`).

## Commits

The first commit reproduces the reviewed code from the old stack; each
later commit is a labeled trim or fix.

- `b1c85560b69` feat: add organization skill sharing ACL routes.
Reproduction: every file this commit changes equals the reviewed old
`acl-routes` head `80c1c3594e6`; the rest of the tree differs only by
#30609's migration merge and main.
- `b5d2ee265c8` test(coderd): merge duplicate organization skill ACL
route tests (+49/-111). The removed cases repeated
`TestMCPServerConfigACL`, `TestMCPServerConfigACLAvailable` or
`TestRolePermissions`; with the MCP tests included, the covered block
set of `organizationskills_acl.go`, `mcp_acl.go` and
`rbac/acl/updatevalidator.go` is identical before and after. Kept:
`TestOrganizationSkillACL` (`OrgAdminManagesACL`, `ReadersGetNotFound`,
`SparseUpdateChangesReaders` with the audit diff,
`RejectsUnsupportedRole`, `ScopedAPIKeys`),
`TestOrganizationSkillACLConcurrentDelete`, and the lock order tests
`TestOrganizationSkillACLMemberRemoval` (`RemovalBeforeGrant`,
`RemovalAfterGrant`). `OrgAdminManagesACL` now also checks that users
from another organization are not candidates (mutation checked). Sharing
the param extractor with MCP was skipped: it would save about 10 lines
of security-sensitive code.
- `e09c4dba66b` Merge the updated org-api layer into sharing. Brings in
#30610's `ad0a7a37504`; the merge has no changes of its own.
- `1d3817dc639` and `c8c88f84d18` merge the updated #30610 layer,
including main; no changes of their own.
- `c4d22c47990` merges the updated #30610 layer (main at `e7b76872098`);
no changes of its own.

## Size

Production +431/-102, tests +377/-0, generated +918/-0; total
+1726/-102. This is above the 500-line reviewer-friendly limit on
purpose: Mike asked for 4 to 5 PRs instead of the 21 small ones this
stack replaces.

## Replaces

#30591 (ACL queries), #30592 (ACL routes).

## Validation

- `go build` and `go vet` passed; `make gen` exited 0 with no diff.
- `go test` passed for `coderd` (skill, MCP and ACL tests),
`coderd/database`, `dbauthz`, `migrations`, `gentest`,
`coderd/rbac/...`, `coderd/httpmw`, `coderd/x/skills/...`,
`coderd/x/chatd/...`, and the audit and skill tests in
`enterprise/audit` and `enterprise/coderd`.
- The covered block comparison above, before and after the test merge.
- On `c4d22c47990`: the same checks as #30610's head, plus `go test
./coderd/ -run 'Skill|MCP|ACL'`, pass.
- Remote UAT round 7 through Coder Agents passed on the whole stack; see
#30613's Validation for scope and findings.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 16:43:15 +00:00
Michael Suchacz db7f5a7703 feat: add organization skill API routes (#30610)
## Stack

Part of
[CODAGT-1341](https://linear.app/codercom/issue/CODAGT-1341/support-organization-level-skills-in-coder-agents).
This stack adds organization skills to Coder Agents: admins publish a
skill once per organization, share it with groups or members, and chats
in that organization load it next to personal and workspace skills. It
replaces the 21-PR draft stack #30584 to #30604 with five PRs, bottom to
top:

1. #30609 data model: one migration, queries, RBAC and dbauthz
2. **#30610** organization skill API routes and the scope-neutral SDK
(this PR)
3. #30611 sharing ACL routes
4. #30612 settings UI: shared skills table, admin page, member section
5. #30613 chats: chatd loading, `/` menu, docs

## What changes

This PR adds the organization skill CRUD routes and makes the skill SDK
types owner-neutral so personal and organization skills share them.

**API contract change (experimental API, personal and organization
skills):** skill list and get responses gain `enabled`, and `PATCH
.../skills/{skillName}` now takes `{content?, enabled?}`, so `content`
is optional and a toggle doesn't resend it. A PATCH with neither field
returns 400; `content`, when present, is validated as before. In the
SDK, `UserSkill`, `UserSkillMetadata`, `CreateUserSkillRequest` and
`UpdateUserSkillRequest` become `Skill`, `SkillMetadata`,
`CreateSkillRequest` and `UpdateSkillRequest` (`codersdk/userskills.go`
moves to `codersdk/skills.go`), and `UpdateSkillRequest.Content` is now
`*string`. The personal client method names are unchanged. The site
changes are the handwritten edits that rename forces (`api.ts`,
`queries/userSkills.ts`, `testHelpers/skills.ts` and three call sites),
with no UI change.

Organization routes under
`/api/experimental/organizations/{organization}/skills`, not gated by an
experiment or license, like the personal ones:

- `GET` lists with the caller's own permissions, so admins, the site
owner and org auditors see every skill and members see only skills
shared with them. `GET /{skillName}` goes through the new
`httpmw.ExtractOrganizationSkillParam` and admits only read, so a
missing skill and a denied one both return 404.
- `POST` checks `create` on the organization before reading the body,
then seeds `group_acl` with the Everyone group (whose ID is the
organization ID) so a new skill reaches every member until an admin
narrows it. The 100-skill cap and a duplicate name return 409.
- `PATCH` admits only callers who can read the skill, because its
response includes the content; `DELETE` admits callers who can read or
delete it. A reader who can't change the skill gets a write-specific 403
from the database wrapper, and everyone else gets 404. PATCH locks the
row as system, updates as the caller in the same transaction, and audits
the locked row only after the transaction commits.
- Audit: `database.AuditableOrganizationSkill` records resource type
`organization_skill` with the organization ID; personal skills keep
`user_skill`.

Personal and organization handlers share one create and update path in
`coderd/userskills.go` (`createSkill`, `updateSkill`, and a
`skillWriteErrors` table per owner and action).

## Commits

The first commit reproduces the reviewed code from the old stack; each
later commit is a labeled trim or fix.

- `49cb2c84276` feat: add organization skill API routes. Reproduction:
every file this commit changes, including the SDK layer's site edits,
equals the reviewed old `write-routes` head `aa597100f28`; the rest of
the tree differs only by #30609's migration merge and main.
- `dc893bc60d6` refactor(coderd): share the skill create and update path
across owners (production +164/-188). It keeps the organization create
check before the body read, the lock as system then update as caller
order, and audit assignment after the transaction. No swagger,
`codersdk` or `typesGenerated.ts` change; `make gen` is clean.
- `f94925425ef` test(coderd): merge duplicate personal and organization
skill tests. `TestSkillsCRUD`, `TestSkillValidationAndConflicts` and
`TestSkillAudit` are table-driven over Personal, OrgAdmin and SiteOwner,
alongside `TestOrganizationSkillAuditsDeniedWrites` and one
`ScopedAPIKeys` subtest; `TestPatchUserSkill` is deleted because none of
its blocks were unique. Coverage of `userskills.go`,
`organizationskills.go` and `httpmw/organizationskillparam.go` is 101 of
117 blocks before and after, the same block set.
- `ad0a7a37504` fix(coderd): require read access to patch an
organization skill. The organization PATCH route now admits only `read`,
because its response carries the skill's content: a key scoped to
`organization_skill:update` without read gets 404, like GET, instead of
200 with the content. Readers without update still get 403, and DELETE
is unchanged. `TestOrganizationSkillAccess/ScopedAPIKeys` asserts the
404, that the response has no content, and that the skill is unchanged;
against the old route it fails with 200.
- `69d00ded0b6` and `f67b79343ec` merge the updated #30609 layer,
including main; `69d00ded0b6` resolves a conflict in the personal skills
page with main. No other changes of their own.
- `18373ffd59e` merges the updated #30609 layer (main at `e7b76872098`)
and reapplies the `AuditableOrganizationSkill` entry in
`enterprise/audit/table.go` alongside main's new
`AuditableChatProjectInstructions` entries.

## Size

Production +838/-308, tests +733/-322, generated +801/-274; total
+2372/-904. This is above the 500-line reviewer-friendly limit on
purpose: Mike asked for 4 to 5 PRs instead of the 21 small ones this
stack replaces.

## Replaces

#30587 (scope-neutral SDK and personal enabled state), #30588 (read
routes), #30589 (write routes and audit).

## Validation

- The coverage comparison above, before and after the test merge.
- `make gen` leaves no diff after the shared create and update refactor.
- On `18373ffd59e`: `make gen` is clean; build, vet, the `coderd` and
`enterprise/coderd` skill tests, `rbac`, `httpmw`, `dbauthz` and
`enterprise/audit` pass; `pnpm check`, `pnpm lint` and `make pre-commit`
pass.
- Remote UAT round 7 through Coder Agents passed on the whole stack; see
#30613's Validation for scope and findings.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 16:24:45 +00:00
Michael Suchacz b67587c875 feat: add the organization skills data model (#30609)
## Stack

Part of
[CODAGT-1341](https://linear.app/codercom/issue/CODAGT-1341/support-organization-level-skills-in-coder-agents).
This stack adds organization skills to Coder Agents: admins publish a
skill once per organization, share it with groups or members, and chats
in that organization load it next to personal and workspace skills. It
replaces the 21-PR draft stack #30584 to #30604 with five PRs, bottom to
top:

1. **#30609** data model: one migration, queries, RBAC and dbauthz (this
PR)
2. #30610 organization skill API routes and the scope-neutral SDK
3. #30611 sharing ACL routes
4. #30612 settings UI: shared skills table, admin page, member section
5. #30613 chats: chatd loading, `/` menu, docs

## What changes

This PR adds the data model and authorization for organization skills.
Personal skills keep working unchanged: `git diff origin/main --
codersdk site` shows only generated RBAC and API key scope additions
(`apikey_scopes_gen.go`, `rbacresources_gen.go`,
`rbacresourcesGenerated.ts`, the RBAC and scope unions in
`typesGenerated.ts`) and `codersdk.ResourceTypeOrganizationSkill` with
its friendly string. No personal route, SDK type or site component
changes, and `coderd/userskills_test.go` changes only by mechanical
constant renames.

**One migration, `000621_skills`** (please review it closely):

- renames `user_skills` to `skills` with its constraints, index and
triggers, and recreates the cap function and
`delete_deleted_user_resources`, whose PL/pgSQL bodies name the table;
- adds `organization_id` and `project_id` (`ON DELETE CASCADE`),
`enabled` (default true), and `group_acl` / `user_acl` (`jsonb`, default
`{}`), with CHECKs for exactly one owner, ACLs that are JSON objects,
and ACLs that stay empty unless an organization owns the row, plus
partial unique name indexes per owner kind;
- replaces the cap trigger with `enforce_skills_per_owner_limit()`: 100
rows per owner, disabled rows included, locking the owner row `FOR NO
KEY UPDATE` so unrelated foreign key checks are not blocked;
- adds a `BEFORE DELETE` trigger on `organization_members` that removes
a departing member from `user_acl` on that organization's skills, so
rejoining doesn't restore a direct grant;
- adds the `organization_skill` `resource_type` and `api_key_scope` enum
values last; nothing in the migration uses them.

The down migration undoes the three old migrations in reverse order: it
drops organization and project rows and restores `user_skills`, its
names, the cap function and `user_id NOT NULL`.

Authorization: a new RBAC resource `organization_skill` (create, read,
update, delete, share). Owner and org admin get it; site and org
auditors get read; members read only through the skill's ACL, which
applies only to members of its organization. `Skill.RBACObject()`
returns the organization object with both ACLs; project rows stay denied
to everyone. New sqlc queries cover organization insert, get, list
(SQL-filtered through `GetAuthorizedOrganizationSkillMetadata` and a
`regosql` converter), update and delete, with dbauthz wrappers and the
audit table entries. No routes yet.

## Commits

The first commit reproduces the reviewed code from the old stack; each
later commit is a labeled trim or fix.

- `baa3150e3b7` feat: add the organization skills data model.
Reproduction: every non-site file this commit changes equals the
reviewed old `authz` head `1e16b3004c4`, except that the old stack's
migrations 000615, 000616 and 000617 are merged into one migration (then
`000615_skills`, now `000621_skills`) with one fixture
(`testdata/fixtures/000621_skills.up.sql`) and one migration test (now
`testMigration000621Skills`). At that commit, `dump.sql` was
byte-identical to the old head's.
- `1b84e83463a` test(coderd/database): keep only the SQL paths of the
org skill matrix. `TestOrganizationSkillAuthorization` becomes
`TestOrganizationSkillQueries` instead of being deleted, because
coverage showed it is this PR's only run of the
`GetAuthorizedOrganizationSkillMetadata` row scan (80% to 65% without
it) and of the organization update and delete queries (100% to 0%).
Swapping `group_acl` and `user_acl` in the converter makes
`GrantedMember` fail. The removed cases are decided by
`TestRolePermissions`, `TestSkillRBACObjectOrganizationACL` and the
dbauthz method suite.
- `e2931b412e9` test(coderd/database): fold the skill cap cases into
existing coverage. The user case is covered by `TestUserSkillLimit` and
`TestUserSkillLimitConcurrentCreates`; the organization case folds into
`ConcurrentOrganizationInsertsHonorCap`, which now also checks that
disabled rows count and another organization is unaffected (mutation
checked); the project case stays.
- `be62aea9021` test(coderd/rbac): drop
`TestOrganizationSkillReadScope`, covered by `TestExternalScopeNames`
and the generated scope file.
- `0c275ba37de` merges main at `454a2fcc697`, which took 000615 to
000618: it renumbers the migration to 000619 and resolves `dump.sql`,
`check_constraint.go` and the generated API docs. `8f2b4b87ee2` merges
main at `ad85646164e`, which took 000619: it renumbers the migration to
000620.
- `5248d56b64f` merges main at `e7b76872098`, which took 000620
(`000620_audit_chat_project_instructions_resource_type`): it renumbers
the migration, fixture and migration test to `000621_skills` (step
`Migration000621Skills`, version 621), and resolves
`enterprise/audit/table.go` (keeping main's
`AuditableChatProjectInstructions` entries and the `Skill` entry),
`dump.sql` and `models.go` (the `resource_type` enum gets
`chat_project_instructions`, then `organization_skill`) and the
regenerated `schemas.md`. The up and down SQL are unchanged by every
renumbering.

## Size

Production +549/-67, tests +728/-33, generated +881/-314; total
+2158/-414. This is above the 500-line reviewer-friendly limit on
purpose: Mike asked for 4 to 5 PRs instead of the 21 small ones this
stack replaces.

## Replaces

#30584 (rename `user_skills` to `skills`), #30585 (skill owners), #30586
(organization skill authorization).

## Validation

- Migration test: up keeps the existing personal row and its ID; down
restores the `user_skills` names, cap function and `NOT NULL`, and drops
organization rows; soft-deleting a user removes their skills after up,
after down, and after re-up.
- `go test` passed on `be62aea9021`, before the main merges, for
`coderd` (skill tests), `coderd/database`, `dbauthz`, `migrations`,
`gentest`, `coderd/rbac/...`, `coderd/x/chatd`, `coderd/x/skills`,
`enterprise/audit` and `enterprise/coderd`; `make lint/check-scopes`
passed; the four personal skills Vitest files pass unchanged.
- On `5248d56b64f`: build, vet, `TestMigrate`, `TestMigrationChain`, the
`migrations`, `database`, `dbauthz`, `gentest`, `rbac` and
`enterprise/audit` packages pass; `make gen` run twice is clean, and
`make pre-commit` passes.
- Remote UAT round 7 through Coder Agents passed on the whole stack; see
#30613's Validation for scope and findings.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 15:51:31 +00:00
ad85646164 feat(coderd): add chat project instructions storage and prompt injection (#30367)
Adds storage for project-level instructions in Coder Agents chat
projects and injects them into every chat in the project. This is the
first of four stacked PRs that replace #30349.

A new `chat_project_instructions` table (migration 000613) holds at most
one row per project, scoped to the project's organization. It records
`updated_by` and cascades on project delete. The dbauthz wrappers
authorize against the parent project: read access to get the
instructions, update access to upsert or delete them. No new RBAC
resource is added; project RBAC comes in a later PR.

chatd loads the instructions on every turn, so edits reach existing
chats on their next turn. They are added to the system prompt as a
`<project-instructions>` block after the memory guidance and before
personal instructions, so a user's personal instructions still win a
conflict. Subagent chats carry no `project_id`, so they use their root
chat's project. A load error other than no rows is logged, and the turn
continues without instructions.

**What to scrutinize:** the prompt ordering in `buildSystemPrompt`, and
the choice to inject per turn rather than snapshot at chat creation.
Per-turn injection costs one prompt-cache miss after each edit; the org
instructions in #30272 use a creation-time snapshot instead.

**Generated** (`make gen` from the migration and
`queries/chatprojectinstructions.sql`): `dump.sql`, `models.go`,
`querier.go`, `queries.sql.go`, `dbmetrics/querymetrics.go`,
`dbmock/dbmock.go`, and the `*_constraint.go` files.

`coderd/x/chatd/ARCHITECTURE.md` gets two TODOs for the PR author to
replace with the real description, per AGENTS.md.

**Validation:** `make gen` leaves no diff. `go test
./coderd/database/dbauthz -run TestMethodTestSuite/TestChats`, `go test
./coderd/x/chatd -run 'SystemPrompt|ProjectInstructions|Memory'`, and
`go test ./coderd/database/migrations/...` pass.

---

Stack (merge top to bottom). #30377 through #29583 are f0ssel's split of
the original #29583, and this stack sits on #29583:
- #30377 data layer and project dialog (f0ssel)
- #30378 new-chat form locked to a project (f0ssel)
- #30379 project page route (f0ssel)
- #29583 sidebar folders (f0ssel), the base of this stack
- #30291 composer frame
- #30292 project chat list caches
- #30293 project page header
- #30294 project chats list
- #30367 instructions storage and prompt injection 👈
- #30368 instructions API
- #30369 instructions editor dialog
- #30370 instructions Details panel

---------

Co-authored-by: Garrett Delfosse <delfossegarrett@gmail.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 16:45:44 +07:00
Thomas Kosiewski 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`_

![Agents sidebar after the upgrade, with no Automations entry](https://github.com/user-attachments/assets/bd446035-7fc8-4ca4-a735-3a4f36380738)
2026-10-11 19:57:49 +02:00
McKayla はな 86ebc72236 chore: remove unused autofill-parameters endpoint and experiment (#30525) 2026-10-09 16:42:41 -06:00
Michael Suchacz 782fb30f09 feat: load whole chat turns per history page (#30524)
Closes
[CODAGT-1372](https://linear.app/codercom/issue/CODAGT-1372/load-whole-turns-per-history-page-so-collapsed-working-blocks-fill-in).

With collapsed working blocks, a long agent turn renders as one row, but
chat history pages hold a fixed 50 messages. A 400-step turn took about
eight sequential page loads to fill, and its block showed partial labels
("at least", "or more") until then.

`GET /api/v2/chats/{chat}/messages` now returns `turn_start_id` on
newest-first pages: the ID of the user prompt that starts the turn
containing the page's oldest message. It comes from a new
`GetChatTurnStartID` query on the existing
`idx_chat_messages_user_prompts` index, so there is no migration.
Soft-deleted prompts and model-only user rows never start a turn.

The history query then fills each page back to that prompt with requests
of up to 200 messages, capped at 1000 messages per page, so a page holds
whole turns and a complete block renders without partial labels. Past
the cap, or when a fill request fails or returns no messages, the page
keeps what loaded and ends mid-turn, and the next page continues it, as
before. Because the fill runs inside the page fetch, a chat now waits
for its fill requests (one to five) before it first renders: with an
injected 500 ms per-request delay, a chat whose newest turn hits the cap
appeared after 3.8 s instead of 1.1 s.

## Screenshots

From the dogfood UAT, the same 200-step turn with its next history
request held, so each label shows only what loaded before it:

**Before**, on the base commit `29e876df4da`, after two 50-message
pages: "Worked for at least 1m 35s (48 steps or more)", partly hidden by
the loading indicator.

![Before: partial label for a 200-step
turn](https://github.com/user-attachments/assets/6b4e4abf-4bc6-4476-8ed5-52c39c8eebe6)

**After**, on `186a9b053a0`, after the first page: "Worked for 6m 39s
(200 steps)".

![After: exact label for the same 200-step
turn](https://github.com/user-attachments/assets/22ec1900-1e7b-4c98-87a9-0463e1d852c2)

A 750-step turn, larger than one 1000-message page, is exact once the
next page loads:

![After: 750-step turn,
expanded](https://github.com/user-attachments/assets/f927a848-62b1-4eb7-a548-fbdff61fc9c4)

A malformed fill response keeps the loaded messages and the partial
label instead of showing "Failed to load chat", as `ecdfb27ec29` did:

![Malformed fill response: partial label, no error
screen](https://github.com/user-attachments/assets/6d393df9-15a2-471e-9bb6-71e919aca570)

## Testing

- Go: `TestGetChatMessages_TurnStartID` (pages spanning turns, deleted
prompts, model-only user rows, polling and empty pages) and the dbauthz
suite entry.
- Vitest: fill request parameters, the 1000-message cap, failed,
malformed, and empty fill responses, and servers without
`turn_start_id`.
- Dogfood UAT through Coder Agents: PASS on `186a9b053a0` (round 4):
whole-turn first pages, the 1000-message cap and its continuation, fill
failures, a live turn, and API checks for deleted prompts and model-only
user rows. Round 3 on `ecdfb27ec29` failed: a malformed fill failed the
chat load, and an empty fill reporting `has_more` repeated forever.
`7266f468290` fixes both, with regression tests.

## Review record

- Test audit with mutation checks: the Go test now covers a page
spanning two turns, which catches a lookup keyed on the newest message.
A re-audit of later test changes changed nothing; the one surviving
mutation drops the `!older.has_more` stop, costing one extra request
when the prompt is deleted mid-fill.
- Frontend review (8 roles, 5 rounds): fixed doc, naming, loose-type,
and test findings. Its suggestions to catch only the fill request (DF5)
and drop the empty-page stop (SD4) caused the round 3 failures and are
reverted. Kept: SD1 (`MAX_MESSAGES_PER_REQUEST` is used once, named like
`MESSAGES_PAGE_SIZE`) and round 5 SD4 (`!older.has_more` is the
endpoint's pagination signal). Declined DF6: the `queued_messages`
refetch race predates this change, and a failed refetch fill only
unloads older history that reloads on scroll.
- Codex: no findings on `186a9b053a0`.
- Known: a hung fill delays the first render (no client timeout); fills
are not cancelled when the user leaves; the top of history costs one
extra empty request; injected malformed fill rows break the page as they
do on the first page.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-09 13:32:39 +02:00
Michael Suchacz 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`) |
|---|---|
| ![Organization admin saves organization instructions and sees a
success
toast](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r1-admin-saved.png)
| ![Organization auditor sees the instructions
read-only](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r1-auditor-readonly.png)
|
| **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`)** |
| ![Loading spinner with no textarea or
buttons](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r2-loading.png)
| ![Error alert above the instructions field with the unsaved edit
preserved](https://gist.githubusercontent.com/ibetitsmike/1027eba97c252d6f3e921d2f46debd01/raw/5a70872eae4170b4e9330c07696727071f0962e8/r2-refetch-error-edit-kept.png)
|

## 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.
2026-10-06 10:48:07 +02:00
Garrett DelfosseandClaude Opus 5.5 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>


![save_memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-01-chat-saves-memory-raw.png)

![read_memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-02-chat-reads-memory-raw.png)
![Agent reads every
memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-agent-lists-memories-raw.png)

</details>

---
Generated with Coder Agents on behalf of @f0ssel.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 12:52:10 -04:00
Mathias Fredriksson 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
2026-10-02 22:36:59 +03:00
Thomas Kosiewski 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`_
2026-10-02 15:54:55 +00:00
Thomas Kosiewski 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`_
2026-10-02 15:54:52 +00:00
Thomas Kosiewski 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>
2026-10-02 15:54:51 +00:00
Thomas Kosiewski 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`_
2026-10-02 15:54:51 +00:00
Thomas Kosiewski 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>
2026-10-02 15:54:50 +00:00
Thomas Kosiewski 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>
2026-10-02 15:54:49 +00:00
Thomas Kosiewski 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`_
2026-10-02 15:54:49 +00:00
Thomas Kosiewski f55aa6c50d feat: add chat automations schema, RBAC resource, and audit entries (#30085)
Adds the storage and authorization pieces for Automations for Coder
Agents. No route, SDK request type, or chatd code uses them yet, so
nothing is exposed.

This is the bottom PR of the Automations stack (RFC step 1). Later PRs
add the chatd acceptance seam, management routes, webhooks, and
schedules on top of these names and constraints.

**Schema** (migrations 000609, 000610)

- `chat_automations` table with enums `chat_automation_kind`,
`chat_automation_target_mode`, `chat_automation_webhook_use`, and
`chat_automation_when_busy`. It includes `created_by_chat_id`, the
webhook secret hash and version, the single-use `webhook_consumed_at`
marker, the schedule cursor and revision, and `queue_generation`. Named
CHECKs enforce the target and kind shapes from the RFC. A composite
foreign key keeps `new_chat_model_config_id` in the automation's
organization, the same pattern the model override tables use. A trigger
(`chat_automations_chat_organization`) keeps `target_chat_id` and
`created_by_chat_id` in that organization too. A composite foreign key
cannot do that while keeping `ON DELETE SET NULL` on PostgreSQL 13. The
trigger validates a reference only on insert or when it changes, so chat
deletion can still clear both references. Indexes cover the owner and
both chat references for cascades and `SET NULL`.
- Provenance columns with partial indexes and no foreign key to
`chat_automations`: `automation_id`, `input_id`, `queue_generation` on
`chat_queued_messages` (all set or all null), `automation_id` and
`input_id` on `chat_messages`, and `chats.automation_id`.
`chats_expanded` is recreated to include `automation_id`.
- `chat_automation` values for `api_key_scope` and `resource_type`. The
down migration is a no-op because enum values cannot be dropped.

**Authorization**

- New organization-scoped RBAC resource `chat_automation` (create, read,
update, delete). The `agents-access` role grants it for the member's own
automations. It is excluded from the member role's user-level
permissions, so a member without `agents-access` gets nothing. Site
owners and organization admins get it through their existing
all-permissions lists. The owner-only update, enable, and run rule from
the RFC belongs to the management service in a later PR.
- The generated scopes stay out of `externalLowLevel`, so API keys gain
no user-requestable scopes.
- `dbauthz` wrappers for the three queries this PR adds:
`InsertChatAutomation`, `GetChatAutomationByID`, and
`DeleteChatAutomationByID`. `InsertChatAutomation` also requires update
on the target chat, read on the creating chat, and read on the new-chat
model config (its user and group ACL). There is also a
`dbgen.ChatAutomation` helper.

**Audit**

- `enterprise/audit/table.go` entries for `ChatAutomation`, with
`webhook_secret_hash` and `prompt` marked `ActionSecret`. The prompt is
treated as chat content, like chat titles. The schedule cursor,
revision, and queue generation are ignored as internal bookkeeping.
`Chat.automation_id` is tracked.

**Required checks from the ticket**

- Migrations apply and roll back: `TestMigrate` and
`TestMigrateUpWithFixtures` (new fixture for 000609). Dogfood UAT also
applied the migrations on a dev instance, rolled them back, re-applied
them, and compared schema dumps. After rollback, the only differences
from main were the enum values that cannot be dropped and develop.sh's
own `_develop` schema. After re-applying, the only difference from this
branch's `dump.sql` was the `_develop` schema.
- Secret hash marked secret: `Test_chatAutomationSecretFieldsRedacted`
checks the table entries and that an audit diff contains neither the raw
hash, its base64 form, nor the prompt text.

Also covered: `TestRolePermissions` cases for own, other owner, other
organization, and a member without `agents-access`.
`TestChatAutomationShapeConstraints` covers the named CHECKs, the
cross-organization foreign key and trigger, a cross-organization
retarget, and deleting referenced chats. Under `site/`, only generated
files changed (`typesGenerated.ts`, `rbacresourcesGenerated.ts`).

Closes CODAGT-1207
Part of CODAGT-1135

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-10-02 15:54:48 +00:00
Mathias Fredriksson 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
2026-10-02 12:58:53 +00:00
Garrett DelfosseandClaude Opus 5.5 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>

![Create
project](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-01-create-project-dialog.png)
![Sidebar
folders](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-02-sidebar-folders.png)
![Project
page](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-03-project-page.png)
![Folder
menu](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-05-folder-menu.png)
![Another member sees no
projects](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr5-member-sees-no-projects.png)

</details>

---
Generated with Coder Agents on behalf of @f0ssel.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 11:49:21 -04:00
Thomas Kosiewski 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`_
2026-10-01 17:41:56 +02:00
Thomas Kosiewski 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`_
2026-10-01 16:42:51 +02:00