Commit Graph
4834 Commits
Author SHA1 Message Date
Michael Suchacz ea287daf71 docs(coderd/x/chatd): resolve ARCHITECTURE.md TODOs for idle chats and workspace files (#30039)
Resolves the four TODO notes that #27079 and #27111 left in
`coderd/x/chatd/ARCHITECTURE.md`. Each note pointed at a real change in
documented behavior, so each is replaced with a short description that
keeps the architectural facts and drops the implementation detail the
notes carried (part field lists, the agent upload path, the prompt text
format, helper names).

- `Create` takes an explicit initial status that defaults to `running`,
matching `chatstate.CreateChat`; callers request `waiting` for an idle
chat. The execution state diagram gains the `N --> W: Create(waiting)`
edge, and the `POST /api/v2/chats` section documents that empty
`content` creates an idle chat, so clients can use the chat ID (for
example to upload workspace files) before the first turn. The child-chat
locking bullet from #30240 now uses the same `Create(initialMessages,
initialStatus)` signature.
- Files uploaded into the chat's workspace get no file links, so the
attachment cap and eviction do not apply to them. A message can
reference only a file in the chat's upload directory in the currently
bound workspace, and the model gets the reference as text, never the
bytes.
- `POST /api/v2/chats/{chat}/workspace-files` is owner-only and needs
SSH access to the workspace. It uses no transition, rejects archived
chats, and works in every other execution state. It prefers the chat's
bound agent and otherwise uses the worker's deterministic agent
selection without binding the chat.

Testing:

- Docs-only change, rebased onto `main` at `8245457c8a5`. All four TODO
notes were still on `main`, and each statement above was rechecked
against the code there.
- `make pre-commit-light` passes (markdown format and lint, `typos`, the
dash check). `markdownlint-cli2` reports the same 10 pre-existing
findings on `main` and on this branch.
- The existing tests that pin each documented behavior pass on the
rebased head: `TestCreateChat_AllowsNoUserMessages`,
`TestCreateChat_RejectsInvalidInitialStatus`,
`TestTransitionCreate_NToW`, `TestCreateChatWithoutInitialUserContent`,
`TestPostChats_EmptyContent`, `TestWorkspaceFilePartToText`,
`TestWorkspaceFilePartToTextStaleWorkspace`, `TestPostChatWorkspaceFile`
(including `NotOwner`, `Archived`, `SharedWorkspaceRequiresSSH`),
`TestCreateChatMessageWorkspaceFilePartRejectsInvalidPath`, and
`TestCreateChatMessageWorkspaceFileWorkspaceValidation`.

Review record:

- Codex round 1 on `e3c5053`: 3 P2 findings (explicit `Create` status,
model sees more than the path, missing owner-only constraint). All
confirmed against existing tests and fixed in `41c40a2`.
- Codex round 2 on `41c40a2`: 3 P2 findings (SSH requirement, `running`
default for the initial status, per-chat reference path rule). All
confirmed against existing tests and fixed in `5a55996`.
- Codex round 3 on `5a55996`: no findings.
- Codex round 4 on `46f94d0`, the head rebased onto `main` (review
started by marking the PR ready): no findings. The rebase changed no
reviewed text; it only updated the signature in the child-chat bullet
that `main` added since.

Refs #27079, #27111

> Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike.
2026-10-20 01:48:51 +02:00
Michael Suchacz 8245457c8a fix(coderd/x/chatd): make compaction fit an overflowing context (#30766)
Compaction is the recovery path for a chat near its context window, but
its summary request was larger than the turn that overflowed: the whole
history plus the tool definitions. Its only fallback, a retry without
tools, also missed context-window errors that arrive inside an HTTP 200
stream (OpenAI Responses API, Bedrock Mantle). In the incident behind
this PR, one MCP tool result of about 1 MB moved a 1M-token chat from
67% to 92% of its window in one step. After that, every turn and every
`/compact` failed with "Your input exceeds the context window of this
model."

This PR does not try to predict whether the summary request fits. Each
time the model rejects it for its size, the next request is thinner:

1. The full request: tool definitions and the whole history.
2. The same history without tool definitions (as before).
3. Tool results longer than 32 KiB cut to 32 KiB, keeping their head and
tail.
4. Tool results longer than 4 KiB cut to 4 KiB.

A step that would cut nothing is skipped. Only locally executed text and
error tool results are cut. User messages, attachments,
provider-executed results, and media stay whole. The cuts apply only to
the summary request, not to the stored history.

Other changes:

- **In-stream rejections match.** Fantasy stream errors without a status
code and Responses `error` and `response.failed` events now count as
size rejections. A Responses error code other than
`context_length_exceeded` never matches, so a rate limit stays
retryable. Anthropic's "input length and `max_tokens` exceed context
limit" also matches.
- **A conversation that still does not fit** fails as a non-retryable
config error that tells the user how to recover.
- **Each rejected summary request is logged at Warn** with its tool
count, tool result cap, and the bytes it cut.

Not in this PR: counting tool results that arrive after the measured
step in the compaction trigger, estimating the summary request before
sending it, and a tighter per-result cap for large-window models.
Earlier revisions of this branch did these and were dropped for the
simpler path above.

## Testing

- `go test ./coderd/x/chatd/...` (20 packages), `golangci-lint` on
`chatd` and `chatloop`, and the pre-commit hook pass.
- The real OpenAI Responses client runs against `httptest` for each
in-stream error shape and must retry without tools.
- Each of these breaks a test: removing the cut steps, sending a cut
that cuts nothing, turning error results into text, cutting
provider-executed results, and dropping the in-stream match.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-20 00:30:05 +02:00
Faur Ioan-AurelandClaude Opus 5.5 1a65385a4b fix: log workspace shutdown reasons for SSH connections (#30515)
Workspace stops and deletes closed active SSH connections with generic
shutdown or process-exit reasons. This obscured the workspace action
that ended a connection and made related logs harder to correlate.

The agent’s SSH tracking and logging now identify connections closed by
the SSH server as server_shutdown, while preserving earlier client or
network disconnects. The agent includes the client session ID when
available for ordinary sessions and connections used only for port
forwarding.

Coderd now enriches shutdown reasons when it processes connection
reports. It translates server_shutdown into workspace_stopped when the
latest build is a running or successful stop or delete requested before
the connection closed. Coderd persists the enriched reason and logs the
build reason, transition, and build ID alongside the client session ID.
Unavailable or unrelated build state retains the generic shutdown
reason.

The CLI now logs shutdown context once per stop or delete build through
its existing workspace watcher. This includes the client session ID when
available and preserves the existing graceful SSH shutdown behavior.

Regarding the PTY connections, when the agent shut down, the
reconnecting PTY server closed each PTY
and its attached connections, and the connection handler then returned
without an error. The server therefore logged and reported those
connections as graceful closes. Its fallback for a forced shutdown
reported a free-form reason that coderd did not recognize, so coderd
never refined either case into a workspace shutdown.

We change the reconnecting PTY server so that it reports any connection
that ends after the agent begins shutting down as a server shutdown
initiated by the agent, and its log keeps the client session ID. The
forced shutdown fallback now reports the same standard reason, which
lets coderd translate it into a workspace stop or delete in the
connection log, as it already does for SSH. A client that closes its
connection before the shutdown still keeps its graceful reason.

Regression tests cover shutdown attribution, fallback behavior, CLI
logging, and PostgreSQL persistence with and without a client session
ID. The test logging helper also synchronizes with cleanup to prevent
logging after a test completes

- resolves
https://linear.app/codercom/issue/CLIENT-665/close-workspace-tunnel-with-a-reason

<!--

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.

-->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:06:41 +03:00
Michael Suchacz 200fa7dea7 perf(coderd): bound the initial chat stream snapshot to the client cursor (#29761)
Opening a chat on the Agents page loads its transcript over REST and
then connects the chat stream with `after_id` set to the newest loaded
message. The first sync of the stream ignores that cursor when it
queries the database: it fetches every row of the chat on each
connection, and then sends only the rows above `after_id`.

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

## Performance

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

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

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

## Not changed

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

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

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

</details>

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-19 19:15:56 +02:00
Ehab Younes f4cd0deccb feat!: report template insights session usage per app (#29796)
Report template insights session usage per app instead of five fixed
family rows, with registry names and icons.

- Add per-app rows for reported session apps (VS Code, Cursor, GoLand,
  Zed, etc.); unused apps are omitted
- Replace `type` (`builtin`/`app`) with `method` (`ssh`,
  `reconnecting_pty`, `port_forwarding`, `workspace_app`); session
  methods are derived from the app name until #31012 stores them
- Add `usage_total_seconds` to count each user's active minutes once,
  and use it as the UI bar denominator so overlapping apps can exceed
  100%
- Merge template apps sharing a slug into one row across templates,
  using the newest display name and icon
- Rename Web Terminal slug from `reconnecting-pty` to
  `reconnecting_pty`
- Cap the response at the 64 busiest unregistered apps and fold the
  rest into "Other apps", flagged with `seconds_is_upper_bound`
  ("Up to" in the UI)
- Add `unknown` and `overflow` accounting rows with explanatory
  tooltips, and a fallback icon for apps without one
- Remove the unused `codersdk.UnionByFamily` helper from the Go SDK

BREAKING CHANGE: `report.apps_usage` in `GET /api/v2/insights/templates`
no longer returns the fixed five rows, family slugs, or previous display
names. Consumers must update.

Part of CLIENT-642
Prometheus metrics handled separately in #29906
2026-10-19 17:59:18 +03:00
Michael Suchacz dfdd6a59a5 feat: move chats between projects through the chat update API (#30894)
`PATCH /api/v2/chats/{chat}` now takes `project_id`. A project ID moves
the chat into that project, and `uuid.Nil` removes it from its project.

**Stack** (moving chats between projects, bottom first):
1. #30893: the move in chatd
2. **This PR**: the chat update API takes `project_id`
3. #30895: **Move to project** in the chat menu
4. #30795: drag a chat onto a project folder in the sidebar

**Why:** #30893 can move a chat family, and the UI layers above need an
endpoint to call.

- A move accepts the same projects as chat creation, through
`validateChatProjectSelection()`, which this PR extracts from
`postChats()` without a change in behavior.
- A project that the chat's owner cannot use gives 404, even for an
admin. The owner must own the project or hold a grant on it
(`chatd.ChatProjectUsableBy`, the check that chat creation uses since
#30439). So an admin cannot put a member's chat into a project that the
member has no access to and expose its memory.
- A child chat, an archived chat or a disabled `chat-projects`
experiment gives 400. A family that is not idle gives 409 ("Cannot move
an active chat. Interrupt or wait for the chat to finish first."). A
project deleted between the check and the move gives 404.
- The move is the last write in `patchChat()`, so a refused move keeps
the earlier writes of the same request, as a refused archive does.

**What to scrutinize:** the access check in
`validateChatProjectSelection()` and the order of the refusals in
`patchChat()` (`coderd/exp_chats.go`).

**Architecture doc:** the `PATCH /api/v2/chats/{chat}` section of
`coderd/x/chatd/ARCHITECTURE.md` lists the `SetProject` states of a move
and its refusals, and no longer says that only an `archived` change
emits transitions.

**Generated** (`make gen`): `coderd/apidoc`,
`docs/reference/api/chats.md`, `docs/reference/api/schemas.md` and
`typesGenerated.ts` come from `UpdateChatRequest.ProjectID` in
`codersdk/chats.go`.

## Testing

- `make pre-commit` passes, and so does `go test ./coderd -run
TestPatchChatProject` (14 subtests).
- `TestPatchChatProject/AnotherOwnersProject` gets 404 for another
user's project, then moves the chat after the project is shared with the
chat's owner. It fails without the access check, and also with an
owner-only check. `MoveBackWaitsForAPendingMove` ends in the wrong
project when the handler skips the move before the lock.
`ActiveFamilyReturnsConflict` checks the 409 for a running, interrupting
or action-waiting root and for a running subagent.
`PublishesProjectChange` and `AuditsTheMove` cover the watch event and
the audit entry.
- Untested: the 404 when the project is deleted between the check and
the move.

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

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

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

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

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

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

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

## Testing

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

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

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

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

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

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

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

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

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

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

> Generated by Coder Agents.
2026-10-19 11:32:26 +00:00
Jaayden Halko 452654d07f test(coderd/database): use subtest context in TestProjectSkillQueries (#31011) 2026-10-19 19:05:27 +08:00
Ethan de42c37f76 refactor(coderd): share chat creation with in-process callers (#30027)
Right now, the only way to create a chat is through `POST
/api/v2/chats`. That's fine for clients, but an integration running
inside coderd (say, a Slack bot) would have to store or mint an API key
just to call its own server.

So, we'll pull chat creation out of the handler into a shared function,
and add `api.CreateChatAsUser` for in-process callers. They get the same
validation, errors, and audit entry as the endpoint, and the endpoint's
behaviour doesn't change. This is the same pattern `chatCreateWorkspace`
already uses to let chatd create workspaces as a user. I've also
exported the chat daemon for in-process callers.

Chat errors are now just values that carry the endpoint's status,
message, and cause, so in-process callers can use `errors.As` on them
(e.g. to spot a prompt hook denial) rather than decoding an HTTP
response. The audit entry is written in the background, as auto-archive
already does, rather than through a fake request. As with an API key, a
dormant user is activated on use, whilst a suspended or deleted user
gets a 403.

The PRs above this one do the same for sending, interrupting, and
updating chats.
2026-10-19 14:37:36 +11:00
Ethan e254086494 fix(coderd/x/chatd/chattool): return database errors from workspace tools (#30822)
Relates to CODAGT-1330

`create_workspace`, `start_workspace` and `stop_workspace` read a fair
bit from the database whilst they wait on a build: the chat workspace
TTL setting, the workspace's agents, the agent's lifecycle state, and
the chat row once the build is done. When one of those reads failed,
we'd log it (or just ignore it) and carry on as if it hadn't, e.g.
falling back to the template's TTL or leaving out the agent status, and
the tool still reported success. A failed write of the new build ID to
the chat binding was handled the same way.

To fix, we'll return a tool error for those database errors, so the
model knows the call failed and can retry. `start_workspace` and
`stop_workspace` now also re-bind the chat when its build is stale, so a
retried call repairs a binding write that failed. An invalid TTL
setting, a workspace with no build yet, and agent selection errors all
behave like they do today.

A tool error doesn't stop the build. The tools only watch the build and
the agent, so the build, the startup scripts and the turn all carry on.
If the model calls the tool again, `create_workspace` finds the
workspace through the chat binding, which #30663 commits with the
workspace, and waits on it again rather than creating a second one. It
only creates a replacement if the agent has since disconnected or timed
out, like it does today. `start_workspace` just waits on the latest
build again, and the other workspace tools find and dial the agent
themselves.

This follows on from #30663.
2026-10-19 14:02:47 +11:00
Ethan e09407c366 fix(coderd): commit chat workspace bindings with dependent state (#30663)
Relates to CODAGT-1330

When a workspace rebuild gives a chat a new agent, chatd saves the new
agent binding and then re-pins the chat's context to that agent. These
committed separately, and a failed re-pin was just logged. The next turn
would see the new agent already bound, so it never re-pinned, and the
chat kept injecting the old agent's context.

`create_workspace` had a similar problem. It bound the chat to the
workspace after the workspace was committed, and if that failed it
logged an error and still reported success. The workspace was left
orphaned, and the next call would just create another one.

To fix, we'll commit the binding and the re-pin in one transaction.
`create_workspace` now binds the chat inside the workspace create
transaction. I've done this with the unused `postCreateInTX` hook in
`createWorkspace`, which I've renamed to `postBuildInTX` and moved after
the build insert so it has the build ID.
2026-10-19 14:02:47 +11:00
Ethan 096db5de02 fix(coderd/x/chatd): return MCP OAuth token database errors (#30662)
Relates to CODAGT-1330

Before chatd connects to MCP servers, it refreshes any expired OAuth
tokens. If saving a refreshed token failed, we'd log it and use the new
token for that turn only. A failed write when marking a revoked grant
for reconnect, and a failed re-read after losing a refresh race, were
also just logged, and the turn connected without the token.

To fix, we'll return those database errors so the prepare retry runs. A
transient error from the OAuth provider still keeps the current token
for the turn, like it does today.

This doesn't help if the provider already rotated the refresh token and
the save fails, since the new token is lost either way. On retry, a
provider that rotates tokens rejects the old one and we mark the token
for reconnect, which is where we'd end up today anyway, just a turn
earlier.
2026-10-19 14:02:47 +11:00
Ethan aedd998db6 fix(coderd/x/chatd): return agent and subagent lookup database errors (#30661)
Relates to CODAGT-1330

When chatd prepares a turn for a chat with a workspace, it looks up the
chat's agent so the agent binding is up to date before anything uses it.
That lookup dropped every error, so a failed database read looked the
same as a chat with no agent, and the turn carried on with whatever
binding the chat already had. If reading the chat's bound agent failed,
we'd also log it and resolve a new agent from scratch. Separately, a
failed read of the computer use provider setting hid the `computer_use`
subagent type from `spawn_agent` for that turn.

To fix, we'll just return the database error, so the prepare retry runs.
Not having a usable agent is still a normal result, e.g. the chat has no
workspace, the workspace was deleted, or more than one agent uses the
chat suffix, so a broken template doesn't fail every turn. A computer
use provider we don't recognise still just makes `computer_use`
unavailable.

This follows on from #30492.
2026-10-19 14:02:46 +11:00
Michael Suchacz 121393842c test(coderd/notifications/dispatch/smtptest): renew the expired TLS test certificate (#30922)
Renews the SMTP test server certificate in
`coderd/notifications/dispatch/smtptest/fixtures`. It expired on
2026-10-18 at 13:36:08Z, so the TLS cases of `TestSMTP`
(`TLS:_self-signed`, `TLS:_self-signed_+_SNI`, `PLAIN_auth_and_TLS`)
fail in `test-go-pg-17` and `test-go-race-pg` on every PR.

## What changed

- `server.crt`: the committed `server.csr`, re-signed with the committed
CA (`ca.crt`, `ca.key`) and `v3_ext.conf`. It is valid until 2034-07-12,
a day before the CA expires. The key pair, subject, and extensions (SANs
`myserver.local`, `www.myserver.local`, `127.0.0.1`) are unchanged. Only
the serial, the validity, and the signature differ.
- `ca.srl`: the next serial, which the new certificate uses.
- `generate.sh`: it issued the server certificate for 825 days, and
2024-07-15 plus 825 days is 2026-10-18. It now uses 3649 days, a day
less than the CA's 3650.

The command, run in the fixtures directory:

```sh
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -set_serial 0x0330C6D190E3FE649DAFCDA2F4D765E2D29328DF -out server.crt -days 2824 -extfile v3_ext.conf
```

With OpenSSL 3.0.2, `-CAserial ca.srl` issued a random serial and left
`ca.srl` unchanged, so the command sets the next serial explicitly.

## Review focus

Re-signing keeps the CA and the server key, so no other fixture or test
changes. The one choice is the validity: about 7.7 years, ending a day
before the CA.

## Validation

| Check | `main` | This PR |
|---|---|---|
| `openssl x509 -noout -dates` | `notAfter=Oct 18 13:36:08 2026 GMT` |
`notAfter=Jul 12 14:24:37 2034 GMT` |
| `openssl verify -CAfile ca.crt server.crt` | `certificate has expired`
| `server.crt: OK` |
| `go test ./coderd/notifications/dispatch/... -run TestSMTP -count=1` |
the 3 TLS cases fail with `x509: certificate has expired or is not yet
valid` | pass |

`go test ./coderd/notifications/... -count=1` passes, including
`notifications_test.go`, the other user of `smtptest`. A text diff of
the old and new certificates (`openssl x509 -noout -text`) shows only
the serial, the dates, and the signature.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-18 18:46:46 +02:00
Jaayden Halko e289c6fe01 feat: add project skill API routes (#30827)
Adds experimental routes for managing a chat project's skills under
`/api/experimental/organizations/{organization}/chats/projects/{project}/skills`:
list, create, get, update (PATCH) and delete by skill name.

The handlers reuse the shared skill create and update path from the
personal and organization skill APIs. Reading needs `chat_project:read`
on the project and writing needs `chat_project:update`; callers without
access get 404, matching the project instructions routes. Duplicate
names and the 100-skill-per-project cap return 409. Writes are audited
as `chat_project_skill` with the skill name as the target. The SDK gains
the matching `ExperimentalClient` methods.

Stack (merge top to bottom):
- #30826
- #30827 👈
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882
- #30884
2026-10-18 13:16:23 +07:00
Jaayden Halko a379c849da feat: add project skill queries and authorization (#30826)
Adds the storage and authorization layer for chat project skills. The
`skills` table already allows a `project_id` owner (migration 000621);
this adds the queries for it and authorizes them through the parent chat
project, the same way project instructions work.

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

Stack (merge top to bottom):
- #30826 👈
- #30827
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882
- #30884
2026-10-18 12:58:39 +07:00
Michael Suchacz 54ba766f77 refactor(coderd/x/chatd): move turn preparation helpers into turn_environment.go (#30870)
Moves the helpers that `buildTurnEnvironment` uses from `chatd.go`, and
the `turnEnvironment` type from `generation.go`, into
`turn_environment.go`. The code moves without edits. Only the import
blocks change.

The moved helpers build the turn's workspace context, tool set, system
prompt, and skills. `chatd.go` goes from 4,396 to 3,131 lines, and
`turn_environment.go` from 1,187 to 2,520.

To check that only imports changed, compare the removed lines with the
added lines:

```sh
B=mike/chatd-turn-env-split/receiver-name
H=mike/chatd-turn-env-split/move-turn-helpers
git fetch origin "$B" "$H"
diff <(git diff "origin/$B" "origin/$H" | grep '^-[^-]' | cut -c2- | sort) \
  <(git diff "origin/$B" "origin/$H" | grep '^+[^+]' | cut -c2- | sort)
