Commit Graph
17121 Commits
Author SHA1 Message Date
Bobby Ho 0ea3f16dd3 fix(coderd/database/migrations): renumber MCP OAuth2 resource migration to 000622 (#30722)
Main is red: #30625 and #30651 both added a migration numbered 000618,
and the
loader refuses to start with a duplicate number. See the failing run on
fa7cd62c8b.

- Rename 000618_mcp_server_oauth2_resource.{up,down}.sql to 000622, the
next
  free number after 000621_skills.
- No schema change; dump.sql regenerates identically.
2026-10-13 23:08:37 +00:00
Michael Suchacz fa7cd62c8b feat: send RFC 8707 resource parameter on MCP server OAuth2 flows (#30651)
Coder's MCP OAuth2 client never sent the RFC 8707 `resource` parameter,
which the MCP authorization spec requires on authorization and token
requests. Authorization servers that enforce it cannot be connected:
with Dagster+, discovery and dynamic client registration succeed, then
the authorize request fails with "MCP OAuth requests must include
resource".

MCP server configs get an `oauth2_resource` field (migration 000618,
admin-only in API responses, audited). Coder sends it on the authorize
redirect, the authorization-code exchange, and token refresh. Refresh
now goes through `clientcredentials` with `grant_type=refresh_token`,
because `oauth2.Config` cannot add parameters to refresh requests; it
keeps the same auth-style detection and error types, and adds no
dependency.

Auto-discovery fills the field with the most specific Protected Resource
Metadata `resource` that covers the server URL, stored as advertised. As
in the MCP SDKs, a resource covers URLs on its origin at or under its
path, so `/mcp` covers `/mcp/` but `/mcp/` does not cover `/mcp`. URLs
compare in RFC 3986 normal form (default ports, percent-encodings, dot
segments, and an empty path as `/`), ports ignore leading zeros, IPv6
literals compare by address, and `%2F` stays inside its segment. Unlike
the SDKs, a resource with a query, even an empty one, only covers a
server URL with the same query. When none covers it, Coder uses the
server URL with the scheme and host lowercased and user information and
fragment removed, or sends no resource when that is not a valid resource
indicator. An explicit value in the create request wins.

Manual configurations send no `resource` unless an admin sets one,
because some providers reject it (Microsoft Entra ID v2 fails with
AADSTS901002). Values must be absolute RFC 3986 URIs without a fragment,
user information, or an IPv6 zone identifier.

The resource binds grants like the other OAuth settings: changing it
deletes stored user tokens, and a callback whose config resource changed
after the user started connecting returns 409 before the code is
redeemed. The connect step records the resource in a callback-scoped
cookie for that check.

Discovery only runs when a configuration is created, so existing
auto-discovered configurations, including the Dagster+ one that prompted
this, keep an empty resource until an admin sets the new "Resource URL"
field or re-creates the server.

![MCP server edit form showing the Resource URL field filled by
auto-discovery](https://github.com/user-attachments/assets/319bc8a0-f6e1-4b7d-8878-8e341c94e590)

## Testing

- Go: discovery (most specific match, path and trailing-slash
boundaries, query matching including empty queries, equivalent ports,
IPv6 literals, escapes, and dot segments including escaped ones, the
normalized fallback and an invalid one, explicit override), validation
(URI characters, brackets, IP literals, user information, trimming),
grant deletion on change, clearing on an auth type change, redaction for
members, refresh with and without a resource, the 409 when the resource
changes mid-flow (the authorization server never receives the code), and
a connect and callback flow against an authorization server that rejects
requests without the resource. Each new test was checked to fail when
the behavior it covers is broken, except two malformed IP literal hosts
that Go's URL parser already rejects.
- Vitest: the form round-trips the stored value, and clearing the field
sends `""` on update.
- Remote UAT through Coder Agents
([chat](https://dogfood.cdr.dev/agents/58695d5b-2112-400b-88f7-ab64c678f756))
on a test deployment with loopback MCP and authorization server mocks:
- Round 1 on 2b875068e0: literal verdict FAIL. When the resource
changed between connect and callback, the callback redeemed the code for
the new resource and stored a grant. The 409 binding fixes it.
- Round 2 on 4b54ffb5f9: PASS. The mid-flow change returned 409 with no
token request in every variant (strict and lenient servers, set,
cleared, abandoned flows, parallel configs); auto-discovery, connect,
refresh, validation, and the docs matched. Minor observations: the
binding cookie is an unkeyed digest, so a member who edits their own
HttpOnly cookie can redeem a code with the current resource, which a
fresh connect also gives them; other settings changed mid-flow still
reach the token endpoint, as on main; the 409 popup shows raw JSON; the
UI does not warn that a resource change disconnects users; validation
toasts omit the server's detail.
- Round 3 on the final head 2d6abfac49: PASS. The head moved during the
round, so it ran in four parts, the last on 2d6abfac49. That part
covered the matching rules (queries including empty ones, default and
zero-padded ports, `%2F`, escaped dot segments, trailing slashes, IPv6
literals), the invalid fallback (stored empty, no `resource` sent),
every validation value through the API and the UI, and the discovery,
connect, refresh, and mid-flow 409 flows. The equivalent-encoding cases
last ran live on 5c23fe00dca; unit tests cover them on the final head.
Observation: the path-aware metadata URL is built from the decoded path,
so `/mcp%2Ftenant` fetches metadata for `/mcp/tenant`, as on main.
- `frontend-review` and the eight-role `coder-frontend-review` ran on
the `site/` diff; every role passes after the label, help text, row
layout, API doc wording, and form test fixes. Declined: linking field
descriptions with `aria-describedby`, because the form's shared `Field`
primitive renders every description without one, so it belongs in a
change to all fields.

## Review record

| Review | Commit | Findings | Disposition |
|---|---|---|---|
| [Codex round
1](https://github.com/coder/coder/pull/30651#pullrequestreview-5492085359)
| 4b54ffb5f9 | P2: a resource with another query was treated as
covering the server URL | Reproduced with a failing test, fixed in
bf0879560c, resolved |
| [Codex round
2](https://github.com/coder/coder/pull/30651#pullrequestreview-5492305363)
| bf0879560c | P2: explicit default ports; P2: `%2F` treated as a
segment boundary; P2: `url.Parse` accepts spaces and invalid escapes |
Each reproduced with a failing test, fixed in 16a1d783fa, resolved |
| [Codex round
3](https://github.com/coder/coder/pull/30651#pullrequestreview-5492677517)
| 16a1d783fa | P1: docs wrapped mid-sentence (DOC1); P2: equivalent
percent-encodings compared unequal; P2: brackets accepted outside an IP
literal host | Fixed in 8d617f0528 (the P2s reproduced with failing
tests; the same pass also covers the query, dot segment, and user
information cases), resolved |
| [Codex round
4](https://github.com/coder/coder/pull/30651#pullrequestreview-5493033885)
| 8d617f0528 | P2: the server URL fallback was not validated; P2:
escaped dot segments were compared before decoding | Each reproduced
with a failing test, fixed in 5c23fe00dc, resolved |
| [Codex round
5](https://github.com/coder/coder/pull/30651#pullrequestreview-5493342889)
| 5c23fe00dc | P2: an empty query (`?`) was treated as no query |
Reproduced with a failing test, fixed in 72c019ff5e, resolved |
| [Codex round
6](https://github.com/coder/coder/pull/30651#pullrequestreview-5493524846)
| 72c019ff5e | P2: `/mcp/` covered `/mcp`; P2: equivalent IPv6 literals
compared unequal; P2: malformed IP literals accepted | The first two
reproduced with failing tests. Go 1.26.5 `url.Parse` already rejects the
hosts named in the third, but it accepted an IPv6 zone identifier. All
fixed in ef2df2c4e7, resolved |
| [Codex round
7](https://github.com/coder/coder/pull/30651#pullrequestreview-5493668131)
| ef2df2c4e7 | P2: leading zeros in a port made equal origins differ |
Reproduced with a failing test, fixed in 2d6abfac49, resolved |
| [Codex round
8](https://github.com/coder/coder/pull/30651#issuecomment-6128743972) |
2d6abfac49 | None: "Didn't find any major issues" | Clean verdict on
the current head |

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 23:03:08 +02:00
Michael Suchacz b7d63121b0 refactor(coderd/x/chatd): move chat mutations into chat_mutations.go (#28756)
Moves the chat mutation verbs out of `chatd.go` into
`chat_mutations.go`. They share one helper, `Server.updateChat`, instead
of each repeating the transition, reload and publish steps.

## Changes

- `chat_mutations.go`: `SendMessage`, `EditMessage`, `PromoteQueued`,
`DeleteQueued`, `ArchiveChat`, `UnarchiveChat`, `SubmitToolResults`,
`InterruptChat`, `CompactChat`, `ClearChat` and
`ReconcileInvalidStateChat`, plus their private helpers. They stay
`*Server` methods; there is no wrapper type.
- `updateChat` runs the transition in one chatstate transaction and
reloads the chat inside it, so the result and the sidebar watch event
carry the snapshot bump. Then it publishes only the `status_change`
watch event. Compact and clear already hold the post-transition row, so
they skip the reload.
- Edit-target checks reuse `validateEditTarget`. The root-chat archive
guard lives only in `setChatFamilyArchived`. `publishChatPubsubEvent(s)`
stay in `chatd.go`.
- Net diff: +1,125/-1,128 (production -83, tests +80).

## Behavior

No intended behavior change. Transaction boundaries, locking, hook
order, error strings, publish order and the debug cleanup cutoff match
main. The moved code includes main's later changes: inline MCP server
replacement on send (#29546), the first-turn fallback title (#27111),
configurable limits (#28927), queue wait metrics (#29771) and inline
interruption finish (#30259). `auto_archive.go` keeps its own archive
path. Its precondition is checked under the lock, it uses the worker's
store, and it returns rows for auditing.

## Testing

Rebuilt on main `b2c8798e0e0`. A 42-mutant sweep ran on main and on this
branch, and nothing main's tests caught goes uncaught here. New tests,
each red-green checked by removing the code it guards:

- `TestUpdateChat` covers the reload, skipping the reload, and rollback
with nothing published.
- `TestArchiveStateRejectsChildChat` uses the public methods on a real
database, uses `ErrorIs`, and checks both archive flags stay unchanged.
It replaces `TestUnarchiveChildChat` and
`TestArchiveChat_RejectsChildChat`.
- `TestArchivedChatRejectsMutations` covers the in-transaction archived
check for six verbs; no test covered it before.
- A `title_change` assertion is added to
`TestSendMessageFirstUserTurnFallbackTitle`, and
`TestArchiveChatDeletesDebugRuns` covers archive debug cleanup.

Validation:

- `go build ./coderd/... ./enterprise/...`, `go vet
./coderd/x/chatd/...`, `golangci-lint` and `make lint/go/new-code`:
clean.
- `go test ./coderd/x/chatd/... -count=1` passes on all packages, and a
race run on the touched tests passes.
- `./coderd` chat tests pass, including `TestInlineMCPServers`,
`TestWatchChats` and `TestSubmitToolResults` (158 runs), as do the chat
state and hook tests and `./enterprise/coderd` chat tests.
- Local pre-push checks were skipped at the author's request; CI is the
gate.

## Review record

- [Codex
OK](https://github.com/coder/coder/pull/28756#issuecomment-6151488087)
on head `fc327b8b873`, no unresolved threads. [CI
passed](https://github.com/coder/coder/actions/runs/38439818111) on the
same head. The first CI run on `3d9b0e83369` caught a test bug: parallel
subtests shared one parent context and timed out while waiting for a
slot. `fc327b8b873` gives each subtest its own context.
- Earlier Codex OKs and @ThomasK33's approval are on superseded heads
(`fe038a5f13a` and earlier). This description replaces the old "single
mutator" framing.
- Independent agent review of the rebuilt branch: GO, with every verb's
behavior equal to main. P3 fixes applied: moved code kept in main's
formatting, and a retry rationale comment restored. Not added: a unit
test of the tool-result validation detail strings, because it would make
the PR net-positive. Main also only checks those details through coderd
`TestSubmitToolResults`.
- This PR and #28757 conflict in `chatd_test.go`. Whichever merges
second needs main merged in.

> Xum (an AI coding agent) rebuilt this PR on behalf of @ibetitsmike.
2026-10-13 22:57:46 +02:00
Michael Suchacz 0702372dcf chore: add frontend-deep-review agent skill (#30182)
Adds a `frontend-deep-review` agent skill and tells agents to run it and
fix its findings whenever they modify frontend code.

The skill reviews a `site/` diff with eight parallel read-only reviewer
roles (simplicity, comments, tests and stories, React patterns, reuse,
styling and a11y, types and naming, data flow). Each role owns numbered
checkpoints distilled from 671 human inline review comments on `site/`
PRs between April and September 2026. It complements the existing
`frontend-review` FE1 to FE10 gate rather than replacing it. Where a
checkpoint conflicts with the root `AGENTS.md`, `site/AGENTS.md`, or
`FRONTEND_PATTERNS.md`, the repository rule wins and the reviewer
reports the conflict. To review someone else's PR, the skill does not
check out the branch, so the author's Git hooks never run. Instead it
pins the head and base SHAs, reads the PR only as Git objects, reads the
rules at the base branch tip, and treats the PR's text and file names as
data.

Changes:

- `.claude/skills/frontend-deep-review/`: `SKILL.md`,
`reviewer-prompt.md`, and eight `roles/*.md` checkpoint files, symlinked
from `.agents/skills/` like `frontend-review`.
- `AGENTS.md` and `site/AGENTS.md`: run the skill for frontend changes
and fix `blocking` and `should-fix` findings before handoff.
- `.claude/skills/frontend-review/SKILL.md`: points to the new skill
after the FE audit passes.

The published version drops reviewer names, verbatim quoted comments, PR
references, per-checkpoint comment counts, and the raw comment dataset
from the internal original, keeping only the checkpoints and their
fixes. The helpers, files, and lint rules a checkpoint recommends or
cites as a correct example exist on `main`. Identifiers inside a
checkpoint's examples of what to flag come from past reviews, and some
have since been renamed or removed; `SKILL.md` and the reviewer prompt
tell reviewers to match the pattern, not the name.

Testing: `make lint/agents lint/markdown lint/emdash`,
`markdownlint-cli2` on the skill files, and the pre-commit hook pass.
Every file path and identifier the skill cites was checked against
`origin/main` with `git grep`; the only misses are those past-review
example names and placeholders such as `mockX`.

> Xum opened this PR on behalf of Mike.
2026-10-13 22:53:38 +02:00
Michael Suchacz adcce66826 feat: load organization skills in chats (#30613)
## Stack

Closes
[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
4. #30612 settings UI: shared skills table, admin page, member section
5. **#30613** chats: chatd loading, `/` menu, docs (this PR)

## What changes

This PR makes chats use organization skills: chatd adds the skills
shared with the chat owner in the chat's organization to the skill
index, `read_skill` loads them, the `/` menu offers them, and the docs
describe the feature.

**chatd** (`coderd/x/skills`, `coderd/x/chatd`):

- New source `skills.SourceOrganization` (`"org"`).
`MergeSkills(personal, organization, workspace)` sorts by name, then
source. A name in one source keeps its bare alias; a name in more than
one source gets a qualified alias in every source that has it
(`personal/<name>`, `org/<name>`, `workspace/<name>`), so no source
overrides another. `Lookup` returns `ErrSkillAmbiguous` for a bare name
that matches several sources.
- **Authorization (please review closely):** each turn, chatd reads
organization skill metadata and bodies as the chat owner's real RBAC
subject with their roles and groups (`chatOwnerSubject`), never as the
chatd system actor, so per-skill ACLs apply. Disabled skills are
skipped. A skill that is deleted, disabled, or no longer shared by the
time `read_skill` runs is reported as not found. If the owner subject or
the metadata can't be loaded, turn preparation fails with the error, as
main now does for personal skills (#30492), instead of running the turn
without organization skills.
- `read_skill` loads personal and organization bodies through one
`LoadStoredSkillBody` callback. An index description longer than 1,024
runes, the Agent Skills specification limit
(`maxSkillIndexDescriptionRunes`), is cut to 1,023 runes plus an
ellipsis so it stays within the limit; `read_skill` still returns the
full skill.
- Parse and lookup errors keep `%w` last on purpose: with `xerrors`, a
`%w` that isn't last repeats the cause, so main's detail read "skill is
too large: got N bytes, maximum is 65536 bytes: skill is too large".
This stack returns the cause once (ThomasK33 asked about the order in
review).

**`/` menu** (`site/src/pages/AgentsPage`): the chat page fetches the
chat organization's enabled skills (`organizationSkills(...)` from
#30612's queries) next to personal ones. `utils/skillAliases.ts`
(`resolveSkillTriggers`) follows `MergeSkills`: a personal or
organization trigger is bare unless its name is in more than one source,
then it becomes `/personal/<name>` or `/org/<name>`. While any list is
unknown every trigger is qualified, because a qualified alias always
resolves; workspace triggers are always qualified. Built-in `/clear` and
`/compact` stay pending until every skill list is known, and a list with
no data counts as unknown even after an error, so a failed fetch can't
make a built-in run in place of a same-named skill. Disabled skills
never shadow a built-in.

**Docs:** `docs/ai-coder/agents/extending-agents.md` gains two sections,
Organization skills (manage them, control who can use one, find the ones
you can use) and How chats load stored skills (turning a skill on or
off, skills with the same name). The admin page's organization picker
shows only for a user who can view more than one organization's skills.
The member "From your organizations" section shows one organization at a
time with its own picker, starts on the default organization, and has
Export all for the selected organization. The Enabled column is a switch
for editors and a check or X otherwise. The settings table in
`platform-controls/organizations.md` gains rows for organization and
personal skills.

## Commits

The first commit reproduces the reviewed chatd code from the old stack;
the site and docs commits reapply the old layers on #30612's queries,
and the rest are labeled trims or fixes.

- `aa634eec94a` feat(coderd/x): load organization skills in chats.
Reproduction of the old skill sources and chatd layers (old head
`a1047f4986`).
- `97945db4e86` test(coderd/x/skills): make `TestMergeSkills` (6 cases)
and `TestLookup` (8 cases) table-driven; coverage is 100% before and
after, with the same blocks.
- `dde61cc5fe2` test(coderd/x/chatd): drop skill tests duplicated by the
organization skills integration test
`TestOrganizationSkillsFollowChatOwnerAccess`; the covered block set of
the touched code is identical (348 of 506 blocks).
- `aad14b2dd05` feat(site/src/pages/AgentsPage): show organization
skills in the slash menu. The old alias helper and slash menu layers,
applied cleanly on #30612's queries.
- `712e272e140` test(site/src/pages/AgentsPage): trim duplicated slash
menu tests and stories. Deletes `AgentChatPage.test.tsx` (177 lines; its
assertions live in `submitChatTurn.test.ts` and
`ChatMessageInput.test.tsx`), two duplicate `ChatMessageInput` cases,
six of 17 `SkillsTriggerMenu` stories, and one disabled-skill fixture
row from a `ChatMessageInput` story.
- `232535e1011` docs(docs/ai-coder/agents): document organization
skills. From the old docs layer, with the View line updated for #30612's
read-only dialog and Download.
- `62dbbd2dfd3` refactor(site/src/pages/AgentsPage): address frontend
review on the slash menu.
- `7349eac4389` Merge the updated settings-ui layer into chats. Brings
in the #30610 and #30612 fixes; the merge has no changes of its own.
- `0f84a30ec69` Merge the updated settings-ui layer into chats again,
for #30612's read-only View fix; no changes of its own.
- `fb37822f985` fix(coderd/x/chatd/chattool): keep truncated skill index
descriptions within 1,024 runes. The cut now happens at 1,023 runes so
the ellipsis fits; the existing `skill_test.go` assertion now expects
1,023 runes plus the ellipsis.
- `1543666b584` docs(docs/ai-coder/agents): state the 1,023-character
cut before the skill index ellipsis.
- `96f1da47c9a` and `13f03d095ff` merge the updated settings-ui layer
for #30612's cache and Skills link fixes; no changes of their own.
- `b03c14c86de` and `41cc078b85a` merge the updated settings-ui layer;
`b03c14c86de` moves the `AgentChatPage.tsx` and `ChatMessageInput.tsx`
call sites, and their tests and stories, to #30612's split
`organizationSkills(...)` query.
- `1a32d05c9bc`
test(site/src/pages/AgentsPage/components/ChatMessageInput): restore
per-source loading stories for the slash menu.
- `830b0466982` fix(coderd/x/chatd): fail turn preparation when
organization skills cannot load. Main now returns database errors from
turn preparation (#30492); organization skills still logged and dropped
the failure, so a failed read silently hid them from the model. The new
`TestFetchOrganizationSkillMetadataListFailure` covers the returned
error.
- `84c135f8801` and `a6f8f63ad13` merge the updated settings-ui layer,
which brings in main; they resolve `generation_preparer.go` against
main's turn preparation error handling.
- `19b7880840f` merges #30612's member page test change; no changes of
its own.
- `c74d597f3c5` merges #30612's read-only status change; no changes of
its own.
- `f89c232c081` merges #30612's skills test changes; no changes of its
own.
- `17d5b9bfbc5` docs(docs/ai-coder/agents): describe the member skills
organization picker and read-only Enabled status.
- `f97b1710f71` merges the updated settings-ui layer (main at
`e7b76872098`); no changes of its own.

## Size

Production +558/-213 (docs +116/-6), tests +895/-262; total +1453/-475.
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

#30593 (skill sources), #30594 (chatd), #30601 (alias helper), #30602
(slash menu), #30604 (docs).

## Validation

- Go: all 21 packages under `coderd/x/skills` and `coderd/x/chatd` pass
on `62dbbd2dfd3`, plus the coverage comparisons above;
`coderd/x/chatd/chattool` passes again on `13f03d095ff` after the
truncation fix.
- Site: `pnpm run lint` and Biome clean; Vitest 102 tests; Storybook
Vitest 49 + 4 tests. `pnpm run lint` reran clean on `13f03d095ff`.
- On `a6f8f63ad13`, this PR's head before the test-only `19b7880840f`
merge: `go test` passes for `coderd/x/skills`,
`coderd/x/chatd/chattool`, and the `coderd/x/chatd` skill tests (`-run
'OrganizationSkill|Skill'`); 38 Vitest files covering skills and the
slash menu pass, 542 tests with 2 skipped.
- Docs: markdownlint 0 findings, Vale 0 findings.
- On `17d5b9bfbc5`: Vale clean, markdownlint and `make pre-commit` pass.
On `f97b1710f71`: `go build`, the `coderd/x/skills` and `chattool`
tests, `pnpm check` and `tsc` pass.
- Remote UAT round 7 through Coder Agents: PASS
([chat](https://dogfood.cdr.dev/agents/3426d4d3-2139-4ae1-8e0c-72ddeff413a8)).
- Full run on `62dbbd2dfd3`, including an in-place upgrade from main
`50c785cc6d7`: personal skills kept their IDs, names, content hashes and
timestamps, came up enabled, and worked in chats (`read_skill`) and the
`/` menu; create, edit, download and delete worked after the upgrade.
The admin page, sharing, the Enabled toggle, the member section, the `/`
menu, chats reading organization skills as the owner, limits, audit,
authorization and scoped keys, and the docs all passed.
- Delta run on `7349eac4389`: an update-only key gets 404 on PATCH with
no content in the response; saving permissions refreshes Updated without
a reload; smoke of the admin page, auditor View and Download, the `/`
menu and `read_skill`.
- Delta run on `0f84a30ec69` for `aaa356f0fd5`: read-only View, as an
org auditor and as a member, shows no Name hint, focuses no field and
starts on Close, and Escape or Close returns focus to the row menu
button; Add skill and Edit still show the hint and focus the import
field, and a saved edit persisted; smoke of the admin page, the `/` menu
organization group and `read_skill`. Screen-reader behavior was not
tested.
- Delta run on `13f03d095ff` for `698dd83946d`, `f82573cd1c2`,
`0e55137de7b` and `fb37822f985`: for an organization admin of org B who
is a plain member of org A, the sidebar Skills link drops `?org=` for
org A on seven AI settings pages and opens org B's skills, keeps `?org=`
for org B, and a typed `/ai/settings/skills?org=` for org A still shows
the permission error. A skill deleted and recreated with the same name
loads a fresh sharing list showing only Everyone, with no stale grant. A
1,500-character description appears in the chat's skill index as 1,023
characters plus an ellipsis, while `read_skill` returns all of it. Smoke
of the admin toggle, the member section, the `/` menu organization group
and `read_skill`.
- Low findings: the read-only View hint and field focus, fixed in
`aaa356f0fd5` and verified by the delta run above. The member section's
always-on disabled Enabled switch (also in the old stack) is replaced by
a read-only status icon in #30612's `63bb42754e3`, which has no UAT run.
Not fixed: `/` shows the `/personal/` prefix while organization skills
fail to load (the unknown-list rule above); the shared Switch
component's disabled styling (unchanged from main). A user who can read
skills in only one organization sees no organization name on the Skills
page, because the picker is hidden for a single organization, as on the
MCP servers page on main.
- Not tested: the workspace skills group (no running agent on the test
deployment), the 100-per-user personal cap, and behavior without a
Premium license.
- Remote UAT round 8 through Coder Agents: PASS on `b03c14c86de` (same
chat). The remote grader marked the unknown `read_skill` item FAIL only
because the prompt asked for the literal phrase "skill not found"; the
result names the skill once and says "not found" once, the same format
as main, so the runner graded it PASS on intent.
- Member page: starts on the default organization, shows one
organization's table with the read-only note once, Export all downloads
only the selected organization's skills, the picker is hidden with one
organization, and an organization without enabled skills isn't listed.
- Personal and admin tables: create, edit, toggle and delete each
refetch the list; reopening the editor shows the new content even with
the detail request delayed; a toggle changes state once, with no
flicker. A skill deleted and recreated with the same name shows only
Everyone in sharing.
- The sidebar Skills link keeps `?org=` only for an organization whose
skills the user can read. A create over 64 KiB returns 400 with the
detail "got 70000 bytes, maximum is 65536 bytes: skill is too large",
the cause once. The `/` menu shows Commands, Personal skills and
Organization skills, and invoking an organization skill loads its body
through `read_skill`.
- New low findings, not fixed: the member page picker's listbox is
labeled "Suggestions" (likely from the shared
`OrganizationAutocomplete`); a typed body over 64 KiB shows only the
size counter and a disabled Create until Import; `/ai/settings?org=`
redirects to the models page without `?org=`. The first and third were
not checked against main.
- `9002dc60382`, `1a32d05c9bc`, `830b0466982`, `ac3e62c83b7`,
`63bb42754e3`, `82b2487ad17`, `17d5b9bfbc5` and the main merges came
after `b03c14c86de`; they have tests but no UAT run.
- Every UAT round ran the migration as `000615_skills`. The heads ship
the same up and down SQL as `000621_skills`, so the upgrade path from
main's 000620 to 000621 has no UAT run.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 17:13:36 +00:00
Michael Suchacz 6498c5776d feat(site): add organization skill settings with a shared skills UI (#30612)
## 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
4. **#30612** settings UI: shared skills table, admin page, member
section (this PR)
5. #30613 chats: chatd loading, `/` menu, docs

## What changes

This PR turns the personal skills page into a skills table that works
for any owner, then uses it for an organization admin page and a
read-only member section. It changes only `site/`.

**Shared skills table.** The personal page's files move to owner-neutral
paths (kept as git renames, so the diff shows edits):
`AgentSettingsPersonalSkillsPageView.tsx` becomes
`components/SkillsTableView.tsx`, `AgentSettingsPersonalSkillsPage.tsx`
becomes `components/SkillsTable.tsx`, `PersonalSkillEditor` becomes
`SkillEditor`, and `utils/personalSkills` becomes `utils/skills`.
`queries/userSkills.ts` keeps main's query names and keys for personal
skills, and the new `queries/organizationSkills.ts` holds the
organization and ACL queries. The table takes a `SkillsScope` (list,
detail, create, update and delete queries), built by `userSkillsScope`
or `organizationSkillsScope` in `utils/skills.ts`, plus an `access`
object (`create`, `update`, `delete`) and its copy as props.

- **Enabled toggle:** `SkillEnabledSwitch` runs one update mutation per
row from the table's scope, is disabled while it is pending, and
invalidates the list when it settles, which also drops a skill deleted
elsewhere.
- **Read-only status:** a table without update access (the member
section, and auditors on the admin page) shows a green check ("Enabled")
or a gray cross ("Disabled") in the Enabled column instead of a disabled
switch. Editable tables keep the switch.
- **Read-only view:** when the caller can't update a skill, the row
opens `SkillEditor` in read-only mode with a Close button, replacing the
old View dialog. It omits the naming hint and starts focus on Close.
- Dialogs return focus to the control that opened them
(`useDialogFocusReturn`).
- Create, update and delete invalidate the skill list instead of
patching it by hand. Update also writes the PATCH response to the
skill's detail, so a reopened editor shows the new content.
- Saving an ACL refreshes the organization skill list and the skill's
detail. Deleting a skill removes its detail and the ACL queries cached
under it, so a skill recreated with the same name doesn't inherit them.

**Admin page** at `/ai/settings/skills?org=<name>`
(`AISettingsPage/SkillsPage`): lists, creates, edits, toggles and
deletes organization skills with the caller's per-organization
permissions, and opens `OrganizationSkillSharingDialog` for users with
share. A requested organization the caller can't read shows the
permission error instead of falling back to another organization, so a
skill is never added to an organization the URL didn't name. The new
`viewAnyOrganizationSkills` permission adds Skills to the AI settings
sidebar, shows the navbar's AI settings link, and lets the AI settings
index redirect to the skills page. The sidebar's Skills link keeps the
current `?org=` only when the user can read that organization's skills,
using the page's own filter (`readableSkillsOrganizations`), so
following the link never lands on the permission error.

**Member section.** The agent settings page becomes
`/agents/settings/skills` ("Skills" in the sidebar; the old
`/agents/settings/personal-skills` URL redirects). Below personal
skills, "From your organizations" shows one organization at a time,
read-only. Its picker lists the organizations the user is a member of
that have enabled skills for them (an organization still loading or
whose list failed stays listed), starts on the default organization, and
is hidden when only one organization qualifies. Export all downloads
only the selected organization's skills. If the selected organization's
list fails, a retry button (labeled "Retry loading _name_ skills")
replaces the table.

**Shared sharing helpers.** `ChatModelPrincipalAutocomplete` becomes
`components/ACLPrincipalAutocomplete`, used by the model, MCP server and
skill sharing dialogs; `MCPServerPrincipalAutocomplete` is deleted and
the common ACL diff logic moves to `aclSharing.ts`. A new
`ChatModelSharingDialog.test.tsx` guards the model dialog through the
swap.

Declined on purpose (Mike's call): extra toggle cache hardening, namely
a pending-toggle map, reconciling a View that 404s, and guarding a stale
refetch against a retried toggle. Invalidating on settle already
refetches the list after every toggle.

## Commits

This PR reworks the old site layers rather than reproducing them. The
commits go in review order: shared helpers, renames, the shared table,
the two pages, then review fixes.

1. `6463992b717` refactor: share the ACL principal autocomplete and
sharing helpers.
2. `e18599f5049` refactor: move the personal skills files to shared
skills paths (file moves plus import path updates only).
3. `3c71e6c2168` refactor: drop the personal prefix from shared skill
symbols.
4. `3be35bcde68` refactor: key the skills table and queries by owner.
5. `d0c1dfcfdd1` fix: return focus to the opener when a skills dialog
closes.
6. `92ef6351eb4` feat: add an Enabled toggle to the skills table.
7. `31c103e5396` refactor: move the skill edit and delete dialogs to
their own file.
8. `cff0bef4576` feat: view a skill read-only when the user cannot edit
it.
9. `a8b54a22981` feat: add the organization skills admin page with
sharing.
10. `391401b62b7` feat: show organization skills on the personal skills
page.
11. `2cf6e250a60` refactor: keep the skill dialogs in the table view and
extract focus return. This undoes the file split from commit 7 so
`SkillsTableView.tsx` still diffs as a rename (497 lines then, 507 at
the head).
12. `0af93452c7d` test: keep only the role wiring test for the skills
page.
13. `8032c6708a8` fix: refetch the skill list after a create when no
list is cached (superseded by item 22).
14. `a52f9ba659c` refactor: tidy skills copy, editor prop naming, and
story fixtures.
15. `f10bc316305` fix: refresh the organization skill list after saving
its ACL. Saving an ACL bumps the skill's `updated_at`, so the save now
also invalidates the organization skill list and the skill's detail; a
new test in `api/queries/skills.test.ts` (now
`organizationSkills.test.ts`) covers it.
16. `698a6d0b55f` Merge the updated sharing layer into settings-ui,
bringing in #30610's PATCH fix.
17. `aaa356f0fd5` fix: drop the editing hint and field focus from the
read-only skill view. From the remote UAT: read-only View no longer
shows the Name field's naming hint, and the dialog opens with focus on
Close instead of a field (`onOpenAutoFocus`, like `ChatSearchDialog`).
The new `SkillEditor.test.tsx` case "starts focus on Close when
read-only" fails without the fix.
18. `698dd83946d` fix: drop a deleted skill's ACL caches with its
detail. The delete now removes every query under the skill's key, not
only the exact detail; a new case in `api/queries/skills.test.ts` (now
`organizationSkills.test.ts`) covers it.
19. `f82573cd1c2` fix: carry only a skill-readable organization on the
Skills link, with a table-driven `AISettingsSidebar.test.tsx` case.
20. `0e55137de7b` fix: share the skill-readable organization filter
(`SkillsPage/readableSkillsOrganizations.ts`, used by the sidebar and
`SkillsPage`) and cover an organization that is listed but unreadable.
21. `97d42fd3cd8` refactor: split skill queries by owner.
`queries/skills.ts` goes back to main's `userSkills.ts` (main's names
and keys) plus a new `organizationSkills.ts` for the organization and
ACL queries; the table takes a `SkillsScope` instead of an owner union.
22. `4ddfb80ac54` refactor: invalidate skill lists after writes, instead
of patching the cached list; update still writes the detail from the
PATCH response.
23. `14d5b755087` refactor: pass skill organizations to the sidebar as
`Organization` objects instead of names.
24. `463df6a5e69` feat: pick one organization on the member skills page.
25. `9c802557b9c` refactor: tighten the skill query comments and tests.
26. `9002dc60382` test: cover the failed sharing save in Vitest
(`OrganizationSkillSharingDialog.test.tsx`).
27. `a9df756b976` and `5ebf7b8984a` merge the updated sharing layer,
which brings in main. `a9df756b976` moves the `toast` imports in
`OrganizationSkillSharingDialog.tsx` and `SkillEnabledSwitch.tsx` to
`#/components/Toaster/toast`, as main's Biome import rule now requires,
and resolves conflicts with main in the model and MCP server sharing
dialogs.
28. `ac3e62c83b7` test: assert the member page's organization switch
through requests. After a switch, the test checks that the list and the
viewed skill are requested from the selected organization (a Codex
review finding).
29. `63bb42754e3` fix: show read-only skill status instead of a disabled
switch (from jaaydenh's review). `SkillEnabledSwitch` loses its
`disabled` prop; a new `ReadOnly` story in `SkillsTableView.stories.tsx`
shows the icons, and the read-only case in `SkillsTable.test.tsx`
asserted the status icon and no switch (removed again in item 30).
30. `82b2487ad17` test: address Codex review on skills tests. The
`SkillsPage.test.tsx` update-only case now edits the description, saves,
and asserts the `updateOrganizationSkill` call. The read-only status
case in `SkillsTable.test.tsx` is removed because the `ReadOnly` story
covers that visual state, and `renderTable` loses its `access` argument.
`AISettingsSidebar.test.tsx`'s hoisted permissions mock drops its cast
for an explicit return type.
31. `658be8b8df5` merges the updated sharing layer (main at
`e7b76872098`); no changes of its own.

## Size

Production +1465/-617, tests and stories +1104/-141 (tests +690 net,
stories +273 net), generated +4/-0; total +2573/-758. The site changes
in this PR and #30613 net +2263 lines, against +3058 for the same scope
in the old stack. 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

#30590 (site rename), #30595 (site API), #30596 (skills table), #30597
(Enabled toggle), #30598 (organization page), #30599 (ACL autocomplete),
#30600 (permissions), #30603 (member page).

## Validation

- `pnpm run lint` clean (tsc, oxlint, knip, React Compiler) and Biome
clean; `pnpm run lint` reran clean on `13f03d095ff`, which contains this
PR up to `0e55137de7b`.
- Vitest: 9 files, 49 tests. Storybook Vitest: 7 files, 101 tests. These
full runs were on `a52f9ba659c`; on `0e55137de7b`, the three test files
the later fixes change (`api/queries/skills.test.ts`,
`AISettingsSidebar.test.tsx`, `SkillEditor.test.tsx`) and the two
`SkillsPage` tests that cover the changed `SkillsPage.tsx` pass, 20
tests.
- On `a6f8f63ad13`, which contains this PR up to `5ebf7b8984a` and both
main merges: 38 Vitest files (the skill queries, the sidebar, the skill
pages and components, the slash menu, and `pages/AgentsPage/utils`)
pass, 542 tests with 2 skipped.
- On `63bb42754e3`: `pnpm check` and the full `pnpm run lint` pass;
Vitest (`SkillsTable`, `SkillsPage`, `AgentSettingsSkillsPage`: 6 tests)
and Storybook Vitest (the `SkillsTableView`, `AgentSettingsSkillsPage`
and `SkillsPage` stories: 34 tests) pass; `coder-frontend-review`
passed.
- On `82b2487ad17`: `pnpm check`, the full `pnpm run lint`, and Vitest
on the three changed test files (7 tests) pass.
- On `658be8b8df5`: `go build`, `pnpm check` and the full `pnpm lint`
pass; 6 Vitest files with 39 tests pass.
- `frontend-review` (FE1 to FE10) and `coder-frontend-review` (8
reviewer roles); findings fixed or declined as noted above.
- Remote UAT round 7 through Coder Agents passed on the whole stack,
last on `13f03d095ff`, which contains this PR up to `0e55137de7b`; see
#30613's Validation for scope and findings.
- Remote UAT round 8 passed on `b03c14c86de` (one item graded on intent;
see #30613), which contains this PR up to `9c802557b9c`: the member page
organization picker, list refresh after writes on the personal and admin
tables, no stale ACL after deleting and recreating a skill, and the
sidebar Skills `?org=`. See #30613 for details. `9002dc60382`,
`ac3e62c83b7`, `63bb42754e3`, `82b2487ad17` and the main merges have
tests but no UAT run.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 16:57:41 +00: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
Mathias Fredriksson e7b7687209 fix(site): keep paragraph breaks in streamed chat text (#30551)
The chat UI dropped every whitespace-only text or reasoning delta.
Providers can stream a paragraph break as its own "\n\n" delta, so the
live preview showed "writing.Like this", and headings and list items
that need a line start rendered inline, until the saved message
replaced the preview. Interrupted turns, saved with one part per
delta, kept the joined text permanently.

Whitespace-only text now extends the preceding block of the same type
and is dropped only where it would start a block. A leading
whitespace delta still leaves the stream state null, so it does not
end the "starting" phase early, which is what the old check was for.
2026-10-13 15:47:21 +03:00
Danielle Maywood ff5edf2c3a refactor(site/src/pages/AgentsPage/components/ChatElements/tools): add ToolCall.Scrollable (#30648) 2026-10-13 13:24:12 +01:00
97c5260adb feat: add chat project instructions API (#30368)
Adds the experimental API for chat project instructions: `GET`, `PUT`,
and `DELETE
/api/experimental/organizations/{organization}/chats/projects/{project}/instructions`,
behind the `chat-projects` experiment.

- `GET` returns 200 with empty instructions and null
`updated_by`/`updated_at` when nothing is set, so clients don't need a
404 path.
- `PUT` requires update access only (the read-back runs under a system
context, so a custom role with update but not read can save). It
sanitizes the text with `SanitizePromptText`. It rejects blank text with
400, pointing the caller to `DELETE`, and rejects text over the chat
prompt byte limit. It records the caller as `updated_by`. The upsert and
the read-back that returns the editor's profile run in one transaction.
- `DELETE` returns 204, including when nothing is set.
- Users without access to the project get 404, like the other project
routes.
- `PUT` and `DELETE` are audited as a new `chat_project_instructions`
resource (`write` and `delete`), with the project as the resource ID and
its name as the target. The diff tracks only the instruction text.
Saving unchanged text and deleting unset instructions are not audited. A
per-project advisory lock serializes reading the previous value with the
write, so concurrent edits produce accurate diffs. Migration `000615`
adds the enum value.

The codersdk client gains `ChatProjectInstructions`,
`UpdateChatProjectInstructions`, and `DeleteChatProjectInstructions`.

**What to scrutinize:** writes are last-writer-wins with no version
precondition, matching the deployment, user, and organization prompt
settings.

**Generated:** `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
and `docs/reference/api/schemas.md` come from the Swagger annotations;
`site/src/api/typesGenerated.ts` comes from `codersdk`;
`docs/admin/security/audit-logs.md`, `coderd/database/dump.sql`, and
`coderd/database/models.go` come from the audit table and migration.
Together they are about 400 of this PR's lines.

**Validation:** `make gen` leaves no diff. `go test ./coderd -run
TestChatProject` and `go test ./enterprise/coderd -run
TestChatProjectInstructions` pass. `TestChatProjectInstructionsAudit`
checks the audit entries for create, update, and delete, and that no-op
saves and deletes are not audited. It covers unset GET, create, update,
blank and oversized PUT, delete, access denial, and cascade on project
delete.

---

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 19:15:16 +07:00
Michael Suchacz b2c8798e0e fix: replay stateless OpenAI reasoning across chat turns (#30298)
OpenAI Responses chats default to `store=false`, and chatd only replayed
reasoning as an `item_reference`, which needs provider-side storage.
Reasoning was therefore dropped between tool steps and turns, so
reasoning models lost their chain of thought mid-task.

This pins coder/fantasy `coder_2_33` at 6ba8681, which includes fantasy
#63 (and #64, #65, and #66). #63 captures each completed reasoning item
(ID, `encrypted_content`, summary) and replays it in full regardless of
`store`. In chatd:

- Every Responses call requests `reasoning.encrypted_content`. The
`store` default and configured includes are unchanged, and Chat
Completions requests are untouched.
- Prompt rebuilds keep reasoning parts without visible text when they
carry finalized encrypted state, so reasoning survives durable history
and coderd restarts.
- The provider-switch sanitizer also strips OpenAI reasoning from
history produced by a different or unknown provider instance, since
reasoning IDs and encrypted content only resolve where they were issued.
- A compaction model override on a different provider instance, or with
a different model, gets a compaction prompt without the chat's OpenAI
reasoning.
- Each saved reasoning part records the provider instance, model, and
credential (the deployment's or the user's personal API key) that
produced it, and the sanitizer keeps it only when all three match the
current turn, because another model, or the organization behind another
credential, can reject the encrypted content. Switching models, adding
or removing a personal key, or editing a config's model or provider
drops the earlier reasoning; switching back restores it. The record is
never returned by the API. Reasoning saved before this change has no
record and follows its model config.
- If OpenAI rejects replayed reasoning it cannot decrypt
(`invalid_encrypted_content`), for example after the deployment's key is
replaced with one from another organization, the request is retried once
without reasoning, and the reasoning that step produces is saved with
the provider's next rejection epoch. Epochs are kept separately for each
provider, model, and credential. Later steps and turns leave out
reasoning from earlier epochs, on any replica and after restarts, so
only the first request after the change is rejected and newer reasoning
keeps replaying. A retried step that returns no reasoning saves its
epoch on its first part. The advisor's prompt never includes OpenAI
reasoning, as on `main`.

## Testing

Rebased onto main at 98332c739b as 5735acb36ed (same tree as merging
the pre-rebase head a378071862a with main; older SHAs below refer to the
pre-rebase history). 3c17d807a33 then adds the model to the reasoning
record, 21156b2b32e pins Fantasy d55a867, which treats a response that
echoes `store: false` as unstored, bf795daa923 adds the retry and the
advisor change, 7eb8b1d029a moves the pin to 88cffb5 (`coder_2_33`
merged into #63; its OpenAI provider code is identical to d55a867), and
f4f40734a41 pins `coder_2_33` at 6ba8681 once #63 merged. That adds
fantasy #66, which replays the Responses message phase on assistant
text. abccede81f7 makes the retry remember rejected reasoning in the
process. The branch was then rebased onto main at abc2faed60, so every
SHA above refers to the pre-rebase history. 5fb3ce1689 replaces that
memory with the credential and a rejection epoch saved on each reasoning
part, and 62b5cb532a keeps epochs per provider, model, and credential
and saves the epoch when the retried step returns no reasoning.
1057beb327 hides the four internal fields from the Swagger spec and API
reference, and 29a705e099 merges main at d68b2c8b25. Its only
conflicts were the fantasy pin (kept at 6ba8681, whose `coder_2_33`
history includes main's 3510552) and test imports.

- Tests in `chatprompt`, `chatprovider`, `chatsanitize`, the
provider-switch sanitizer, and `integration_responses_test.go` cover
tool-step and durable replay, legacy and incomplete metadata, provider
switches, and a web search chat switching from `store=false` to
`store=true`. Integration tests also cover the retry, a later tool step
after it, the next turn on a fresh server against the same database
(with and without reasoning in the retried step), a personal key added
mid-chat, and the advisor prompt. Red-green verified, including a config
whose model is edited in place. The compaction override's model check
has unit tests and UAT coverage but no integration test. `go vet`,
targeted race tests, and the pre-commit hook (gen, fmt, lint, build)
pass. Local pre-push hooks were skipped; CI covers them.
- Remote UAT on dogfood with real gpt-5-mini and gpt-5.4 behind a
logging proxy that checks every request body. Rounds 1 and 2 failed on
dangling item references (both fixed). Rounds 3 to 5 passed
(ee3c0bf3d60, 0580870b5ff, a378071862a): tool-step and durable replay,
restarts, interrupts, provider switches and config repoints, web search
history, and compaction overrides. Both test providers shared one
upstream account, so cross-provider checks cover request shape, not a
real rejection. Round 6 at 21156b2b32e (model record) with gpt-5-mini
and gpt-5-nano: PASS. 151 Responses requests, all 200; no request
carried reasoning from a different model except an older, unrecorded
part that follows its config by design. Same-model config switches,
switching back, edits to a config's model, a mid-turn switch, restarts,
and a same-provider compaction override with a different model all
behaved as described. Round 7 at bf795daa923 (retry and advisor): PASS.
Through AI Gateway, a corrupted saved blob is rejected with HTTP 400
`invalid_encrypted_content`. All 14 rejected requests were retried once
without reasoning and returned 200, a different 400 was not retried, and
advisor requests on the chat model, a same-provider override, and
another provider carried no reasoning.
- f4f40734a41 changes only the pin. Its new OpenAI code is fantasy #66,
which UAT rounds 1 to 7 did not run. A live check of fantasy 6ba8681
through AI Gateway, two turns with tool calls on gpt-5.5 and gpt-5-mini
with `store` false and true: all 18 requests returned 200, and the
gpt-5.5 requests replayed encrypted reasoning followed by assistant
messages with the `commentary` and `final_answer` phases. `go test
./coderd/x/chatd/... ./codersdk/` passes (21 packages) on the same
fantasy tree.
- UAT round 8 at abccede81f7 (remembered rejection, and fantasy #66
through chatd) with gpt-5.5, gpt-5-mini, and gpt-5-nano: PASS. 110
requests; the 6 rejections were 5 corrupted saved blobs, each retried
once without reasoning and answered 200, and one unrelated `temperature`
error that was not retried. After the first rejection, later steps and
turns in that chat were never rejected again and replayed newer
reasoning. A coderd restart cost one more rejection, which also dropped
reasoning saved after the first one, and a second chat was unaffected.
gpt-5.5 requests replayed assistant messages with the phases the model
returned, with `store` false and true.
- UAT round 9 at 62b5cb532a (saved rejection epoch, personal key
switch) with gpt-5.5, gpt-5-mini, and gpt-5-nano: PASS. 158 Responses
and 7 Chat Completions requests; the 6 rejections were corrupted saved
blobs, each retried once without reasoning and answered 200, and an
unrelated `temperature` error was not retried. After a coderd restart,
and on a second coderd against the same database, the chat was not
rejected again and kept replaying the reasoning saved after the
rejection. Adding a personal key left out the deployment key's reasoning
before sending, and removing it brought that reasoning back. A retried
step without reasoning, two chats rejected at once, compaction, a model
switch after a rejection, and a switch to Chat Completions and back all
behaved as described.

## Review record

- Independent full-branch test audit at bbe1a1b27a: PASS.
- Codex through a378071862: compaction overrides kept foreign reasoning
and configs could be repointed to another provider (both fixed); a
request for documentation TODOs and two behaviors that already exist on
`main` (declined).
- Codex on 5735acb36e: two findings. Reasoning replayed after a
same-provider model switch: fixed in 3c17d807a33. A provider's base URL
edited in place keeps its reasoning: covered by the retry in
bf795daa923.
- Codex on 21156b2b32, bf795daa92, and 7eb8b1d029: no major issues.
Codex on f4f40734a4: rejected reasoning stayed in the chat's history, so
each later request in that chat was rejected and retried again without
any reasoning. Fixed in abccede81f7. Codex on abccede81f: that memory
was lost on a restart or another replica, where the next rejection also
dropped newer reasoning, and it grew without bound. Fixed in
5fb3ce1689. Codex on 5fb3ce1689: a rejection advanced the epoch for
every model and credential on the provider, and a retried step without
reasoning lost the new epoch. Both fixed in 62b5cb532a. Codex on
62b5cb532a: keep reasoning out of a config switched from Responses to
Chat Completions (declined: the Chat Completions converter already skips
reasoning parts, confirmed with a probe test). Codex on 29a705e099: no
major issues.
- ethanndickson: retry without reasoning on `invalid_encrypted_content`,
and keep OpenAI reasoning out of the advisor prompt. Both fixed in
bf795daa923. Then: in-process memory is not enough because dogfood
restarts on every merge and runs several replicas. Fixed in 5fb3ce1689
with his proposed rejection epoch in chat history, plus the credential
record, and tested with the next turn on a fresh server. Then: hide the
internal fields from Swagger, fixed in 1057beb327. Approved on
62b5cb532a.
- coder/fantasy#63 review: honoring an echoed `store: false` is fixed in
d55a867; replaying web searches that had no preceding reasoning is a
pre-existing gap, tracked in #30528.
- CI on 5735acb36ed: green after rerunning two failures outside this
change (a `cli` `TestSSH` data race, and a `test-go-pg` job timeout that
also fails on `main`). CI on 21156b2b32e: all checks pass. CI on
bf795daa923: all checks pass. CI on 7eb8b1d029a: all checks pass. CI on
f4f40734a41: all checks pass. CI on abccede81f7 did not run, because the
branch conflicted with `main` (#30492 changed the provider-switch
sanitizer to return database errors). CI on 62b5cb532a: all checks
pass. CI on 29a705e099: all checks pass.

> Xum, an AI coding agent, implemented, tested, and opened this PR on
behalf of @ibetitsmike.
2026-10-13 13:49:12 +02:00
Danny Kopping 71e8e526fa fix(aibridge): correlate Codex custom tool results to their AI Gateway thread (#30667)
Codex sends the results of custom (freeform) tools such as `apply_patch`
back as `custom_tool_call_output` input items.
`RequestPayload.correlatingToolCallID` only matched
`function_call_output`, so these follow-up interceptions had no
correlating tool call ID. They were not linked to the interception that
issued the tool call, which left blank AI Gateway sessions.

[Example
session](https://dogfood.cdr.dev/ai-gateway/sessions/01a1184a-08a4-7d50-8e15-a12368302a2f)

<img width="996" height="576" alt="image"
src="https://github.com/user-attachments/assets/5bce6035-963b-4438-897b-bee36ead5a47"
/>

`custom_tool_call_output` is now handled the same way as
`function_call_output`. The earlier `custom_tool_call` is already
recorded as a tool usage with its `call_id`, and
`GetAIBridgeInterceptionLineageByToolCallID` does not check the tool
type, so lineage now resolves without any other change.

Fixes AIGOV-707

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

- **Reproduction first:** the first commit adds blocking and streaming
`custom_tool_result.txtar` fixtures. Each one is a follow-up turn that
replays a `custom_tool_call` and ends with its
`custom_tool_call_output`. `TestResponsesOutputMatchesUpstream` now
checks `CorrelatingToolCallID` on every case, and
`TestCorrelatingToolCallID` gains a `custom_tool_call_output` case plus
a case where the last item is the tool call itself rather than its
result. On that commit, both fixture cases and the unit case fail with
`nil` instead of the custom tool's call ID. The second commit makes them
pass.
- **Out of scope:** other client-executed result types
(`computer_call_output`, `shell_call_output`, `apply_patch_call_output`,
`local_shell_call_output`) are not correlated either. Codex's
`apply_patch` arrives as a custom tool, so it is covered here. Those
other types were left out to keep this change tied to the reported bug.

</details>

> Generated by Coder Agents on behalf of @dannykopping.
2026-10-13 13:36:04 +02: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
Danielle Maywood 454a2fcc69 fix(site/src): show a loader instead of the error page during stale chunk reload (#30658) 2026-10-13 08:27:20 +00:00
christinandAndrew Aquino 4e4603eae9 fix(site/src/pages/UserSettingsPage/AppearancePage): raise theme swatch ring contrast to 3:1 (#30539)
The ring around each theme swatch in the Appearance settings (Theme mode
set to "Sync with system") used the decorative border color: `#27272A`
on the `#09090B` page, 1.33:1. The Dark default swatch is filled with
the page color, so that ring is its only visible boundary, which fails
WCAG 1.4.11 Non-text Contrast.

The ring now uses the existing `surface-invert-secondary` token, which
the Slider handle already uses for its border: `#A1A1AA` on the dark
page (7.8:1) and `#3F3F46` on white (10.5:1). The blue selected and
focus outline is unchanged.

Fixes DEQ-597

## Before and after

Appearance > Theme mode "Sync with system", resting state. Dark default
is the first swatch.

| | Before | After |
|---|---|---|
| Dark page | <img width="360"
src="https://raw.githubusercontent.com/coder/coder/assets/a11y-theme-swatch-contrast/dark-before.png"
/> | <img width="360"
src="https://raw.githubusercontent.com/coder/coder/3e8883931834186feab055d104b7c62fb352240d/dark-after.png"
/> |
| Light page | <img width="360"
src="https://raw.githubusercontent.com/coder/coder/assets/a11y-theme-swatch-contrast/light-before.png"
/> | <img width="360"
src="https://raw.githubusercontent.com/coder/coder/3e8883931834186feab055d104b7c62fb352240d/light-after.png"
/> |

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

- **Resting border, not a focus state.** 1.4.11 requires the control's
boundary to be visible without interaction. The swatches already show a
blue `content-link` outline when focused or selected, and the audit
flagged the unselected, unfocused swatches.
- **Existing token instead of a new one.** `surface-invert-secondary`
already exists on `main` and is used as a control border by the Slider
handle. It passes 3:1 in both modes. None of the existing `border-*`
tokens do on the dark page (`border-secondary` is 1.9:1).
- **Before images** were captured on the same dev server with the
previous border value (`hsl(var(--border))`) applied through an injected
style. Light-page images force the `light` class on `<html>`.

</details>

<details>
<summary>Verification</summary>

- Playwright on the dev server at `/settings/appearance`: the Dark
default swatch's computed border is `rgb(161, 161, 170)` on the dark
page (`rgb(9, 9, 11)`) and `rgb(63, 63, 70)` on the light page
(`rgb(255, 255, 255)`).
- `pnpm check` and `pnpm lint` pass.
- vitest unit (`src/pages/UserSettingsPage`, `src/theme`): 13 files, 399
tests pass.

</details>

---

_Generated by Coder Agents on behalf of @chrifro._

---------

Co-authored-by: Andrew Aquino <dawneraq@gmail.com>
2026-10-13 10:02:22 +02:00
Michael Suchacz 7517301ffa chore: add golangci new-code quality gates (#30622)
Stack context: second layer of the Go lint gate stack, built on the
exclusion fix below.

Why: adds commented-out code detection and a `log/slog` ban to the main
config, plus a new-code-only pass requiring reasons on lint
suppressions, flagging ignored errors (including `_, _ = w.Write(...)`),
and banning `time.Sleep` in tests. Fixing the hits surfaced a real bug:
GitLab warnings went to the wrong logger. The new-code pass resolves
symlinked checkout paths so it does not silently report nothing.

Validation: both configs report 0 issues; each seeded violation is
caught; `make pre-commit` passed.

> Xum acted for Mike to open this PR.
2026-10-13 07:57:56 +00:00
Michael Suchacz e8dcf9a3f1 fix: anchor golangci .git exclusion and fix hidden findings (#30621)
Stack context: two-layer stack tightening Go lint gates. This bottom
layer fixes the lint exclusion; the layer above adds new rules.

Why: a `.git` path exclusion in the golangci config was hiding Go files,
masking 70 findings. This fixes the exclusion, fixes the findings
(`agent/agentgit` now runs git through `agentexec.Execer`), and adds a
`make lint/go` check that fails when an exclusion hides Go files. `make
lint/go` now waits for a concurrent golangci-lint run instead of
failing. The exhaustruct exclusion rule for `scripts/*` had the same
problem: as a regex it also matched `agent/agentscripts` and
`coderd/agentapi/scripts.go`, so it is now `^scripts/`.

Validation: full-tree lint reports 0 issues; the new check fails on the
old entry and passes on the new one.

> Xum acted for Mike to open and update this PR.
2026-10-13 07:57:56 +00:00
christin d68b2c8b25 fix: keep error toasts visible until dismissed (#30420)
Error toasts now stay on screen until the user closes them, to meet WCAG
2.2.1 Timing Adjustable. Success, info, and warning toasts keep Sonner's
default timer.

Fixes
[DEQ-463](https://linear.app/codercom/issue/DEQ-463/timed-toast-without-user-control)
(Open Cursor Desktop failure) and
[DEQ-310](https://linear.app/codercom/issue/DEQ-310/timed-toast-without-user-control)
(adding a user who is already in a group).

Sonner has no default duration per toast type, so this adds
`site/src/components/Toaster/toast.ts`, a thin wrapper around Sonner's
`toast`:

- `toast.error` defaults to `duration: Infinity`. A caller can still set
its own `duration`.
- `toast.promise` failures get the same default. Sonner renders a
rejected promise without calling `toast.error`, and the group member
flow (DEQ-310) uses `toast.promise`.
- All other methods pass straight through.

All `toast` imports now go through the wrapper. A Biome
`noRestrictedImports` rule blocks importing `toast` directly from
`sonner`, following the existing `@pierre/diffs` rule. Tests that mocked
`sonner` now mock the wrapper. Most of the 130-file diff is the import
swap.

### Proof

Error toast on the create token page (duplicate name), with the pointer
off the toast so Sonner doesn't pause the timer. Shots are taken once
the enter animation has finished:

| | 1 second after the error | 11 seconds after the error |
|---|---|---|
| Before | ![before
1s](https://raw.githubusercontent.com/coder/coder/9f65d67d10d43265082ab4f60e48527239845061/pr/pr-before-1s.png)
| ![before
11s](https://raw.githubusercontent.com/coder/coder/9f65d67d10d43265082ab4f60e48527239845061/pr/pr-before-11s.png)
|
| After | ![after
1s](https://raw.githubusercontent.com/coder/coder/9f65d67d10d43265082ab4f60e48527239845061/pr/pr-after-1s.png)
| ![after
11s](https://raw.githubusercontent.com/coder/coder/9f65d67d10d43265082ab4f60e48527239845061/pr/pr-after-11s.png)
|

Also checked in the running app: the close button dismisses the error
toast, and a "Token created" success toast still disappears on its own.

`toast.test.tsx` covers the error and rejected `toast.promise` cases
staying visible, dismissing them with the close button, and success
toasts still timing out. With the persistent duration removed, the two
error cases fail.

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

- A first version set `duration: Infinity` on the shared `<Toaster>` for
every toast type. Product feedback: only error toasts were reported, so
success and info toasts should keep their timer.
- The wrapper sets the duration when each toast is created. The
alternative was to watch toasts from `<Toaster>` with `useSonner` and
change them afterward. That would add subscription and timer-ordering
issues.
- I didn't change Sonner's exported `toast` object in place. The wrapper
plus a lint rule is explicit and enforced.
- The experimental chat board undo toast (`runPlan.ts`) uses `toast()`
with a timer that matches its undo window, so it isn't affected.
- Not reproduced end to end: the Groups flow needs a Premium license,
and the Cursor flow needs the app installed. Both use the
`toast.promise` and `toast.error` paths the tests cover.

</details>

---

_Generated by Coder Agents on behalf of @chrifro._
2026-10-13 09:21:53 +02:00
christin bc445defd6 fix(site/src/components): raise breadcrumb and topbar separator contrast (#30546)
Raises the contrast of the `/` separators in `BreadcrumbSeparator` and
`TopbarDivider` to meet WCAG 1.4.11 (non-text contrast, 3:1). Fixes
DEQ-163 and DEQ-418.

Both separators now use `content-secondary`, which measures 7.78:1
against `surface-primary` in dark mode and 7.69:1 in light mode. The
previous colors were `content-disabled` (1.90:1 dark, 2.55:1 light) and
`border-default` (1.34:1 dark, 1.27:1 light). `border-secondary` and
`content-disabled` resolve to the same values, so neither was a viable
fix.

Affects every breadcrumb in the settings layouts (deployment,
organization, user, template, workspace) and the topbar dividers on the
workspace page and the template version editor.

| | Before | After |
|---|---|---|
| Breadcrumb (`/deployment/overview`) | ![breadcrumb
before](https://raw.githubusercontent.com/coder/coder/pr-assets/fix-separator-contrast/breadcrumb-before.png)
| ![breadcrumb
after](https://raw.githubusercontent.com/coder/coder/pr-assets/fix-separator-contrast/breadcrumb-after.png)
|
| Topbar divider (template version editor) | ![topbar
before](https://raw.githubusercontent.com/coder/coder/pr-assets/fix-separator-contrast/topbar-before.png)
| ![topbar
after](https://raw.githubusercontent.com/coder/coder/pr-assets/fix-separator-contrast/topbar-after.png)
|

In the running app (dark theme), both separators now compute to
`rgb(161, 161, 170)` on `rgb(9, 9, 11)`. The topbar divider measured
`rgb(39, 39, 42)` before the change.

Design note: both tickets carry `ux-input-needed`. The separator now has
the same weight as secondary text. A dedicated, subtler separator token
at about 3:1 is an alternative if design prefers.

> [!NOTE]
> This PR was generated by Coder Agents on behalf of @chrifro.
2026-10-13 09:19:45 +02:00
Sas Swart 1320c010af feat(site): show provider type in model form and model list icon tooltip (#30353)
The model form and models list showed the provider type only through an
icon, which falls back to a generic icon for unmapped types like
`openai-compat`. Model prices are keyed by provider type, so admins
could not tell which type to use with `coder exp ai-model-prices update
--provider`.

- The model form shows `Provider type: <type>` under the provider
select, in both add and edit mode.
- The provider icon on each models list row shows a `Provider type:
<type>` tooltip on hover and has a matching accessible name.

Fixes AIGOV-686

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

- An earlier revision rendered the raw type inline next to the label in
the provider select, the Add model menu, and the models list. When a
provider has no display name, the label falls back to its name, which
defaults to the type, so most rows read like "anthropic anthropic".
Review feedback suggested helper text under the form's select plus a
tooltip on the icon instead.
- The tooltip is only on the models list icon. Tooltips on icons inside
select options or menu items conflict with their hover and keyboard
handling, and the form's helper text already covers that flow.
- The icon trigger is a non-focusable `role="img"` span with an
`aria-label`, so it adds no tab stop inside the clickable row.
- Existing exact accessible-name assertions in the ModelForm and
ModelsPageView stories are restored; they guard the aria-hidden icon
fix.
- Coverage: the `ModelForm` `ShowProviderType` story (plus the existing
`Add` and `Edit` stories) captures the helper text for an
`openai-compat` provider. The `ModelRow` `UnmappedProviderType` story
hovers the generic icon so Pixel captures the tooltip.

</details>

> Generated by Coder Agents on behalf of @SasSwart.
2026-10-13 09:07:35 +02:00
Bobby Ho dae7967bd1 feat: persist script resource addresses and dependencies (#30625)
feat(coderd): persist workspace agent script dependencies

Persist Terraform resource addresses and script dependencies supplied by
the provisioner (#30451, #30491), and expose them through the SDK and
REST API.

- Add migration 000618 with `resource_address` and `dependencies`
  columns, empty defaults, and a JSON-array constraint. API responses
  always include the address and omit empty dependency lists.
- Preserve `success` and `completion` requirements, including scripts
  on devcontainer subagents. Legacy scripts and older provisioners
  remain compatible through empty defaults.
- Reject empty prerequisite addresses and unsupported requirements,
  rolling back the entire job. Invalid stored dependencies return HTTP
  500 rather than silently dropping ordering.
- Add persistence, validation, rollback, devcontainer, API, and migration
  coverage; regenerate API docs and TypeScript types.

Unordered templates retain their existing execution behavior.
Dependency lists remain empty until #30556. Agent manifest wiring and
the agent API version bump are deferred to a follow-up.

Refs PLAT-548.
2026-10-13 03:43:55 +00:00
Ehab Younes 2f2169ed19 fix: deduplicate template insights family metrics (#30497)
coderd_insights_applications_usage_seconds summed each family's per-app
minutes, so a user with VS Code and Cursor open in the same minute was
counted as two VS Code minutes. GetTemplateInsightsByTemplate now takes
the registry's app-to-family mapping as jsonb, groups the raw agent
stats by family, and counts each minute once per user and family.

- Keep the metric's four built-in series (Visual Studio Code, JetBrains,
  Web Terminal, SSH) and their labels; only their values change. The
  HELP text now says built-in apps are grouped by family.
- Add AppFamilyName.DisplayName() and remove the duplicate
  TemplateBuiltinAppDisplayName* constants from codersdk. The template
  insights handler returns the same display names.
- Pin how the migration 000596 rollback approximates family minutes
  from per-app rows.

Family values can drop wherever the old per-app sum double-counted
overlapping apps. No migration or storage changes.
2026-10-12 23:58:35 +03:00
Michael Suchacz 41f5caafec fix: fold web searches, answer reasoning, and OpenAI narration into working blocks (#30529) 2026-10-12 22:53:07 +02:00
Jeremy Ruppel c4fabe90ae fix(agent/x/agentmcp): disable standalone SSE for HTTP MCP servers (#30484)
tl;dr is this should fix the storybook mcp server in Coder Agents. the
storybook mcp never responds to the SSE GET, so it never connects, and
reload fails. this disables that SSE GET and should let storybook
reconnect on config reload

---

HTTP workspace MCP servers whose `/mcp` endpoint never answers the
standalone SSE GET (for example, the Storybook dev server) hang the
agent's MCP reload indefinitely. The go-sdk opens that GET inside
`Connect` on a context the agent's 30s connect timeout does not bound,
and because reloads are singleflighted, every later `.mcp.json` change
waits behind the hung one. The server never shows up as connected or
failed, and no MCP config change is picked up until the agent restarts.

Set `DisableStandaloneSSE: true` on the streamable HTTP transport. The
agent's client registers no handlers for server-initiated messages, so
the stream is unused; tool call responses and in-request notifications
still arrive on the POST.

<details>
<summary>Investigation and decision log</summary>

**Symptom:** a `storybook` HTTP server in `.mcp.json` never produced
`storybook__*` tools in chats, while stdio servers worked.

**Findings:**

- Agent log showed the startup connect failing with `connection refused`
(Storybook was not up yet), and a later reload failing with `standalone
SSE request failed (session ID: ...)`, meaning `initialize` had
succeeded and the GET stream was the failure point.
- After touching `.mcp.json` with Storybook running, no reload result
was ever logged (success or warning).
- A standalone probe using go-sdk v1.8.0 and the same transport config
hung in `Connect` past its 30s timeout. Goroutine dump: `Client.Connect
-> sessionUpdated -> connectStandaloneSSE -> connectSSE`, which uses the
connection's lifetime context, not the connect context.
- `curl` against Storybook: `POST initialize` returns a session ID; `GET
/mcp` with that session sends no response headers at all. The spec
requires either `text/event-stream` or 405, so Storybook is
non-compliant, but the agent should not wedge on it.
- With `DisableStandaloneSSE: true`, the same probe connected in ~7ms
and listed all 8 Storybook tools.

**Why disable instead of alternatives:**

- `mcp.NewClient(..., nil)` in `manager.go` registers no
`tools/list_changed`, sampling, elicitation, roots, or logging handlers,
so nothing on the standalone stream is consumed today.
- The spec makes the standalone GET optional for clients; responses to
client requests are never sent on it.
- Bounding `Connect` with our own timeout would require abandoning a
stuck goroutine and session per bad server, since the hang is inside the
SDK call on a context we do not control.
- Tradeoff: live `tools/list_changed` refresh would need the stream
back, opened after `Connect` and off the reload path.

**Out of scope, noted for follow-up:**

- A server that is down when the agent first connects is not retried
until `.mcp.json` changes.
- A server that restarts invalidates the session ID, so the next POST
fails and nothing reconnects the session. Disabling the standalone
stream does not change this.

</details>

---

Generated by Coder Agents on behalf of @jeremyruppel.
2026-10-12 16:01:23 -04:00
TJ ca7d7afea9 fix(site/src/pages/AISettingsPage): align collapsible section chevron with title (#30654)
Moves the expand/collapse chevron in the AI settings collapsible
sections (Cost estimate, Provider configuration, and the MCP server form
equivalents) from `mt-0.5` to `mt-1` so it centers on the title's first
line. The `text-sm` title has a 24px line-height and the icon is 16px,
so it needs a 4px offset.

Fixes DES-22168

> Generated by Coder Agents on behalf of @tracyjohnsonux.
2026-10-12 15:53:18 -04:00
Atif Ali 8a063ef0d5 docs: add Claude Desktop as a supported client (#30653)
Closes
[DOCS-1198](https://linear.app/codercom/issue/DOCS-1198/document-claude-desktop-as-a-supported-coder-client)

Adds Claude Desktop alongside the other supported clients and IDEs. Once
the Coder CLI is installed and logged in, running workspaces appear in
Claude Desktop.

## Changes

- New page `docs/user-guides/workspace-access/claude-desktop.md`:
prerequisites, setup, troubleshooting.
- New `## Claude Desktop` section in `workspace-access/index.md`.
- Registered the page in `docs/manifest.json`.
- Added Claude Desktop to the IDE list in the glossary.

## Notes

- Setup steps checked against `docs/reference/cli/` and the existing SSH
docs.
- `make fmt/markdown`, `lint/markdown`, `lint/docs-manifest`,
`lint/emdash`, `lint/docs-html` pass.

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑💻
2026-10-12 19:09:46 +00:00
Nick Vigilante f2ddf215dc docs(docs/user-guides/workspace-access): fix broken vscode-coder demo GIF links (#30655)
Closes
[DOCS-1201](https://linear.app/codercom/issue/DOCS-1201/fix-broken-vscode-coder-demo-gif-links-in-workspace-access-docs)

## Summary

coder/vscode-coder#1134 moved `demo.gif` from the repo root into
`media/`, so the VS Code demo GIF embed now returns a 404.
Linkspector flagged it on #30653
([thread](https://github.com/coder/coder/pull/30653#discussion_r4249822055)).

## Changes

- Point the demo GIF embed at `media/demo.gif` in
`docs/user-guides/workspace-access/index.md` and `vscode.md`.

## Testing

- `curl -sIL`: new URL returns 200, old URL returns 404.
- `make lint/markdown` and `make fmt/markdown` pass.

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑‍💻
2026-10-12 14:50:24 -04:00
coder[bot]andAtif Ali 8674e8529e docs: note coder_agent dir un-deprecation in 2.29-2.34 ESR upgrade guide (#30533)
## Summary

Follow-up to
[coder/terraform-provider-coder#549](https://github.com/coder/terraform-provider-coder/pull/549),
which un-deprecated `coder_agent.dir`.

The 2.29-2.34 ESR upgrade guide still says `dir` is deprecated, warns,
and breaks Coder Desktop file sync, and tells admins to set it to
`$HOME`. As planned in #549, this keeps the original row as history and
appends an **Update** to the New State and Action cells:

- Coder Terraform provider 2.20.0 removed the deprecation and warning.
- Coder Desktop file sync works with any `dir` on macOS
[v0.8.4](https://github.com/coder/coder-desktop-macos/releases/tag/v0.8.4)
and Windows
[v0.8.5](https://github.com/coder/coder-desktop-windows/releases/tag/v0.8.5)
(Mutagen v0.18.5,
[coder/mutagen#10](https://github.com/coder/mutagen/pull/10)).

The rest of the diff is `markdown-table-formatter` re-padding the table.
`markdownlint-cli2` passes.

## Merge timing

Opened as a draft. #549 is only in `v2.20.0-pre0` so far; mark ready and
merge once provider 2.20.0 is published to the registry. If the release
number changes, update the version in the row.

Review requested from @aqandrew.

---
Opened by Superblink on behalf of @matifali.

Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com>
Co-authored-by: Atif Ali <atif@coder.com>
2026-10-12 23:47:48 +05:00
Denis AfonsoandClaude d7bf081e57 docs: point the 2.29 ESR row at v2.29.21 (#30538)
Updates the latest-patch link for the 2.29 Extended Support Release in
the release calendar to
[v2.29.21](https://github.com/coder/coder/releases/tag/v2.29.21),
released 2026-10-09.

One-line change; no other rows touched.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 15:57:02 +01:00
Jeremy Ruppel abc2faed60 fix(site): keep path separator in terminal websocket URL (#30573)
Enables oxlint's `no-unused-expressions` rule and fixes its violations,
two of which were bugs.

- `terminalWebsocketUrl` built `` `${url.pathname}/` `` without
assigning it, so a base URL with a path (for example a proxy at
`/prefix`) produced `/prefixapi/v2/...`. It now assigns `url.pathname`,
and a test covers it (the test fails without the fix).
- The deployment `experiments` e2e test called `expect(...).toBeVisible`
without `()` or `await`, so those two assertions never ran.

The remaining three hits were `a && f()` and ternaries used as
statements. These are rewritten as `if` statements with no behavior
change.

Depends on #30572

<details>
<summary>Context and findings</summary>

Part of evaluating oxlint's `correctness` category one rule at a time
(see #30572). This rule had 6 hits in 5 files.

The e2e fix makes two assertions active for the first time. Enabled
experiments render with `option-enabled` in `OptionValue`, so they are
expected to pass, but they were not run locally.

Validation: `pnpm run lint` (Biome, oxlint, types, circular deps, React
Compiler, knip) and the full unit suite.

</details>

_Generated by Coder Agents on behalf of @jeremyruppel._
2026-10-12 10:31:07 -04:00
Jeremy Ruppel 1c805b0931 fix(site): use page count in usePaginatedQuery overshoot fallback (#30572)
Enables oxlint's `erasing-op` rule and fixes the one violation it found,
an operator precedence bug in `usePaginatedQuery`.

When the requested page reports a count of 0, the hook refetches page 1
to compute where to clamp. `Math.ceil(firstPageResult?.count ?? 0 /
limit)` parsed as `count ?? (0 / limit)`, so it used the record count as
the page count and left the user on the overshot page. The fix adds
parentheses, and a regression test covers it (the test fails without the
fix).

<details>
<summary>Context and findings</summary>

Part of evaluating oxlint's `correctness` category. Turning on the whole
category reported 1152 diagnostics across 24 rules, so rules are being
enabled one at a time instead, which keeps the explicit allowlist model
in `.oxlintrc.jsonc`. `erasing-op` had a single hit, and it was a real
bug.

Validation: `pnpm run lint` (Biome, oxlint, types, circular deps, React
Compiler, knip) and the full unit suite.

</details>

_Generated by Coder Agents on behalf of @jeremyruppel._
2026-10-12 10:31:06 -04:00
Ehab Younes 5b060beeb1 feat: separate connection log methods from app names (#30466)
Connection logs now record how a connection was made
(`connection_method`) separately from which app made it (`app_name`).
Storage, the HTTP API, search filters, and the UI move to the new
fields. Legacy agent reports and the deprecated `type` field keep
working.

- Add `connection_method` (`ssh`, `reconnecting_pty`, `workspace_app`,
  `port_forwarding`, `tunnel`) and optional `app_name` and
  `app_display_name` to `GET /api/v2/connectionlog`. Deprecate `type`
  and make it a plain string in the API and the Go SDK.
- Add `method:` and repeatable `app:` search filters. `type:` keeps its
  old results but can't be combined with the new filters.
- Replace the Type menu with a Method menu, show the app next to the
  method in each row, and warn when a filter uses `type:`.
- Change the Active SSH connections preset to `method:ssh`, so it also
  includes SSH sessions from VS Code and JetBrains apps.
- Generate `codersdk.ConnectionLogMethod` from the database enum with
  `typegen dbenums`.
- Migration 000617 rewrites `connection_logs` under an ACCESS EXCLUSIVE
  lock, which takes about 50 seconds for 10 million rows. `vscode` and
  `jetbrains` rows become `ssh` rows with that app. Rolling back folds
  apps into the old types and loses per-app names.
- Document the new filters and how to replace each `type:` value.

Closes #27412
2026-10-12 15:56:40 +03:00
Denis AfonsoandClaude 594bc829c1 ci: keep coder-preview images for 30 days instead of 7 (#30635)
<!--

If you have used AI to produce some or all of this PR, please ensure you
have read our [AI Contribution
guidelines](https://github.com/coder/coder/blob/main/contributing/AI_CONTRIBUTING.md)
before submitting.

-->

Raises `keep-younger-than` in the `Prune old images` step from 7 to 30
days.

## Why

Release-branch builds push per-arch images tagged `v<version>-<arch>`,
then a multi-arch index tagged `<version>` and `release-X.Y`. The prune
step deletes `^v` tags older than 7 days, but it keeps the index because
its tags don't match. After a week, anything pinned to a `release-*`
digest points at an index whose children are gone, and pulls fail.

This took down cdrstable.dev today (coder/dogfood#694) and on Sep 11
(coder/dogfood#524). Running pods were fine until their nodes were
replaced, then every coder and provisioner pod hit `ImagePullBackOff`.

## Evidence

The pinned index still exists:
```
$ curl -sI -H "Authorization: Bearer $T" -H "Accept: application/vnd.oci.image.index.v1+json" \
    https://ghcr.io/v2/coder/coder-preview/manifests/release-2.38
HTTP/2 200
docker-content-digest: sha256:b95a60b623a8f67223fb7dfe6479159b0edb809c96bee70249de152c3edde724
```
Its per-arch children were pruned:
```
v2.37.3-devel-c3c6a67282-amd64                 HTTP/2 404
v2.37.3-devel-c3c6a67282-arm64                 HTTP/2 404
sha256:be71cee3… (amd64 child of the index)    404
```
Kubelet:
```
failed to pull and unpack image "ghcr.io/coder/coder-preview@sha256:b95a60b6…": content at
https://ghcr.io/v2/coder/coder-preview/manifests/sha256:be71cee3… not found
```

## Why 30 days

Stable's longest preview pin has been 14 days, and both outages happened
at day 7+. 30 days is about 2× that.

- **Cost:** `coder-preview` is public, and Container registry storage
and bandwidth are currently free.
- **Size:** about 17 builds a day at about 220 MiB of unshared binary
layer per arch. Storage grows from roughly 75 GiB to roughly 330 GiB.
- **Limits:** GitHub documents no total-storage or version-count limit
for ghcr.

This makes the failure much less likely but doesn't remove it: a kept
index can still outlive its children. A real fix would be an index-aware
prune. Separately, coder/dogfood will add a daily check that every
pinned image is still pullable.

AI disclosure: this PR was prepared with Claude Code. I reviewed the
change and checked the registry state above myself.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 12:58:05 +01:00
Danielle Maywood cf6ab8739e fix(coderd/x/gitsync): attach subagent git refs to the root chat (#30647) 2026-10-12 12:55:20 +01:00
Danielle Maywood c735c1dd1d fix(site): keep agent chat scroll on tool toggles and log streams (#29354)
Help keep position better in Coder Agents chat transcript during active
scrolling

<details>
<summary>LLM slop description</summary>

In the agent chat, a tool call that expands or collapses can make the
transcript jump. The clicked row can scroll out of view, or the next
streamed output can pull the view to the bottom. The scroller cannot
tell a layout change from new output, so it reacts to a toggle as if the
reply grew.

`ToolCall` now tells the scroller before it toggles. The scroller then
holds the view in place until the reader scrolls, a scroll command runs,
or a new turn starts. The changes are `LOCAL CHANGE` edits to the
scroller source that #29473 vendored.

The `create_workspace` and `start_workspace` rows also made the
transcript jump while the workspace built. Their log boxes used
`scrollIntoView` to show new lines, and that also scrolls the
transcript. At the end of the build, the view could stop following the
reply. Now each box scrolls only itself, and only while the reader is at
its end, so a reader who scrolls up in the box keeps their place. Other
pages use the scroll in the shared `WorkspaceBuildLogs` component, so
that component does not change.

Four behavior changes are intentional. While a turn is anchored, a large
block of output no longer pulls the view to the bottom. The reader stays
on the turn and can use the jump-to-bottom button. Collapsing a tool
while the view follows the reply also stops following, so the rows near
the pointer stay put for the next click. A press on the scrollbar now
counts as a scroll, so it releases the held view like a wheel or key
scroll. Space on a button does not count as a scroll, because Space
activates the button.

Related upstream bug reports, all open with no upstream fix:
shadcn-ui/ui#11175, shadcn-ui/ui#11577, shadcn-ui/ui#11224

</details>

> [!NOTE]
> Generated with [Coder Agents](https://coder.com/docs/ai-coder/agents)


---


https://github.com/user-attachments/assets/deb75f78-5f4e-49b8-baa3-9e2196234756



https://github.com/user-attachments/assets/0f03c526-d60d-4533-8098-1f200e8f11c1



https://github.com/user-attachments/assets/4a014fd6-a3f0-42cd-b5fc-7a61b8f783f5



https://github.com/user-attachments/assets/25d7fb5f-51f1-412d-95ab-a4f3dbeeb167



https://github.com/user-attachments/assets/a1e08441-8d87-4779-96f0-cd676ae217a7



https://github.com/user-attachments/assets/81577372-3e07-4d5a-b732-8ea756d7b604



https://github.com/user-attachments/assets/7dd03bc3-f5f7-4ea9-b602-0369ad120575



https://github.com/user-attachments/assets/41393122-85a8-4e4d-b0f2-1e392ccc4cb9


https://github.com/user-attachments/assets/38caf176-2cb5-4920-9cbc-0262c2157a35



https://github.com/user-attachments/assets/5606106a-2466-4cdf-9fcf-4df38f45d20f



https://github.com/user-attachments/assets/03b1060d-82c5-4844-aaf2-12c29572ae8c



https://github.com/user-attachments/assets/4b966412-0278-4d41-ac2e-91de2a61d803



https://github.com/user-attachments/assets/64ff8cce-0491-46c6-a563-afcb726b2dd1



https://github.com/user-attachments/assets/5c005789-ce82-4d7c-a918-ce2d5ec819c4



https://github.com/user-attachments/assets/0b9bfcda-4971-47c6-802b-3ed4e78a2f75



https://github.com/user-attachments/assets/683ac4ef-cd02-470f-b301-8a80554b9122



https://github.com/user-attachments/assets/dc8da762-b4c3-42ef-93d9-d1a3b13eb7eb
2026-10-12 09:03:44 +01:00
Ethan 4afd834ad2 fix(coderd/x/chatd): return database errors from turn preparation (#30492)
Relates to CODAGT-1330

When chatd prepares a turn, it reads a bunch of things from the
database: the user's custom prompt, plan mode instructions, personal
skills, the advisor config, the user's compaction threshold override,
MCP server configs, inline MCP servers, MCP user tokens and the pinned
workspace MCP tools. If any of those reads failed, we'd log a warning
and run the turn without them, so the model would quietly ignore the
user's instructions or be missing tools for that turn.

To fix, we'll just return the error instead, so the prepare retry runs,
and the chat shows an error if the reads keep failing. The provider
switch history sanitizer and the cancel of deleted tool calls also
return their database errors now. A model config that's unavailable,
e.g. deleted, is still treated as foreign by the sanitizer like it is
today.

An inline MCP server with invalid stored headers still shows up as a
failed connect in the chat debug panel, but a failed read of the inline
MCP servers themselves now fails the turn.

This PR is in a stack on top of #30449.
2026-10-12 09:53:45 +11:00
Ethan 807878c1ab fix(coderd): return database errors at chat create and subagent spawn (#30449)
Relates to CODAGT-1330

chatd stores the deployment and organization system prompts in a chat
when it's created. If either read failed, we'd log it and use the
built-in default, or skip the organization prompt, so the chat ignored
the admin's instructions for its whole life. The subagent model override
had the same problem, and the compaction and advisor overrides quietly
fell back to the chat model for that turn.

To fix, we'll just return the database error instead. Overrides that
can't be used, e.g. the model was deleted or the user has no API key for
its provider, still fall back like they do today.
2026-10-12 09:53:44 +11: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
dfa72df9aa docs: remove references to unsupported SAML authentication (#30507)
## Summary

Coder doesn't support SAML, but a few docs pages implied it did.
This PR removes those mentions.

Resolves
[DOCS-1194](https://linear.app/codercom/issue/DOCS-1194/remove-saml-mentions-from-docs-coder-doesnt-support-saml).

## Changes

- `docs/install/index.md` and `docs/install/prepare/index.md`: "OIDC or
SAML application" is now "OIDC application".
- `docs/.style/style-guide/audience-and-scope.md`: the example snippets
no longer mention SAML or link to a `./saml.md` page that doesn't exist.
The hub-page example now lists headless authentication instead, and the
persona "Coder surface" lines say "OIDC" in place of "OIDC/SAML".

<details>
<summary>Evidence that Coder doesn't support SAML</summary>

Checked against `main`:

- No SAML library in `go.mod`, `go.sum`, or `site/package.json`.
- The `login_type` enum in `coderd/database/dump.sql` and
`codersdk.LoginType` only cover `password`, `github`, `oidc`, `token`,
`none`, and `oauth2_provider_app`.
- No SAML handlers, endpoints, or deployment options in `coderd/` or
`enterprise/`.
- The only code mention is a comment in `coderd/userauth.go` about
SAML-to-OIDC bridges sending `email_verified` as a string.

</details>

## Testing

- `pnpm run lint-docs`: 0 errors.
- The pre-commit hook passed.
- `git grep -i saml -- docs` returns nothing.

---

*Generated by Coder Agents on behalf of @nickvigilante.*

---------

Co-authored-by: Ben Potter <me@bpmct.net>
Co-authored-by: Ben Potter <ben@coder.com>
2026-10-11 08:36:17 -07:00
Michael Suchacz 2d96e88ebe fix(site/src/api): abort chat history requests when the query is cancelled (#30542)
Chat history requests now honor React Query's abort signal.
`getChatMessages` takes an optional `signal`, and
`chatMessagesForInfiniteScroll` passes the query's signal to the first
page request and to every turn fill request.

## Stack context

Stacked on #30524, which loads whole chat turns per history page by
following the first page request with fill requests back to the turn's
prompt.

## Why

A review question on #30524 asked whether the fill loop bypasses React
Query. It does not (the merged page is cached under `chatMessagesKey`
and a refetch reruns the queryFn per page), but no history request
received the abort signal, so a cancelled query kept its HTTP requests
running. With this change, leaving a chat or `cancelChatMessages` in the
edit mutation aborts the in-flight page and fill requests. An aborted
fill is caught by the existing catch/break, and React Query discards the
result.

Behavior change: because the queryFn now reads `signal`, unmounting the
last observer cancels and reverts an in-flight history fetch instead of
letting it finish in the background.

## Testing

- `pnpm exec vitest run src/api/queries/chats.test.ts`: 247 passed.
- New test `aborts the page and fill requests when the query is
cancelled`; the existing first-request and per-page-cap assertions now
expect the signal.
- Red-green: removing the signal from the first request, from the fill
request, or from the queryFn each fails the new test.
- `pnpm lint:types`, `biome check --error-on-warnings`, `oxlint
--deny-warnings` on touched files: clean. Pre-commit hook passed.

## Frontend review

- `frontend-review` FE1 to FE10: all pass.
- `coder-frontend-review` round 1: SD1 (single-use `history` binding in
the new test) fixed. TN3 (wrap the factory in `infiniteQueryOptions`)
declined: the hand-typed queryFn context is pre-existing on main, and
converting it would change the factory's type and every direct `queryFn`
call in tests, which is outside this change. All other roles: no
findings.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-11 12:13:46 +02:00
Michael Suchacz c28ae0dc9b feat: trigger compaction independently for the chat and compaction models (#28568)
> [!NOTE]
> Xum (an AI agent) authored this pull request on Mike's behalf.

## Summary

Automatic compaction now fires at whichever of two independent triggers
is reached first, and the UI shows when the organization override's
trigger applies.

- **Chat trigger**: the chat owner's personal threshold (or the chat
model's) against the chat model's window. A threshold of 100 turns off
only this trigger.
- **Organization trigger**: a fixed 80% of the organization compaction
override model's window. The override model's own compression threshold
is ignored. The other 20% is a target margin for the summary prompt and
the summary, not a guarantee, because the trigger reads the previous
step's prompt size.

On main, the chat threshold was applied to the smaller of the two
windows, and nothing in the UI showed it. Example: with a 20K chat model
at 70% and an 8K override, main compacts at 5,600 tokens; this PR
compacts at 6,400 (80% of 8K, shown as 32%).

## Changes

Backend (`coderd/x/chatd`):

- The trigger with the lower token point binds (ties go to the chat
trigger). It drives the automatic compaction gate and the
still-over-limit check, and every summary, automatic or manual, records
it.
- An override that is unset, deleted, disabled, on a disabled provider,
or without credentials for the chat owner is treated as absent: the chat
model summarizes and only the chat trigger applies.
- The summary's output cap is bounded by the summarizer's own window,
not the trigger's.
- The still-over-limit error names what can clear it: the compaction
threshold (chat trigger), an override model with a larger window
(organization trigger), or both when usage is over both points.
- The still-over-limit check compacts once more when the latest summary
was recorded under a different threshold or trigger window. The
`chat_summarized` result gains `trigger_context_limit_tokens`, and
`context_limit_tokens` now records the chat model's window (main
recorded the smaller window). On main, lowering a threshold after a
compaction ended every later turn with the error.
- The still-over-limit check skips a 0% threshold ("always compact"),
which on main ended the run with the error after every compaction.
- `ARCHITECTURE.md` documents the two triggers, the summary cap, and the
still-over-limit rules.

Frontend (`site`), through a shared `compactionTriggers` helper that
mirrors the backend rules (no new API):

- Coder Agents settings: the compaction override row warns when the
organization trigger undercuts chat models' default triggers ("the
organization override compacts chats at 80% of {model}'s {N}-token
window").
- Personal thresholds page: an Effective column shows the trigger that
applies, with a popover when the organization override binds. "Compacts
at" follows the same trigger, and a point the chat model's window cannot
reach shows as Off. The header's 100% sentence, and the row warning when
a member types 100, say an organization override may still compact chats
when one is set or its organization's overrides failed to load (the
header also while they load).
- Chat context gauge: the compact-at percent follows the binding trigger
and is annotated when the organization override binds. If the overrides
request fails, it shows the chat-only value with "(organization override
not loaded)", or "Compaction off (organization override not loaded)"
when the chat trigger is off.
- An override whose provider the user cannot use is ignored on the gauge
and the personal page, matching chatd.
- The shared `formatContextLimit` prints counts below 1,000 exactly (an
800-token compaction point showed "~1K") and 999,500 to 999,999 as
"1.0M" instead of "1000K". It also labels the model pickers; their other
values are unchanged.
- `HelpPopoverIconTrigger` lets callers set their own `aria-label`; only
the Effective column's popover does.

Known v1 limits: the Coder Agents settings alert is organization-scoped,
so it can warn about an override that some members fall back from for
lack of provider credentials. The gauge checks the viewer's provider
access, so on a shared chat its label can differ from the owner's
runtime trigger (Codex P2, declined). Compaction itself is unaffected.

## Screenshots

From remote UAT round 13 on 093076f402: an isolated test deployment
with a local fake LLM. The models are test fixtures named for their
context windows: Chat model 20K (own threshold 70%), Chat model 5K
(40%), and Chat model 8K (50%). Chat model 8K is also the organization
compaction override, so the organization trigger is 80% of 8,000 = 6,400
tokens, which is 32% of Chat model 20K's window. Chat model 8K's own 50%
applies only to chats that use it as the chat model; changing it to 10%
or 100% left every value below unchanged.

**Coder Agents settings:** the organization trigger undercuts Chat model
20K's 70% default.

![Override warning: 80% of Chat model 8K's window undercuts Chat model
20K](https://github.com/user-attachments/assets/188c92e6-faaa-4e9a-a563-567cbf98af85)

**Personal thresholds:** the organization trigger binds Chat model 20K
at 32%. Chat model 5K (40%) and Chat model 8K (50%) keep their own chat
triggers.

![Effective column: 32% from the organization trigger on Chat model
20K](https://github.com/user-attachments/assets/9949be4e-9417-4cfc-a683-f1367a1dd77a)
![Organization override popover: 80% of Chat model 8K's window, about
32% of this model's
window](https://github.com/user-attachments/assets/4bc3e002-0be1-46fd-91f0-aa27503034af)

**Personal thresholds, organization settings request failed** (the first
red line is the injected error). Rows fall back to chat-only values.

![Organization settings load failure above usable chat-only
rows](https://github.com/user-attachments/assets/dcf48546-aa47-4f82-a6eb-85f106b4bf45)

**Chat context gauge:** organization trigger binds (Chat model 20K),
chat trigger binds (Chat model 5K), overrides request failed (injected).

![Gauge: Compacts at 32% (organization
override)](https://github.com/user-attachments/assets/cd5402d9-9849-4254-a7a7-6623c4006a2a)
![Gauge: Compacts at
40%](https://github.com/user-attachments/assets/f372c9e9-72ef-41c8-950c-e77d74965f65)
![Gauge: Compacts at 70% (organization override not
loaded)](https://github.com/user-attachments/assets/ab829746-2ab5-4743-848f-dce4e806de3a)

**Still-over-limit errors from real runs:** organization trigger, chat
trigger, both.

![Organization-only over-limit
error](https://github.com/user-attachments/assets/f210807a-a2cc-47a0-807c-f1404373bb28)
![Chat-only over-limit
error](https://github.com/user-attachments/assets/eecec38e-97de-49b6-8670-b32090103bbb)
![Combined over-limit
error](https://github.com/user-attachments/assets/459a6d08-7215-492d-93f5-96a4f767a09e)

## Testing

- Go: `TestBindingCompactionTriggerSource`,
`TestCompactionStillOverLimitError`, `TestCompactionStatusFromHistory`,
and `TestActiveServer_CompactionModelOverride` cover the 80% point
(fails if the override's own threshold is read again), user threshold
100 leaving the organization trigger on, the summary cap for automatic
and manual compaction, the over-limit messages, and recompaction after a
trigger change. The site binding tests mirror the Go table row for row.
- Site: `compactionTriggers` unit tests and Storybook stories for the
three surfaces, including the overrides fetch failure.
- On c6f8750479: `go vet`, the `chatd` and `chatloop` tests, and the
AgentsPage, AISettingsPage, and HelpPopover unit tests (2,274 passed, 2
skipped) pass, and CI is green. On 987cefe399, tsc, the five affected
story files (109 passed), and `make pre-commit` also passed. 093076f402
only changes `ARCHITECTURE.md`; the pre-commit hook's markdown format
and lint checks pass on it.
- On 3cd5b08f1f: tsc, the new `formatContextLimit` test (fails on the
old helper for 800 and 999,999), the `compactionTriggers` and `aiModels`
unit tests (224 passed), and the affected story files pass, and the
pre-commit hook passed on all three commits.

## Review record

- Earlier heads: 12 Codex passes and 3 human reviews, all threads
answered. Rebased onto main several times, most recently ff3fa22f68
(kept #30274, #29892, and #29890 in conflicted files).
- coder-agents-review rounds 1 to 18: findings fixed; approved since
round 15. The round 1 `ARCHITECTURE.md` finding was left for the
maintainer, who asked for the update in the last commit.
- coder-frontend-review (eight roles): all pass. Splitting the PR (RO6)
was declined because it is reviewed as one unit; the
`organizationTriggerFor` story helper stays because its three fields
must match the model.
- Design change after UAT round 11: the organization trigger is a fixed
80% of the override window instead of the override model's own threshold
(171d5f568e, 21d2ce7fce, 987cefe399).
- coder-agents-review round 19: copy, naming, and an unreachable
zero-window gate fixed (6e8efb9054, c6f8750479). A summary-time fit
check with chat-model fallback (CRF-156) was declined: the previous-step
lag applies to every trigger, including main's. Round 20 approved
c6f8750479 with no findings.
- Codex: one P2 on 987cefe399 declined (see known limits); no major
issues on c6f8750479.
- Remote UAT on dogfood (fake LLM, isolated test deployment): rounds 8
to 13 PASS. Round 12 on c6f8750479 first failed one criterion that was
written wrong (the admin alert correctly lists an override model that is
also a chat model at 100%); the reviewer endorsed PASS on the same
evidence after the correction. Round 13 on 093076f402 retook the
screenshots with neutral model names and confirmed that the override
model's own threshold (10%, 50%, 100%) does not move the organization
trigger.
- UAT round 13 notes: the header after a failed or pending overrides
load and the sub-1K labels are fixed in 4e172ab5ff and d5888ce15dc;
coder-agents-review round 21 found the same gap in the row warning
(CRF-167, fixed in 3cd5b08f1f). Left as on main: a summary's
`usage_percent` is measured against the binding trigger's window, so it
can exceed 100 (nothing reads it), and the 100% help text shows only for
an unsaved edit.
- Codex: no major issues on d5888ce15d and 3cd5b08f1f.
coder-agents-review round 22 approved 3cd5b08f1f with no open findings.
- coder-frontend-review on those commits: all roles pass after the
fixes. Declined: moving the formatter fix to its own PR (RO5; the owner
asked for it here), adding "tokens" to sub-1K labels (TN6; "~800" reads
like "~16K"), and splitting the component (RP6).
2026-10-11 12:10:59 +02:00
George K 50c785cc6d refactor(provisioner/terraform/scriptorder): stage script order resolution (#30481)
Runtime resolution needs to know which scripts are selected by
ordering rules. The previous monolithic resolver required runtime data
up front, forcing callers to either resolve every script or resolve
ordering rules twice.

Introduce a staged API:

```
  NewProgram
    -> FilterDataSources
    -> Prepare
    -> resolve selected script runtimes
    -> Finalize
```

`NewProgram` builds reusable state and configuration indexes and records
script lifecycle attributes. `Prepare` resolves declarations, selectors,
and lifecycle phases, and records the selected script addresses needed
for runtime resolution. `Finalize` accepts only caller-resolved runtime
bindings and constructs the dependency graphs.

Filtering remains caller-controlled so plan-time consumers can remove
destroyed coder_script_order instances using the saved-plan graph
before preparation. Existing validation, diagnostics, limits,
warnings, and deterministic graph construction are preserved.

This change establishes the API boundary required by later
Terraform-backed runtime resolution without wiring it into
provisioning.

Refs:
https://linear.app/codercom/issue/PLAT-545
https://linear.app/codercom/issue/PLAT-715
2026-10-09 19:12:38 -07:00
George K e2abd0f01d refactor(provisioner/terraform): extract script ordering (#30337)
refactor(provisioner/terraform): extract script ordering

Move the existing script-order declaration, selector, phase and
runtime resolution, and dependency-graph logic into a focused
`scriptorder` subpackage.

_Reviewer note: Although the diff is large, it is mechanical. Existing
code and tests are moved into a subpackage, split by pipeline stage,
and renamed; behavior is unchanged._

_Reviewer note 2: The next PR in the stack is going to be another
refactor of this code, but it will not be purely mechanical. To make
review easier, I'm keeping the 2 PRs separate so that renamed/moved
code is not mixed with functional changes. I apologize for the
churn 🙏._

Split the monolithic implementation and tests by pipeline stage,
simplify names now that the package supplies the script-order context,
and document the declaration- to-graph pipeline. Preserve existing
validation, limits, deterministic output, diagnostics, and cycle
detection.

This refactor does not change provisioning behavior or wire the
package into provisioning. It establishes the package boundary needed
by later Terraform-backed runtime-resolution work.

Refs:
https://linear.app/codercom/issue/PLAT-545
https://linear.app/codercom/issue/PLAT-711
2026-10-09 19:01:03 -07:00
George K 652ae952a2 feat(provisioner/terraform): query Terraform graphs (#30334)
Add query operations over Terraform graph indexes for later
agent-runtime resolution.

Resolve Terraform value references to their most specific indexed
configuration nodes, then follow dependencies to caller-defined
boundary nodes. Return deterministic, deduplicated results while
honoring context cancellation and cumulative limits on lookups, node
visits, and traversed edges.

Cover config-derived and saved-plan graph shapes, including module
inputs, module outputs, repeated resource instances, and converging
paths.  Provisioning behavior remains unchanged until later commits
add consumers.

Refs:
https://linear.app/codercom/issue/PLAT-545
https://linear.app/codercom/issue/PLAT-710
2026-10-09 18:32:14 -07:00
George K a2686cd747 feat(provisioner/terraform): index Terraform graphs (#30277)
Script ordering needs deterministic address lookups and dependency
topology across Terraform's config-derived plan graphs and saved-plan
apply graphs. Add a `tfgraph` package that normalizes graph nodes into
configuration and instance addresses, preserves operation metadata,
assigns index-scoped node IDs, and stores forward dependencies in an
immutable index.

Bound parser work and retained data for template-controlled DOT,
reject edge forms outside Terraform's emitted subset, and honor
cancellation between synchronous parsing and indexing phases. The
package is not wired into provisioning yet, so this change does not
alter existing behavior. Its API intentionally covers only script
ordering for now and can be expanded separately to consolidate
`ConvertState`'s legacy graph processing.

Refs:
https://linear.app/codercom/issue/PLAT-545
https://linear.app/codercom/issue/PLAT-709
2026-10-09 18:18:36 -07:00
TJ 8697b91870 feat(site/src/pages/AgentsPage): quieter read-only view for other users' chats (#30483)
When a user opens a chat owned by someone else, the page showed an
orange warning band and a full composer whose controls were all
disabled. This replaces that with a quieter read-only view.

- Top bar: no warning band. The share button is shown only to the chat
owner, so viewers with share permission (admins) no longer get it. The
shared-chat icon by the title is unchanged, and the kebab stays (it
holds Copy ID).
- Composer: the "This chat is owned by X. It is read-only." message
moves inside as a neutral info line. The editor is not rendered, so the
composer is short, and it gets the default border.
- Composer controls: `+`, mic, send/stop and the `x` on workspace, MCP
and planning pills are hidden. Model, workspace and MCP pills and the
context indicator stay; the model shows as a plain label rather than a
disabled picker.

The compact view is driven by a new `readOnlyNotice` prop on
`AgentChatInput`, so the new-chat form, which also uses `isReadOnly`, is
unchanged. Sidebar rows and message action rows are out of scope.

Fixes CODAGT-1355

Follow-ups (cleanup tracked in
[CODAGT-1384](https://linear.app/codercom/issue/CODAGT-1384/read-only-chat-view-follow-up-cleanup-from-30483)):

-
[CODAGT-1385](https://linear.app/codercom/issue/CODAGT-1385/split-the-read-only-composer-out-of-agentchatinput):
split the read-only composer out of `AgentChatInput` (replaces
`readOnlyNotice`).
-
[CODAGT-1386](https://linear.app/codercom/issue/CODAGT-1386/use-one-viewer-permission-check-across-the-chat-page):
use one viewer-permission check across the chat page.
-
[CODAGT-1387](https://linear.app/codercom/issue/CODAGT-1387/audit-read-only-treatment-for-sidebar-rows-and-message-actions):
audit read-only treatment for sidebar rows and message actions.
- [CODAGT-1308](https://linear.app/codercom/issue/CODAGT-1308):
read-only viewers still see an enabled "Remove from queue" button
(existing).

<details>
<summary>Design decisions</summary>

From design review with Tracy:

- Remove the red warning band.
- Remove the share button for non-owners. A lock and then a moved shared
icon were tried; the existing shared icon by the title was kept instead.
- Move the warning message into the chat area.
- Make the chat area smaller and outline it so it looks different.
- Remove disabled action buttons in the chat area (only show content the
user can interact with): `+`, mic, send, and the pill `x` buttons. The
spinner in the mockup is the existing context indicator, which stays.

Verified in Storybook (`AgentChatPageView` / `OtherUserChatReadOnly`):
the composer shows the notice, has no editor, its only button is the
context indicator, and the orange band is gone. New visual story:
`AgentChatInput` / `ReadOnlyNotice`.

</details>

---

_Generated by Coder Agents._
2026-10-09 17:23:41 -07:00
Jake Howell 3364368657 fix(site): exclude disabled workspaces from bulk selection (#30517)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

“Select all workspaces” selected pending and deleting workspaces even
though their individual checkboxes were disabled. Reuse the row
eligibility predicate for bulk selection and its checked/disabled state,
including when no rows are eligible. Keep existing selections clearable
if polling makes every selected row pending or deleting.

Preserve pagination and selection-count semantics: stopped, pending, and
running rows now produce “Selected 2 of 3.” Extend existing Vitest
coverage for mixed/all/no eligibility and deselection, with focused
Storybook states.

<details>
<summary>Implementation decisions and verification</summary>

The parent already derives bulk-action inputs and counts from the
selection callback, so the production change stays in the table.
Selection remains page-scoped, and the denominator remains all displayed
rows.

Passed: 24 WorkspacesPage unit tests, 3 focused Chromium Storybook
tests, `pnpm format`, `pnpm check`, full `pnpm lint` including
TypeScript, `git diff --check`, and FE1–FE10 self-review. Browser
automation verified mixed eligibility, clearing/reselecting, and the
disabled no-eligible state, and clearing stale disabled selections;
screenshots were returned in chat only. `EdgeCaseAudit` was absent in
this checkout. Test runners emitted non-failing shutdown/version
warnings. Independent visual review was blocked by agent authentication.

</details>
2026-10-10 10:45:16 +11:00
McKayla はな 86ebc72236 chore: remove unused autofill-parameters endpoint and experiment (#30525) 2026-10-09 16:42:41 -06:00