Commit Graph
14846 Commits
Author SHA1 Message Date
Jeremy Ruppel de31c7c18e feat: add TemplateBuilderCreateTemplate SDK types and client method (#26360)
Adds `POST /api/v2/templatebuilder/compose/template`, a synchronous
endpoint that composes a template from a base and modules, validates it
via a provisioner import job, and creates the template in a single
request.

The handler composes terraform files, bundles them as a tar, inserts the
file with hash-based dedup, creates a template version with an import
job, waits up to 2 minutes for the job to complete, classifies errors
for known failure modes (network-unreachable registry, DNS failures),
then creates the template on success. Canceled and failed jobs return
appropriate error responses.

Also adds `hclwrite.Format` to composed terraform output for canonical
HCL formatting.

Closes https://linear.app/codercom/issue/DEVEX-279

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

- SDK types and client method in `codersdk/templatebuilder.go` with
validation tags matching the standard template creation path
(`template_display_name`, `lt=128`)
- `ClassifyProvisionerError` in `coderd/templatebuilder/errors.go`
detects DNS, connection refused, i/o timeout, and TLS handshake failures
and returns actionable messages
- `waitForProvisionerJob` polls with a ramp-up interval schedule (100ms,
200ms, 500ms, then 1s steady) and accepts an `onUpdate` callback for
future SSE streaming
- Audit logging for both template and template version creation
- TOCTOU name uniqueness: early check for fast feedback, DB unique
constraint catch for the race window (returns 409, not 500)
- Swagger annotations for all error responses (400, 404, 409, 504)

</details>

> 🤖 Generated by Coder Agents
2026-06-15 18:12:55 -04:00
J. Scott Miller d8b76831ff test(testutil): retry terraform provider cache population on transient failures (#26196)
## Problem

Tests that run real Terraform (e.g.
`enterprise/coderd.TestWorkspaceTemplateParamsChange`,
`provisioner/terraform.TestProvision`) intermittently fail when
populating the shared provider cache. On a cache miss,
`DownloadTFProviders` shells out to `terraform init` and `terraform
providers mirror` against the live registry, which periodically returns
transient 5xx errors from the registry/GitHub (504, 500). The
cache-population helper had no application-level retry, so a single
transient failure failed the whole test. Terraform's own registry client
only retries each request once ("the request failed after 2 attempts"),
which is insufficient for these bursts.

## Fix

`runCmd` now retries on any non-zero exit using
`github.com/coder/retry`, logging each failed attempt and preserving the
original failure message format. Retry-all is safe here because
`terraform init` and `terraform providers mirror` are idempotent: each
run reconciles the existing state in the working directory.

The backoff window is deliberately wide: 5 attempts with a 5s floor and
30s ceiling. `coder/retry` grows the delay by phi (~1.618) from the
floor and caps it at the ceiling, so attempts start at roughly t=0s, 8s,
21s, 42s, and 72s (waits of ~8.1s, ~13.1s, ~21.2s, and 30s capped, plus
command runtime). Registry/GitHub incidents typically last seconds to
minutes rather than a single unlucky request, so a narrow window would
only survive an isolated blip, while the early second attempt (~8s)
still recovers quickly from brief ones. This is affordable because the
network path runs only on a cache miss, not on every test: a populated
cache short-circuits via `os.Stat` and is reused within and across runs
(persisted by `.github/actions/test-cache`). The wait is therefore
rarely incurred and is negligible against the 20m per-package test
timeout. The only downside is a slower failure on a genuinely doomed
run.

This only affects the test provider-cache helper. Production provisioner
code, the Windows no-op path, and the CI cache strategy are unchanged.

Refs https://github.com/coder/internal/issues/1201

<details>
<summary>Investigation notes</summary>

The CI cache (`~/.cache/coderv2-test`, via `.github/actions/test-cache`)
is persisted across runs and keyed by a hash of a stable caller-supplied
label + template file contents, so cache hits avoid the network
entirely. The flake only surfaces on a cache miss (provider version
bump, monthly cache reset, or new label/template), where the populating
`terraform init` was the sole unprotected network call. This change
closes that gap without weakening the "use real Terraform" intent of the
tests.

</details>

---
🤖 Generated with Coder Agents on behalf of @jscottmiller.
2026-06-15 16:56:08 -05:00
Kyle Carberry 210261b143 feat: add chat context pinning storage and push trigger (#26385)
Foundation for the Workspace Context Sources RFC (phase 3). The agent
push (#25983) and coderd snapshot storage (#26145) already persist
per-agent context snapshots; this PR lands the **chat-side storage**
plus the **`agentapi` push trigger** that a follow-up will use to read
them. It does **not** touch `chatd` and changes no behavior — nothing
wires an implementation yet.

## What changed

- Adds four nullable columns to `chats` — `context_aggregate_hash`,
`context_dirty_since`, `context_dirty_resources`, and `context_error` —
and rebuilds the `chats_expanded` view.
- Adds three queries — `SetChatContextSnapshot`,
`HydrateAgentChatsContext`, `MarkChatsContextDirtyByAgent` — with
`dbauthz` wrappers and `audit` entries. They are store-interface methods
covered by a Postgres test (`TestChatContextHydration`).
- Adds the `agentapi.ContextDirtyMarker` interface and invokes it inside
the `PushContextState` transaction, publishing collected events only
after commit.

## Intentionally inert

There are **no production callers** of the three queries and **no
implementation** wired for `ContextDirtyMarker`, so the push trigger is
dormant. This is deliberate: the PR is the durable storage/query
foundation only.

The actual integration — the `chatd` implementation that
hydrates/dirties chats and backs a refresh endpoint, consuming the
pinned context in prompt building, the rich SDK types + UI, and retiring
the live per-turn pull — lands as a single follow-up PR. Splitting this
way keeps the schema/query layer reviewable on its own and keeps the
integration whole in one place.

Refs #25983, #26145.

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

- **Columns over a side table.** The four `chats` columns are the
durable model (accepting the one-time `chats_expanded` view/CTE churn).
`last_injected_context` is deliberately left untouched — it is
load-bearing for the live per-turn context pull.
- **Keep `agentapi`, drop `chatd`.** The earlier revision wired the
hydrate/dirty implementation through `chatd` and added a `PUT
/chats/{chat}/context` refresh endpoint. Those were removed so this PR
is pure foundation; `agentapi` defines the trigger + interface (it does
not import `chatd`), and the `chatd` implementation arrives with the
full integration.
- **No new experiment flag.** The columns are dark and unread by prompt
building.
- **Authz.** The new query wrappers authorize chat updates under the
chat RBAC object / `ResourceChat`, consistent with the existing system
chat mutators.

</details>

---

🤖 Generated by Coder Agents on behalf of @kylecarbs.
2026-06-15 14:41:00 -07:00
Callum Styan 89f200872b feat: send connection logs from agentfake agents (#26083)
Signed-off-by: Callum Styan <callumstyan@gmail.com>
2026-06-15 13:35:28 -07:00
dependabot[bot] dc79663573 chore: bump vite from 8.0.10 to 8.0.16 in /site (#26388)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite)
from 8.0.10 to 8.0.16.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/vitejs/vite/releases">vite's
releases</a>.</em></p>
<blockquote>
<h2>v8.0.16</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v8.0.16/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
<h2>v8.0.15</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v8.0.15/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
<h2>v8.0.14</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v8.0.14/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
<h2>v8.0.13</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v8.0.13/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
<h2>v8.0.12</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v8.0.12/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
<h2>v8.0.11</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v8.0.11/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md">vite's
changelog</a>.</em></p>
<blockquote>
<h2><!-- raw HTML omitted --><a
href="https://github.com/vitejs/vite/compare/v8.0.15...v8.0.16">8.0.16</a>
(2026-06-01)<!-- raw HTML omitted --></h2>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> reject UNC paths for launch-editor-middleware
(<a
href="https://redirect.github.com/vitejs/vite/issues/22571">#22571</a>)
(<a
href="https://github.com/vitejs/vite/commit/50b951225bbf6151eb84a3ad5a454908ab4a76c9">50b9512</a>)</li>
<li>reject windows alternate paths (<a
href="https://redirect.github.com/vitejs/vite/issues/22572">#22572</a>)
(<a
href="https://github.com/vitejs/vite/commit/dc245c71e5007ea4d891a025e2d69ac96c736546">dc245c7</a>)</li>
</ul>
<h2><!-- raw HTML omitted --><a
href="https://github.com/vitejs/vite/compare/v8.0.14...v8.0.15">8.0.15</a>
(2026-06-01)<!-- raw HTML omitted --></h2>
<h3>Features</h3>
<ul>
<li>send 408 on request timeout (<a
href="https://redirect.github.com/vitejs/vite/issues/22476">#22476</a>)
(<a
href="https://github.com/vitejs/vite/commit/c85c9eeb9aaf41f477b48b057146887bd5620797">c85c9ee</a>)</li>
<li>update rolldown to 1.0.3 (<a
href="https://redirect.github.com/vitejs/vite/issues/22538">#22538</a>)
(<a
href="https://github.com/vitejs/vite/commit/646dbedd2870f8ec48df0321177d8aa64bbd1575">646dbed</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li>capitalize error messages and remove spurious space in parse error
(<a
href="https://redirect.github.com/vitejs/vite/issues/22488">#22488</a>)
(<a
href="https://github.com/vitejs/vite/commit/85a0eff1c82bbb7c99a0fe8e63704316578a40d3">85a0eff</a>)</li>
<li><strong>deps:</strong> update all non-major dependencies (<a
href="https://redirect.github.com/vitejs/vite/issues/22511">#22511</a>)
(<a
href="https://github.com/vitejs/vite/commit/2686d7d0b722402204d3bcc687a87adea1bcf9fa">2686d7d</a>)</li>
<li><strong>dev:</strong> fix html-proxy cache key mismatch for /@fs/
HTML paths (<a
href="https://redirect.github.com/vitejs/vite/issues/21762">#21762</a>)
(<a
href="https://github.com/vitejs/vite/commit/47c4213f134f562c41ed7c031e4788510cf7e31e">47c4213</a>)</li>
<li><strong>glob:</strong> error on relative glob in virtual module when
no files match (<a
href="https://redirect.github.com/vitejs/vite/issues/22497">#22497</a>)
(<a
href="https://github.com/vitejs/vite/commit/5c8e98f8b584ac5d42f0f9b8580c49792213b13c">5c8e98f</a>)</li>
<li><strong>optimizer:</strong> close the rolldown bundle when write()
rejects (<a
href="https://redirect.github.com/vitejs/vite/issues/22528">#22528</a>)
(<a
href="https://github.com/vitejs/vite/commit/e3cfb9deecff563550fa1b8abd27656b8b292815">e3cfb9d</a>)</li>
<li><strong>resolve:</strong> provide onWarn for viteResolvePlugin in JS
plugin containers (<a
href="https://redirect.github.com/vitejs/vite/issues/22509">#22509</a>)
(<a
href="https://github.com/vitejs/vite/commit/40985f1c09b7696e594e6c5695fbc315d2da2c83">40985f1</a>)</li>
</ul>
<h3>Miscellaneous Chores</h3>
<ul>
<li><strong>deps:</strong> update rolldown-related dependencies (<a
href="https://redirect.github.com/vitejs/vite/issues/22566">#22566</a>)
(<a
href="https://github.com/vitejs/vite/commit/3052a67d9350f4c5076ab1c222c4a21a589cbcdd">3052a67</a>)</li>
</ul>
<h3>Code Refactoring</h3>
<ul>
<li>correct logic in <code>collectAllModules</code> function (<a
href="https://redirect.github.com/vitejs/vite/issues/22562">#22562</a>)
(<a
href="https://github.com/vitejs/vite/commit/6978a9ceb942c4f5e211d52b8a1e569f8a65c80c">6978a9c</a>)</li>
</ul>
<h2><!-- raw HTML omitted --><a
href="https://github.com/vitejs/vite/compare/v8.0.13...v8.0.14">8.0.14</a>
(2026-05-21)<!-- raw HTML omitted --></h2>
<h3>Features</h3>
<ul>
<li>update rolldown to 1.0.2 (<a
href="https://redirect.github.com/vitejs/vite/issues/22484">#22484</a>)
(<a
href="https://github.com/vitejs/vite/commit/96efc88570b6a6ddf1a910f106920cbac07b3cf0">96efc88</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> update all non-major dependencies (<a
href="https://redirect.github.com/vitejs/vite/issues/22471">#22471</a>)
(<a
href="https://github.com/vitejs/vite/commit/98b81632139d51820f82036e58d6fbbf122b77b3">98b8163</a>)</li>
<li><strong>dev:</strong> handle errors when sending messages to vite
server (<a
href="https://redirect.github.com/vitejs/vite/issues/22450">#22450</a>)
(<a
href="https://github.com/vitejs/vite/commit/e8e9a34dcf2540139de558a10187630884d10217">e8e9a34</a>)</li>
<li><strong>html:</strong> handle trailing slash paths in
transformIndexHtml (<a
href="https://redirect.github.com/vitejs/vite/issues/22480">#22480</a>)
(<a
href="https://github.com/vitejs/vite/commit/5d94d1bffdb2a15de9341194d89baec86ce1f693">5d94d1b</a>)</li>
<li><strong>optimizer:</strong> pass oxc jsx options to transformSync in
dependency scan (<a
href="https://redirect.github.com/vitejs/vite/issues/22342">#22342</a>)
(<a
href="https://github.com/vitejs/vite/commit/b3132dacea9c6e0cf526cd9f0f09d850f577c262">b3132da</a>)</li>
</ul>
<h3>Miscellaneous Chores</h3>
<ul>
<li><strong>deps:</strong> update rolldown-related dependencies (<a
href="https://redirect.github.com/vitejs/vite/issues/22470">#22470</a>)
(<a
href="https://github.com/vitejs/vite/commit/7cb728eb629cc677661f1bc52a044ffc0b87fc7f">7cb728e</a>)</li>
<li>remove irrelevant commits from changelog (<a
href="https://github.com/vitejs/vite/commit/2c69495f250edf01132d4a20128de19dbe836086">2c69495</a>)</li>
</ul>
<h3>Code Refactoring</h3>
<ul>
<li><strong>glob:</strong> do not rewrite import path for absolute base
(<a
href="https://redirect.github.com/vitejs/vite/issues/22310">#22310</a>)
(<a
href="https://github.com/vitejs/vite/commit/0ae2844ab6d6d1ccf78a2975b8132769fc35b302">0ae2844</a>)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/vitejs/vite/commit/f94df87ff03b40b65e29bacdc04cc18c7bccaa4a"><code>f94df87</code></a>
release: v8.0.16</li>
<li><a
href="https://github.com/vitejs/vite/commit/dc245c71e5007ea4d891a025e2d69ac96c736546"><code>dc245c7</code></a>
fix: reject windows alternate paths (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22572">#22572</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/50b951225bbf6151eb84a3ad5a454908ab4a76c9"><code>50b9512</code></a>
fix(deps): reject UNC paths for launch-editor-middleware (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22571">#22571</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/8d1b0195fd186d0b3297d7cd17acff6c96797420"><code>8d1b019</code></a>
release: v8.0.15</li>
<li><a
href="https://github.com/vitejs/vite/commit/2686d7d0b722402204d3bcc687a87adea1bcf9fa"><code>2686d7d</code></a>
fix(deps): update all non-major dependencies (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22511">#22511</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/3052a67d9350f4c5076ab1c222c4a21a589cbcdd"><code>3052a67</code></a>
chore(deps): update rolldown-related dependencies (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22566">#22566</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/e3cfb9deecff563550fa1b8abd27656b8b292815"><code>e3cfb9d</code></a>
fix(optimizer): close the rolldown bundle when write() rejects (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22528">#22528</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/6978a9ceb942c4f5e211d52b8a1e569f8a65c80c"><code>6978a9c</code></a>
refactor: correct logic in <code>collectAllModules</code> function (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22562">#22562</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/646dbedd2870f8ec48df0321177d8aa64bbd1575"><code>646dbed</code></a>
feat: update rolldown to 1.0.3 (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22538">#22538</a>)</li>
<li><a
href="https://github.com/vitejs/vite/commit/85a0eff1c82bbb7c99a0fe8e63704316578a40d3"><code>85a0eff</code></a>
fix: capitalize error messages and remove spurious space in parse error
(<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22488">#22488</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/vitejs/vite/commits/v8.0.16/packages/vite">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=vite&package-manager=npm_and_yarn&previous-version=8.0.10&new-version=8.0.16)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts page](https://github.com/coder/coder/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 20:35:15 +00:00
Spike Curtis 792afc0842 ci: capture PostgreSQL logs in the gen job (#26340)
Adds a `test-postgres-docker-logs` Make target that dumps the test
PostgreSQL container's logs via `docker logs`. The container already
logs every statement to stderr (`log_statement=all`, no
`logging_collector`), so Docker captures them and no volume mounting or
reconfiguration is needed.

The CI `gen` job now starts the container with `make
test-postgres-docker` before `make gen`, collects the logs at the end
(always, even on failure), and uploads them as the `gen-postgres-logs`
artifact to help debug generation issues that depend on the database.

Refs: https://github.com/coder/internal/issues/1568

<sub>Opened by Coder Agents on behalf of @spikecurtis.</sub>
2026-06-15 16:23:36 -04:00
Spike Curtis 21aa295fe4 chore: refactor NATS pubsub to use MsgQueue (#26197)
Closes https://github.com/coder/scaletest/issues/151  
Closes GRU-71  
  
Use the existing MsgQueue from the original PGPubsub instead of the 2-channel solution originally built here.

Renames `natsSub` to `groupSub`, since conceptually, a "NATS Subscription" already refers to the underlying subscription on the NATS server.

This PR also simplifies the closing of the PubSub to just close each `localSub`. When the last `localSub` for an event is closed, it unsubscribes and remove the `groupSub`. This ensures we go through the same code paths closing normally and at end of day.
2026-06-15 16:23:07 -04:00
Steven Masley 195c545bc1 fix(coderd/rbac): guard builtInRoles with atomic.Pointer (#26384)
<sub>Coder Agents on behalf of @Emyrk.</sub>
2026-06-15 18:11:37 +00:00
Jakub Domeracki 450ddff568 fix(coderd/httpmw): honor fixed lifetime for CLI API tokens (#26376)
## What

API key validation applied a sliding-window expiry refresh to every key
type. Programmatic API tokens (created via `coder tokens create`, login
type `token`) had their `expires_at` extended to `now + lifetime` on
each authenticated request (with a ~1h debounce), so a token used within
its lifetime window never actually expired.

This restricts the sliding-window refresh to interactive login sessions
(password / OIDC / GitHub). Programmatic tokens now honor their fixed
`expires_at`.

## Why

A finite token `--lifetime` is expected to be a hard expiry. Silently
extending it on use defeats that expectation and prevents rotation of
long-lived automation credentials.

## Changes

- `coderd/httpmw/apikey.go`: skip the expiry refresh when `key.LoginType
== database.LoginTypeToken`.
- `coderd/httpmw/apikey_test.go`: regression test asserting a token's
expiry is not extended on use.

## Notes

- Interactive sessions are unaffected (they still slide while active).
- Tokens already extended are not retroactively shortened; this prevents
future extension.

<details>
<summary>Validation</summary>

- `go build ./coderd/httpmw/...`
- `go test ./coderd/httpmw/ -run TestAPIKey -count=1` (all pass,
including the new `TokenNoExpiryRefresh` and the interactive
`ValidUpdateExpiry`)
- `golangci-lint run ./coderd/httpmw/` (clean)
- Confirmed the new test fails without the production change and passes
with it.
</details>

---
🤖 Generated by Coder Agents on behalf of @jdomeracki-coder.
2026-06-15 18:46:25 +02:00
Kyle Carberry b439b06ee6 feat: persist agent-pushed workspace context snapshots in coderd (#26145)
Replaces the v2.10 `PushContextState` stub with a real coderd write
path. Phase 1 of the chat-side persistence story; nothing reads these
rows yet.

Follows [#25983](https://github.com/coder/coder/pull/25983) and unblocks
[CODAGT-569](https://linear.app/codercom/issue/CODAGT-569/enable-agent-api-v210-pushcontextstate-bump-currentminor-wire-coderd).

## What ships

### Schema (`000517_workspace_agent_context.{up,down}.sql`)

Two new tables plus `api_key_scope` enum extensions:

- `workspace_agent_context_snapshots` (PK `workspace_agent_id` to
`workspace_agents(id) ON DELETE CASCADE`): one row per agent,
overwritten per push. Holds `version`, `schema_version`,
`aggregate_hash`, `snapshot_error`, `received_at`.
- `workspace_agent_context_resources` (PK `(workspace_agent_id,
source)`): per-resource state. `body_kind` and `status` are `TEXT` +
`CHECK` so adding new wire kinds (the RFC's reserved
PLUGIN/HOOK/SUBAGENT/COMMAND) is a one-line CHECK update plus a Go
switch case.

### SQLC queries (`coderd/database/queries/workspaceagentcontext.sql`)

- `UpsertWorkspaceAgentContextSnapshot`
- `UpsertWorkspaceAgentContextResource`
- `DeleteStaleWorkspaceAgentContextResources`
(delete-where-source-not-in)
- `GetLatestWorkspaceAgentContextSnapshot`
- `ListWorkspaceAgentContextResources`

### Handler (`coderd/agentapi/context.go`)

`ContextAPI` is a new sub-API. `PushContextState`:

1. Rejects `schema_version > 1` with a non-`Unimplemented` error so a
forward-incompatible agent fails loudly during rollout instead of
slipping into the permanent fallback path the `Unimplemented`
translation reserves for old coderd deployments.
2. Validates resources: no empty/duplicate sources, every variant maps
to a known body kind, every status maps to a known enum value, the
`Body` oneof is set (even when status is non-OK, mirroring the wire
guarantee so coderd can attribute failures to a known kind).
3. Inside `Database.InTx`, reads the existing snapshot. If the push is
not `initial` and `version` is not strictly greater, returns `accepted =
false` and leaves stored state untouched. Otherwise upserts the snapshot
row, upserts each resource, then runs the stale-source prune so the
snapshot and resource rows always agree.
4. Returns `accepted = true` on success.

Resource bodies are stored as `protojson(body oneof variant)` in `body
JSONB` with `body_kind` as the discriminator. Adding a new field to an
existing variant is zero work since `protojson` tolerates new fields;
adding a new variant is a CHECK + switch case.

### RBAC + dbauthz

- New `ResourceWorkspaceAgentContext` (Create/Read/Update/Delete).
- New `SubjectTypeAgentContext` plus `subjectAgentContext` system role
and `dbauthz.AsAgentContext` helper. The push handler elevates to this
subject; the agent's own role does not get direct write access to the
table.
- New `workspace_agent_context:*` API key scopes registered in the enum
migration; internal-only (not added to `externalLowLevel`).

### Audit

These rows are agent-pushed state, not user-authored. They are
intentionally not added to `AuditActionMap` and not enumerated in
`enterprise/audit/table.go`, matching `boundary_logs`,
`workspace_agent_memory_resource_monitor`, etc. `enterprise/audit` tests
pass unchanged.

## Tests

- `coderd/agentapi/context_test.go`: 12 subtests covering
accepts/rejects (schema version, empty/duplicate source, unknown status,
missing body), version semantics (stale dropped, same-version replay
dropped, `initial=true` overwrites lower version), variant coverage,
non-OK status persistence, and the empty-active-set prune case.
- `coderd/database/dbauthz/dbauthz_test.go`: 5 `MethodTestSuite` cases
covering the new queries.
- `coderd/rbac/roles_test.go`: `WorkspaceAgentContext` permission row
asserting no human role currently has access.
-
`coderd/database/migrations/testdata/fixtures/000517_workspace_agent_context.up.sql`:
one snapshot + one resource per known body kind plus a non-OK status, so
the migration test suite never lands with these tables empty.

## Out of scope (later phases)

- Chat hydration (`chats.context_aggregate_hash`,
`last_injected_context`).
- Dirty-bit fan-out and `PUT /chats/{id}/context`.
- Agent-side `POST /api/v0/context/resync` barrier and the `coder exp
chat context` CLI.
- `codersdk` chat-context wire types and the dashboard Sources drawer.
- Removal of the chatd per-turn pull fallback.

## Compat property

This is a pure write path. If anything here returns errors the agent's
`RunPush` loop backs off, no chat behavior changes, and the workspace
keeps behaving exactly like it did before v2.10.

<details>
<summary>Implementation plan and decision log</summary>

Key design calls:

1. **Concurrency**: Accept iff `req.Initial || req.Version >
existing.Version`. The strict RFC reading ("version comparison is
authoritative") locks restarted agents out because their per-process
counter resets to 1; honoring `initial=true` reflects the real reboot
reality while still rejecting steady-state replays/out-of-order pushes.
2. **Body encoding**: `protojson` over the oneof variant body proto,
stored in JSONB with `body_kind` discriminator. Structured at the API/Go
layer, schema-tolerant at the storage layer, and Phase 2 readers
round-trip back via `protojson.Unmarshal`.
3. **Schema version rejection**: returns a normal error, not
`Unimplemented`. The agent's `RunPush` loop only short-circuits on
`Unimplemented`; that escape hatch is reserved for old coderd
deployments. A forward-incompatible agent should retry-and-back-off, not
flip the connection into permanent fallback.
4. **Validation strictness**: empty sources, duplicate sources,
`STATUS_UNSPECIFIED`, and missing `Body` oneof variants are rejected
before any write so a misbehaving agent cannot poison the snapshot
table. Phase 2 readers can trust every row maps to a known proto
variant.

</details>

_This PR was authored by Coder Agents on Kyle Carberry's behalf._
2026-06-15 09:38:52 -07:00
Paweł BanaszewskiandJake Howell e019210f4b feat(site): add AI Gateway keys management page (#25817)
> Vibe-coded using Coder Agents, author with limited frontend knowledge,
manually tested.

Adds an `AI Gateway Keys` page under `Admin settings > AI > AI Gateway
Keys` for key management of keys used by standalone AI Gateway replicas
to authenticate into `coderd`.
The page is shown to users with `viewAIGatewayKeys` permission and a
Premium license with AI Gateway enabled.
Adds Storybook coverage.

---------

Co-authored-by: Jake Howell <jacob@coder.com>
2026-06-15 18:26:58 +02:00
Hugo Dutka 86bdedb0a9 fix(coderd/x/chatd): dont send web notifs on subagent completion (#26379)
The chat refactor mistakenly started sending web push notifications on
subagent completion. This PR fixes that. Addresses
[CODAGT-624](https://linear.app/codercom/issue/CODAGT-624/subagent-completion-sends-web-push-notifications).
2026-06-15 15:58:36 +00:00
Jeremy Ruppel 4574c7d792 feat: validate module variable keys and values (#26354)
Validates caller-supplied module variable keys and values in the
template builder compose endpoint before template rendering. Previously,
`mergeModuleVariables` accepted any caller-supplied key and value
without validation, allowing unknown keys, computed/sensitive variable
overrides, and malformed HCL literals (including injection payloads) to
pass through to rendered output.

Now `mergeModuleVariables` rejects unknown keys (those not in the
manifest's non-computed, non-sensitive variables) and type-checks
values: strings must be quoted HCL literals without interpolation
markers or unescaped newlines, numbers must be strict numeric literals,
and bools must be exactly `true` or `false`. The literal `null` is
accepted for any type.

Closes https://linear.app/codercom/issue/DEVEX-278

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

- Changed `mergeModuleVariables` signature from `map[string]string` to
`(map[string]string, error)` to surface validation failures
- Added `validateVariableValue`, `validateStringValue`,
`validateNumberValue`, `validateBoolValue` in `compose.go`
- String validation rejects: unquoted values, HCL interpolation (`${`,
`%{`), unescaped newlines/quotes, trailing backslashes (which would
escape the closing delimiter), and values exceeding 4096 bytes
- Errors wrap the module ID and variable name for clear diagnostics
(e.g. `module "code-server": variable "port": invalid number value`)
- Tests cover key validation, type validation, injection attempts, and
full Compose flow integration

> Generated with the help of [Coder Agents](https://coder.com) by
@jeremyruppel
</details>
2026-06-15 11:34:47 -04:00
Hugo Dutka 3cde346cbb fix(coderd/x/chatd): fix compaction still over limit check (#26377)
Addresses
[CODAGT-620](https://linear.app/codercom/issue/CODAGT-620/session-can-get-stuck-at-compaction-with-request-failed).
We have logic that checks whether message compaction still leaves the
chat over the context limit. We want to abort if it does - if we didn't,
we'd get into an endless compaction loop. The check's logic was faulty.
This PR changes fixes it. The new flow is:

1. In iteration 1, a chat runner commits a message compaction summary.
2. In iteration 2, the runner submits the newly compacted conversation
to the LLM provider in order to generate the next message.
3. In iteration 3, 4, 5, etc., if the conversation needs compaction, the
runner looks up the configured context limit and the first assistant
message after the last compaction summary. It compares the context usage
on that message with the context limit. If the usage is over the limit,
it returns an error.
2026-06-15 17:17:50 +02:00
Jeremy Ruppel b61b62f4b3 feat: add POST /api/v2/templatebuilder/compose endpoint (#26351)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Part 4 of DEVEX-277 (POST /api/v2/templatebuilder/compose).

Adds the HTTP handler, route wiring, and integration tests for the
compose endpoint.

The handler accepts a JSON request with a base template ID and optional
modules with variable overrides, renders them via `Compose`/`BundleTar`,
and returns the tar archive directly with `Content-Type:
application/x-tar`. The registry URL comes from the deployment config
(`CODER_TEMPLATE_BUILDER_REGISTRY_URL`).

RBAC uses `policy.ActionCreate` on
`rbac.ResourceTemplate.AnyOrganization()`.

Integration tests cover: base-only compose, base with modules, unknown
base/module errors, missing base template ID, and feature-disabled 404.
2026-06-15 11:07:16 -04:00
Marcin Tojek c50cef5ae1 fix: add Gemini/Google provider support to AI Bridge session page (#26374)
Fixes https://github.com/coder/internal/issues/1576
2026-06-15 16:27:36 +02:00
Ethan 1b9745c311 fix: surface chat error diagnostics (#26367)
Closes CODAGT-223

## What's already on `main` (via #25803)

#25803 fixed how `detail` is *rendered* when present:
`ChatStatusCallout` shows `status.detail` in a monospace `<code>` block
for `kind === "generic"`, `AgentChatPage` reads
`error.response?.data?.detail` inline, and the auth message was
tightened.

It did not fix `detail` being absent in the first place.

## The gap

`chaterror.Classify` only populates `Detail` from
`*fantasy.ProviderError` (OpenAI-shaped JSON envelope). Every other
realistic failure shape produces blank `Detail`:
`context.DeadlineExceeded`, `Post "…": connection refused`, `stream
error: stream ID …; INTERNAL_ERROR`, `Post "https://api.openai.com/…":
400 invalid model: gpt-9000`, `fantasy.Error` from the stream decoder,
`xerrors.New("status 401 from upstream")`, HTTP/2 peer resets. Users
still see the dead-end alert: "Request failed / The chat request failed
unexpectedly." with no third line.

## The fix

A new `chaterror.FormatDiagnosticDetail` entry point shares
diagnostic-detail logic with `classify.go`: non-auth rule-table branches
now fall back to a bounded raw error string when structured detail is
absent, while auth-classified failures keep only structured provider
detail. Curated branches (canceled, interrupted, Responses-API,
stream-incomplete, chain-broken) are left alone. The `exp_chats.go` POST
catch-all uses the exported helper, so the backend consistently emits a
bounded diagnostic string instead of leaving `Detail` blank. Fallback
diagnostics redact URLs preserved in typed transport errors by stripping
userinfo, query strings, and fragments before display, which keeps
provider error text useful while reducing credential exposure from
standard request URL wrappers.

## Security

This change surfaces upstream error text in the chat UI, where it is
also persisted in `chats.last_error`, so it crosses a trust boundary.
Codex brought this up as an issue through reviews. Mindful of cases like
#20968, where a sensitive field leaked into agent logs, the design
deliberately narrows what can reach a user:

- Auth-classified failures keep only structured provider detail and
never fall back to the raw error string.
- Fallback diagnostics redact any URL preserved in a typed `*url.Error`
by removing userinfo, query strings, and fragments, so credentials in
standard transport URL wrappers do not leak.
- Request-side credentials are not exposed: providers authenticate via
headers, and `fantasy.ProviderError.Error()` does not print the URL or
request dump. Dumped response headers are stripped before parsing, and
detail is length-capped.

The remaining channels are structured provider detail (`error.message`
from the provider's response body), which is surfaced verbatim because
it is the useful diagnostic this PR exists to deliver, and
already-flattened fallback text where typed transport context has been
lost. A well-behaved provider returns a description of the failure here,
not a secret; OpenAI, for example, masks the middle of the submitted key
and returns only a short fragment alongside a docs link. For a real
secret to appear, the upstream API, or a proxy an admin points
`base_url` at, would have to echo a plaintext credential into its own
error body or flattened error prose. I judge that any secret leakage as
a result of this PR would require a misbehaving API or middleware, and
that the usefulness of real diagnostics outweighs that bounded risk.
2026-06-16 00:21:13 +10:00
Jeremy Ruppel ce21a565dd feat: add TemplateBuilderCompose SDK types and client method (#26350)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Part 3 of DEVEX-277 (POST /api/v2/templatebuilder/compose).

Adds SDK types and client method for the compose endpoint:

- `TemplateBuilderComposeRequest` with `BaseTemplateID` and `Modules` (list of `{ID, Variables}`). Registry URL is omitted from the request; it comes from server-side deployment config.
- `TemplateBuilderCompose(ctx, req)` client method that POSTs the request and returns raw `application/x-tar` bytes (matching the `Download` pattern in `codersdk/files.go`).
- Generated TypeScript types updated.
2026-06-15 09:29:39 -04:00
Jeremy Ruppel 877f4def4a feat(coderd/templatebuilder): add Compose and BundleTar functions (#26349)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Part 2 of DEVEX-277 (POST /api/v2/templatebuilder/compose).

Adds the core composition and bundling logic for the template builder.

`Compose` renders a base template and selected modules into Terraform source files. It validates modules before rendering (rejects duplicates, ConflictsWith violations, unknown IDs, OS incompatibility), then for each module merges manifest defaults with caller-supplied variable overrides and renders the module template.

`mergeModuleVariables` fills in defaults for non-computed, non-sensitive variables from the manifest (with basic JSON type validation via `isSimpleJSONValue`), uses `null` for non-required variables without defaults, and leaves required variables absent so `missingkey=error` catches omissions at render time.

`BundleTar` packages the result into a tar archive with reproducible timestamps. Writes `main.tf` always, `modules.tf` only when modules are present.

Conflict detection is bidirectional so module ordering in the request does not affect validation.
2026-06-15 09:28:39 -04:00
Jeremy Ruppel 6b890116aa feat(coderd/templatebuilder): add module rendering and agent name extraction (#26347)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Part 1 of DEVEX-277 (POST /api/v2/templatebuilder/compose).

Adds module rendering support and agent resource name extraction to the template builder, preparing for the compose endpoint.

- `ModuleRenderContext` and `RenderModuleTemplate` for rendering module `.tf.tmpl` files with registry URL, pinned version, agent resource name, and variable values. Nil-guards the Variables map to prevent panics.
- Extract shared `renderTemplate` with `missingkey=error` so missing variable keys fail loudly instead of producing `<no value>` in rendered HCL.
- `ExtractAgentResourceName` uses a regex to find the `coder_agent` resource name from rendered base HCL. Errors unless exactly one agent is found.
- `ModuleTemplateFS` exposes module template files from the embedded catalog, with validation that the expected `.tf.tmpl` file exists (`fs.Sub` on `embed.FS` silently succeeds for nonexistent paths).
2026-06-15 09:27:39 -04:00
Jeremy Ruppel 1cdb7ed9f7 feat(coderd/templatebuilder): author initial module catalog for 19 modules (#26194)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Runs the `scripts/modulegen` generator against the coder/registry to produce the initial module catalog for the template builder. Generates `module.json` and `.tf.tmpl` files for 19 modules across four categories:

- **IDE**: code-server, jetbrains, vscode-desktop, vscode-web, cursor, windsurf, zed, kiro
- **AI Agent**: claude-code, aider, goose, amazon-q
- **Source Control**: git-clone, git-config, git-commit-signing
- **Utility**: dotfiles, personalize, filebrowser, jupyterlab

Also updates `catalog_test.go` to validate the new embedded modules load correctly.
2026-06-15 09:26:39 -04:00
Jeremy Ruppel 809bd613e3 feat(scripts): add generator for template builder module catalog (#26193)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Adds `scripts/templatebuildermodulegen/`, a Go tool that fetches module metadata from the Coder registry HTTP API and generates the `module.json` manifests and `.tf.tmpl` files used by the template builder catalog.

The generator calls `GET /api/modules/{id}` for per-module metadata (display name, description, icon, tags, variables) and the Terraform protocol versions endpoint for semver resolution. No git clone or HCL parsing required.

Split into four files:
- `main.go`: orchestration, module config map, CLI flags
- `types.go`: output types (`ModuleManifest`, `ModuleVariable`) and API response types
- `fetch.go`: HTTP fetching, version resolution, variable conversion, icon normalization
- `write.go`: JSON writer, `.tf.tmpl` Go template and writer
2026-06-15 09:25:56 -04:00
35C4n0randAtif Ali 28e83471b3 docs(docs/ai-coder/agent-firewall): fix firewall examples for claude-code v5.x (#26373)
The Agent Firewall docs had a Terraform example using `enable_boundary =
true` on the `claude-code` module at v5.2.0. That input was removed in
the v5.x refactor.

Update the getting-started and configuration examples to use the
standalone `agent-firewall` module
(`registry.coder.com/coder/agent-firewall/coder`), which is the correct
integration point for v5.x. The config is now passed via
`agent_firewall_config` (inline YAML or `file()` reference) instead of a
manual `coder_script` that base64-decoded a file into
`~/.config/coder_boundary/`.

Closes:
[REG-13](https://linear.app/codercom/issue/REG-13/docs-example-uses-nonexistent-enable-boundary-input)

> Generated by Coder Agents

---------

Co-authored-by: Atif Ali <atif@coder.com>
2026-06-15 18:28:11 +05:30
Nick Vigilante 354226342c fix(provisioner/terraform/testdata): make provider version check work with BSD sed (#26337)
The provider version check in `generate.sh --check` uses nested sed
brace blocks that BSD sed rejects ("extra characters at the end of }
command"), so the check always fails on stock macOS. A failing check
makes `make gen` (and therefore the full pre-commit hook) regenerate
every terraform fixture, which is not reproducible on macOS hosts
because the `coder_provisioner` data source records the host `os`/`arch`
(`darwin`/`arm64` instead of the committed `linux`/`amd64`), leaving
permanent unstaged churn that fails `check-unstaged`.

Replace the nested-brace expression with two simple sed passes that
behave identically under GNU and BSD sed. Verified on macOS
(`/usr/bin/sed`) and GNU sed: both extract `2.15.0`, matching
`provider-version.txt`, and `generate.sh --check` now exits 0 on a clean
checkout.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-06-15 08:54:17 -04:00
Hugo Dutka 4cf4ee0121 chore(coderd/x/chatd): log all chat errors (#26371)
When a chat hits a terminal error, for example "Request failed
unexpectedly", we don't log the full underlying error anywhere. This
fixes that.
2026-06-15 14:13:22 +02:00
Sas Swart 6a02f1c626 chore: renumber migration to drop agent firewall foreign key (#26372)
Renumber migration to drop agent firewall foreign key.
2026-06-15 11:32:29 +00:00
Sas Swart f0ac52e83c feat: persist boundary logs (#24812)
Add database persistence to `ReportBoundaryLogs`. On first log for a
session, the handler lazy-creates a `boundary_sessions` row, then
batch-inserts all `BoundaryLog` entries into `boundary_logs`. Structured
logging and usage tracking are preserved. Old boundary clients (no
`session_id`) fall back to log-only mode.

> [!NOTE]
> This PR was authored by Coder Agents.
2026-06-15 12:34:48 +02:00
Sas Swart e1c7e61eb9 feat(coderd): add Agent Firewall correlation columns to aibridge_interceptions (#24817)
Add `agent_firewall_session_id` (UUID NULL) and
`agent_firewall_sequence_number` (INT NULL) to `aibridge_interceptions`
with a partial index on `agent_firewall_session_id`. No FK to
`boundary_sessions` (soft reference, resolved at query time).
`RecordInterception` reads the new fields from the proto request (merged
in #25884) via `parseOptionalUUID` / `parseOptionalInt32` helpers.

> This PR was authored by Coder Agents.
2026-06-15 12:34:16 +02:00
Ethan bfe64d6355 test(coderd): unskip chatd notification flow tests (#26366)
Fixes coder/internal#1519
Fixes CODAGT-353

These nine tests were skipped pending a chatd notification flow refactor
that would let workers distinguish stale control `NOTIFY` messages from
real interrupts. They now pass consistently, so this drops the `t.Skip`
calls and the now-stale `TODO(CODAGT-353)` blocks.

While rerunning the package after unskipping them,
`TestNewReplicaRecoversStaleChatFromDeadReplica` also surfaced as flaky
on `main` because it asserted transient ownership state. This PR keeps
that server-level test as a stable end-to-end recovery check and adds a
deterministic worker-level stale reacquisition test so we still directly
cover lease takeover behavior.

## Tests unskipped

- `coderd`: `TestPatchChatMessage/ChangesModel`
- `coderd/x/chatd`:
  - `TestExploreChatSendMessageCannotMutateMCPSnapshot`
  - `TestAutoPromoteQueuedMessagesPreservesPerTurnModelOrder`
  - `TestSignalWakeSendMessage`
  - `TestAdvisorChainMode_SnapshotKeepsFullHistory`
  - `TestOpenAIResponsesNoStaleWebSearchReplay`
  - `TestOpenAIResponsesFullReplayPairsReasoningAndWebSearch`
  - `TestOpenAIResponsesChainModeSkipsWhenLocalCallPending`
  - `TestOpenAIResponsesChainModeStillFiresForProviderExecutedOnly`

## Stale recovery follow-up

- `coderd/x/chatd`: `TestNewReplicaRecoversStaleChatFromDeadReplica` now
waits for the stable `waiting` and unowned end state after recovery.
- `coderd/x/chatd`: `TestWorker_ReacquiresStaleOwnedChat` blocks the
runner after reacquisition and directly asserts the new worker
ownership, new runner ID, and fresh heartbeat.

I stress-ran the stale recovery tests locally with repeated plain and
race runs, and re-ran the nine unskipped tests plus
`TestPatchChatMessage/ChangesModel` after these follow-up changes.
2026-06-15 20:24:13 +10:00
Danielle Maywood 2c754630f6 fix(site/src/pages/AgentsPage): separate interactive and display file reference chips (#26094) 2026-06-15 10:01:48 +01:00
Nick Vigilante ba64724f8a docs: add canonical content guidelines, close doc-check SKILL gaps (DOCS-332) (#26352)
Closes DOCS-332.

## Summary

Add `docs/.style/content-guidelines.md` as the canonical source of truth
for what belongs in Coder's docs and what doesn't. Slim
`.claude/skills/doc-check/SKILL.md` and reconcile
`.claude/docs/DOCS_STYLE_GUIDE.md` so they defer to that canonical file.
One-line pointer added from root `AGENTS.md`.

## Problem

DOCS-332 cataloged five gaps in the doc-check skill and its sibling
AI-facing docs:

1. Two style guides overlapping and contradicting each other on bold and
italic conventions.
2. The SKILL had a single "do not comment" class (auto-generated CLI
docs); everything else was inferred. Source of sticky-comment noise.
3. Premium signaling split across two files (`(Premium)` H1 suffix in
SKILL, `"state": ["premium"]` manifest entry in DOCS_STYLE_GUIDE).
4. The no-emdash rule lived in root `AGENTS.md` and DOCS_STYLE_GUIDE but
not in the SKILL.
5. The redirects-live-in-`coder/coder.com:redirects.json` rule lived
only in DOCS_STYLE_GUIDE.

In parallel, a cross-repo content guidance discussion (June 2026)
produced a canonical "what belongs in the docs" document in Notion that
disagreed with the existing GitHub guidance in three places:
screenshots, "proactive documentation," and in-docs troubleshooting.

## Fix

**New canonical file**: `docs/.style/content-guidelines.md`. Translates
the canonical content guidance into the repo:

- Diátaxis framing.
- "Documentation lands with the change" rule with three corollaries
(docs in same PR; no docs for unconfirmed features; multi-PR launch
exception, present tense, never as a promise).
- 7-step quick decision checklist.
- "What belongs / what doesn't / routing table" structure.
- Screenshot policy: only when the topic would be confusing without it;
PHI/PII, secrets, minimal surface area, alt text required.
- Premium signaling requires both H1 suffix and `"state": ["premium"]`
in `docs/manifest.json`.
- Redirects must be added to `coder/coder.com:redirects.json`, never
`docs/_redirects`.
- Verify-against-code rule with exact RBAC names and full API paths.
- Terraform exception for minimal teaching examples.

**Slim `.claude/skills/doc-check/SKILL.md`**: defers scope and routing
to `docs/.style/content-guidelines.md`. Adds an explicit "What not to
comment on" list (Gap 2) covering internal refactors, test-only changes,
CI/tooling, dep bumps, and pure code reorganizations. Closes Gaps 3, 4,
and 5 in the same pass.

**Reconcile `.claude/docs/DOCS_STYLE_GUIDE.md`**: removes the
image-driven documentation pattern, the placeholder-screenshot workflow,
the "proactive documentation" pattern, and the in-docs troubleshooting
H3 pattern. Each is replaced with a short pointer to the canonical
guidelines. Prose, formatting, and structural conventions remain; this
file continues to cover those.

**`AGENTS.md`**: one-line pointer added to the navigation section and
the read-when-relevant list.

## What's explicitly out of scope

- **Gap 1** (bold and italic reconciliation): deferred to DOCS-186,
which will redirect the human-facing
`docs/about/contributing/documentation.md` to
`docs/.style/style-guide.md` once DOCS-180 lands.
- **Prose-rule migration** to `docs/.style/style-guide.md`: handled by
DOCS-180.
- **doc-check workflow comment-format changes**: deferred (Phase 2
work).
- **redirect-suggestion behavior in doc-check**: tracked as DOCS-359.
- **Historical predictive-content sweep across `docs/`**: tracked as
DOCS-358.

## Known CI notes

- This PR will trigger `docs-preview`, which posts a comment with a deep
link to the first added Markdown file. The link will 404 because
`docs/.style/**` files are not added to `docs/manifest.json` and
shouldn't be (the directory is contributor-facing, not published).
DOCS-180 negates `docs/.style/**` in the `docs-preview` workflow; once
that lands the papercut goes away. Safe to ignore the comment on this
PR.
- `deploy-docs` will run on merge but is manifest-driven: since
`docs/.style/**` files are not in `docs/manifest.json`, the surgical
Algolia indexer will skip them and no full Vercel rebuild fires.
- `doc-check` will run on this PR; the diff has no user-facing product
change, so it should report no documentation impact.

## Review

This change is documentation-only and does not modify product code or CI
checks in any meaningful way. Per standing instructions this requires a
human review; the `/coder-agents-review` bot is **not** triggered.

<details>
<summary>Implementation plan and decision log</summary>

### Decisions made during scoping

1. **Option B (consolidate)** for DOCS-332: a single canonical
content-guidance file instead of distributing fixes back into the
existing sibling files.
2. **File location**: `docs/.style/content-guidelines.md`. The rules
apply to both humans and AI, so an AI-prefixed naming scheme would
mislead. `docs/.style/` is contributor-facing and not published to
coder.com per the DOCS-180 convention.
3. **Independent merge**: this PR does not block on DOCS-180. The README
in `docs/.style/` is a minimal stub that should merge cleanly with the
DOCS-180 README.
4. **Canonical-source model**: GitHub becomes canonical for docs content
guidance. The cross-repo source page will be rewritten to point at this
file as a follow-up.

### Conflicts resolved

| Topic | Old GitHub guidance | New canonical |

|----------------|---------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|
| Screenshots | Image-driven sections; placeholders welcome | Use only
when topic confusing without; 4 rules (no PHI or PII, no secrets,
minimal surface area, alt text) |
| Timelessness | "Proactive Documentation" pattern (write ahead,
reference PR number) | "Documentation lands with the change" plus 3
corollaries; predictive language banned |
| Troubleshooting| In-docs H3 pattern | Routes to Support KB (Pilon);
embedded widget under investigation |

### Pre-mortem

- **`docs-preview` dead link**: known papercut documented in the CI
notes above.
- **`deploy-docs` over-fire**: addressed by manifest-driven exclusion;
the surgical indexer skips non-manifest paths.
- **Merge conflict with DOCS-180 `docs/.style/README.md`**: expected to
be small and mechanical. Both PRs introduce the same directory and a
"What lives here" table; the merge is "combine the rows".
- **Merge conflict with DOCS-186**: none expected. DOCS-186 changes
`docs/about/contributing/documentation.md`, which this PR does not
touch.

### Follow-up tickets filed

- **DOCS-358**: Sweep `docs/` for predictive or proactive content that
violates the "docs land with the change" rule.
- **DOCS-359**: doc-check suggests `redirects.json` entries on doc
renames and moves.

</details>

---

*Generated via Coder Agents.*
2026-06-12 18:38:49 -04:00
Nick Vigilante fb24110933 feat(.github/workflows): trigger docs reindex on release.published (DOCS-327) (#26070)
Closes
[DOCS-327](https://linear.app/codercom/issue/DOCS-327/trigger-docs-reindex-on-codercoder-releasepublished).

## What

Add `release: { types: [published] }` to
`.github/workflows/deploy-docs.yaml` so that publishing a stable
`vX.Y.Z` GitHub Release on this repo auto-dispatches the docs-sync
handler against the corresponding `release/X.Y` branch. The existing
`push` and `workflow_dispatch` triggers are unchanged.

The `Compute action and ref` step gains a release-event branch that:

- Skips prereleases (`github.event.release.prerelease == true`) with a
workflow notice.
- Matches the tag against `^v([0-9]+)\.([0-9]+)\.[0-9]+$` and translates
`v2.35.0` to `release/2.35`.
- Falls through with a notice and `exit 0` for any tag that doesn't
match the plain semver shape (`v2.35`, `v2.35.0-rc.1`, etc.).

Downstream validation, HMAC body construction, and the POST step are
unchanged. The POST step gains an `if: steps.input.outputs.action != ''`
guard so the two `exit 0` paths skip the POST instead of sending empty
`action`/`ref` to the production handler.

A new `.github/workflows/test-deploy-docs-release.sh` exercises the
release-event bash against the 11 event scenarios in the table below
plus 3 regex boundary cases, mirroring the existing
`test-deploy-docs-diff.sh` pattern.

## Why

Today, every mainline rollover requires a human to dispatch this
workflow manually with `action=index, ref=release/X.Y`. We just hit this
rotation friction on
[DOCS-324](https://linear.app/codercom/issue/DOCS-324/rotate-algolia-indexer-allowlist-for-v234-launch-add-release234-drop)
(v2.34 launch) and the resulting empty-search-results incident on
`/docs/@v2.34.x/...`. `release.published` is the right cue: it fires
exactly when a version becomes user-visible, not when its release branch
is cut weeks earlier with possibly-incomplete docs.

## Coupling (important)

This change is **intentionally inert until coder.com's
`INDEXED_REFS_BY_CORPUS` allowlist becomes self-rotating** (filed under
[DOCS-210](https://linear.app/codercom/issue/DOCS-210/automated-docs-index-lifecycle-management)).
Until that lands, the handler still rejects new minors with `{action:
"skipped", reason: "...not in INDEXED_REFS_BY_CORPUS"}` and this
workflow logs the skip. Pre-wiring lets both halves land roughly in
parallel so the next release cut after both ship is automatic.

Reviewers: feel free to merge this independently. There is no downside
to the wiring being live before the allowlist half ships; worst case,
every release-publish event creates a no-op workflow run.

## Behavior trace (the cases the bash handles)

<details>
<summary>11 event scenarios I walked through by hand</summary>

| Event | Tag | prerelease | Result |
|---|---|---|---|
| push to main | n/a | n/a | `index`, `ref=main` (existing) |
| push to release/2.34 | n/a | n/a | `index`, `ref=release/2.34`
(existing) |
| workflow_dispatch index release/2.34 | n/a | n/a | `index`,
`ref=release/2.34` (existing) |
| workflow_dispatch delete release/2.31 | n/a | n/a | `delete`,
`ref=release/2.31` (existing) |
| release.published | `v2.35.0` | `false` | `index`, `ref=release/2.35`
(new) |
| release.published | `v2.35.0-rc.1` | `true` | notice + `exit 0` (new)
|
| release.published | `v2.35.0-rc.1` | `false` | notice + `exit 0`,
regex miss (new) |
| release.published | `v2.35` | `false` | notice + `exit 0`, regex miss
(new) |
| release.published | `release-2.35` | `false` | notice + `exit 0`,
regex miss (new) |
| release.published | `v0.0.0` | `false` | `index`, `ref=release/0.0`
then handler rejects via allowlist (defense in depth) |
| release.published | `` (empty) | unset | notice with `<unknown>` +
`exit 0` |

</details>

## Safety

- The handler's allowlist gate still applies; this PR can only cause
`{action: "skipped"}` responses until DOCS-210's allowlist-derivation
lands. No risk of indexing an unintended ref.
- The workflow's existing input validation (`case "$REF" in
main|release/*)`) rejects any translation output that isn't
`release/<int>.<int>`. Defense in depth in case the regex ever loosens
by accident.
-
[DOCS-121](https://linear.app/codercom/issue/DOCS-121/post-mortem-docs-search-outage-2026-05-12-pr-25049-merge-wiped-docs)
self-trigger risk is not present here: the new trigger is
`release.published`, not push-on-paths. Workflow file edits cannot
induce a release event.
- `concurrency: { group: deploy-docs-${{ github.ref }} }` already
exists. Release events have `github.ref=refs/tags/vX.Y.Z`, distinct from
push events on the same release branch. A theoretical race resolves
through the handler's atomic deleteBy+saveObjects.
- The POST step now has an `if:` guard that skips downstream calls when
the Compute step exits early without writing outputs. Closes the
empty-env-var failure mode that coder-agents-review CRF-1 flagged.

## Verification

- `actionlint .github/workflows/deploy-docs.yaml` clean.
- `make pre-commit-light` clean: `fmt/shfmt`, `fmt/markdown`,
`lint/actions/actionlint`, `lint/shellcheck`, `lint/markdown`,
`lint/emdash`, `lint/typos`, etc.
- `.github/workflows/test-deploy-docs-release.sh`: 14 cases pass (11
scenario table + 3 regex boundary cases).
- Bash logic hand-traced through 11 event scenarios (table above).

## Out of scope

- Build-time allowlist derivation in coder.com (DOCS-210a, will be
filed/PR'd as a sibling change).
- Webhook-driven cleanup of aged-out refs
([DOCS-210](https://linear.app/codercom/issue/DOCS-210) parent).
- code-server release lifecycle (different repo, code-server's docs
corpus stays at `main`).

---

_Coder Agents on behalf of @nickvigilante._
2026-06-12 17:54:32 -04:00
Jeremy Ruppel 9a6e348f5d feat: add GET /api/v2/templatebuilder/modules endpoint (#26117)
Implement `GET /api/v2/templatebuilder/modules`, which returns the
filtered list of modules available for a given base template. Reads from
the bundled catalog via `LoadModules()` and applies OS-compatibility
filtering based on the `base` query param.

Computed variables (e.g. `agent_id`) are excluded from the API response
at the `ToSDK()` conversion boundary since they are wired automatically
by the builder. The `Computed` field is removed from the SDK type. Adds
`CompatibleWithOS()` to `ModuleManifest` for OS filtering.

Returns 400 for unknown base IDs and 404 when the template builder is
disabled.

Depends on #26116

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-12 17:53:48 -04:00
Jeremy Ruppel 776fbfa748 feat: add GET /api/v2/templatebuilder/bases endpoint (#26116)
Implement `GET /api/v2/templatebuilder/bases`, which returns the list of
base templates available in the template builder. Reads from the bundled
catalog by cross-referencing `templatebuilder.BaseTemplateIDs()` with
`examples.List()`, enriching each entry with the OS from the `exampleID
-> OS` map.

The endpoint is gated behind the template builder feature flag (returns
404 when disabled) and requires `policy.ActionRead` on
`rbac.ResourceTemplate`.

Depends on #26115

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-12 17:40:02 -04:00
McKayla はな 1215210321 fix: fix playwright install on ubuntu 26.04 (#26356) 2026-06-12 15:26:12 -06:00
Jeremy Ruppel 71957a2bc0 feat(coderd/templatebuilder): add exampleID->OS map and base template .tf.tmpl files (#26115)
Add the bundled `exampleID -> OS` Go map for Docker, Kubernetes, and AWS
EC2 Linux base templates. Create `.tf.tmpl` Go template files for each
within `coderd/templatebuilder/bases/`, along with `BaseRenderContext`
and `RenderBaseTemplate` rendering helpers.

The `.tf.tmpl` files are independent copies of the example templates
with module blocks (code-server, jetbrains) removed, since the template
builder composes modules separately into `modules.tf`. When
`ImageOptions` is provided, the container image field references the
Terraform parameter; otherwise it uses the hardcoded value via Go
template whitespace control (`{{-`).

Golden file snapshot tests verify rendered output stability with an
`-update` flag for regeneration.

Depends on #25909

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-12 17:12:17 -04:00
Nick Vigilante a86e1ca4bb fix: pin Terraform 1.15.5 for all Nix platforms (#25799)
The terraform_1_15_5 derivation previously only handled linux/amd64,
falling through to unstablePkgs.terraform on all other platforms. On
macOS this meant a different Terraform version was used, which caused
the version check in make pre-commit to trigger generate.sh,
regenerating all testdata with the host platform's OS/arch
(darwin/arm64) instead of the committed linux/amd64 values.

Three changes:

1. `flake.nix`: add explicit linux_arm64, darwin_arm64, and darwin_amd64
cases with SHA256 hashes from the official HashiCorp release. Unknown
platforms still fall back to unstablePkgs.terraform.

2. `provisioner/terraform/testdata/generate.sh`: guard full regeneration
behind a Linux-only check. The committed testdata encodes linux/amd64
values from the coder_provisioner data source, so regenerating on macOS
would permanently bake in darwin/arm64. The --check path still runs on
all platforms so the version target can detect provider mismatches.
Regeneration via CI or an explicit Linux run is unchanged.

3. `scripts/release/check_commit_metadata.sh`: fix a shfmt (>=3.13)
false positive. The [install.sh] key in an associative array literal was
parsed as floating-point arithmetic (a zsh-only feature). Moving it to a
post-declaration assignment satisfies the stricter parser without
changing runtime behavior.

<!--

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

-->



Linear: DOCS-279
2026-06-12 16:28:54 -04:00
TJ d6aa3d61ee fix(site): add alt text to Avatar so workspaces images pass WCAG (#26223)
## Summary

Fixes the WCAG image-alt failures reported on
https://dev.coder.com/workspaces. The audit flagged ~52 `<img>` elements
without an `alt` attribute, all matching the inner `<img>` rendered by
Radix `AvatarPrimitive.Image` inside our `Avatar` component (selectors
like `.size-full.object-contain`, `.size-[--avatar-lg].rounded-[6px]`,
`.size-[--avatar-sm]`). Two `ExternalImage` callsites on the same page
were also missing `alt`.

## Changes

- `Avatar`: add optional `alt?: string` and forward it to
`AvatarPrimitive.Image`. Default is `""`, which marks the avatar as
decorative and removes it from the accessibility tree. Every callsite on
the workspaces page already renders the human-readable name (owner,
template, organization, user) as adjacent text, so decorative-by-default
is the WCAG-correct behavior. Callers that need a meaningful alt can
override.
- `AvatarData`: thread an optional `alt` through to the internal default
`Avatar`.
- `WorkspacesTable` `IconAppLink` `ExternalImage`: pass `alt=""`. The
wrapping `BaseIconLink` already exposes the app name through an
`sr-only` span on the link.
- `BatchDeleteConfirmation` resource icons `ExternalImage`: pass
`alt=""`. The resource-type label sits next to each icon.
- `WorkspacesPageView.stories.tsx` `AllStates`: add a play function that
scans the rendered canvas and asserts every `<img>` has an `alt`
attribute, to prevent regressions.

## Validation

- `pnpm check`, `pnpm lint`, `pnpm format` clean.
- `pnpm test -- src/pages/WorkspacesPage/WorkspacesPage.test.tsx` passes
(13/13).
- Pre-commit (`make pre-commit`) passes locally.

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

### Root cause

The `Avatar` component (`site/src/components/Avatar/Avatar.tsx`)
rendered `AvatarPrimitive.Image` without an `alt` attribute. Every
consumer (`AvatarData`, `TopbarAvatar`, workspace table rows, filter
menus, empty state, batch dialogs, "New workspace" dropdown) inherited
the missing-alt bug, which is why a single page produced ~52 violations.

### Fix

1. Make `Avatar` accept an `alt` prop, default `""`, and forward it to
the underlying `<img>`. Drop-in compatible with every existing call.
2. Mirror the prop on `AvatarData` so callers can label the implicit
avatar without composing their own.
3. Explicitly mark the workspaces-page `ExternalImage` callsites as
decorative because each is paired with adjacent text.
4. Lock the behavior with a Storybook play function so a future
regression on the workspaces page fails CI.

### Why `alt=""` by default

All workspaces-page avatars are rendered next to the corresponding name.
Per WCAG, repeating that name in the image's alt text would only add
noise for screen-reader users. Empty alt removes the image from the
accessibility tree, which is the correct decorative pattern.

</details>

---

_PR opened by Coder Agents on behalf of @tracyjohnsonux._
2026-06-12 13:25:00 -07:00
Asher ad127d03b9 chore: refactor mock websocket to make open explicit (#26323)
Callers can now choose when to open and emit the initial message. This
will enable finer testing for some incoming bug fixes related to the
timing of dynamic parameter sockets and requests.

Add a callback to preserve the current behavior for existing tests and make
the transition easier.  Future tests can omit the callback and emit the events
under whatever condition they need.

The only behavioral changes are:
- the web socket error test now emits a close error without first
opening to accurately simulate a failure to connect at all.
- add some missing `diagnostics` to some responses (just to be
thorough).
- change one of the IDs to match in two tests (for consistency).
2026-06-12 10:11:48 -08:00
Ben Potter ba776a61e5 docs(docs/ai-coder/ai-gateway): document ChatGPT provider setup for Codex BYOK (#26348)
Following the BYOK (ChatGPT Subscription) instructions in `codex.md` on
a deployment without a ChatGPT provider fails with `404 route not
supported: POST /chatgpt/v1/responses`. The
`/api/v2/aibridge/chatgpt/v1` route only exists when an admin has
created a provider named `chatgpt`, and that requirement wasn't
documented anywhere.

## Changes

- `providers.md`: new **ChatGPT** subsection alongside the other
per-provider sections: type `openai`, name must be exactly `chatgpt`,
base URL `https://chatgpt.com/backend-api/codex`, no API keys (auth
comes from each user's ChatGPT OAuth token via BYOK)
- `codex.md`:
- prerequisite admonition in the ChatGPT Subscription section linking to
the provider setup, with the 404 symptom for troubleshooting
- template recipe for the ChatGPT subscription flow (`base_config_toml`
+ `coder_env` injecting `CODER_API_TOKEN`), since the existing recipe
only covers the centralized API key flow
  - bump the codex module pin from `~> 4.1` to `~> 5.0` (latest is 5.1)

## Verification

- All three gaps were hit and the documented configuration verified
end-to-end on a live deployment: provider created via the AI Providers
API, Codex CLI 0.139.0 authenticated with ChatGPT login, sessions
visible in the AI Sessions UI
- `pnpm run format-docs` and `pnpm run lint-docs` clean (0 errors),
`pre-commit-light` hooks passed

Linear: [DOCS-354](https://linear.app/codercom/issue/DOCS-354)

🤖 Generated with Coder Agents on behalf of @bpmct
2026-06-12 12:39:16 -05:00
Nick Vigilante 7425a3927e fix(offlinedocs): use portable -r flag in copyImages.sh (#26221)
## Summary

`cp --recursive` is GNU-specific and not recognized by BSD `cp` on
macOS. BSD `cp` treats `--recursive` as a third path argument, producing
`cp: --recursive: Not a directory`.

This replaces `--recursive` (placed after operands) with the
POSIX-portable `-r` flag placed before operands, which works on both
Linux and macOS.

---

> Generated by Coder Agents on behalf of @nickvigilante
2026-06-12 13:26:35 -04:00
Ben Potter 61ec5accdb fix(aibridge): recognize hyphenated session-id header from newer Codex releases (#26346)
Codex prompts were showing up as one session per request in the AI
Sessions list instead of being grouped into a conversation.

## Root Cause

AI Gateway extracts the Codex session key from the `session_id` request
header:

https://github.com/coder/coder/blob/main/aibridge/session.go#L57-L58

Newer Codex releases renamed the header to `session-id` (hyphen) in
[`codex-rs/codex-api/src/requests/headers.rs`](https://github.com/openai/codex/blob/main/codex-rs/codex-api/src/requests/headers.rs):

```rust
insert_header(&mut headers, "session-id", &id);
```

`Header.Get` is case-insensitive but not underscore/hyphen-insensitive,
so no session key is extracted and every request falls back to its own
session. Reproduced with Codex CLI 0.139.0.

## Changes

- Check `session-id` first, fall back to the legacy `session_id` for
older Codex versions
- Added test cases for the hyphenated header and precedence

## Before/After

The same three-prompt Codex conversation ("Write a haiku about
Pittsburgh" → "Now make it about Coder" → "Translate it to Spanish", via
`codex exec` + `codex exec resume --last`) against a local build.

**Before**: each prompt of the conversation lands as its own session,
Threads: 1


![before](https://raw.githubusercontent.com/coder/coder/recordings/recordings/codex-session-grouping/before.jpg)

**After**: the conversation is a single session with Threads: 3


![after](https://raw.githubusercontent.com/coder/coder/recordings/recordings/codex-session-grouping/after.jpg)

Clicking into the session shows all three threads on the session
timeline:

![after session
detail](https://raw.githubusercontent.com/coder/coder/recordings/recordings/codex-session-grouping/after-session-detail.jpg)

Linear: [AIGOV-437](https://linear.app/codercom/issue/AIGOV-437)

🤖 Generated with Coder Agents on behalf of @bpmct
2026-06-12 12:25:51 -05:00
Nick Vigilante e18c86354c fix(docs/about/contributing): repoint dead docs-backend-contrib-guide refs to main (DOCS-350) (#26339)
Closes [DOCS-350](https://linear.app/codercom/issue/DOCS-350).

## Problem

Three GitHub links in `docs/about/contributing/backend.md` are pinned to
a feature branch (`docs-backend-contrib-guide`) that no longer exists in
this repo. All three return HTTP 404 on github.com today.

| File:line | Link text | Bad URL |
|---|---|---|
| `docs/about/contributing/backend.md:53` | `cliui` |
`https://github.com/coder/coder/tree/docs-backend-contrib-guide/cli/cliui`
|
| `docs/about/contributing/backend.md:53` | `testdata` |
`https://github.com/coder/coder/tree/docs-backend-contrib-guide/cli/testdata`
|
| `docs/about/contributing/backend.md:75` | `Go functions` |
`https://github.com/coder/coder/blob/docs-backend-contrib-guide/coderd/database/queries.sql.go`
|

## Fix

Repoint each URL's branch segment to `main`. All three targets exist on
`main` unchanged.

## Verification

```
$ curl -fsS -o /dev/null -w '%{http_code}\n' https://github.com/coder/coder/tree/main/cli/cliui
200
$ curl -fsS -o /dev/null -w '%{http_code}\n' https://github.com/coder/coder/tree/main/cli/testdata
200
$ curl -fsS -o /dev/null -w '%{http_code}\n' https://github.com/coder/coder/blob/main/coderd/database/queries.sql.go
200
```

## Not triggering `/coder-agents-review`

Docs-only edit; per `AGENTS.md` the bot review is reserved for
product/CI changes.

## Future-state note

These three URLs are absolute `(blob|tree)/main` references. They will
eventually be flipped to relative paths by
[DOCS-351](https://linear.app/codercom/issue/DOCS-351) once the
coder.com rewriter classifier fix
([DOCS-349](https://linear.app/codercom/issue/DOCS-349)) ships.
Repointing to `main` here is the right interim fix.

---

*Generated by Coder Agents on @nickvigilante's behalf.*
2026-06-12 12:03:42 -04:00
J. Scott Miller 3c5160dd66 test(scaletest/workspacetraffic): fix RPTY close flake on graceful timeout (#26199)
## Summary

Fixes the `TestRun/RPTY` flake tracked in PLAT-116 (`timeout waiting for
read to finish`).

`rptyConn.Close` sends `Ctrl+C` to interrupt the command, then waits up
to 30s for the read to finish. The read only unblocks once the server
closes the reconnecting PTY stream, which depends on the agent
terminating the command under test (a `dd` reading stdin) and tearing
down the backend. When the server-side teardown does not complete within
30s, `Close` returned a hard error and failed the run. Logs from the
March 2026 failure confirm the agent used the `screen` backend
(`backend_type=screen`) and show no session teardown activity at all
after `Ctrl+C`; the interrupt chain stalled rather than merely running
slowly. The previously deferred `c.conn.Close()` ran only *after* the
wait gave up, so nothing actively unblocked the read within the window.

## Changes

- `conn.go`: graceful close is now best-effort. After the grace period,
`Close` actively force-closes the underlying connection to unblock the
read, waits a bounded `forceCloseReadTimeout` (5s) for the read to drain
rather than blocking indefinitely, and returns a distinguishable
sentinel `errRPTYGracefulCloseTimeout`. The same force-close path is
used when the `Ctrl+C` write fails. Timeouts are fields on `rptyConn` so
tests can shrink them deterministically.
- `run.go`: treats `errRPTYGracefulCloseTimeout` as non-fatal (logged as
a warning) so the run no longer fails when the connection was closed,
just not gracefully. Any other close error still fails the run,
preserving signal for a genuine regression.
- `conn_internal_test.go`: new unit tests covering the graceful,
forced-close, stuck-read-after-close, and double-close paths using a
stub connection.

## Testing

- `go test ./scaletest/workspacetraffic/ -run TestRPTYConnClose -race
-count=10` passes.
- `go test ./scaletest/workspacetraffic/ -run TestRun/RPTY` passes.
- `golangci-lint run ./scaletest/workspacetraffic/` clean;
`gofmt`/emdash clean.

<details>
<summary>Root-cause analysis and lifecycle notes</summary>

The client conn is bound to `context.Background()`, so the test context
cannot unblock the read; only an actual websocket close can. The coderd
proxy bridges client and agent with `agentssh.Bicopy`, which propagates
closes promptly, so the stall is not there. On the agent side both
backends do eventually close the connection after the command exits:

- **buffered**: output reader hits EOF on command exit and closes active
conns in-process (one goroutine handoff).
- **screen**: a longer chain (`Ctrl+C` -> screen client PTY -> daemon ->
inner PTY -> SIGINT -> `dd` exit -> session teardown -> `screen -x`
client exit -> agent output reader EOF -> conn close), involving extra
OS processes.

The backend is auto-selected (`screen` if present on Linux, else
`buffered`) and the test does not pin it, so behavior depends on the
runner image. Logs from the March 2026 failure (run 23322663002) confirm
`backend_type=screen` and show no `unable to read pty output` or
session-quit activity between the attach and the moment the client gave
up 30s later, meaning `dd` never exited in response to `Ctrl+C` within
the window. The stall is in delivery or signal handling inside the
screen path, not a slow process exit. No agent-side logic bug was
identified from the logs, which is why the fix makes graceful close
best-effort rather than asserting a fixed deadline.

Possible follow-ups (not in this PR): pin the test to a deterministic
backend, and/or log the agent's chosen `backend_type` in test output to
aid future diagnosis.

</details>

---

This PR was generated with assistance from Coder Agents.
2026-06-12 11:00:43 -05:00
Hugo Dutka bc2d9b607b fix(coderd/x/chatd): deflake TestRunner_StartsRealRequiresActionTimeoutTask (#26343)
Addresses
https://github.com/coder/internal/issues/1588#issuecomment-4692645760
2026-06-12 15:47:20 +00:00
Jaayden Halko 3184ed9e9e chore: remove horizontal wheel scrolling (#26332) 2026-06-12 16:09:13 +01:00
Jeremy RuppelandMcKayla はな dd7d2653ca feat: add template builder module catalog structure and go:embed wiring (#25909)
Scaffolds the `coderd/templatebuilder` package for the guided template
builder ([DEVEX-272](https://linear.app/codercom/issue/DEVEX-272),
[RFC](https://www.notion.so/coderhq/RFC-Guided-Template-Creation-Workflow-342d579be59280dfbf8eea2e5006dbda)).

Adds the module catalog types and `go:embed` wiring that the template
builder endpoints will use:

- `codersdk.TemplateBuilderModule`, `TemplateBuilderModuleVariable`, and
related types matching the RFC schema
- Internal `ModuleManifest` type with `go:embed` wiring to bundle
`module.json` files from `coderd/templatebuilder/modules/`
- `LoadModules()` with defensive copy, unexported
`parseModulesFromFS(fs.FS)` for test isolation, `ToSDK()` conversion
- Real `code-server` module manifest as the first catalog entry
- Strict validation: ID uniqueness, version non-empty, variable
type/name validation, `DisallowUnknownFields`, and requiring
`module.json` in every module directory
- Tests via internal `catalog_internal_test.go` (for
`parseModulesFromFS` with `fstest.MapFS` fixtures) and external
`catalog_test.go` (for `LoadModules` and `ToSDK`), covering multi-module
parsing, all variable types, validation errors, nil-slice normalization,
and full SDK field assertions

> [!NOTE]
> Generated with [Coder Agents](https://coder.com/agents) by
@jeremyruppel

---------

Co-authored-by: McKayla はな <mckayla@hey.com>
2026-06-12 09:40:36 -04:00
Hugo Dutka aab8c862a4 fix(coderd): disable chat worker in tests asserting transient states (#26333)
Follow up to https://github.com/coder/coder/pull/26331. Many tests had
the same flaky failure mode.
2026-06-12 13:03:45 +00:00
Hugo Dutka 84843e619a fix(coderd): disable chat worker in TestPostChatMessagesBusyInterrupt (#26331)
Addresses https://github.com/coder/internal/issues/1584
2026-06-12 14:47:34 +02:00
Danielle Maywood 79a28bad72 feat(site): group shared agents in sidebar (#26328) 2026-06-12 12:39:53 +01:00