```

The output lists only import lines. `git diff --color-moved` also marks
the blocks as moved.

After this PR, the stack has the same code as #28757 (head
`6ee4ecb35f8`, on current `main`), except that `turn_environment.go`
names the `*Server` receiver `p` (#30869).

Validation: `go build ./coderd/... ./enterprise/...` and `go vet
./coderd/x/chatd/...` pass, and the pre-commit hook passed. `go test
./coderd/x/chatd/... ./enterprise/coderd/x/chatd/... -count=1` passed in
all packages except one known load flake,
`TestChatTurnStopsAtStepLimit/Default` (timeout while seeding 1,199
steps). A rerun of `./coderd/x/chatd` passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 22:08:44 +00:00
Michael Suchacz 8065f84af2 refactor(coderd/x/chatd): name the Server receiver p in turn_environment.go (#30869)
Renames the `*Server` receiver in `turn_environment.go` from `server` to
`p`. Nothing else changes: each changed line differs only in that name
(`git diff --word-diff` shows it).

#30870 moves helpers from `chatd.go` into this file. Those helpers name
the receiver `p`, as do 22 files in the package, and revive's
`receiver-naming` rule allows one receiver name per type in a file. With
this rename first, the move needs no edits.

Validation: build and vet pass, the `TestBuildTurnEnvironment*` tests
pass, and the pre-commit hook (`lint/go` with revive) passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:58:06 +00:00
Michael Suchacz 752da8d60f test(coderd/x/chatd): remove end-to-end tool policy tests (#30868)
Removes seven end-to-end tool policy tests from `chatd_test.go` (949
lines). The table test from #30867 checks the same policy at
`buildTurnEnvironment`.

- `TestPlanModeSubagentChatExcludesAskUserQuestion`
- `TestPlanModeRootChatAllowsApprovedExternalMCPTools`
- `TestExploreSubagentIsReadOnly`
- `TestExploreChatUsesPersistedMCPSnapshot`
- `TestExploreChatSendMessageCannotMutateMCPSnapshot`
- `TestRootExploreChatStaysBuiltinOnlyAtRuntime`
- `TestRootExploreChatExcludesWebSearchProviderToolAtRuntime`

Each test started chatd with a fake model server, ran a turn, and read
the tool names from the model request. Each had its own fixture.

**Why removal is safe:** a test was removed only if other tests still
catch every mutant it caught. On `main`, 9 mutants were caught only by
these tests, and the table test catches all 9. Review and two audits of
every check in these tests then found nine more regressions that only
these tests caught, and #30867 now covers each one. That includes the
`TestExploreChatSendMessageCannotMutateMCPSnapshot` scenario: the
`ExploreChildAfterMCPReplacement` case calls `SendMessage` on an Explore
child chat, checks the stored MCP servers, and builds the next turn.
`TestEditMessage_MCPServerIDs` still covers the same guard through
`EditMessage`. The first mutation run used an earlier `main` and the
#28757 branch, which removed the same lines.

**Tradeoff:** the table test stops at the result of
`buildTurnEnvironment`. No test now checks plan mode and Explore tool
lists in the model request itself. The audits found one mutant that only
these tests catch: a branch in `generation.go` that clears the active
tools of Explore chats just before the model call. The same change
without the Explore condition fails `TestMCPToolSearchGenerationFlows`,
because the step from `buildTurnEnvironment` to the model request is the
same for every mode. Only an end-to-end test like the ones this PR
removes would catch the Explore-only form, so this PR does not add one.

Validation: build and vet pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:47:32 +00:00
Michael Suchacz c42c9af23a test(coderd): cover the turn tool policy at buildTurnEnvironment (#30867)
Adds `TestBuildTurnEnvironmentToolPolicy`, a table test of the tool
policy at the place chatd applies it: the result of
`buildTurnEnvironment`. #30868 then removes seven end-to-end tests that
checked the same policy through a full turn.

The six cases (`Root`, `PlanRoot`, `PlanChild`, `ExploreRoot`,
`ExploreChild`, `ExploreChildAfterMCPReplacement`) share one fixture:

- three MCP servers that every chat selects: approved for plan mode, not
approved, and approved with a tool allowlist
- two MCP servers that no chat selects: one Force On and one ordinary
- one inline MCP server on each root chat, one without
`allow_in_subagents` on the parent of the child chats, and one workspace
MCP server
- a model with the `web_search` provider tool

Each case builds the tool definitions with
`chatloop.BuildToolDefinitions`, the same function the chat loop uses
for the model request. It then compares the tool names, active tools,
and provider tools with the case. It also searches the full system
prompt for the plan mode and Explore mode overlays and for the root-only
`propose_plan` instruction.

`ExploreChildAfterMCPReplacement` first calls `SendMessage` with a
request to replace the Explore child's MCP servers with the unselected
one. The test checks that the stored selection does not change, then
builds the next turn from the stored chat and messages. `PlanRoot` runs
its `spawn_agent` tool and checks that the general sub-agent keeps the
plan mode.

The PR also adds:

- `TestCreateExploreChatPreservesMCPSelection`: `Server.CreateChat`
stores the MCP servers that a root Explore chat selects
- a plan-mode request in `TestPostChats/Success`: `POST /chats` stores
the requested plan mode
- `TestBuildTurnEnvironmentSplitsPendingUserRowsFromCompactionPrompt`
and a project instructions assertion in `TestBuildTurnEnvironmentMemory`

## Validation

- For each new assertion, Xum removed the code that the assertion checks
and saw the test fail. On this branch, for example, removing the Explore
overlay in `chatd.go` fails `ExploreRoot` and `ExploreChild`.
- In a mutation run, these tests catch 7 mutants (copies of the code
with one policy branch removed) that no test on `main` caught. Two
examples: root Explore chats get MCP tools, and Explore chats get
workspace MCP tools. That run used an earlier `main` and the #28757
branch, which has the same test code.
- Review found regressions that only the end-to-end tests removed in
#30868 caught. Xum applied each one to this branch: the first version of
these tests passes, and the current version fails in the cases below.
- Two independent audits then listed every check in the seven removed
tests, including implicit ones such as a scripted `spawn_agent` call,
and tried a mutant for each check without an obvious replacement. A
mutant counts as a gap only if a removed test fails with it and the rest
of `coderd/x/chatd/...` plus the chat, MCP, Explore, and plan tests in
`coderd` and `enterprise/coderd` pass. The audits found the last two
rows. They also found one gap that this PR leaves open; #30868 explains
why.
- A line coverage comparison found 4 statements in `coderd/x/chatd/...`
that only the seven removed tests run. All 4 are error returns.

| Regression | Failing cases |
|---|---|
| Explore chats get `edit_files` | `ExploreRoot`, `ExploreChild` |
| Explore children keep only the MCP servers approved for plan mode |
`ExploreChild`, `ExploreChildAfterMCPReplacement` |
| `SendMessage` replaces an Explore child's MCP servers |
`ExploreChildAfterMCPReplacement` |
| Chats outside Explore mode get every enabled MCP server in the
organization | `Root` |
| A plan-mode child gets the root-only `propose_plan` instruction |
`PlanChild` |
| A plan-mode root chat does not get `spawn_agent` | `PlanRoot` |
| `Server.CreateChat` drops the MCP servers of a root Explore chat |
`TestCreateExploreChatPreservesMCPSelection` |
| A general sub-agent of a plan-mode chat loses the plan mode |
`PlanRoot` |
| `POST /chats` drops the requested plan mode | `TestPostChats/Success`
|

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:34:52 +00:00
Michael Suchacz a41e5ae6eb refactor: rename prepareGeneration to buildTurnEnvironment (#30866)
Renames the turn preparation step after what it returns: the environment
for one turn. Only names change, plus one small change to how callers
release the environment.

- `generation_preparer.go` becomes `turn_environment.go`, and its test
file becomes `turn_environment_internal_test.go`. GitHub shows both as
renames. A comment in `compactionTriggers.test.ts` that names the test
file follows the rename.
- `prepareGeneration` becomes `buildTurnEnvironment`, and its result
type `generationPrepared` becomes `turnEnvironment`. Four
`TestPrepareGeneration*` tests become `TestBuildTurnEnvironment*`.
- The `Cleanup` field becomes the unexported `cleanup`, and callers use
`Close()`. `Close()` does nothing on a zero value.

The type stays in `generation.go` for now. #30870 moves it next to
`buildTurnEnvironment`.

Validation: build and vet pass, the renamed tests and the `toolinput`
tests pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:20:00 +00:00
Michael Suchacz 2088618930 chore(coderd/x/chatd): log workspace agent lookup errors in turn preparation (#30865)
Logs the error from `getWorkspaceAgent` at debug level in turn
preparation. `prepareGeneration` discarded it.

The turn still goes on without the agent, as before. The agent only adds
its OS and working directory to the instruction header.

Validation: build and vet pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 20:59:22 +00:00
Michael Suchacz 5ccbef037b refactor(coderd/x/chatd): remove the no-op allowedBehaviorToolNames filter (#30864)
Removes `allowedBehaviorToolNames`, `allToolNames`, and
`TestAllowedBehaviorToolNames`, and the active-name check they fed in
`appendDynamicTools`.

The check never skipped a tool. `appendDynamicTools` returns early for
Explore mode and plan mode, so at the check, `allowedBehaviorToolNames`
always returned every tool name. A dynamic tool that shares a built-in
tool's name is still dropped with a warning.

Validation: `go test ./coderd/x/chatd/ -run
'Dynamic|AllowedExplore|StopAfterPlan'` passes, and the pre-commit hook
(build, `lint/go`, `lint/go/new-code`) passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 20:44:13 +00:00
J. Scott Miller 939146b077 fix(coderd/x/chatd): reset stream history only if after_id is deleted (#29808)
Fixes
[CODAGT-1175](https://linear.app/codercom/issue/CODAGT-1175/prevent-chat-stream-resets-from-loading-full-history)

**tl;dr:** The chat stream no longer sends the full history on every
connect when a chat contains old edit tombstones.

On its first sync, the chat stream WebSocket treated any soft-deleted
message (edits create them) as a history reset and sent `history_reset`
plus every message, ignoring `after_id`. The client replaced its
paginated cache with that history, so every connect, reconnect and PWA
resume of a long chat that had ever been edited rendered the whole
transcript. A dogfood chat of about 3.2k messages sent 7.1 MB per
connect.

`historyResetRequired` in `stream_loop.go` now resets on the first sync
with an `after_id` only if message `after_id` is missing or deleted.
Messages are only deleted as a suffix of the chat (an edit deletes the
edited message and every later one), so while that message is live the
client holds none of the deleted rows. Otherwise the stream sends only
live messages newer than `after_id`, and `messageEvents` never sends
tombstones as messages. Deletions after the first sync still reset.
`stream_loop_internal_test.go` covers the initial-sync cases and the
deletion of a streamed message after the first sync,
`TestSubscribeAfterMessageIDWithEdit` runs a real `EditMessage` against
the database, and `ARCHITECTURE.md` gets TODOs for the new rule.

> Generated by Coder Agents on behalf of @jscottmiller.
2026-10-16 15:40:17 -05:00
Bobby Ho 764e67bcff feat: expose skipped and canceled script outcomes in coderd and the Build Timeline (#30875)
feat: expose skipped and canceled script outcomes

Add `skipped` and `canceled` statuses across the Agent API, database,
SDK, and Build Timeline for startup scripts.

- Store and return both outcomes, preserving zero-duration timings,
  and reject unknown statuses. Rollbacks rewrite the new outcomes to
  `exit_failure` with exit code 255.
- Add typed legends, outcome-specific tooltips, and keyboard-accessible
  bars. Fix timeline crashes for `timed_out` and `pipes_left_open`.
- Bump the Agent API to v2.15 while agents continue using v2.14.
  Add API, migration, and Storybook coverage.

First of two PRs for PLAT-550. Agents do not emit the new statuses yet;
a follow-up after #30765 enables reporting. Shutdown scripts remain
outside the timeline, and agent health and badge rules are unchanged.

Refs: https://linear.app/codercom/issue/PLAT-550/phase-3-expose-skipped-and-canceled-script-outcomes
2026-10-16 15:55:28 +00:00
Asher 899d25a5b1 feat: add byte tracking to ssh and pty connections (#30389) 2026-10-16 00:21:40 -08:00
Steven Masley 357e81b470 feat(coderd): list workspace secrets on workspace build audit entries (#30459)
Workspace build audit entries now list the build's secrets: name, env var, file path, and whether the request set the secret or it was carried forward from the previous build. Values are never included. Follows up on [this review thread](https://github.com/coder/coder/pull/30250#discussion_r4199276004).

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

- Every workspace build audit entry includes its secrets, including builds that fail and orphaned deletes.
- The entry lists the build's full set of secrets. Removed secrets show up only by being absent.
- The three places that write build audit entries now share one helper instead of building the fields by hand.

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

- `audit.AdditionalFields` gains `workspace_secrets`: `name`, `env_name`, `file_path`, and `source` (`request` or `carry_forward`) for each secret.
- New `audit.WorkspaceBuildFields` is used for job success and failure in `provisionerdserver`, and for the orphan delete completed in `workspacebuilds.go`.
- `source` comes from the `workspace_secrets.source` column (#30248), set by `persistSecrets` (#30250).

</details>

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

(existing decision log, unchanged)

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 18:03:15 -05:00
George K 6d34557d74 feat: add script ordering adoption telemetry (#30860)
Count `coder_script_order` declarations and literal `rule` blocks in
coderd from the existing START plan in
`CompletedJob.TemplateImport.Plan`,
including child modules, without multiplying counts by resource or
module instances. Persist these counts per template version on
successful import after START plan graph validation, without changing
the provisioner API.

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

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

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

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

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

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

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

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

</details>

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

(existing decision log, unchanged)

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 17:40:00 -05:00
Bobby Ho 4d1f95e73e feat: order lifecycle scripts by their dependencies (#30765)
feat(agent): enforce lifecycle script ordering

Honor `coder_script_order` dependencies for startup and shutdown scripts
using the existing outcome-aware unit manager. Cron, legacy scripts,
and scripts without dependencies retain their existing behavior.

- Wait for all prerequisites before running. `success` requires a
  successful prerequisite; `completion` also accepts failure, timeout,
  or skip. Skip dependents as soon as a required success becomes
  impossible, preserving the original failure as the lifecycle error.
- Reject invalid dependency graphs before any scripts start and write
  the reason to every selected script's log.
- Log unmet dependencies every 30 seconds and explain skips. Populate
  display names in the manifest so skip messages use readable names,
  falling back to Terraform addresses.
- Exclude dependency waits from script timeouts, record an outcome on
  every exit, and use fresh state per execution. Cancellation stops
  waiters without starting dependents or emitting skip messages.

Add regression coverage for ordering, skip propagation, timeouts,
cancellation, invalid graphs, and unchanged unordered execution.

Refs https://linear.app/codercom/issue/PLAT-549/phase-3-enforce-lifecycle-script-ordering
2026-10-15 20:33:48 +00:00
Steven Masley 7d75210abf feat: deliver workspace secrets in the agent manifest (#30251)
Delivers workspace secrets to the agent, so they show up as env vars and files in the workspace. Part of [RELAY-7](https://linear.app/codercom/issue/RELAY-7/agent-relay-deliver-provider-credentials-via-coder-secrets-instead-of).

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

- The agent receives the secrets of the build that created it, alongside the owner's user secrets.
- A workspace secret wins over a user secret on the same env var or file path.
- An agent from an older build gets no workspace secrets.
- The agent itself needs no changes.

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

- `GetManifest` finds the agent's build through its resource and provisioner job, then lists that build's live secrets as `AsWorkspaceSecretManager`.
- In this PR, precedence comes from order: user secrets are emitted first and workspace secrets after, so the agent applies the workspace value last. #30388 replaces this with `workspacesecrets.Resolve`, which decides one winner per target and is shared with the build secrets API.
- The deployment's file path policy applies to both kinds of secret. When file delivery is blocked, a file-only secret is dropped.

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 14:38:42 -05:00
Steven Masley f25b6294b6 feat: set workspace secrets on workspace builds (#30250)
Lets clients set secrets when creating a workspace or a build. Secrets are saved with the build and are never sent to the provisioner. Part of [RELAY-7](https://linear.app/codercom/issue/RELAY-7/agent-relay-deliver-provider-credentials-via-coder-secrets-instead-of).

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

- `secrets` is a new field on the create workspace and create build requests.
- Each secret is delivered as an env var, a file, or both. `ephemeral` secrets last for one build only.
- Secrets carry forward to every later build until a request replaces or removes them.
- A secret set on another secret's env var or file path replaces that secret entirely.
- A null `value` removes a secret, which needs `update` permission on the owner's workspace secrets.
- Deleting a workspace clears its secret values.

Secrets are stored but not delivered to the agent until #30251.

<details>
<summary>Example request</summary>

```json
POST /api/v2/workspaces/{workspace}/builds
{
  "transition": "start",
  "secrets": [
    { "name": "openai-key", "value": "sk-...", "env_name": "OPENAI_API_KEY" },
    { "name": "kubeconfig", "value": "apiVersion: v1 ...", "file_path": "~/.kube/config" },
    { "name": "session-jwt", "value": "eyJ...", "env_name": "SESSION_JWT", "ephemeral": true },
    { "name": "old-token", "value": null }
  ]
}
```

</details>

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

- Validation reuses the user secret field rules and the file path delivery policy. It rejects:
  - duplicate names, env names, or file paths within one request
  - a removal that also sets a target or `ephemeral`
- In the build transaction, the builder:
  1. copies the previous build's live, non-ephemeral secrets that the request does not name or take over
  2. inserts the requested secrets
  3. "Earlier builds' rows are cleared when the new build's job completes
- Copying and clearing run as `AsWorkspaceSecretManager`, so autostart and other system-initiated builds work without secret permissions. Requested secrets are authorized as the build's actor.
- Each row records `source` (`request` or `carry_forward`).
- Per-build limit violations return a 400.
- A completed delete in `provisionerdserver`, or an orphan delete in the builder, clears the workspace's values and keeps the rows.

</details>

---

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

Each secret belongs to one workspace build. A new build copies the previous build's secrets, then the old copies lose their values but stay as history.
2026-10-15 13:32:40 -05:00
Nick Vigilante c6a47c4428 docs: replace references to the retired Enterprise license tier (#30853)
## Summary

Coder has only Community and Premium license tiers, but several docs
pages, CLI help strings, and SDK field comments still called features
"Enterprise" or "enterprise-only".
This PR changes them to say Premium and regenerates the reference docs
built from those strings.

Resolves
[DOCS-1298](https://linear.app/codercom/issue/DOCS-1298/remove-references-to-the-retired-enterprise-license-tier).

## Changes

- `docs/admin/users/quotas.md`: Replace "scoped to Groups in Enterprise
and organizations in Premium" with a correct sentence. Quotas are
Premium, allowances are set on groups, and each user's budget is
calculated separately in each organization (per
`GetQuotaAllowanceForUser`).
- `docs/user-guides/workspace-lifecycle.md`: Replace "Enterprise" with
Premium, and correct the quotas sentence to match the quotas page.
- `docs/ai-coder/agents/platform-controls/mcp-servers.md`: Replace
"enterprise entitlement" with Premium license.
- `cli/templatecreate.go`, `cli/templateedit.go`: Update
`--require-active-version`, `--allow-user-autostart`, and
`--allow-user-autostop` help text. Point the `--require-active-version`
help at the renamed `#template-update-policies` section, because the old
`#require-automatic-updates-enterprise` anchor is broken. Make the
errors for these flags tier-neutral.
- `enterprise/cli/features.go`: `coder features` now says "List license
features and entitlements", and its AGPL error no longer names a tier.
- `codersdk/templates.go`, `codersdk/organizations.go`: Update field
comments that feed the API reference and TypeScript types.
- `docs/reference/glossary.md`: The Premium entry now says "paid license
tier" instead of "paid enterprise tier".
- `docs/.style/style-guide/voice-and-tone.md`: The example sentence now
says "Premium licensing".
- Regenerated: CLI golden files, `docs/reference/cli/`,
`docs/manifest.json`, `docs/manifest/generated/cli.json`,
`docs/reference/api/`, `coderd/apidoc/`, and
`site/src/api/typesGenerated.ts`.

