Telemetry builds now report whether Agent Relay created them. Before
this, relay workspaces looked like any other build.
A start build counts as a relay build when it has the
`agent_relay_session_id` parameter. Stop and delete builds never get the
field. For those builds, the new `agent_relay` field on `WorkspaceBuild`
reports:
- `provider`: `claude_code`, `cursor`, `ambiguous`, or `unknown`
- `client_platform`: Claude Code only. Lowercased, characters outside
`[a-z0-9_]` become `_`, and cut to 15 characters
- `attempt`: omitted when missing or not an integer, so `0` is sent
- `session_id_hash` and `pool_hash`: SHA-256 hashes
No other parameter values are sent. Other builds leave the field out.
The snapshot fetches these parameters with one new batch query. The
workspace-create event reads the stored parameters with one extra query,
only when telemetry is enabled, so it reports the same data as the
snapshot. `docs/admin/setup/telemetry.md` lists the parameters that are
read.
The collector side is
[coder/coder-telemetry-server#56](https://github.com/coder/coder-telemetry-server/pull/56).
Merge this PR first.
Refs
[RELAY-9](https://linear.app/codercom/issue/RELAY-9/telemetry-report-agent-relay-usage-from-codercoder)
<details>
<summary>Decision log</summary>
- **Detect relay builds from parameters.** This needs no relay changes.
Relay registration or
[CORE-426](https://linear.app/codercom/issue/CORE-426) provenance
metadata can come later.
- **Builds only, not workspaces.** `GetWorkspaces` doesn't return the
latest build's parameters, so a workspace field would cost another
query. The collector can join on `workspace_id`.
- **Provider comes from parameter names only.**
`agent_relay_claude_code_*` means Claude Code and `agent_relay_cursor_*`
means Cursor. A build with both reports `ambiguous`; a build with
neither reports `unknown`. coderd stores every declared parameter on
every build (ephemeral ones with their default), so a Claude Code start
after a stop still reports `claude_code`.
- **Start builds only.** Stop and delete builds of a relay workspace
carry the same parameters but are not dispatches, so the snapshot skips
them before querying parameters.
- **Hash session ID and pool.** Pool names are user content, and
sessions only need counting.
- **Known gaps.** Cursor has no client platform. Relay version and
health would need relay registration.
- **Parameter names are shared with coder/agent-relay.** If agent-relay
renames one, telemetry silently stops reading it.
</details>
<details>
<summary>Manual test on <code>develop.sh</code></summary>
Ran on `8ad7cd491f` with `CODER_TELEMETRY_ENABLE=true
CODER_TELEMETRY_URL=http://127.0.0.1:8081` and `go run
./scripts/telemetry-server --port 8081` as the collector.
Pushed three templates with no infrastructure, each declaring the same
parameters as the real modules:
- `relay-claude`: `agent_relay_session_id`, `_delivery_id`, `_pool`,
`_client_platform`, plus ephemeral `agent_relay_attempt` and
`agent_relay_claude_code_lock_to_account`
- `relay-cursor`: `agent_relay_session_id`, `_delivery_id`, `_pool`,
`agent_relay_cursor_pool_name`, `_idle_release_timeout`, `_repo_url`
- `relay-plain`: `region`
Created workspaces with `POST /api/v2/users/me/workspaces` and
`rich_parameter_values`, the same call the relay makes. Then ran stop
and start builds on the relay workspaces, and restarted coderd to get a
periodic snapshot.
| Workspace | Build 1 (create event and snapshot) | Builds 2 and 3
(stop, start) |
|---|---|---|
| Claude (`claude_in_slack`, attempt 1) | `claude_code`, platform,
attempt 1 | `claude_code`, platform, no attempt |
| Cursor | `cursor` | `cursor` |
| Plain | field omitted | n/a |
| Claude template, no session ID | field omitted | n/a |
- Stop and start builds keep `agent_relay_claude_code_lock_to_account`,
with an empty value, so Claude Code rebuilds still report `claude_code`.
- No session ID, pool name, or `region` value appears in the captured
telemetry. The hashes match `sha256` of the inputs.
- Fed the captured snapshot through the conversion code in
coder/coder-telemetry-server#56: all 8 builds converted, 6 of them with
`agent_relay` set.
- No telemetry errors or panics in the coderd logs.
This run predates the start-only change: build 2 (stop) carried the
field then. Stop and delete builds are now omitted, which
`TestTelemetry_WorkspaceBuildAgentRelay` covers.
</details>
---
*Generated by Coder Agents on behalf of @Emyrk.*
Workspace create and TTL update pass the requested `ttl_ms` to
`validWorkspaceTTLMillis`, which multiplied it by `time.Millisecond`
before it checked the bounds. Values outside the `int64` nanosecond
range wrapped around: `18446744133710` ms and `-18446744013709` ms both
became about one minute, so the API accepted them and stored a
one-minute TTL instead of returning a validation error.
The helper now rejects negative values with the minimum error and values
above 30 days with the maximum error before it converts to a
`time.Duration`. The maximum check compares whole minutes to match the
existing round down to the minute, so inputs that do not overflow keep
their current result.
Two new `TestWorkspaceUpdateTTL` rows send these values. Without the fix
both fail with `An error is expected but got nil.` (the endpoint returns
204); with the fix both get the expected validation error.
Related to #31036, which fixes the same overflow in the chat workspace
TTL setting.
> Xum, an AI agent, opened this PR for @ibetitsmike.
Stacked on #29855.
Wires `WorkspaceOptions.IncludeRelated` through
`codersdk.Client.WorkspaceByOwnerAndName`. The method now applies
`params.asRequestOption()` (matching `Client.Workspace`), so the
`include_related` query parameter is sent to the server. Previously it
only forwarded `include_deleted` and silently dropped `IncludeRelated`.
- `include_deleted` behavior is unchanged: `asRequestOption` sets it
when true; the server treats an omitted value the same as `false`.
- Updated the `TemplateOnly` and `LatestBuildOnly` subtests of
`TestWorkspaceByOwnerAndNameIncludeRelated` to drive narrowing through
the SDK method and its options, exercising the wiring end to end.
Option-level encoding is already covered by
`TestWorkspaceOptionsAsRequestOption`.
_This PR was created by Coder Agents on behalf of @spikecurtis._
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.*
`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.*
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.*
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.
Adds `include_related` support to `GET
/api/v2/users/{user}/workspace/{workspacename}`
(`API.workspaceByOwnerAndName`), matching the get-workspace-by-ID
endpoint.
- Parses `include_related` via `wsrelated.Parse`; absent defaults to
`wsrelated.All()`, present-but-invalid returns 400.
- Passes the parsed config to `singleWorkspaceData`, preserving template
concealment (unauthorized template maps to 404 on this route).
- Omitted related data (build/template) is converted from zero values;
the build-not-found 404 only applies when the build was requested.
- Adds `TestWorkspaceByOwnerAndNameIncludeRelated` covering full,
template-only, latest-build-only, and invalid selections.
- Regenerated API docs/swagger.
_This PR was created by Coder Agents on behalf of @spikecurtis._
## What
Adds `POST /api/v2/chats/{chat}/workspace-files`, which streams the
request body to the chat's bound workspace agent and returns the final
path/name/size, plus the `workspace-file-reference` message part type
that carries the uploaded file's metadata through chat messages:
- `coderd/exp_chats.go`: owner-only middleware (chat RBAC update +
reject archived), workspace exec authorization (403/409 like the
existing chat exec paths), agent selection (prefer the chat's bound
agent, else deterministic `agentselect.FindChatAgent`, without
persisting a binding), 30s dial timeout, chat/ancestor tracking headers
on the agent connection, and agent error passthrough (agent HTTP status
preserved, 502 with a generic detail for transport failures; the real
error is logged). Deleted and non-running workspaces get a specific 409
("Workspace is stopped. Start the workspace before uploading files.")
before agent lookup. Each failed upload logs one structured warning, and
`coderd_chat_workspace_upload_total{status}` counts outcomes. The route
shares the files rate limit and documents its 429.
- Input validation: client-supplied `workspace-file-reference` parts
must point inside `/.coder/chats/<chat-id>/files/` with a matching
basename, non-negative size, and a `workspace_file_workspace_id` equal
to the chat's currently bound workspace (the upload response echoes it
as `workspace_id`). References uploaded before a workspace rebind are
rejected instead of silently sending the agent an unreadable path. The
file name must already be in sanitized form
(`SanitizeWorkspaceUploadName(name) == name`), and the cleaned path and
base media type are what gets persisted; message edits share the same
validation. Parts are rejected on chat creation (no chat ID exists yet).
- `coderd/x/chatd/chatprompt`: references render into the prompt as text
only, `[workspace file: <name> (<size>) at <path>]`; file bytes never
reach the LLM. Title derivation (`TitleText`) uses the bare file name,
so fallback titles carry no internal marker.
- `codersdk`: part-type constants/fields,
`ChatMessageWorkspaceFileReference` builder, and
`Client.UploadChatWorkspaceFile` (RFC 5987 filename in
`Content-Disposition`).
No DB migration: parts persist as JSON in `chat_messages.content`.
## Why
Bridges chat and the workspace filesystem for CODAGT-211: users drop a
file in chat, the bytes land where the agent's tools can operate on
them, and the model learns the path from the reference part.
## How tested
- `go test ./coderd -run 'WorkspaceFile|ChatInput|UploadChat'` including
an integration test that runs a real in-memory agent, uploads through
the coderd route, verifies bytes on disk, and exercises collision
suffixes.
- `go test ./codersdk ./coderd/x/chatd/...`, `make gen`
(swagger/types/docs), `make lint`.
- Rebased onto main 2026-09-21: the chat API moved from
`/api/experimental` to `/api/v2`, so the route is registered in
`coderd/chat_routes.go` and the SDK method lives on `codersdk.Client`.
## Follow-ups
- The files rate limit counts requests, not bytes or concurrency;
whether this route should use a per-user concurrency cap instead, and
whether the new-chat page should keep partial successes on a 429, is
still open
([CODAGT-1171](https://linear.app/codercom/issue/CODAGT-1171)).
Part of CODAGT-211. Stack: agent API -> coderd endpoint (this PR) -> UI.
> This PR was authored by Mux (AI) working on Mike's behalf.
Part of the lite `codersdk.Workspace` work
([GRU-82](https://linear.app/codercom/issue/GRU-82),
[RFC](https://app.notion.com/p/coderhq/Lite-Workspace-API-Requests-3aad579be5928060b5e7cc65c539717f)).
Follows #28639, which added the `wsrelated` package and parser.
Wires the `include_related` query parameter into `GET
/api/v2/workspaces/{workspace}`, the first endpoint to accept it. When
present, the value is parsed with `wsrelated.Parse` and the resulting
selection is threaded into `workspaceData`, so only the requested
related data is queried. Omitting the parameter is backward compatible
and returns everything (`wsrelated.All`). An invalid value returns
`400`.
Because related data can now be omitted, the handler no longer assumes
the build and template are present: it uses zero values when they are
absent, and only enforces the template read-authorization check (`403`)
when the template was actually requested.
### Partial-build conversion
`convertWorkspaceBuilds` now tolerates a build whose provisioner job or
template version was deliberately omitted from the selection, so
selections such as `latest_build` (build only) or
`latest_build.resources.*` (resources without the job) convert correctly
instead of erroring. The omitted fields are left zero (empty `Job`,
empty `TemplateVersionName`). Resources are keyed by the build's `JobID`
rather than the fetched job row, so they load independently of whether
the job is selected. The integrity error is preserved for full-data
callers: when a job or template version is requested but missing,
conversion still fails. The selection config (`wsrelated.LatestBuild`)
is threaded into `convertWorkspaceBuilds` to distinguish "not requested"
from "missing".
Only this endpoint is wired; the other endpoints that produce
`codersdk.Workspace` objects, and the codersdk client functions, come in
later PRs.
---
*Generated by Coder Agents on behalf of @spikecurtis.*
Report session counts as a dynamic app-name map from the agent, the SSH CLI, and the workspace usage API, so a new IDE flows end to end without a schema, proto, or server change.
- Report through `Stats.session_counts` on Agent API v2.11. Older agents keep reporting through the deprecated count fields.
- Accept arbitrary names from `coder ssh --usage-app` and the workspace usage API. A name the registry does not recognize keeps its identity and is attributed to the `unknown` family.
- Add reconnecting PTY counts to the map without overwriting the counts SSH reported.
- Normalize and merge names before applying the deterministic 64-name cap, ordered by known apps, then count, then name. Overflow sums into `unknown`, and non-positive counts cannot cancel valid activity.
- Strip control characters, treat whitespace-only HTTP app names as absent, and require the exact environment variable prefix when you extract an SSH session type.
- Count overflow entries in `coderd_agentstats_session_counts_overflow_total` and keep raw payloads out of logs.
- Change the usage API's `app_name` to a string, and update the SDK types and API reference.
closes#27410
When a template requires a non-optional external auth provider that the
workspace owner hasn't linked yet, `create_workspace` rejects the
request with a 403, but the error never included a way to actually
resolve it. The web UI and CLI don't hit this path in practice, since
they preflight-check `/templateversions/{id}/external-auth` and render a
login button before ever submitting. Coder Agents' `create_workspace`
chat tool has no such preflight, so it's the one place a real user hits
this error, and the assistant could only repeat "external authentication
is required" with no way forward.
`requireWorkspaceOwnerExternalAuth` now includes each missing provider's
authenticate URL in the error `Detail`, and the chatd `create_workspace`
tool's `responseErrorResult` adds an `action_required` hint so the model
reliably tells the user to open the link and retry, instead of just
echoing the raw error.
Fixes
[CODAGT-1011](https://linear.app/codercom/issue/CODAGT-1011/external-authentication-is-required-is-a-dead-end-in-coder-agents)

<details>
<summary>Full recording and thumbnail</summary>
-
[mp4](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/recording.mp4)
-
[Thumbnail](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/thumbnail.jpg)
</details>
<details>
<summary>Implementation notes</summary>
- Only the free-text `Detail` string changed. The `Validations` shape
(`Field: "external_auth"`, `Detail: provider.ID`) is untouched, since
it's a separate, tested, machine-readable contract that other code may
rely on.
- Recorded against a local dev instance with a dummy GitHub OAuth
client, so the clip ends right after the assistant surfaces the link.
Following the link past Coder's own external-auth page would fail
regardless of this fix, since there's no real OAuth client secret
configured in that environment.
- Generated by Coder Agents on behalf of @bpmct.
</details>
Removes the Tasks API and task orchestration from coderd and codersdk:
the `/api/v2/tasks` handlers, task middleware and search filters, task
name generation, autobuild pause/resume logic, task notification
enqueues, telemetry, and the codersdk task types. Regenerates apidoc,
the API reference docs, and `typesGenerated.ts`.
**Breaking change:** the Tasks API is removed; requests to
`/api/v2/tasks` fail. Tasks was deprecated in v2.34.
**Stack context:** Coder Tasks removal stack (CODAGT-642): #28743
frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084
notifications → #29085 build reasons → #29086 tables → #28750
permissions. The last four PRs replace the single data-drop migration
that used to live in #28750; each carries one concern and its own
migration number.
**Why:** with the UI (#28743) and CLI (#28788) gone, this deletes the
server surface. Database tables, RBAC, and notification templates stay
until the top of the stack so every layer builds and migrates
independently.
**What to scrutinize:**
- The `enable-ai-tasks` option is removed outright (review feedback):
configs still carrying `enableAITasks` fail to parse until the key is
deleted.
- provisionerdserver now writes `HasAITask: false` on template/build
flags; the column and these lines are dropped in #29085.
- `codersdk.ResourceTypeTask` stays so audit logs recorded before the
removal keep rendering.
**Validation:** `go build ./...`, `go vet ./...`, `go test
./codersdk/...`, site biome and tsc, CLI goldens regenerated, pre-commit
hooks.
**Size:** +242/-10,792 over 76 files; additions are regenerated
docs/goldens and test fixture updates.
> Created by Xum (AI agent) on behalf of @ibetitsmike.
Follow-up to #27934; this fix was pushed to the branch after the
squash-merge and missed it.
`jsonb_build_object` renders timestamptz in the session `TimeZone`,
which Coder never pins, and `collected_at` defaults to year 1 until the
agent's first report. On a non-UTC Postgres session a
registered-but-never-collected item renders with an LMT second-offset
(even `BC`, e.g. `0001-12-31T19:03:58-04:56:02 BC`), which Go's RFC3339
parsing rejects - a 500 for the entire list page whenever
`include_agent_metadata` is used.
- `to_char(... AT TIME ZONE 'UTC', ...)` pins the rendering;
never-collected items round-trip as Go's zero time.
- The test now runs against a named-zone database
(`dbtestutil.WithTimezone("America/Caracas")`) and requests a registered
but never-collected key; it reproduces the 500 without the fix.
Also contains the failure mode Go-side: an unparsable aggregate now
degrades to missing metadata for that workspace (with a warning log)
instead of failing the entire page. The SQL fix prevents the known
cause; the containment covers any future one. The test still catches
regressions because it asserts the metadata values, not just a 200.
---
Authored by Coder Agents on behalf of @Emyrk.
Closes#27933. Related: #27897 (single-agent GET).
Agent metadata is only readable via a per-agent watch stream, so reading
it across N workspaces costs N+1 requests. This adds a batch read to the
list endpoint:
```text
GET /api/v2/workspaces?q=param:"pool=demo" include_agent_metadata:task_status
```
- New `include_agent_metadata` search key, repeatable and key-scoped. It
expands the response, it does not filter workspaces.
- `GetWorkspaces` aggregates the requested keys as JSON behind a `CASE`:
without opt-in the response is unchanged and the subquery never runs.
Runs only for the returned page, inside the same authorized query.
- Agents in the response gain `metadata`
(`[]codersdk.WorkspaceAgentMetadata`, `omitempty`), mapped by the
`workspace_agent_id` each element carries. The collection script is
omitted; it can be long.
- `codersdk.WorkspaceFilter` gains `IncludeAgentMetadata []string`.
- No wildcard, no schema change, no migration.
---
Authored by Coder Agents on behalf of @Emyrk.
Closes PLAT-219 /
[coder/internal#1532](https://github.com/coder/internal/issues/1532).
The reported failure (`should have 2 item(s), but has 3`) was the stop
build's outcome audit landing after `auditor.ResetLogs()`; that path was
already deflaked by #26232 and the pre-reset drain added in #25037.
This closes the remaining hole in the same class: the dormancy update's
audit log is exported in a middleware `defer` after the API response, so
it can also land after `ResetLogs` and break the exact `len == 2`
assertion. Extend the pre-reset poll to drain the dormancy write entry
alongside the stop build entry.
Verified with `go test ./coderd -run TestWorkspaceDormant -count=5` and
`-race`.
> Generated by Coder Agents on behalf of @Emyrk.
This can cause bad refresh token errors, since it can only be used once.
Looks like there was an attempt to fix this by checking the database
after a failed refresh, but of course this depends on the first request
having updated the database in time, so both that and this fix are
required to fully solve.
Required external auth (`optional = false`) was only enforced by
client-side preflight checks, so creating a workspace via the REST API
succeeded even when the owner had never authenticated, producing a
broken workspace.
`createWorkspace` now validates the workspace owner's external auth
server-side and returns 403 before any row is inserted or prebuild is
claimed. The owner (not the initiator) is checked because build-time
token injection uses their links, so this also covers admin-on-behalf-of
creates and prebuild claims. Use `optional = true` to allow
pre-provisioning for unauthenticated users.
Fixes PLAT-241.
> This PR was generated by Coder Agents on behalf of
@dylanhuff-at-coder.
The dormancy notification's "will be automatically deleted in X"
sentence rendered the dormancy threshold instead of the auto-delete
duration. A 30-day threshold rendered as "4 weeks" even when auto-delete
was 90 days; a 60-day threshold rendered as "1 month" with a 7-day
auto-delete. Render the countdown from the auto-delete setting, and skip
the deletion sentence entirely when auto-delete is disabled so the
notification no longer promises a deletion that will never happen.
closes CODAGT-203
## Summary
`list_templates` now returns a ranked shortlist with a recommendation,
so the chat agent can pick the right template the way a colleague would:
prefer what matches the request, what the user already uses, and what
the rest of the organization uses. Instead of teaching the model an enum
protocol in prompts, every result carries a fixed `next_step`
instruction telling the agent what to do.
## How list_templates works
1. **Fetch**: active, non-deprecated templates in the chat's
organization, filtered by the admin template allowlist, authorized as
the chat owner (no system escalation).
2. **Query relevance** (optional `query` argument): each template
receives the highest tier any of its fields matches, and a higher tier
always outranks a lower one regardless of usage:
| Tier | Match |
|------|-------|
| 4 | name or display name equals the query |
| 3 | name or display name starts with the query |
| 2 | name or display name contains the query |
| 1 | description contains the query (checked only when no name field
matched) |
| 0 | no match; the template is excluded |
Matching is case-insensitive and ignores spaces/hyphens/underscores
(`python gpu` matches `python-gpu`).
3. **Usage signals**: a new `GetTemplateRankingSignalsByOwnerID` query
returns, per template, the owner's active and recently-deleted workspace
counts within a 60-day window, the last in-window usage, and the count
of distinct developers with an active workspace (unclaimed prebuilds
excluded).
4. **Affinity score** (computed in Go, per template, from that
template's signals only):
```text
affinity = 10 x (active + 0.5 x deleted) x 0.5^(days_since_last_use /
14)
+ ln(1 + active_developers)
```
`active`/`deleted` are the owner's in-window workspace counts,
`days_since_last_use` is measured from the most recent in-window usage
(the personal term is zero without in-window usage), and
`active_developers` is the org-wide count. Personal usage carries 10x
the weight of org popularity; the confidence floor is the score of two
active developers (`ln 3`) and the required lead over the runner-up is
`ln 3 - ln 2`.
5. **Rank**: query tier first (when a query is present), then affinity
score, then name/ID for determinism. Results paginate 10 per page with
`next_page` present only when more exist.
## Recommendation contract
The result tells the agent what to do next instead of describing
confidence levels:
- `recommended_template_id` is present only when the top template is a
clear winner: the only available template, a decisive query match, or an
affinity score that clears a floor and leads the runner-up by a derived
margin.
- `next_step` is always present and is one of four fixed sentences: use
the recommendation, ask the user to choose, retry a query that matched
nothing, or report that no templates are available.
Per-template items carry raw evidence (`active_developers`,
`your_workspace_count`, `last_used_by_you`) rather than derived labels.
When signals fail to load, the tool logs and degrades to asking the user
unless the query alone is decisive.
Prompts and the `create_workspace`/`read_template` descriptions
reference the field through the `chattool.NextStepField` constant, so
the instruction lives in one place and cannot drift. `create_workspace`
remains idempotent and allowlist-enforced.
## Authorization
The signals query runs with the chat owner's permissions: reading the
owner's own workspaces plus a template-metadata read for the cross-user
popularity count. dbauthz rejects the call if any requested template is
not readable by the owner (covered by allow and deny method tests).
## Docs
Adds `docs/ai-coder/agents/tools/` explaining how agent tool calls work,
with `list_templates` ranking and the `next_step` contract as the first
documented tools.
Fixes a flake in `TestWorkspaceBuildStatus` where the test asserted an
exact audit log count immediately after the stop build completed:
```
workspacebuilds_test.go:1261: Error: "[...]" should have 7 item(s), but has 6
```
The audit log for a workspace build is exported asynchronously relative
to what `AwaitWorkspaceBuildJobCompleted` observes, so the strict
`require.Len` could run before the stop log was recorded. The assertion
now polls with `require.Eventually` until the expected log count and
stop action appear, matching the existing poll pattern in the file.
Also fixes the same race in
`TestWorkspaceDormant/StartWakesUpDormantWorkspace`
(`workspaces_test.go`), flagged during review as a sibling risk: its
exact `require.Len(t, auditor.AuditLogs(), 2)` after build completion is
now an equivalent `require.Eventually` poll.
Verified with `go test ./coderd -run TestWorkspaceBuildStatus -count=10`
and `go test ./coderd -run
'TestWorkspaceDormant/StartWakesUpDormantWorkspace' -count=5`.
Closes https://github.com/coder/internal/issues/1565 (PLAT-304).
🤖 Generated by Coder Agents on behalf of @jscottmiller
`TestExecutorAutostartOK` and its sibling positive autostart tests
compute the autobuild tick from
`sched.Next(workspace.LatestBuild.CreatedAt)`, but the server persists
`next_start_at` from the build's completion time. When build creation
and completion straddle the schedule's next fire time, the persisted
value advances past the test's tick, the executor's eligibility query
(`next_start_at <= tick`) drops the workspace, and the test fails with
an empty transitions map. This surfaced in flaky test runs.
Add `coderdtest.NextAutostartTick(t, workspace)` which returns
`*workspace.NextStartAt`, and use it across the affected positive
autostart paths in `coderd/autobuild`, `coderd`, and
`enterprise/coderd`.
Generated with assistance from Coder Agents.
Closes https://github.com/coder/coder/issues/13112
**Breaking Change**: Removed status code `StatusNotModified` when no
diffs occur in a patch. Now the patch is always applied and a template
is always returned.
## Problem
Workspaces showed as "Healthy" immediately after creation while the
agent was still downloading, starting, or connecting. If the agent never
connected, the workspace stayed "Healthy" for the entire connection
timeout (~120s), then abruptly flipped to "Unhealthy".
## Root cause
In `db2sdk.WorkspaceAgent`, the health switch had no case for
`WorkspaceAgentConnecting`. Agents in `connecting` status with a
non-`off` lifecycle (e.g. `created` after a fresh build) fell through to
the `default` case and were marked `Healthy = true`.
## Fix
Add an explicit case for `WorkspaceAgentConnecting` that sets `Healthy =
false` with reason `"agent has not yet connected"`. The case is placed
after the existing `!connected + off` case (which correctly catches
stopped agents as "not running") and before the `timeout`/`disconnected`
cases.
```
Status + Lifecycle → Health reason
──────────────────────────────────────────────────────
any !connected + off → "agent is not running"
connecting + created/starting → "agent has not yet connected" ← NEW
timeout + any → "agent is taking too long to connect"
disconnected + any → "agent has lost connection"
connected + start_error → "agent startup script exited with an error"
connected + shutting_down → "agent is shutting down"
connected + ready/starting → healthy
```
The frontend already handles this case — `getAgentHealthIssue()` returns
"Workspace agent is still connecting" with `severity: "info"` for
unhealthy workspaces with connecting agents.
## Test changes
- **Healthy test**: now actually connects the agent via `agenttest.New`
before asserting health (previously passed due to the bug).
- **New Connecting test**: verifies a never-connected agent is correctly
marked unhealthy.
- **Mixed health test**: connects a1 and waits for the mixed state
(`a1.Healthy && !workspace.Healthy`) to avoid a race where both agents
are initially connecting.
- **Sub-agent excluded test**: connects the parent agent and waits for
it to be healthy before creating the sub-agent.
- **TestWorkspaceAgent/Connect**: flipped assertion to `Health.Healthy
== false` for a `dbfake` agent that never connects.
<details>
<summary>Review notes</summary>
### Known follow-up
The `healthy:false` workspace search filter maps to `[disconnected,
timeout]` and does not include `connecting`. This is a pre-existing gap
that is now more consequential — a workspace unhealthy solely due to a
connecting agent won't appear in `healthy:false` results. Worth a
follow-up issue.
### Deep review findings addressed
| Finding | Severity | Status |
|---------|----------|--------|
| Mixed health test race (all 3 reviewers) | P2 | Fixed — tightened
`Eventually` condition |
| `TestWorkspaceAgent/Connect` assertion break | P1 | Fixed — flipped
assertion |
| CLI renders red for connecting agents | Obs | Acknowledged — design
trade-off, accurate but visually strong for transient state |
| Switch case ordering overlap | Obs | Documented with inline comment |
</details>
> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑💻
Dynamic parameters supports ephemeral parameters. Updated the test to
use dynamic parameters.
Ephemeral params **require** a default value.
Closes https://github.com/coder/coder/issues/19065
This PR adds a `WatchAllWorkspaces` function with `watch-all-workspaces`
endpoint, which can be used to listen on a single global pubsub channel
for _all_ workspace build updates, and makes use of it in the autostart
scaletest.
This negates the need to use a workspace watch pubsub channel _per_
workspace, which has auth overhead associated with each call. This is
especially relevant in situations such as the autostart scaletest, where
we need to start/stop a set of workspaces before we can configure their
autostart config. The overhead associated with all the watch requests
skews the scaletest results and makes it harder to reason about the
performance of the autostart feature itself.
The autostart scaletest also no longer generates its own metrics nor
does it wait for all the workspaces to actually start via autostart. We
should update the scaletest dashboard after both PRs are merged to
measure autostart performance via the new metrics.
The new function/endpoint and its usage in the autostart scaletest are
gated behind an experiment feature flag, this is something we should
discuss whether we want to enable the endpoint in prod by default or
not. If so, we can remove the experiment.
---------
Signed-off-by: Callum Styan <callumstyan@gmail.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Callum Styan <callum@coder.com>
`time.Now()` has nanosecond precision while Postgres timestamps are
microsecond precision. When tests compare `time.Now()` against
DB-sourced timestamps using `Before`/`After`/`WithinRange`/etc., there
is a non-zero flake risk from the precision mismatch.
This replaces `time.Now()` with `dbtime.Now()` (which rounds to
microsecond precision) in all test assertions that compare against
database timestamps.
Follows from #22684.
## Changes (11 files)
| File | Changes |
|---|---|
| `coderd/apikey_test.go` | 11 comparisons with `ExpiresAt` |
| `coderd/users_test.go` | 2 comparisons with `ExpiresAt` |
| `coderd/oauth2_test.go` | 1 comparison with `token.Expiry` |
| `coderd/workspaces_test.go` | 2 comparisons with `DormantAt` |
| `coderd/workspaceagents_test.go` | 3 comparisons with
`ConnectedAt`/`DisconnectedAt` |
| `coderd/workspaceapps/db_test.go` | 1 comparison with `token.Expiry` |
| `coderd/provisionerdserver/provisionerdserver_test.go` | 1 comparison
with `key.ExpiresAt` |
| `enterprise/coderd/workspaces_test.go` | 1 comparison with `DormantAt`
|
| `enterprise/coderd/license/license_test.go` | 3 `NotBefore` values |
| `enterprise/coderd/licenses_test.go` | 2 `NotBefore` values |
| `enterprise/coderd/users_test.go` | 3 `Next()` comparisons |
## Not changed (intentionally)
- `scaletest/placebo/run_test.go` — compares wall-clock elapsed time,
not DB timestamps
- `cli/server_test.go`, `coderd/jwtutils/jwt_test.go`,
`enterprise/aibridgeproxyd/aibridgeproxyd_test.go` — TLS cert fields,
not DB-stored
- `coderd/azureidentity/azureidentity_test.go` — Azure cert expiry, not
DB
🤖 Generated by Claude Opus 4.6 but reviewed manually.
Currently the sharing UI is only hidden under certain circumstances,
rather than on a permission basis. This makes it permissions based, and
makes some backend changes to make sure permissions are correct.
## Summary
Custom roles that can create workspaces on behalf of other users need to
be able to list users to populate the owner dropdown in the workspace
creation UI. Previously, this required a separate `user:read`
permission, causing the dropdown to fail for custom roles.
## Changes
- Modified `GetUsers` in `dbauthz` to check if the user can create
workspaces for any owner (`workspace:create` with `owner_id: *`)
- If the user has this permission, they can list all users without
needing explicit `user:read` permission
- Added tests to verify the new behavior
## Testing
- Updated mock tests to assert the new authorization check
- Added integration tests for both positive and negative cases
Fixes#18203
This PR adds some metrics to help identify job enqueue rates and
latencies. This work was initiated as a way to help reduce the cost of
the observation/measurement itself for autostart scaletests, which
impacts our ability to identify/reason about the load caused by
autostart. See: https://github.com/coder/internal/issues/1209
I've extended the metrics here to account for regular user initiated
builds, prebuilds, autostarts, etc. IMO there is still the question here
of whether we want to include or need the `transition` label, which is
only present on workspace builds. Including it does lead to an increase
in cardinality, and in the case of the histogram (when not using native
histograms) that's at least a few extra series for every bucket. We
could remove the transition label there but keep it on the counter.
Additionally, the histogram is currently observing latencies for other
jobs, such as template builds/version imports, those do not have a
transition type associated with them.
Tested briefly in a workspace, can see metric values like the following:
-
`coderd_workspace_builds_enqueued_total{build_reason="autostart",provisioner_type="terraform",status="success",transition="start"}
1`
-
`coderd_provisioner_job_queue_wait_seconds_bucket{build_reason="autostart",job_type="workspace_build",provisioner_type="terraform",transition="start",le="0.025"}
1`
---------
Signed-off-by: Callum Styan <callumstyan@gmail.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Adds support for filtering workspaces by health status using
healthy:true or healthy:false in the search query.
This is done by changing `has-agent` to accept a list of statuses and
aliasing `health:true` to `has-agent:connected` and `healthy:false` to
`has-agent:timeout,disconnected`.
Fixes#21623
Adds a per-organization setting to disable workspace sharing. When enabled,
all existing workspace ACLs in the organization are cleared and the workspace
ACL mutation API endpoints return `403 Forbidden`.
This complements the existing site-wide `--disable-workspace-sharing` flag by
providing more granular control at the organization level.
Closes https://github.com/coder/internal/issues/1073 (part 2)
---------
Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
Fixes all our Go file imports to match the preferred spec that we've _mostly_ been using. For example:
```
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/xerrors"
"gopkg.in/natefinch/lumberjack.v2"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/serpent"
)
```
3 groups: standard library, 3rd partly libs, Coder libs.
This PR makes the change across the codebase. The PR in the stack above modifies our formatting to maintain this state of affairs, and is a separate PR so it's possible to review that one in detail.
Upgrades to slog v3 which includes a small, but backward incompatible API change to the acceptible call arguments when logging. This change allows us to verify via compile time type checking that arguments are correct and won't cause a panic, as was possible in slog v1, which this replaces (v2 was tagged but never used in coder/coder).
It also updates dependencies that also use slog and were updated.
I've left the `aibridge` dependency as a commit SHA, under the assumption that the team there (cc @pawbana @dannykopping ) will tag and update the dependency soon and on their own schedule.
Other dependencies, I pushed new tags.
Relates to #20925
This PR modifies the `postWorkspaceBuild` handler to automatically unset
dormancy on a workspace when a start transition is requested.
Previously, the client was responsible for unsetting the dormancy on the
workspace prior to posting a workspace build.
Provisioner steps broken into smaller granular actions.
Changes:
- `ExtractArchive` moved to `init` request (was in `configure`)
- Writing `tfstate` moved to `plan` (was in `configure`)
- Moved most plan/apply outputs to `GraphComplete`
Adds `--disable-workspace-sharing` option.
Workspace sharing is disabled by not including user and group ACLs in
the workspace RBAC object, which prevents ACL-based authz.
Closes https://github.com/coder/internal/issues/1072
The commit also adds saving of workspace user/group ACLs in the test DB
data generator.