## Testing

- `go test ./cli -run 'TestCommandHelp|TestCliTemplateCreate'` and `go
test ./enterprise/cli -run
'TestEnterpriseCommandHelp|TestTemplateCreate|TestTemplateEdit|TestFeaturesList'`
pass.
- The pre-commit hook passed, including `make gen`, `fmt`, `lint/go`,
`lint/ts`, `lint/markdown`, and a slim build.

<details>
<summary>Decisions and out-of-scope items</summary>

### Decisions

- **Premium wording and legacy Enterprise licenses:** Coder still
accepts existing Enterprise licenses, and `FeatureSetEnterprise`
includes the features labeled Premium here. Docs and help text say
"Premium" because that is the tier sold today, and about 25 other docs
pages already use "Premium feature". Error strings are tier-neutral, so
they're accurate for every license holder.
- **Glossary and style guide:** The issue marked these as borderline.
Both were one-word changes, so I made them.

### Not changed

- `docs/reference/api/enterprise.md` keeps the "Enterprise" sidebar
title. It comes from the swagger tag on the `enterprise/` Go package, so
renaming it is a larger change.
- Other "Enterprise" references the review flagged as out of scope: the
`coder server --help` option group, quiet hours SDK comments, internal
`coderd` comments, and the dashboard's "Enterprise" badge on the
require-active-version option.
- No docs page says that legacy Enterprise licenses are still valid.
- Uses that don't refer to the license tier: GitHub Enterprise, Red Hat
Enterprise Linux, "enterprise environments", and `enterprise/` package
paths.

</details>

---

_This PR was generated by Coder Agents on behalf of @nickvigilante._
2026-10-15 17:46:05 +00:00
Atif Ali c85ebc1346 fix: make workspace create denials on behalf of another user actionable (#30537)
Creating a workspace for another user as a caller without permission
returned the same 403 as creating your own: "You are unable to create a
workspace in this organization. It is possible to have access to the
template, but not be able to create a workspace." For service accounts
and integrations that always create for someone else, that doesn't say
who the workspace was for, which organization, or what to do about it.

When the caller is not the owner, the two 403s now say what is missing
and for whom. Messages and details only; status codes and authorization
are unchanged, and self-creates keep their existing text.

Missing create permission:

> You can't create workspaces for other users in this organization.
> Creating a workspace for "alice" needs permission to create workspaces
owned by other users in organization "coder", which your account doesn't
have. Use an account with that permission (for example an organization
admin), or create the workspace as "alice".

Missing `use` on the template:

> You can't use the template "demo" to create workspaces for other
users.
> Creating a workspace for "alice" from this template needs "use" access
to template "demo", which your account doesn't have. Ask a template
admin to grant it, or use an account that has it.

`preflightWorkspaceCreate` now receives the caller's ID and the owner
(name included) instead of just the owner ID. `coder create` prints the
detail already, and the web UI shows it through `ErrorAlert`.

**How it renders**

Web UI (create page, `ErrorAlert`):

<img width="2592" height="1490" alt="Web UI error for creating a
workspace on behalf of another user"
src="https://github.com/user-attachments/assets/9b1f1378-e4df-40df-8b6f-ca6cccdc4238"
/>

CLI (`coder create alice/ws1 --template demo` as a plain member):

```
error: Trace=[create workspace: ]
You can't create workspaces for other users in this organization.
Creating a workspace for "alice" needs permission to create workspaces owned by other users in organization "coder", which your account doesn't have. Use an account with that permission (for example an organization admin), or create the workspace as "alice".
```

Refs PLAT-726. Related owner-state inconsistencies are tracked in
PLAT-749.
2026-10-15 17:27:13 +05:00
cdrciandgithub-actions[bot] 7e69cd0af7 chore: refresh AI model price book (#30828)
## Price book changes

0 models added, 0 models removed, 24 models changed.

<details>
<summary>Changed</summary>

- openrouter/deepseek/deepseek-v4-pro
- openrouter/deepseek/deepseek-v4-pro-0813
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/google/gemma-4-31b-it
- openrouter/minimax/minimax-m2.5
- openrouter/mistralai/mistral-small-3.2-24b-instruct
- openrouter/moonshotai/kimi-k3
- openrouter/openai/gpt-5.6-sol
- openrouter/openai/gpt-5.6-sol-pro
- openrouter/openai/gpt-oss-120b
- openrouter/qwen/qwen3.6-35b-a3b
- openrouter/qwen/qwen3.8-27b
- openrouter/tencent/hy3
- openrouter/tencent/hy4-preview
- openrouter/z-ai/glm-5
- openrouter/z-ai/glm-5.1
- openrouter/z-ai/glm-5.2
- openrouter/z-ai/glm-5.3
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-pro-latest
- openrouter/~google/gemini-pro-latest
- openrouter/~moonshotai/kimi-latest
- openrouter/~z-ai/glm-flash-latest
- openrouter/~z-ai/glm-latest
</details>

## Review notes

Regenerated by `make gen/aibridge-prices` from the live
[models.dev](https://models.dev) catalog. Both artifacts come from one
snapshot, so they ship together:

- `coderd/aibridge/prices/data/prices.json`
- `site/src/modules/aiModels/knownModels/knownModelsGenerated.json`

These are customer-visible cost numbers taken from upstream data, so
this PR is never merged automatically. The summary above lists what
moved; check the diff for exact figures before approving.

Opened automatically by the [aigateway-prices-refresh
workflow](https://github.com/coder/coder/actions/runs/38710433812).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-15 12:01:26 +01:00
Ethan aef7f15510 fix(coderd/x/chatd): only retry without drop_block when it's rejected (#30821)
In #29792, once a provider and model had accepted `drop_block`, any 400
on a request with it retried once without it, since I didn't know what
error a provider returns for an unsupported beta. That turned out to
hide real errors. On dogfood, a chat replaying some very tall
screenshots hit Anthropic's many-image limit:

```
messages.9.content.43.image.source.base64.data: At least one of the image dimensions exceed max allowed size for many-image requests: 3000 pixels
```

The retry without `drop_block` then hit the stale thinking block, so the
chat failed with the binding error instead, and the image error only
showed up in a warn log.

To fix, we'll only retry without `drop_block` when the 400 is a known
rejection of the field or its beta, and otherwise return the error as is
and keep the hint. The catch is that if a provider rejects the beta with
an error we don't recognise, chats on that model will see it until a
restart clears the hint, rather than us recovering.

Claude Code (as of 2.1.300) does the same on Anthropic's own API, Claude
Platform on AWS included: it only retries without the beta when the 400
names it or the `block_binding` field. On Bedrock, Vertex and Mantle it
also retries on any 400 it doesn't otherwise recognise, which we could
copy if that catch turns out to matter.

The oversized screenshots are a separate problem, since chatd doesn't
resize images at all.
2026-10-15 14:39:21 +11:00
Bobby Ho 603dd420d1 feat: add ServerTailnet logs and metrics for unreachable agents (#30133)
Add default-level metrics and warn-level diagnostics to investigate
ServerTailnet reachability failures causing agent-specific 502s, without
restarting coderd or enabling debug logging.

- Enrich request logs and PTY/chatd warnings with agent ID, failure
  reason, wait duration, coordinator state, WireGuard handshake and
  byte counts, and DERP regions.
- Add metrics for unreachable attempts by reason, reachability latency,
  embedded DERP connections, and offline app/terminal requests.
- Distinguish reachability failures from subsequent TCP dial failures,
  cap reverse proxy dials at one minute, and exclude expected chatd
  readiness polls and superseded-agent dials from unreachable counts.
- Report missing handshakes as zero time instead of 1970, also fixing
  `coder ping`.

Part of PLAT-680, a sub-issue of PLAT-360.
2026-10-14 14:55:29 -07:00
Michael Suchacz e7c2fd5d2e feat: add Gemini 4 Argon to Agents and AI Gateway (#30780)
Add Gemini 4 Argon to the Agents known models catalog, so it appears as
a suggestion when an admin adds a chat model, and regenerate the AI
Gateway price book from models.dev.

| Provider | Model ID | Placed before |
|---|---|---|
| google | `gemini-4-argon` | `gemini-3.1-pro-preview` |
| openrouter, vercel | `google/gemini-4-argon` |
`google/gemini-3.8-flash` |

**Pricing.** The price book carries Google's launch rates on google,
openrouter, vercel, and copilot: $2 per 1M input tokens, $10 per 1M
output tokens, and $0.10 per 1M cached input tokens. Google doubles them
on 2026-12-01 ($4, $20, $0.20); the weekly refresh picks that up once
models.dev changes. The google entry keeps models.dev's 32,768 max
output tokens, the cap Google enforces on non-streaming
`generateContent` calls (larger values return HTTP 400 there).

**Thinking levels.** `googleSupportedThinkingLevels` did not recognize
the `argon` name token and failed closed, so chatd sent Argon no
`thinking_level` and no `include_thoughts`: the native Google path
dropped the reasoning effort, and neither path showed thought summaries.
Argon accepts LOW, MEDIUM, and HIGH like Gemini 3.1 Pro and rejects
MINIMAL, so the map now treats it like the Pro family.

**Upstream drift.** `prices.json` covers every model of its 8 providers,
so the regeneration also brings the changes since the last weekly
refresh, all on OpenRouter and Vercel: 14 other new entries, 26 entries
models.dev delisted, and 51 price changes. The catalog picks up the same
changes for 8 curated OpenRouter entries (DeepSeek, Kimi, Qwen, and
GLM).

## Testing

- Live requests to `gemini-4-argon` through the AI Gateway's Google
provider (Google's OpenAI-compatible endpoint): `reasoning_effort` and
`thinking_level` values `low`, `medium`, and `high` return 200 and
`minimal` returns 400; `include_thoughts` returns thought text in
streaming and non-streaming responses.
- Red-green: removing the `argon` token fails
`TestGoogleSupportedThinkingLevels/gemini-4-argon` (expected LOW,
MEDIUM, HIGH; got nil).
- Regenerating from the saved models.dev snapshot reproduces both
generated files byte for byte.
- `go test ./scripts/aibridgepricesgen/... ./coderd/aibridge/prices/...
./coderd/x/chatd/chatprovider/...` and `pnpm exec vitest run
--project=unit src/modules/aiModels/` pass. The pre-commit hook passed;
local pre-push checks were skipped, so CI is the first full run.

## Review record

- Frontend review: the only `site/` change is the generated
`knownModelsGenerated.json`, so the FE1 to FE10 checklist does not
apply; no hand-written frontend code changed.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-14 22:39:00 +02:00
Bobby Ho ee5e3a4029 feat: send script resource addresses and dependencies in the agent manifest (#30627)
feat: include script dependencies in agent manifests

Send persisted script Terraform addresses and dependency lists on every
manifest request, preserving them across agent restarts, reconnects, and
shutdown without rebuilding the workspace.

- Add `resource_address` and `dependencies` to the agent proto, with
  `SUCCESS` and `COMPLETION` requirements.
- Reuse shared database-to-SDK validation and add bidirectional SDK/proto
  conversion. Reject empty prerequisite addresses and invalid requirements
  rather than accepting partial lists.
- Bump the agent API to v2.13 and update the agent's RPC connection.
  Older agents ignore the new fields; older servers return empty fields.
- Test manifest delivery, subagent isolation, round trips, invalid
  dependencies, and unchanged encoding when the new fields are unset.

Script execution is unchanged; ordering enforcement follows in PLAT-549.
Production dependency lists remain empty until #30556 merges.

Stacked on #30625. Refs PLAT-548.
2026-10-14 17:26:31 +00:00
Nick Vigilante 6afd1515e0 fix(coderd/templatebuilder): guard quickstart C/C++ install on every tool it installs (#30374)
The Quickstart base's C/C++ branch guarded on `command -v gcc`, but
installs `gcc g++ make cmake`. `codercom/enterprise-base:ubuntu` ships
gcc but not cmake, so cmake was never installed while the script
reported success. The guard now checks every tool the install provides
(`gcc`, `g++`, `make`, `cmake`).

Adds `TestQuickstartCppInstallGuard`, which runs the rendered C/C++
branch against stubbed tools and asserts the install runs when any of
them is missing. It fails without the fix.

Fixes DOCS-736. The matching example template change is in the DOCS-613
PR.

Generated by Coder Agents on behalf of @nickvigilante.
2026-10-14 12:35:48 -04:00
Garrett Delfosse 2b9fad8bba feat: add chat project sharing database layer (#30479)
Database and authorization layer for chat project sharing (experiment
`chat-projects`), part 1 of 2. #30439 adds the API on top of it. Nothing
here changes behavior: projects start with empty ACLs, no endpoint
writes them yet, and deleting a project still detaches its chats.
Project deletion is in #30683.

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

The generated TypeScript changes only add the new scope value.

> Generated by Coder Agents.
2026-10-14 10:42:00 -04:00
coder[bot] 69fab7de06 chore!: remove the coder_report_task MCP tool (#30742)
Coder Tasks have been removed from coder/coder, so the
`coder_report_task` MCP tool and the status reporting pipeline behind it
no longer do anything useful. This PR removes the tool and the code that
only existed to support it.

### Removed

- `codersdk/toolsdk`: `ToolNameReportTask`, `ReportTaskArgs`,
`ReportTask`, `Deps.report`, `WithTaskReporter`, and the `All` entry,
plus their tests.
- `coderd/mcp`: the remote MCP exclusion for `coder_report_task`.
- `coder exp mcp server`: the task reporter, the AgentAPI screen
watcher, the agent socket connection, and the `coder_report_task` skip
logic. The server now requires an authenticated user client, because
every remaining tool needs one.
- `coder exp mcp configure claude-code`: the
`mcp__coder__coder_report_task` allowed tool, the injected
`coder_report_task` CLAUDE.md prompt, the `report tasks properly`
history line, the default system prompt asking the agent to send task
status updates, and the `CODER_MCP_APP_STATUS_SLUG` /
`CODER_MCP_AI_AGENTAPI_URL` env written to the Claude MCP config.
- `cli/cliutil/queue.go`: only used by the reporter.
- `github.com/coder/agentapi-sdk-go` (and transitive `tmaxmax/go-sse`)
via `go mod tidy`.
- The "task reporting" mention in `docs/ai-coder/mcp-server.md`.

### Breaking: removed `coder exp` flags and env

`coder exp` is experimental. Any scripts that still pass these flags
will now fail with an unknown flag error. Env vars that are no longer
read are ignored.

| Command | Flag | Env |
|---|---|---|
| `coder exp mcp server` | `--app-status-slug` |
`CODER_MCP_APP_STATUS_SLUG` |
| `coder exp mcp server` | `--ai-agentapi-url` |
`CODER_MCP_AI_AGENTAPI_URL` |
| `coder exp mcp server` | `--socket-path` | `CODER_AGENT_SOCKET_PATH`
(still used by `coder agent` and `coder exp sync`) |
| `coder exp mcp configure claude-code` | `--claude-app-status-slug` |
`CODER_MCP_APP_STATUS_SLUG` |
| `coder exp mcp configure claude-code` | `--ai-agentapi-url` |
`CODER_MCP_AI_AGENTAPI_URL` |

`--claude-system-prompt` no longer has a default.

<details>
<summary>Intentionally kept</summary>

- **Workspace app status reporting** (`UpdateAppStatus` on the agent API
and agent socket, `agentsdk.PatchAppStatus` / `ProtoFromPatchAppStatus`,
the deprecated `PATCH /workspaceagents/me/app-status` endpoint): still
served by coderd and the agent and part of versioned protocols. With
this change, nothing in the CLI calls the agent socket `UpdateAppStatus`
client anymore. Removing it would need a separate protocol change.
- **`report_tasks` in
`coderd/templatebuilder/modules/{aider,amazon-q}`**: these catalog
entries mirror the input variables of pinned coder/registry module
versions, and the behavior lives in those modules. Dropping the variable
here would not disable it, because `amazon-q` defaults it to `true`. The
registry modules need a follow-up instead.
- **`UserClientOptional` on toolsdk tools**: other tools still set it,
and remote MCP still uses it.
- No CLI golden files or generated CLI docs changed, because `coder exp`
commands are hidden.

</details>

### Verification

- `go build ./...`
- `go test ./codersdk/toolsdk/... ./coderd/mcp/... ./cli/cliutil/...`
- `go test ./cli -run 'TestExpMcp|TestCommandHelp'`
- `golangci-lint run ./cli/... ./codersdk/toolsdk/... ./coderd/mcp/...`
(0 issues)

---

_Generated by Coder Agents._

Co-authored-by: coder[bot] <137810501+coder[bot]@users.noreply.github.com>
2026-10-14 16:34:56 +05:00
Ehab Younes f573ec3533 feat: report agent connection methods and app identities (#30467)
Agents now report how a connection was made and which app made it, so
the connection log records the method and the client app separately.

- Bump the Agent API to v2.13. `Connection` gains `connection_method`
  and `app_name`, and `type` is deprecated.
- SSH and reconnecting PTY handlers set the method themselves, so a
  client-supplied app name can't change it.
- SSH sessions report the app from `CODER_SSH_SESSION_TYPE`. Sessions
  without one count as SSH but report no app.
- Disconnect reports repeat the connect report's method, app, and
  client session ID.
- Coderd logs the reported method and normalized app name. For agents
  older than v2.13, it maps `type` as before.
- Coderd rejects unknown methods instead of logging them as SSH.

Closes CLIENT-1037
2026-10-14 13:54:17 +03:00
Ethan 60c6c0959e fix: run chat interrupt messages before earlier queued messages (#30729)
If an agent is working with a message already queued, and you send
another message with `busy_behavior=interrupt`, the agent stops, but
then answers the queued message first and yours second. The interrupt
send appends to the end of the queue, and finishing the interruption
promotes the head of the queue, which is the older message.

To fix, we'll put the message that starts the interruption at the front
of the queue, so it's the one promoted once the partial response is
saved. Messages sent whilst an interruption is already in progress still
go to the back, as they do today, so a burst of interrupts keeps the
order it was sent in. On a chat waiting on dynamic tool results, or one
that errored with messages still queued, an interrupt send now goes
straight into history ahead of the queue (cancelling any pending tool
calls), instead of waiting behind it.

This is just a narrow fix to the current queue behaviour, and it doesn't
change the API shape. It's compatible with the queued message delivery
rework I've got in progress, which replaces these code paths. The one
case this doesn't fix is a second interrupt sent during the first, which
still waits behind earlier queued messages; that rework handles it
properly.
2026-10-14 14:00:19 +11:00
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 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