Commit Graph
4924 Commits
Author SHA1 Message Date
Michael Suchacz 67d586bb13 refactor(coderd): share the chat prompt length check (#31020)
Five `PUT` handlers wrote the same `400` when the sanitized text is
longer than the deployment's prompt byte limit: the deployment system
prompt, the organization system prompt, plan mode instructions, the user
custom prompt, and chat project instructions. This PR moves that check
into `api.writePromptTooLongError`, which takes the sanitized text and
each handler's message. It adds 16 lines and removes 28, and drops two
comments that only said the limits match.

Each handler still reads its body and calls
`codersdk.SanitizePromptText` itself, because it keeps using the
sanitized text. Moving the sanitize call into the helper would not
remove any more lines: each call site would still need the sanitized
value and the early return.

**Why it is safe:** the messages, the detail text, and the limit are
unchanged. I ran 6 mutants with `go test -overlay`: reject a text of
exactly the limit, change the message or the detail in the helper, and
change the project instructions, custom prompt, and plan mode messages
at their call sites. The tests fail on each.

**Review focus:** the boolean result. `true` means the helper wrote the
`400`, and every call site returns on it.

Validation: on `main` and on this branch, `go test ./coderd -run
'^(TestChatLimitsFromDeploymentConfig|TestChatProjectInstructions|TestChatSystemPrompt|TestChatPlanModeInstructions)$'
-count=1` passes (4 tests, 68 with subtests) and `go test
./enterprise/coderd -run
'^(TestOrganizationChatSystemPrompt|TestChatProjectInstructionsUpdateOnlyRole|TestChatProjectInstructionsAudit)$'
-count=1` passes (3 tests, 14 with subtests). The pre-commit hook passed
(`make gen`, formatting, golangci-lint, slim build).

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:23:59 +01:00
Michael Suchacz 44149fb3e9 refactor(coderd): share the chat model config write error mapping (#31019)
Create, update, and delete of chat model configs each mapped their
transaction errors to responses with their own `switch`. This PR moves
update's mapping into `writeChatModelConfigWriteError` and calls it from
all three handlers, with each handler's `500` message as an argument. It
adds 33 lines and removes 69.

**What changes:** every handler now has every case of update's mapping.
Create gains the `404` case, and delete gains the `412`, `400`, and
`409` cases. The delete transaction returns none of those errors. Create
returns a not-found error only if a row it reads disappears inside its
transaction, which holds the organization's model config write lock;
before, that was a `500`.

**Why it is safe:** I ran 7 mutants of `writeChatModelConfigWriteError`
and its callers with `go test -overlay`. The tests below fail on 5: skip
the precondition check, return `500` for a provider model error, return
`404` instead of `403` for an authorization error, return `500` for a
not-found error, and change the `500` message. Two survive on `main` as
well:

- The `409` case: the only unique index besides the primary key allows
one default config per organization, and every writer changes the
default under the write lock, so no test can reach it.
- The delete `500` message: no test makes delete fail with a `500`. The
message is the same literal as on `main`.

**Review focus:** the order of the `403` and `404` cases.
`httpapi.Is404Error` also matches authorization errors, so the `403`
case stays first, as in update's mapping.

Validation: on `main` and on this branch, `go test ./coderd -run
'^(TestCreateChatModelConfig|TestUpdateChatModel|TestDeleteChatModelConfig|TestChatModelConfigAudit|TestChatModelActionScopesWithOrgRead|TestCreateChatModelRejectsACLKeys|TestChatModelReasoningMode.*|TestChatModelACLShareDenied)$'
-count=1` passes (10 tests, 103 with subtests). The pre-commit hook
passed (`make gen`, formatting, golangci-lint, slim build).

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:22:14 +01:00
Michael Suchacz 4630e2e2e7 refactor(coderd): share the deployment chat setting PUT handler (#31018)
Seven deployment chat setting `PUT` handlers repeated the same steps:
start the audit entry, check the deployment config `update` permission,
decode the body, run the audited write, and write the `500` or `204`.
This PR moves those steps into one generic `putChatOperationalSetting`,
so each handler keeps only its validation and upsert. The three day
settings share `validateChatSettingDays`, and
`initChatOperationalSettingsAudit` is inlined into the helper because
only these handlers used it. The PR adds 113 lines and removes 241.

The seven handlers set personal model overrides, the computer use
provider, debug logging, the workspace TTL, chat retention days, debug
retention days, and auto-archive days.

**What changes:** the workspace TTL handler loses a branch that turned a
not-found or not-authorized write error into a `404`. The branch cannot
run: `GetChatSiteConfigValue` is an aggregate that always returns a row,
and it and `UpsertChatWorkspaceTTL` check the same deployment config
`update` permission that the handler checks first. The other six
handlers never had the branch.

**Why it is safe:** each handler has its own coderd test, and
`TestChatOperationalSettingsAudit` writes all seven settings and checks
their audit entries. I also ran a throwaway test, not part of this PR,
that sends 98 requests to the seven endpoints as an admin and as a
member, with valid, unchanged, out-of-range, wrongly typed, and
malformed bodies, and reads each setting back after every write. The
status codes, response bodies, and audit entries are identical on `main`
and on this branch.

The second commit makes the chat retention days tests check what the
shared helper sends: the message and detail of the `500` when the
audited write fails, and the message of the `400` for 3651 days. With
the first commit's tests, `go test -overlay` mutants that change the
`500` message, the `500` detail, or the day setting label in that `400`
message passed; now each fails.

**Review focus:** the `prepare` callback, which returns the audited
value and the write, or a `400` response.

#31036 fixes an overflow in the workspace TTL handler on `main` by
checking the 30-day maximum before the duration conversion. It conflicts
with this PR in that handler, so whichever merges second will merge
`main` and keep that check.

Validation: on `main` and on this branch, `go test ./coderd -run
'^(TestChatPersonalModelOverridesAdminSettings|TestChatComputerUseProvider|TestChatDebugLoggingSettings|TestChatWorkspaceTTL|TestChatRetentionDays.*|TestChatDebugRetentionDays|TestChatAutoArchiveDays|TestAuditedChatOperationalSettingWrite.*)$'
-count=1` passes (11 tests, 27 with subtests) and `go test
./enterprise/coderd -run '^TestChatOperationalSettingsAudit$' -count=1`
passes (17 with subtests). The pre-commit hook passed (`make gen`,
formatting, golangci-lint, slim build).

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:20:31 +01:00
Michael Suchacz 9551fa3b3e fix(coderd): store chat ACL keys as canonical UUIDs (#31037)
`PATCH /api/v2/chats/{chat}/acl` stored user and group IDs as the
request spelled them. `uuid.Parse` accepts uppercase spellings, so such
a request passed validation and returned `204`, but RBAC matches ACL
keys as canonical UUID strings: the share granted nothing, and a
`deleted` role sent with another spelling left the stored entry in
place. This PR rekeys both role maps with `canonicalACLRoles`, as the
MCP server config and organization skill ACLs do, and returns `400` when
two spellings name one principal.

Releases v2.34.0 through v2.38.0 store keys as sent, so before it
applies a request, the handler also deletes stored keys that spell a
requested principal's ID in a noncanonical form: a `deleted` role then
removes every spelling, and a `read` role leaves one canonical entry.
Principals that the request does not name keep their stored keys, since
rekeying them would grant access that RBAC never enforced.

**Why it is safe:** a canonical ID maps to itself, so requests with
canonical IDs behave as before. The chat project ACL already
canonicalizes its keys.

**Red tests:** `TestChatACLNoncanonicalIDs` shares a chat with a user
and a group by uppercase IDs, checks that the user and a group member
can read it, then removes both by uppercase IDs and checks that they
cannot. It then writes user and group keys straight to the database in
each spelling that `uuid.Parse` accepts and older servers stored as
sent: uppercase, braced, `urn:uuid:`, and unhyphenated. For each
spelling, a `deleted` request with the canonical or the stored spelling
must leave no stored key, and a `read` request with the stored spelling
must leave only the canonical keys, let both readers in, and notify the
user. Two new `TestChatACLValidation` cases send one user ID or one
group ID in two spellings and expect a `400`. On `main`:

```text
TestChatACLNoncanonicalIDs: GET /api/v2/chats/<id>: unexpected status code 404: Resource not found or you do not have access to this resource
TestChatACLValidation/DuplicateUserSpellings: An error is expected but got nil.
TestChatACLValidation/DuplicateGroupSpellings: An error is expected but got nil.
```

With the rekey but without the cleanup (`79865b4afc9`), each uppercase
legacy case fails when run on its own:

```text
deleted, canonical spelling: Should be empty, but was map[<UPPERCASE ID>:{[read]}]
deleted, uppercase spelling: Should be empty, but was map[<UPPERCASE ID>:{[read]}]
read: Not equal: expected: database.ChatACL{"<canonical ID>": {[read]}}, actual: database.ChatACL{"<UPPERCASE ID>": {[read]}, "<canonical ID>": {[read]}}
```

These tests also fail on nine `go test -overlay` mutants. Seven skip the
rekey, the duplicate check, or the cleanup for users or for groups, or
run the cleanup after the `oldChat` snapshot. The other two lowercase
keys instead of parsing them, one in the cleanup and one in the rekey.
They passed while the legacy cases used only uppercase keys, and now
fail on the braced spelling:

```text
lowercasing cleanup: Should be empty, but was map[{<ID>}:{[read]}]
lowercasing rekey: Not equal: expected: database.ChatACL{"<ID>": {[read]}}, actual: database.ChatACL{"{<ID>}": {[read]}}
```

**Review focus:** the maps are rekeyed in place after `acl.Validate`,
which still reports IDs that do not parse, so the role loops below read
canonical keys. The cleanup runs before the `oldChat` snapshot, so the
share notification treats a user whose legacy entry granted nothing as
newly added. On `main`, that user is not notified again.

#31016 replaces those loops with `applyACLReadRoles`. The two merge
without conflicts and the merged loops read the rekeyed maps; whichever
merges second will merge `main` first.

The PR adds 153 lines and removes none: 23 in `coderd/exp_chats_acl.go`
and 130 in `coderd/exp_chats_acl_test.go`.

Validation: `go test ./coderd -run
'^(TestChatACLValidation|TestChatACLNoncanonicalIDs)$' -count=1` fails
on `main` and on `79865b4afc9` as above and passes here (9 tests with
subtests), as does `go test -race ./coderd -run
'^TestChatACLNoncanonicalIDs$' -count=10`. Also passing here: `go test
./coderd -run '(?i)acl|mcp|skill' -count=1` (65 with subtests), `go test
./coderd -run
'^(TestChatProjectSharing|TestChatSharingDisabled|TestListChatsSharedScope|TestSharedReaderStreamChat|TestChatFileDownloadURL)$'
-count=1` (22), and `go test ./enterprise/coderd -run
'(?i)acl|mcp|skill|TestEnterpriseAuditLogs' -count=1` (46). A local
merge with #31016 passes `go test ./coderd -run
'^(TestChatACLValidation|TestChatACLNoncanonicalIDs|TestChatACLSharingLifecycle|TestChatProjectSharing)$'
-count=1` (16 with subtests). `go vet ./coderd/` is clean on both, and
the pre-commit hook passed (`make gen`, formatting, golangci-lint, slim
build).

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:18:00 +01:00
Michael Suchacz 70b1e4716e fix(coderd/x/chatd/chattool)!: fail closed when the plan path cannot be resolved (#30983)
Removes the 404 bypass from the plan-turn symlink guard in `write_file`
and `edit_files`. `ensurePlanPathResolvesToItself` treated a 404 from
the agent's `resolve-path` endpoint as success, so a plan turn on an
agent without that endpoint wrote the plan file with no symlink check.
Now every `ResolvePath` error fails the tool call. The PR deletes the
status predicate and its `net/http` import, the two tests that expected
a write after a 404, and the test-only `statusError` file. The PR adds
77 lines and removes 147.

**Behavior change, approved by Mike:** an agent too old to serve the
`resolve-path` endpoint can no longer write plan files during plan
turns. The tool returns `resolve plan path: ...` instead. The endpoint
arrived with plan mode in #24236. Coder does not support mixed coderd
and agent versions, and upgrades happen in maintenance windows.

**Why it is safe:** the agent's `resolve-path` handler never answers
404. It returns 400 for a relative path, 403 for a permission error, and
500 for other errors, and it resolves a path whose last components do
not exist yet, such as a new plan file. So a 404 means that the route is
missing.

- In each tool's tests, the symlink case is now a table with three more
rows: a 404 and a 500 built with `codersdk.NewError`, and a connection
error without a status code. No row expects a write, and the strict
gomock controller fails on any `WriteFile` or `EditFiles` call.
- With the old resolver (`go test -overlay`), the 404 row fails for both
tools.
- A mutant that ignores every `ResolvePath` error fails all three error
rows for both tools. On `main`, the whole `chattool` package passes with
that mutant.
- A mutant that ignores only errors without a status code, such as a
dropped connection, fails the connection error row for both tools.
Without that row, both tools' tests pass with it.
- The success, shared plan path, and mixed-path tests do not change and
pass.

**Review focus:** the behavior change. Only `write_file` and
`edit_files` call the guard. `propose_plan` does not call `ResolvePath`,
and this PR does not change it.

Validation: `go test ./coderd/x/chatd/chattool -count=1` passes, `go vet
./coderd/x/chatd/chattool` is clean, and the pre-commit hook passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:16:30 +01:00
Michael Suchacz c9204a5cff refactor(coderd/x/gitsync): remove unused Worker.RefreshChat (#30944)
Removes `Worker.RefreshChat` and the four `TestRefreshChat_*` tests that
only exercised it. `RefreshChat` has had no production caller since
#23901 stopped resolving diff statuses inline on `GetChat`. The worker's
periodic tick is the only refresh path.

`TestWorker_RefreshDoesNotReorderPrimary` used `RefreshChat` to refresh
one of two refs. It now keeps the newer ref fresh (`StaleAt` one hour
ahead) and runs one worker tick, so it checks the same ordering rule
through the production path.

**Why removal is safe:** `git grep '\.RefreshChat('` finds no caller.
Each removed assertion either checked `RefreshChat` itself or is still
caught by a remaining test. I mutated the production line behind each
shared assertion with `go test -overlay`:

| Removed test and assertion | Mutant | Remaining tests that fail |
|---|---|---|
| `TestRefreshChat_Success`: the upsert uses the chat's ID |
`Refresher.refreshOne` upserts a random chat ID |
`TestRefresher_WithPRURL`, `TestWorker`,
`TestWorker_UpsertError_ContinuesNextRow`,
`TestWorker_RefreshDoesNotReorderPrimary` |
| `TestRefreshChat_NoPR`: a branch without a PR is not an error |
`refreshOne` returns an error when there is no PR |
`TestRefresher_BranchNoPRYet` and the three `TestWorker_NoPR_*` tests |
| `TestRefreshChat_RefreshError`: the "no provider" error |
`Refresher.Refresh` changes the "no provider" message |
`TestRefresher_NoProviderForOrigin` |

The other assertions (the returned row, the `upsert chat diff status`
error wrap, and the publish call inside `RefreshChat`) checked only the
deleted method. For the rewritten test, a mutant that sets `updated_at`
in `UpsertChatDiffStatus` fails both the old and the new version. A
mutant that sets `updated_at` in `AcquireStaleChatDiffStatuses` fails
only the new version, because the old version never ran a tick.

**Review focus:** the fixture change in
`TestWorker_RefreshDoesNotReorderPrimary`. #29997 changes one line in
`TestRefreshChat_RefreshError`, so whichever PR lands second drops that
test.

Validation:

- `go test ./coderd/x/gitsync/ -count=1` passes, and `-race -count=5`
passes.
- `golangci-lint run ./coderd/x/gitsync/...` reports 0 issues, and the
pre-commit hook passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:15:02 +01:00
Michael Suchacz bcaf21b812 test(coderd/x/chatd): merge the computer-use child CreateChat tests (#30943)
The four `TestSpawnComputerUseAgent_*` tests in `subagent_test.go`
(`CreatesChildWithChatMode`, `SystemPromptFormat`,
`ChildIsListedUnderParent` and `RootChatIDPropagation`) each built a
database and a server, created a parent and a computer-use child through
`Server.CreateChat` with the same options, and checked a different part
of the result. This PR merges them into one test,
`TestCreateChat_ComputerUseChildPersistsLineage`, that builds the
fixture once and keeps every check. The old names suggested
`spawn_agent` coverage, but `spawn_agent` creates its child through
`chatstate.CreateChatWithID`, and its tests live in
`subagent_internal_test.go`, which this PR does not touch.

**Why it is safe**

- Every removed assertion is kept. ParentChatID, RootChatID and Mode are
checked on both the returned chat and a fresh `GetChatByID` read, and
the test still checks that a system-role message contains the prompt.
- I ran 14 production mutants with `go test -overlay` against the old
tests on `main` and against the new test. They drop ParentChatID,
RootChatID or Mode from the `CreateChat` input, from the insert or from
the returned chat, drop the system prompt or store it with the user
role, replace the returned chat with a zero chat, force every message
role to user, or blank the message content. The old tests and the new
test each catch all 14.

**Review focus**

The loop over `{"returned": child, "fetched": got}` runs the same six
checks on both sources, and each failure message names its source.

**Validation**

- `go test ./coderd/x/chatd/ -run
'TestSpawnComputerUseAgent|TestCreateChat_ComputerUse' -count=1 -p 4
-parallel 4`: passes on `main` (old names) and on this PR (new name)
- `go vet ./coderd/x/chatd/`: clean
- `golangci-lint run --fix=false ./coderd/x/chatd/`: 0 issues
- pre-commit hook: passed

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:13:00 +01:00
Michael Suchacz 453e21a050 test(coderd/x/chatd): fold the effort clamp fixture into the pending-user test (#30942)
`TestBuildTurnEnvironmentClampsRequestedReasoningEffortToMax` built its
own database fixture (OpenAI provider, model config, chat created
through `chatstate.CreateChat`) only to call `buildTurnEnvironment`,
which
`TestBuildTurnEnvironmentSplitsPendingUserRowsFromCompactionPrompt`
already does with the same kind of fixture. This PR deletes the clamp
test and moves its checks into the pending-user test. That test's model
config now carries the clamp test's options (OpenAI `User` sentinel,
reasoning effort default `low` and max `medium`), and its unanswered
user message stores `high` effort. The message is the last one, so
`InsertChatMessages` copies its effort into
`chats.last_reasoning_effort`, the value `buildTurnEnvironment` reads.

**Why it is safe**

- Every assertion of the deleted test has a match in the remaining one:
Responses provider options with effort clamped to `medium`, the `User`
sentinel, the default max output tokens, compaction tool definitions
equal to `BuildToolDefinitions`, and the compaction summary call. The
exception is `require.NotNil(prepared.Compaction)`, which was redundant
because the test already dereferenced `prepared.Compaction` earlier.
- I ran 12 production mutants with `go test -overlay` against the old
test on `main` and the extended test. The mutants drop the requested
effort at the call site or in `chatRequestedEffort`, skip the clamp in
`ResolveReasoningEffort`, map the unresolved effort in
`ProviderOptionsForCall`, drop the config provider options, or remove
the default output cap. Others replace the summary call with
`newCall()`, drop its tool choice, raise its output cap by half or drop
it, or pass nil or truncated tool definitions. Both tests fail on all 12
and pass without a mutant.

**Review focus**

The summary call is now checked with one equality: the call template
with tool choice `none`. Since #31042 the summary call keeps the chat
call's output cap, so the equality pins that cap too, along with the
template's sampling fields, which the old field checks did not.

**Validation**

- `go test -count=1 ./coderd/x/chatd/`: passes
- `go vet ./coderd/x/chatd/...`: clean
- `golangci-lint run --fix=false ./coderd/x/chatd/...`: 0 issues
- `paralleltestctx -custom-funcs="testutil.Context,chatdTestContext"
./coderd/x/chatd/...`: clean
- pre-commit hook: passed

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 16:11:34 +01:00
Ehab Younes 8b0c0cc35e fix!: validate workspace app URLs on the server (#31262)
- Reject external app URLs with javascript, vbscript, data, blob, file,
  or filesystem schemes, or control characters, for template and
  sub-agent apps.
- Skip invalid sub-agent apps and log the reason; the dev container
  still starts.
- Strip the $SESSION_TOKEN placeholder from sub-agent app URLs.
- Drop app status URIs that aren't http, https, or file.
2026-10-27 11:44:25 +00:00
Ehab Younes 0d1cba2def feat: expose connection duration and client session ID in connection logs (#30759)
Show how long each SSH and reconnecting PTY connection lasted, and let
users find connections that share a client session ID. No schema changes.

API (ssh_info):
- Add client_session_id, the ID supplied by the client (the Coder CLI
  or a tool that launches it), if any.
- Add a client_session_id:<32 hex chars> filter.

UI:
- Each row shows the connect → disconnect time range and the duration
  as badges. A connection with no disconnect shows "Ongoing", equal
  timestamps show an "Unknown" start, and a disconnect recorded before
  its connect is labeled as such.
- The info icon opens a details popover instead of a hover tooltip. It
  uses the default popover styling and sentence-case labels, and lets
  users copy the client session ID and open "View related connections"
  for the same workspace.

Closes CLIENT-1010
2026-10-27 14:04:37 +03:00
Mathias Fredriksson 2cb10b5cec feat: show web searches and the pages they found in chats (#29861)
Provider-executed web searches were invisible in chats. The UI skipped
provider-executed parts, and the only trace was one source row per
message that mixed OpenAI citations with Anthropic search results.

The fantasy pin moves to coder/fantasy#62, which tags each found page
with the search that found it and makes OpenAI request and report its
found pages and search actions. chatd stores the tag and marks a
search failed on an Anthropic error_code or an OpenAI failed status.
Each search renders as one row with its queries or opened page, a
running or unfinished state, and the pages it found. Cited pages stay
in the answer's source row, which now follows the answer text.

Closes CODAGT-795
2026-10-27 12:46:27 +02:00
Ehab Younes 28192213ab feat!: label the VS Code family and report built-in app usage per app (#29906)
The session banner now labels the VS Code family "VS Code Family", so it isn't confused with the VS Code editor. coderd_insights_applications_usage_seconds now reports built-in apps per app instead of per family.

- Generate the frontend's family labels from the Go table in codersdk.
- Add the connection_method label: workspace_app for template apps, and ssh, reconnecting_pty, or port_forwarding for built-in apps.
- Rename the application_name label to display_name. For built-in apps it holds the registry name, "Unknown" for unknown, and "Other apps" for overflow.
- Built-in apps get one series per app name, only for apps used in the window. The series limit and the fold rule are shared with the template insights API.
- Breaking: selectors with a value for application_name, or with slug="", match nothing. The Prometheus docs map each old series to its new one.

Closes #29940
Closes CLIENT-1034
Closes CLIENT-1036
2026-10-27 09:58:36 +00:00
Michael Suchacz 85f02dfc29 refactor(coderd/x/chatd/chatsanitize): drop Anthropic guard escalation passes (#30970)
`ApplyAnthropicProviderToolGuard` now validates the result of its
targeted repair once, then returns it or fails closed. This removes 163
production lines (2 added): the escalation that ran after a failed
repair (an all-messages repair, then two strip passes) and its helpers
`isSafeAnthropicProviderToolPrompt`,
`providerExecutedToolMessageIndexes`,
`stripAnthropicProviderToolHistoryFromMessages` and
`addAnthropicProviderToolSanitizationStats`, plus their internal tests.
`git grep` finds no other callers.

## Why it is safe

The escalation ran but could never repair a prompt.
`SanitizeAnthropicProviderToolHistory` loops until nothing is left to
remove outside the last assistant message when that message carries
signed or redacted reasoning, so after the targeted repair any violation
left is in that message. Every later pass skips that message, so the
guard failed anyway.

- A differential test (not committed) ran the old and new guard on
1,000,000 random prompts and on every prompt the existing
`chatsanitize`, `chatloop` and chatd Anthropic tests pass in. Outputs
and errors matched in 1,000,000 of 1,000,000. 200,020 of 1,000,000
prompts reached the escalation; 0 came out repaired.
- New subtest `invalid pair in latest signed assistant fails closed`
pins the failure path (nil prompt,
`ErrAnthropicProviderToolPromptUnsafe`, log fields). It passes before
and after; no other test covered that path.
- New sanitizer row `drops provider result without output text` takes
over the one deleted assertion no other test made: it kills the mutant
that keeps an empty-output provider result as empty text. The log detail
cap test stays. All 12 mutants of the code the deleted tests touched
fail a remaining test.

## Review focus

Failures log less: the fallback and strip warnings are gone, and the
error log drops `immutable_latest_signed_assistant` (always true), no
longer says "nuclear strip", and its `message_index` values point into
the prompt the guard validated.

## Validation

- `go test ./coderd/x/chatd/chatsanitize/...
./coderd/x/chatd/chatloop/... -count=1`, `go test ./coderd/x/chatd/ -run
'Anthropic|Guard|Sanitiz' -count=1 -p 4 -parallel 4`, `go vet`,
`golangci-lint` on `chatsanitize`: pass.

## Stack

This stack moves the Anthropic guard unit test into `chatsanitize`, then
deletes the guard escalation that can never repair a prompt.

1. #30968 Move the Anthropic guard unit test into its own file
2. #30969 Move the Anthropic guard unit test into `chatsanitize`
3. #30970 Drop the Anthropic guard escalation passes

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 09:56:02 +00:00
Michael Suchacz 0647a096f2 test(coderd/x/chatd): move the Anthropic guard unit test into chatsanitize (#30969)
Renames `coderd/x/chatd/anthropic_guard_test.go` to
`coderd/x/chatd/chatsanitize/anthropic_guard_test.go` and moves the ten
helpers only `TestAnthropicProviderToolPreRequestGuard` uses from
`chatd_test.go` into it. The test now lives in `chatsanitize`, the
package it tests.

## Why it is safe

This is a pure move. The only changed lines are the package clause
(`chatd_test` to `chatsanitize_test`) and the `chatsanitize` import that
`chatd_test.go` no longer needs. Git records the file as a rename
(`R056`).

- Every moved helper had no other caller in package `chatd_test` (`git
grep -nw` per name), and none collides with a name in
`chatsanitize_test`.
- Purity check: the sorted `-`/`+` diff prints only the package clause
and the removed import. `git diff --color-moved=plain` marks all 128
moved helper lines as moved and leaves those 3 lines unmarked.
- The same four subtests pass in `./coderd/x/chatd/chatsanitize/` as
before in `./coderd/x/chatd/`.

## Review focus

Confirm that the helpers arrived unchanged. `git diff -M
--color-moved=plain` shows it.

## Validation

- `go test ./coderd/x/chatd/chatsanitize/... -count=1` and `-run
'^TestAnthropicProviderToolPreRequestGuard$' -v`: pass, same 4 subtests.
- `go vet ./coderd/x/chatd/ ./coderd/x/chatd/chatsanitize/`: clean.
- Pre-commit hook: passed.

## Stack

This stack moves the Anthropic guard unit test into `chatsanitize`, then
deletes the guard escalation that can never repair a prompt.

1. #30968 Move the Anthropic guard unit test into its own file
2. #30969 Move the Anthropic guard unit test into `chatsanitize`
3. #30970 Drop the Anthropic guard escalation passes

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 09:38:42 +00:00
Michael Suchacz b9e130283f test(coderd): make the chatd idle wait fail on timeout (#30967)
`chatd.WaitUntilIdleForTest` waited up to 10 seconds for the chat worker
to go idle, dropped the timeout error, and then drained tracked work, so
a test whose worker never went idle passed after a silent 10-second
stall. The hook now takes the caller's `ctx` and returns an error when
`ctx` ends before the worker is idle or the tracked work finishes. The
26 callers that expect success wrap it in `require.NoError`. The poll
loop moves from `chatWorker.WaitIdle`, whose only caller was the hook,
into `testhooks.go`. It polls on a real 10 ms ticker instead of the
server clock, which a mock clock never advances.

## Why it is safe

- The idle check is unchanged: the hook reads the runner manager under
the worker's lock and returns at once when the worker or manager is nil.
The drain still calls `drainInflight`, now in a goroutine so that `ctx`
bounds it; that goroutine exits once `Close` cancels the tracked work.
- `TestWaitUntilIdleForTestTimeout` pins both error returns without a
database: it passes an expired `ctx` while one runner is open
(`RunnerOpen`) or one tracked task is in flight (`InflightWork`) and
requires `context.DeadlineExceeded`. Changing both returns to `return
nil` fails both subtests with `Expected error with "context deadline
exceeded" in chain but got nil`; changing one fails only its subtest.
- Red-green for the idle wait: with `runnerManager.idle` forced to
return `false`, `TestCreateChatImmediatelyProcessesNewChat` passes on
`main` after 10.2 s and fails here at its 25 s context with `wait for
the chat worker to go idle: context deadline exceeded`.
- Red-green for the drain: on this PR's first head, whose drain ignored
`ctx`, a probe holding one tracked task open stayed blocked 2 s past a
100 ms context, then returned `nil`.
- Hidden timeouts: on `main`, with the hook instrumented to report
errors and idle waits over 1 s, all 119 hook calls in the packages below
returned in under 1 s without an error.

## Review focus

Callers now pass their own test context instead of getting a fresh 10 s
one. Every direct caller, and every caller of
`coderdtest.WaitForChatSettled` and `waitForChatProcessed`, passes
`testutil.WaitLong` or longer, so the budget grows, but the rest of the
test shares it.

The PR adds 100 lines and removes 54: the drain goroutine is 9 of them
and the new test 39. Without the goroutine, a stalled title or summary
call holds the hook past its deadline.

## Validation

- `go test ./coderd/x/chatd/ -count=3`: pass.
- `go test ./coderd/ -count=3 -run '<every test in exp_chats_test.go,
exp_chats_workspace_file_test.go, and exp_chats_hooks_test.go>'`: pass.
- `go test ./codersdk/toolsdk/ -count=3 -run
'^(TestChatTools|TestCreateChatOrganizationDefaultModel)$'`: pass.
- `go test -race ./coderd/x/chatd/ -run
'^TestWaitUntilIdleForTestTimeout$' -count=50`: pass.
- Mutants and the probe use `go test -overlay`; a copy with a syntax
error fails to build, so the overlay applies.
- `make pre-commit` passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 10:23:01 +01:00
Michael Suchacz 94b4c9d7fe test(coderd/x/chatd): move the Anthropic guard unit test into its own file (#30968)
Moves `TestAnthropicProviderToolPreRequestGuard` out of
`coderd/x/chatd/chatd_test.go` into a new
`coderd/x/chatd/anthropic_guard_test.go` in the same package. The test
calls `chatsanitize.ApplyAnthropicProviderToolGuard` on in-memory
messages and builds no server or database. Giving it its own file lets
the next PR move it into `chatsanitize` as a git rename. The end-to-end
`TestActiveServer_AnthropicProviderToolPreRequestGuard` stays in
`chatd_test.go`.

## Why it is safe

This is a pure move, with no edits. The helpers the test uses stay in
`chatd_test.go` for now; the next PR moves them.

- Purity check: `diff <(git diff B H | grep '^-[^-]' | cut -c2- | sort)
<(git diff B H | grep '^+[^+]' | cut -c2- | sort)` prints only the new
file's package clause, `import (`, `)` and import paths. `git diff
--color-moved=plain` marks all 137 removed lines as moved; the only 12
added lines it leaves unmarked are that package clause and import block.
- The same four subtests pass before and after:
`non_Anthropic_providers_are_unchanged`,
`orphan_provider_result_is_textified`,
`valid_provider_history_is_unchanged`, `logs_removals`.

## Review focus

Nothing changed outside the new file's header. `git diff
--color-moved=plain` shows this at a glance.

## Validation

- `go test ./coderd/x/chatd/ -run
'^TestAnthropicProviderToolPreRequestGuard$' -count=1 -v`: 4 of 4
subtests pass.
- `go vet ./coderd/x/chatd/`: clean.
- Pre-commit hook (`make pre-commit`: gen, fmt, `lint/go`,
`lint/go/new-code`, slim build): passed.

## Stack

This stack moves the Anthropic guard unit test into `chatsanitize`, then
deletes the guard escalation that can never repair a prompt.

1. #30968 Move the Anthropic guard unit test into its own file
2. #30969 Move the Anthropic guard unit test into `chatsanitize`
3. #30970 Drop the Anthropic guard escalation passes

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 09:18:04 +00:00
Michael Suchacz c7f1f4b9ef refactor: delete the ChatProviderAPIKeys test seam (#30927)
This PR deletes `coderd.Options.ChatProviderAPIKeys`, its
`coderdtest.Options` copy, and the
`coderdtest.OpenAICompatProviderAPIKeys` and
`coderdtest.FakeOpenAICompatProviderAPIKeys` helpers. Only tests set the
option. `newChatTestOptions` and 27 other chat, MCP, and toolsdk
fixtures used it to start a fake OpenAI-compatible server whose fallback
keys no model call reads.

## Why it is safe

- Model calls never read the fallback keys. `newModel` builds the client
from `fantasyConfigForAIBridge`, which returns AI Gateway placeholder
keys (`coderd/x/chatd/model_routing_aibridge.go`).
- Key resolution for a selected provider passes empty fallback keys
(`resolveUserProviderAPIKeysForProvider` in `chatd.go`), and so does the
HTTP availability check in `coderd/exp_chats.go`. Active model configs
always have an `ai_provider_id` (the
`chat_model_configs_ai_provider_required_when_active` check constraint).
- The only path that merges `chatd.Config.ProviderAPIKeys` is the
provider-type lookup for the computer-use subagent. It asks only for
`anthropic` or `openai`, and the test keys were stored only under
`openai-compat`.
- Model-backed tests get their key and base URL from the DB provider
that `CreateOpenAICompatChatModel` creates.
- `git grep -n 'ChatProviderAPIKeys\|OpenAICompatProviderAPIKeys'`
matches nothing after the change.

## Review focus

`coderd.go` no longer passes `ProviderAPIKeys` to `chatd.Config`.
Production never set `ChatProviderAPIKeys`, so chatd gets the zero value
it always got in production. `chatd.Config.ProviderAPIKeys` stays for
now, because chatd internal tests still set it directly.

## Validation

Each suite ran before the change (on `e289c6fe011`) and after it, with
the same results:

- `go test ./coderd/ -run '(?i)chat|mcp' -count=1 -p 4 -parallel 4 -v`:
pass, 163 top-level tests, 899 PASS lines, 0 failures, same test set
both times.
- `go test ./codersdk/toolsdk/ -count=1 -parallel 4 -v`: pass, 234 PASS
lines, 0 failures.
- `go test ./coderd/coderdtest/... -count=1 -v`: pass, 350 PASS lines, 0
failures.
- `go build ./...`, `go vet` on the touched packages and
`./enterprise/coderd/...`, and `golangci-lint run --fix=false ./coderd/
./coderd/coderdtest/... ./codersdk/toolsdk/...`: clean.
- `make pre-commit`: passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 10:15:44 +01:00
Michael Suchacz 16486f7c7f refactor(coderd/x/chatd): delete the test-only advisor runtime getters (#30952)
Deletes `chatadvisor.Runtime.MaxOutputTokens` and
`Runtime.ProviderOptions`, which only tests called. The two
`TestNewAdvisorRuntime` subtests that read them now run one advisor call
against a provider that rejects it, and check the request body:
`max_output_tokens`, `user`, and `reasoning.effort`. The PR also deletes
`TestNewRuntimeDeepClonesOpenAIResponsesProviderOptions`, a one-call
copy of `TestAdvisorRunDisablesStoreAndIsConsistentAcrossCalls`.

## Why it is safe

`git grep` finds no other caller of the getters. The rewritten subtests
read what the provider receives instead of the runtime's stored config,
so they catch more:

| Mutant | `main` | This branch |
|---|---|---|
| a zero output cap defaults to half of `defaultAdvisorMaxOutputTokens`
| fails | fails |
| `NewRuntime` drops the call template's `MaxOutputTokens` | passes |
fails |
| the per-call option reset also clears `ReasoningEffort` | passes |
fails |
| the per-call option reset also clears `User` | passes | fails |

The deleted clone test checked that `NewRuntime` succeeds, that one call
returns advice, and that the parent's `Store` stays `true`.
`TestAdvisorRunDisablesStoreAndIsConsistentAcrossCalls` makes the same
checks over two calls. With `cloneProviderOptions` sharing the
`ResponsesProviderOptions` pointer instead of copying it, both tests
fail on `main`, and the remaining one fails on this branch.

## Review focus

The subtests decode the OpenAI Responses request shape. The old helpers
accepted both OpenAI option types, so if the transport moved this
fixture to Chat Completions, these subtests would fail on the renamed
fields instead of passing.

## Validation

- `go test ./coderd/x/chatd/ -race -count=1 -run
'^TestNewAdvisorRuntime$'`: pass.
- `go test ./coderd/x/chatd/chatadvisor/ -race -count=1`: pass, with one
test fewer on this branch.
- Mutants (`go test -overlay`): results as listed. A copy with a syntax
error fails to build, so the overlay applies.
- The pre-commit hook (`make pre-commit`) passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 10:14:27 +01:00
Michael Suchacz 509f142781 refactor(coderd/x/chatd): delete the runner's unreachable task index (#30936)
Deletes the runner's secondary task index. `spawnTaskIfNeeded` skipped a
spawn when the active task had the same kind, history version, and
status, but that guard cannot fire. The PR removes the guard, the
`tasksByIndex` map that only it read, the `taskIndexKey` type, the
`taskRecord` fields that fed the index, and a redundant check before
`cancelActiveTask`. It renames `spawnTaskIfNeeded` to `spawnTask` and
deletes `TestRunner_CleansUpOnOwnershipTakeover`, whose steps all repeat
in `TestWorker_CleanupStopsRoutingAndCancelsTasks`.

## Why it is safe

- Only `spawnTaskIfNeeded` sets `activeTaskSet`, and `processState`
calls `acceptState` (which sets `hasAcceptedState`) right after every
spawn. On each later event, `processState` cancels the active task,
which clears `activeTaskSet`, before it spawns. So the guard's first
operand is always false.
- For the same reason, `activeTaskSet` implies `hasAcceptedState`, so
`processState` drops the `r.hasAcceptedState && r.activeTaskSet` check
and calls `cancelActiveTask`, which already returns when no task is
active.
- With the guard replaced by `if r.activeTaskSet { panic(...) }`, `go
test ./coderd/x/chatd/` and `go test ./coderd/ -run Chat` pass.
- `localLocks` still serializes a canceled task with its same-key
replacement
(`TestRunner_SerializesReplacementTasksForSameHistoryAndStatus`), and
the task-ID map stays.
- `git grep` finds no other use of `taskIndexKey`, `tasksByIndex`, or
`spawnTaskIfNeeded`.

Each deleted check, its copy in the remaining test, and a mutant that
fails both tests on `main` and the remaining test here:

| Deleted check | Remaining check | Mutant |
|---|---|---|
| first generation task starts | same `waitCall` | `running` spawns an
interrupt task |
| takeover cancels the task | same `requireTaskCanceled` | no ownership
check; no `requestCleanup` |
| no task starts after takeover | `assertNoCall` after one more publish
| takeover cancels the task and spawns an abandon task |

## Review focus

The dead-guard argument depends on the order in `processState`: cancel
the active task, spawn, then `acceptState`. The `newRunner` and
`taskRecord` hunks otherwise only realign fields after gofmt.

## Validation

- `go test ./coderd/x/chatd/ -race -count=1 -run
'^(TestRunner_|TestWorker)'`: 67 tests pass on `main`, 66 on this
branch.
- `go test ./coderd/x/chatd/ -count=1`: pass.
- Mutants (`go test -overlay`): each fails as listed. A copy with a
syntax error fails to build, so the overlay applies.
- The pre-commit hook (`make pre-commit`) passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 10:14:19 +01:00
Michael Suchacz aef1917171 refactor(coderd/x/chatd): delete the write-only generatedChatTitle (#30926)
Deletes `generatedChatTitle`, a mutex-guarded cell in which
`maybeGenerateChatTitle` stored each generated title so that tests could
read it. Production passed a fresh one and never read it. The PR removes
the type, its `Store` and `Load` methods, the parameter, and the six
`Load` checks in the title tests, including the one that #30933 added to
`quickgen_debug_internal_test.go`.

## Why it is safe

`git grep generatedChatTitle` finds nothing. Each removed `Load` check
has a remaining check on the stored chat row or the published event:

| Removed check | Remaining check |
|---|---|
| `WritesGeneratedTitle`: title stored | stored title and source,
`title_change` event |
| `KeepsCurrentTitleWhenNoTitleIsWritten`, both cases: nothing stored |
stored title unchanged, no publish |
| `TestQuickgenFollowsConfiguredRetries/Title`: nothing stored | `model
call failed` and `TitleGenerationOverrideCallFailure` cover the same
return |
| `TitleGenerationOverrideSetUsable`: title stored | gomock expects the
exact `UpdateChatTitleByID` |
| `TitleGenerationOverrideCallFailure`: nothing stored | gomock fails on
any `UpdateChatTitleByID` |
| `TestQuickgenDebugRun/TitleGeneration`: whether a title was stored |
whether the owner's channel got one event |

One gap needed a test change. Without the `return` after a refused title
write, the code publishes the zero `updatedChat` on the nil owner's
channel, which only the observer caught on `main`
(`quickgen_internal_test.go:688`). The two no-write cases now use a
`psmock` pubsub with no expectations, so any publish fails them.

Mutants of `maybeGenerateChatTitle` (`go test -overlay`) and the tests
they fail:

| Mutant | Fails |
|---|---|
| no `return` after a refused write | `write refused by a rename during
the call` |
| no `return` after a failed model call | `model call failed`,
`TitleGenerationOverrideCallFailure`, `TitleGeneration/ModelFails` |
| writes `title + "!"` | `WritesGeneratedTitle`,
`TitleGenerationOverrideSetUsable`,
`TestMaybeGenerateChatTitleAppliesModelConfigReasoningEffort` |
| no `publishChatPubsubEvent` | `WritesGeneratedTitle`,
`TitleGeneration/Completed` and `/CreateFails` |

## Review focus

- The mock in the two no-write cases is stricter than the old owner
subscription: a publish on any channel fails.
- `TitleGeneration` checks the event because a recorded
`UpdateChatTitleByID` call stays true when the write fails.
`MemoryPubsub.Publish` waits for its subscribers, so `len(events)` is
final when the call returns.

## Validation

- `go test ./coderd/x/chatd/ -count=1 -race -run 'Title|Quickgen'`:
pass.
- Mutants: each fails as listed, and the first passes with only the
observer removed. A copy with a syntax error fails to build, so the
overlay applies.
- `TitleGeneration` fails when `generate` always returns true
(`ModelFails`) or when the title write fails (`Completed`,
`CreateFails`).
- The pre-commit hook (`make pre-commit`) passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 10:14:11 +01:00
Michael Suchacz 3f055e7a56 feat: list every chat attachment in the Summary panel (#31140)
In long chats, the Summary panel's **Attachments** section only listed
agent files from the messages already loaded in the transcript. It
showed "No attachments in the loaded messages." and a **Load earlier
messages** button, so finding a chat's files meant paging through its
history.

## What changes

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

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

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

Closes CODAGT-1436.

## Testing

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

## Review record

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

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 03:13:52 +01:00
Michael Suchacz 27db7ace68 fix(coderd): restrict chat workspace rebinding to the chat owner (#30185)
`PATCH /api/v2/chats/{chat}` let any caller with update permission on a
chat set or clear its `workspace_id`, and it checked the new workspace
against the caller's SSH access instead of the owner's. Site owners and
organization admins can update any chat in scope, so they could bind
another user's chat to a workspace they control, and the owner's later
prompts and agent tool calls would then run there. Checking the owner's
SSH access instead would not help, because the caller can share their
own workspace with the owner first.

`updateChat`, which backs the PATCH route and the in-process
`UpdateChatAsUser`, now returns 403 ("Only the chat owner can change its
workspace.") when anyone other than the owner sends `workspace_id`,
including the nil UUID that clears the binding. The check sits next to
the existing owner-only read-state check, before any field is written,
so a rejected multi-field request changes nothing. The UI already offers
workspace changes only to the chat owner.

Other paths checked, no change needed: the PATCH route is the only HTTP
route that writes the binding, chatd binds workspaces directly on the
owner's behalf, chat sharing grants read only, and creating a chat for
another user (`owner_id`) already requires the authority to mint that
user's API key and validates the workspace as that user.

Security review follow-up (ISSUE-14).

## Testing
- `TestPatchChat/WorkspaceBinding/NonOwnerForbidden`: the deployment
owner renames a member's chat while rebinding it to the owner's own
workspace, then while clearing it. Both requests get 403 and the chat is
unchanged. The test fails without the check.
- Remote dogfood
[UAT](https://dogfood.cdr.dev/agents/0f64f91d-a03e-4067-8038-a6d846511d8d)
passed on `08059d73a82`. Workspace changes from the site owner and an
org admin got 403 with the chat unchanged (rebind, rebind plus title,
clear, current workspace, unknown ID, after sharing the target
workspace), a title-only PATCH still returns 204, and the owner
detached, attached, and switched workspaces in the UI.

## Review record
- Test audit (Xum agent) on `08059d73a82`: passed, no changes.
- Remote UAT round 1 on `08059d73a82`: passed.
- Codex r1 on `08059d73a82`: no major issues, no threads.
- Rebased onto `main` at `34ef30ee902` as `21102abadb5`. `main` had
moved the PATCH body into `updateChat`, so the check now returns an
`httperror` with the caller ID passed in. The test merged unchanged,
passes, and fails again with the check disabled. The UAT and test audit
above ran on the pre-rebase head.

> 🤖 This PR was opened by [Xum](https://mux.coder.com) on behalf of
@ibetitsmike.
2026-10-27 02:14:33 +01:00
Michael Suchacz 34ef30ee90 fix: harden chat workspace file upload input validation (#30184) 2026-10-27 01:50:56 +01:00
Mathias Fredriksson 1aff810443 chore: sync fantasy with upstream v0.45.5 (#31288)
Moves the fantasy pin to the tip of `coder_2_33` (`85ffbbe`). That
commit is coder/fantasy#72, which merges 87 upstream
charmbracelet/fantasy commits, v0.40.0 to v0.45.5. Between the two pins
117 files change. Upstream's own v0.40.0 to v0.45.5 change, without
tests, testdata, examples, `go.sum` and the kronk provider, is 43 files,
+2271/−928.

## What reaches chatd

chatd builds only the `anthropic`, `openai` and `openaicompat` fantasy
clients (`chatprovider.ModelFromConfig`); other vendors reach it through
the AI Gateway on one of those. So the upstream changes to the Google,
Vercel, OpenRouter, Bedrock, Azure and kronk providers, and to the
`fantasy.Agent` loop and its retries, do not run in chatd. These do:

- **Chat Completions and openaicompat streams** keep reasoning on
batched and DeepSeek-shaped chunks, keep `finish_reason: length` when
tool calls are truncated, and stop sending empty reasoning fields.
openaicompat drops assistant turns that hold only reasoning.
- **Token usage.** When an OpenAI-shaped backend reports reasoning
tokens apart from completion tokens (reasoning larger than output),
output tokens now include them, so that backend's reported output tokens
and cost rise. OpenAI's own shape, where reasoning is a subset, is
unchanged.
- **Responses.** A content-filtered turn no longer reads as a tool-call
turn.
- **Context overflow.** Baseten, Fireworks and Parasail prompt-length
errors set `ContextTooLargeErr`, which compaction acts on.
- **Anthropic.** Tool calls whose content block never closes are
reported. For Claude 5 models, thinking defaults to `display:
"summarized"` when the chat config sets none; a configured display still
wins. `TestThinkingDropBlockModel_RetriesWithEffort` now expects the
field in the retry body.
- **Anthropic keepalives.** Fantasy forwards `message_start`,
`message_delta` and unknown events as content-free `keepalive` parts.
The first one arrives before any model output, so this PR makes
`ttft_seconds` and the `time_to_first_token` stage skip them, as they
skip warnings. They still reset the stream silence guard.
`processStepStream` ignores them, and the debug recorder counts them in
its part count but records no content.
- **Tool-result media** now goes through upstream's shared
`ToolRunBuffer`, which replaces coder/fantasy#64 and does the same
thing.

#72 keeps coder's anthropic-sdk-go and openai-go forks, Go 1.26 and
kronk v1.31.5, so upstream's SDK and Go moves do not come along.

`go mod tidy` raises the modules fantasy v0.45.5 requires, among them
otel exporters v1.47, the AWS SDK, `google.golang.org/api` v0.307 and
go-openapi v1. All are upgrades.

The `go.mod` comment now names #72 as the upstream sync.

coder/coder#29861 stacks on this PR to pin coder/fantasy#62.

<details>
<summary>Verification</summary>

- `go build ./...`.
- `go test` passes on every package that imports fantasy
(`coderd/x/chatd/...`), and `go test ./coderd -run
'TestChat|TestExpChat|TestMCP|TestAIBridge'` passes.
-
`TestGuardedStreamTTFTStage/WarningsAndKeepalivesThenContentObservesOnce`
fails without the TTFT change (TTFT observed 0s instead of 1s) and
passes with it.
- `make pre-commit` passes. The generated Prometheus docs pick up the
metric help change.

Not verified against live backends in this PR: the stream fixes, the
token usage change and the context-overflow patterns have no coder test
against a real provider. coder/fantasy#72 reports a local chatd run
against the AI Gateway on Anthropic, Responses, OpenAI Chat and
openaicompat.

</details>

> 🤖 This PR was created with the help of Coder Agents, and _will be_
reviewed by a human. 🏂🏻
2026-10-27 11:29:10 +11:00
Michael Suchacz a33af01605 refactor(coderd/x/chatd/chatloop): create the compaction debug run through StartRun (#31087)
Compaction was the last debug-run caller that did by hand what
`chatdebug.Service.StartRun` does: insert the run on a detached context
with a 5 second limit, rebuild the run context, and finalize it with
`ClassifyError`. This PR moves `startCompactionDebugRun` onto `StartRun`
and deletes `compactionDebugCreateRunTimeout`. #30934 moved the other
callers; compaction waited for #30766, which has merged.

**Why it is safe:**
- The first commit changes only the test, renamed from
`TestStartCompactionDebugRun_DoesNotReportDebugErrors` to
`TestStartCompactionDebugRun`. It now asserts the whole inserted row:
kind `compaction`, status `in_progress`, the parent run's root chat,
parent chat and trigger message, the summary model's provider, model,
model config and history tip when the caller sets them and the parent
run's otherwise, and no summary. It also asserts the returned run
context and the `completed` and `interrupted` finalize statuses. It
passes on the old code and on the new code.
- On the old code, 16 mutants (wrong kind or status, a dropped parent
field, an ignored override or fallback, a seeded summary, a wrong run
context field, a wrong finalize status) all fail the new test. Before
this PR, the chatloop tests caught 1 of them and
`TestActiveServer_CompactionModelOverride` 3 more (kind, model and model
config); the other 12 passed both. On the new code, all 13 mutants of
the `StartRun` call fail the test.
- `StartRun` keeps the rest: a failed insert returns the caller's
context and a no-op finalizer, the insert ignores the caller's
cancellation, and the run still finalizes through `FinalizeRun` with its
default 5 second limit. `TestService_StartRun` pins the first two. A nil
seed summary still stores no summary, because `nullJSON` maps a nil map
to SQL NULL.

**Review focus:** log output. The old code discarded create and finalize
errors. `StartRun` logs them at Warn as `failed to create debug run` and
`failed to finalize debug run`, like the other callers. A debug failure
still never fails compaction.

Validation:
- `go test -count=1 ./coderd/x/chatd/chatloop/...` passes, and so does
`go test -race` on the compaction debug tests.
- `go test -count=1 -p 2 -parallel 4 ./coderd/x/chatd/chatdebug/...`
passes.
- `go test -count=1 -parallel 4 -run 'Debug|Compact' ./coderd/x/chatd/`:
the same 53 tests pass before and after.
- `go vet` is clean on both packages, and the pre-commit hook, which
runs `paralleltestctx`, passed on both commits.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 01:13:58 +01:00
514f23979a feat: honor disable-model-invocation in skill frontmatter (#31147)
Extends #30882's `model_invocable` semantics to workspace skills and to
stored skills created through the API.

Claude Code and Xum let skill authors set `disable-model-invocation:
true` in SKILL.md frontmatter, so agents never pick the skill on their
own and it runs only when a person invokes it. Coder Agents honored the
key only when someone imported a SKILL.md file while adding a project
skill (#30884).

## What changes

- **Workspace skills:** when the pinned SKILL.md sets the key to the
YAML boolean `true`, chatd leaves the skill out of `<available-skills>`
before merging sources, so a listed skill with the same name keeps its
bare name, and `read_skill` reports it as not found. The skill stays in
the `/` menu, and invoking it still loads its body. `read_skill_file`
serves its supporting files under the bare name or `workspace/<name>`
and refuses its `SKILL.md` (case-insensitive, after `path.Clean`).
Skills without the key behave as on the base.
- **Invoked workspace skills:** invoking a workspace skill now stores
the pinned skill directory on the invocation part, and the prompt
renders it as `dir` on `<invoked-skill>`, escaped as an attribute value.
Before, only `read_skill` gave the model a skill's directory, and it
refuses a hidden skill, so a hidden skill could not run the scripts it
bundles. The part also stores the chat's workspace, and the prompt shows
`dir` only while the chat stays bound to it, as it does for workspace
file references. This changes #30861's invocation code. Hook payloads
drop the directory and its workspace like the body, and API responses
strip both.
- **Stored skills:** a create request whose content sets the key and
that omits `model_invocable` stores `model_invocable = false`. An
explicit value wins, and PATCH is unchanged. This covers personal,
organization, and project skills, which share `createSkill`.
- `workspacesdk.SkillDisablesModelInvocation` reads the key. The
`CreateSkillRequest.ModelInvocable` doc comment, the generated API docs,
and `extending-agents.md` (the SKILL.md format, a new "Turn off
automatic use" section, and the notes on the skill index, the skill
tools, and aliases) describe the new behavior.

## Follow-ups

- The personal and organization skill editors have no "Agents can use it
automatically" switch yet. Only the project editor from #30884 has one.

## Testing

- Go tests cover the parser, the turn's skill index and aliases,
`read_skill`, `read_skill_file`, invocation of a hidden skill and the
directory it carries (attribute escaping, no directory after the chat
changes workspace, no directory in hook payloads), and the create
default for personal and organization skills. Each new test fails when
its code path is removed.
- Remote dogfood UAT with a real model failed rounds 1 to 3. Rounds 1
and 2 found the hidden SKILL.md still readable through `read_skill_file`
by symlinks and stale pins, plus a bare-name lookup bug and a docs gap
that round 2 fixed. Round 3 found that the content check added against
those bypasses refused a listed skill's file whose own frontmatter sets
the key. After round 3 we narrowed the rule to the hidden skill's
`SKILL.md` path. The key decides what agents are offered (the index and
`read_skill`), not which files they can read: `read_file` and `execute`
already open any workspace file, so a content check in `read_skill_file`
protected nothing and kept producing edge cases.
- Round 4 passed on `c9ff25dc29f`. Later commits added a
behavior-neutral cleanup (`cd617533c2e`), one test case from the test
audit (`044c1e6e23a`), and a comment fix (`9ec3768b18b`), which passed
validation without another UAT round. Round 5 passed on `2b518c6c2b1`,
which adds the skill directory. A real model ran hidden skills' scripts
from the `dir` on `<invoked-skill>`, including directories whose paths
contain `&`, `'`, `"`, `<` and `>`, and API responses carried no
directory. Merging main after #30884 landed (`2d7d3cb9674`) did not
change this PR's diff, so UAT was not rerun. `8f043b2a342`, which shows
the directory only while the chat stays bound to the skill's workspace,
has Go tests but no UAT round.
- The doc-check skill ran in author self-check mode on `2d7d3cb9674`,
and `27de7f5c6d7` fixes its findings: the skill index sentence said
every skill is listed, the stored-skill sentence claimed any project
editor import honors the key and presented the API default as fixed, the
API path came before the UI path, and some wording broke the docs style
rules. The fix is docs-only, so UAT was not rerun.
- Polish and the test audit stayed inside the implementation diff. No
new dependencies.
- Codex review found no major issues on `9ec3768b18b`, then raised one
P2 on the same head when the PR was marked ready: an invoked hidden
skill gets no skill directory. A probe confirmed it, and `2b518c6c2b1`
fixes it. Its earlier finding on that head (honor
`CODER_AGENT_EXP_SKILL_META_FILE`) was refuted, because the pinned skill
snapshot always reads `SKILL.md`. Both threads are resolved, and Codex
found no major issues on `2b518c6c2b1` or on the merge `2d7d3cb9674`.
- On `27de7f5c6d7`, Codex raised two P2s. One was confirmed: an invoked
skill's directory stayed in the prompt after the chat moved to another
workspace, which a prompt test showed on that head, and `8f043b2a342`
fixes it. The other was declined: on Windows, `scripts\..\SKILL.md` gets
past the `SKILL.md` check in `read_skill_file`, but that check is not an
access boundary (`read_file` opens any path), and Windows has more
aliases (`SKILL.md.`, `SKILL.md::$DATA`, `SKILL~1.MD`) that normalizing
backslashes would not stop. On `8f043b2a342`, Codex asked to bind the
directory to the workspace build instead. That was declined: every
workspace start is a new build with new agent IDs, so the directory
would drop after each stop and start, and the pinned body and the live
files can diverge without a rebuild anyway, as they do for `read_skill`.
A later request on that head asked to limit a hidden skill's
`read_skill_file` access to invocations in the current workspace. That
was declined too: `read_skill_file` resolves names against the current
pin for listed skills on main as well, and the key decides which skills
agents are offered, not which files they can read. All four threads are
resolved. `a697dcd927f` adds the `format:"uuid"` tag that
`TestSDKFieldsFormatted` requires on the new field, and Codex found no
major issues on `a697dcd927f`. `ae70b2c533f` is docs-only: it applies
the doc-check suggestion to say that an invoked skill's directory is
included only while the chat stays in that workspace. The author
doc-check self-check found no blocking findings on it, and Codex found
no major issues on `ae70b2c533f`.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.

---------

Co-authored-by: Jaayden Halko <jaayden.halko@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 01:06:49 +01:00
dylanhuff-at-coder 1e0a481a60 fix: retry workspace quota commits with jittered backoff (#31207)
Bursts of builds for the same user and org (usually autostarts) can hit
serialization failures in `CommitQuota`. `InTx` only retried those 3
times back-to-back, so once retries ran out the build failed outright.

`CommitQuota` stays `SERIALIZABLE` and now gets up to 10 retries with
full-jitter exponential backoff (50ms base, 2s cap, about 11s of backoff
at most). These builds aren't interactive, so a longer wait is a better
trade than a failed build. The wait respects the request context and
happens between transactions, so nothing holds a connection while it
sleeps. Each attempt also resets its results now, so a rolled-back
attempt can't leak `Ok: true` into the response.

The retry settings are opt-in fields on `database.TxOptions`
(`SerialMaxAttempts` and `BeforeSerialRetry`). Every other `InTx` caller
keeps the default 3 attempts with no delay. Since this touches
`coderd/database/db.go`, it'll need a look from a `coderd/database`
owner.

This replaces #30126 with the simpler approach Spike and I landed on. If
we still see failures after this ships, the next step is making
autostart replica-aware so a single replica handles each user, rather
than adding locking here.

Fixes [CORE-198](https://linear.app/codercom/issue/CORE-198)
2026-10-26 15:38:48 -07:00
Ehab Younes 7e9735c4ec refactor: share the session app fold rule and method derivation (#31028)
Ingest, the template insights API, and the Prometheus metric now use one rule to fold apps and one rule to derive each app's connection method. The method is derived from the app name, not stored. Every current reporter's app name implies its method.

- Add codersdk.SessionAppMethod: reconnecting_pty and port_forwarding keep their own method, and every other app name is ssh. It replaces the private helper in coderd/insights.go.
- Add codersdk.FoldUnregisteredSessionApps, the fold rule that GetTemplateInsights already applies in SQL. Registered apps, unknown, and overflow keep their entries, and so do the 64 busiest other apps. Ties break by app name in byte order, and the rest add up under overflow.
- Ingest uses the shared rule instead of capSessionCounts. Registered apps and unknown no longer fold, and at most 64 unregistered app names keep their entries.

Refs #31012, CLIENT-1062
2026-10-26 21:48:36 +00:00
Hugo Dutka e75885a37e feat: add ACP subagent waiting and transcript streaming (#30560)
Add `acp_wait_agent` to stream ACP transcripts, including reasoning and
nested tool activity, to users while returning the subagent's text
response to the parent model. Reconnect dropped streams from their
transcript cursor, preserve running sessions on wait timeout or
cancellation, and persist separate user-visible and model-visible
results.

Depends on #31022.

Generated with Codex, carefully reviewed by Hugo.
2026-10-26 17:55:52 +01:00
Hugo Dutka 8fd94eba27 feat: add tools to start, message, and interrupt ACP agents (#31022)
Add tools to spawn, message, and interrupt workspace-local ACP agents
when the `chat-acp-subagents` experiment is enabled. Derive harness
choices and configuration validation from the chat's pinned context, and
deduplicate session creation and prompt submission across retries.

Depends on #30831.

Generated with Codex, carefully reviewed by Hugo.
2026-10-26 17:55:52 +01:00
Hugo Dutka 457d777af1 fix(coderd/x/chatd/toolschema): traverse schema branches (#31128)
Tool input validation skipped properties declared inside composed
schemas, allowing case-variant keys to bypass ambiguity checks. Traverse
`anyOf`, `oneOf`, and `allOf` branches when checking nested objects,
arrays, and free-form map values, while preserving exact property
matches.

Generated with Codex, carefully reviewed by Hugo.
2026-10-26 17:55:48 +01:00
Michael Suchacz 9cda919eb1 test(coderd/x/chatd): fold the duplicate advisor scenarios (#30993)
Two end-to-end advisor scenarios repeated other tests. This PR moves
their unique checks into tests that stay and deletes them.

- `TestAdvisorGating_RootChat` replayed the advisor and `read_file`
batch of the `mixed exclusive and local tools commit policy errors`
subtest. Its exact two-call count moves into that subtest, which already
checks that `read_file` never runs and both stored errors. Its check
that the first request carries the advisor guidance moves into
`TestAdvisorHappyPath_RootChat`; the `Root` row (#30990) checks the
advisor tool and the guidance in the turn environment.
- The `solo exclusive tool executes` subtest is a subset of
`TestAdvisorHappyPath_RootChat`, which now also checks the stored
advisor result.

### Why it is safe

| Deleted assertion | Remaining check |
| --- | --- |
| Exactly two streamed calls | the mixed local subtest: `>= 2` became
`== 2` |
| Advisor offered | `Root` row (turn environment), and
`TestAdvisorHappyPath_RootChat` now checks that the first request lists
`advisor` |
| Guidance in the first request | happy path test, new check |
| Advisor and skipped tool errors sent back | the mixed local subtest
(stored errors), `TestExclusiveToolPolicy_MixedBatchErrors` (text) |
| Solo: stored result is not an error and holds the reply | happy path
test, new checks |
| Solo: three streamed calls | happy path test waits for the same three
|

| Mutant | Fails before | Fails after |
| --- | --- | --- |
| Exclusive batch check off | both mixed subtests, `RootChat` | both
mixed subtests |
| No exclusive tool set | both mixed subtests, `RootChat`, `Root` row |
both mixed subtests, `Root` row |
| Advisor runs, then the batch is rejected | `RootChat` only | the mixed
local subtest |
| Advisor result marked as an error | provider executed subtest, solo |
provider executed subtest, happy path |
| Advisor result replaced with `{}` | solo, happy path | happy path |
| Guidance dropped from the request (`generation.go:898`) | `RootChat`
only | happy path |

Only an exact count sees the nested advisor call of the third mutant, so
the count moves instead of going away.

Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1
-p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that
all runs at #30990 reach is also reached at #30993. The other
differences are blocks that some runs of the same head reach and others
miss, mostly error paths that depend on timing, so one run per head can
show them as lost or gained.

### Review focus

The subtest reads the count after the chat reaches `waiting`, and its
fake model server counts only streamed requests, so title requests do
not change it.

### Timing

From 10 runs, the two deleted scenarios took 0.83 s summed (median per
test).

### Validation

- `go test ./coderd/x/chatd/ -run
'^(TestActiveServer_ExclusiveToolPolicy|TestAdvisorHappyPath_RootChat)$'
-count=10`, and with `-race -count=3`: pass
- `go test ./coderd/x/chatd/...`: pass
- `go test -overlay` mutant runs of the whole `./coderd/x/chatd/`
package before and after this PR: results above
- the pre-commit hook (gen, fmt, lint, slim build) passed

### Stack

The stack moves advisor eligibility and the root versus child tool split
into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end
tests that only checked them, finishing #30868. #30911 has merged, so
the stack now starts at `main`.

1. #30990 Advisor and general child rows in the tool policy table
2. #30991 Remove the end-to-end advisor gating tests
3. #30992 Remove the end-to-end root and child tool list tests
4. #30993 Fold the duplicate advisor scenarios (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 15:59:01 +00:00
Michael Suchacz c78ceccfaa test(coderd/x/chatd): remove end-to-end root and child tool list tests (#30992)
This PR deletes three end-to-end checks of model request tool lists (309
lines); the rows from #30990 check the same lists on the turn
environment.

The plan child tail also proved that a follow-up message without
`PlanMode` keeps the stored plan mode. The plan rows of
`TestBuildTurnEnvironmentToolPolicy` now send that follow-up and check
the stored plan mode, so clearing it in `SendMessage` fails the table.

- `TestSubagentChatExcludesWorkspaceProvisioningTools` booted coderd
with a provisioner and AI Bridge to compare root and child tool names.
- The plan child tail of
`TestActiveServer_BasicAssistantGenerationAndPromptPreparation` checked
`read_file` and `write_file`. Its only helper,
`createPlanSubagentChatWithHistory`, goes too.
- `TestPlanModeRootChatApprovedExternalMCPToolInvocation` is the first
half of
`TestPlanModeRootChatApprovedExternalMCPWorkflowCanReachProposePlan`,
with the same three checks.

### Why it is safe

Each mutant of `turn_environment.go` below failed the deleted check and
fails the remaining one:

| Deleted assertion | Remaining check | Mutant |
| --- | --- | --- |
| Root has the five workspace and five sub-agent tools | `Root` |
root-only tools in no chat |
| Standard root has no `ask_user_question` or `propose_plan` | `Root` |
either tool added there |
| Child has no workspace, sub-agent, or `ask_user_question` tools |
`GeneralChild` | root-only tools or `ask_user_question` in children |
| Plan child has `read_file` and no `write_file` | `PlanChild` | each
flipped |
| Plan root offers the approved MCP tool, ends `waiting`, and sends the
result to the next call | the workflow test, and `PlanRoot` | approved
MCP tools dropped |

The split reads only `ParentChatID`, `Mode`, and `PlanMode` from the
chat row (`turn_environment.go:258-261`), so a table child made with
`chatstate.CreateChat` gets the tools of a `spawn_agent` child made with
`chatstate.CreateChatWithID`. The `TestSpawnAgent_*` tests cover
spawning. The deleted sub-agent test replied with an escaped NUL
sequence but never checked the stored reply;
`TestNulEscapeRoundTrip/BackslashU0000Text` covers that text.

Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1
-p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that
all runs at #30990 reach is also reached at #30993. The other
differences are blocks that some runs of the same head reach and others
miss, mostly error paths that depend on timing, so one run per head can
show them as lost or gained.

### Timing

From 10 runs, the two deleted tests took 1.14 s summed (median per
test). The basic test went from 0.51 s to 0.41 s (median of 5).

### Validation

- `go test -overlay` mutant runs of the whole `./coderd/x/chatd/`
package before and after this PR: results above
- `go vet ./coderd/x/chatd/`: clean; the pre-commit hook (gen, fmt,
lint, slim build) passed

### Stack

The stack moves advisor eligibility and the root versus child tool split
into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end
tests that only checked them, finishing #30868. #30911 has merged, so
the stack now starts at `main`.

1. #30990 Advisor and general child rows in the tool policy table
2. #30991 Remove the end-to-end advisor gating tests
3. #30992 Remove the end-to-end root and child tool list tests (this PR)
4. #30993 Fold the duplicate advisor scenarios

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 15:33:21 +00:00
Michael Suchacz ac62f2e760 test(coderd/x/chatd): remove the end-to-end advisor gating tests (#30991)
`TestAdvisorGating_ExperimentDisabled`, `_ChildChat`, `_PlanMode`, and
`_ExploreSubagent` each started Postgres, an active server, and a fake
model server for one chat turn, only to check that the request had no
advisor tool and, except for `_ExperimentDisabled`, no advisor guidance.
The rows from #30990 check the same absence in the turn environment, so
this PR deletes the four tests (353 lines). To keep one request-level
check, `TestComputerUseSubagentToolsAndModel` now also checks that its
child's first streamed request has no `advisor` tool and no guidance
block.

### Why it is safe

Each test guarded one condition of the advisor gate
(`turn_environment.go:291`). Removing the condition failed the test and
fails its row:

| Deleted test | Its assertions | Row | Gate mutant |
| --- | --- | --- | --- |
| `_ExperimentDisabled` | No advisor tool with the experiment off and a
stored config that says enabled | `RootAdvisorOff` (same config) |
experiment check removed |
| `_ChildChat` | No advisor tool or guidance in a chat with a parent |
`GeneralChild`, the computer use test | root check removed |
| `_PlanMode` | Same, in a plan mode root chat | `PlanRoot` | plan check
removed |
| `_ExploreSubagent` | Same, in an Explore chat | `ExploreRoot` |
Explore check removed |

The rows read the turn environment, not the request. A mutant that adds
the guidance to every request (`generation.go:898`) failed `_ChildChat`,
`_PlanMode`, and `_ExploreSubagent` and passes every row; it fails the
computer use test.

`_ExploreSubagent` made an Explore root chat (`isExploreSubagentMode`
matches any Explore chat); `ExploreChild` also rejects the advisor.
`_ExperimentDisabled` enabled every other known experiment, but the gate
reads only `ExperimentChatAdvisor`.

Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1
-p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that
all runs at #30990 reach is also reached at #30993. The other
differences are blocks that some runs of the same head reach and others
miss, mostly error paths that depend on timing, so one run per head can
show them as lost or gained.

### Timing

From 10 runs, the four tests took 1.25 s summed (median per test).

### Validation

- `go test -overlay` mutant runs of the whole `./coderd/x/chatd/`
package before and after this PR: results above
- `go test ./coderd/x/chatd/ -run
'^TestComputerUseSubagentToolsAndModel$' -count=10`, and with `-race
-count=3`: pass
- `go vet ./coderd/x/chatd/`: clean; the pre-commit hook (gen, fmt,
lint, slim build) passed

### Stack

The stack moves advisor eligibility and the root versus child tool split
into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end
tests that only checked them, finishing #30868. #30911 has merged, so
the stack now starts at `main`.

1. #30990 Advisor and general child rows in the tool policy table
2. #30991 Remove the end-to-end advisor gating tests (this PR)
3. #30992 Remove the end-to-end root and child tool list tests
4. #30993 Fold the duplicate advisor scenarios

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 15:14:56 +00:00
Michael Suchacz 56fe6ec5e3 test(coderd): run the TestPostChats workspace, input, and MCP rejections on one server (#30976)
This PR moves the remaining 9 isolated rejection subtests of
`TestPostChats` into the shared `Rejects` table from the previous PR:
the 4 workspace cases, `EmptyText`, `UnsupportedPartType`,
`RejectsInvalidReasoningEffort`, and the cross-org and third-org MCP
server cases. Each one no longer starts its own coderd and AI Bridge
daemon.

`MCPServerIDsDisabledConfigRejected` keeps its own server: after the
create rejection it sends a message on a chat it creates, which a
single-request case cannot express.

### Why it is safe

- Cases keep the old subtest names, callers, status, and message checks,
and now also check the exact `Detail`. The reasoning-effort case
compares the full detail instead of two substrings.
- I mutated 12 lines in `postChats` and its workspace, input, effort,
and MCP helpers and ran the old and new test files against each one. The
old file caught 10 and the new file catches the same 10, each in the
case that owns it, plus a detail-text mutant the old file missed. The
one mutant both survive (reading the workspace as system) returns the
same response from the SSH check.

### Review focus

The workspace cases now run with the shared default model present.
`postChats` rejects them before it resolves a model, so the model does
not change their result. `EmptyText` and `UnsupportedPartType` run in an
organization without a model, so they still prove that input is rejected
before model resolution: moving the input check after it fails both. The
MCP cases add their configs to orgs that no other case reads, or to the
default org with `default_off`, where no other case passes MCP IDs.

### Timing

From 5 alternating runs, the moved subtests took 2.83 s summed (median);
their 9 cases take 0.27 s on the shared server. For the whole stack, `go
test` reports 1.96 s instead of 3.19 s for the package.

### Validation

- `go test ./coderd -run '^TestPostChats$' -count=3`: pass
- the same run with `-race`: pass
- `go test -overlay` mutant runs against the old and new test files:
results above
- `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the
pre-commit hook passed

### Stack

The stack runs every isolated `TestPostChats` rejection case on one
shared server instead of one server per case.

1. #30975 Model and organization rejection cases
2. #30976 Workspace, request input, and MCP server rejection cases (this
PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 15:13:21 +00:00
Michael Suchacz f34aaeb017 test(coderd): share one server across the chat child archive tests (#30956)
Merges `TestPatchChatArchiveChildRejected`,
`TestPatchChatUnarchiveChildRejected`, and
`TestPatchChatArchiveRootRollsBackWhenChildCannotArchive` in
`coderd/exp_chats_chatstate_test.go` into `TestPatchChatChildArchive`.
Each old test started its own coderd server and built the same root and
child family. The new subtests share one server and a `createFamily`
helper that takes the child statuses, and each subtest still builds its
own family. The file starts 11 coderd servers instead of 13.

**Why it is safe:** each subtest makes the same requests and the same
status and archive-state assertions as the test it replaces. With the
old tests compiled back in through `go test -overlay`, both production
mutants failed the old tests that guarded the line and the subtests that
replace them:

| Mutant | Failed, old and new |
|---|---|
| a child archive or unarchive returns 409 instead of 400 |
`ArchiveChildRejected`, `UnarchiveChildRejected` |
| the family cascade ignores a child's `SetArchived` error |
`RootArchiveRollsBackWhenChildCannotArchive` |

**Review focus:** the subtests share a server, user, and model config.
Each one builds its own root and children and checks only those rows,
and `withChatWorkerDisabled` stays on.

**Timing** (`-count=1 -v -p 4 -parallel 4`, median of 5 paired runs on a
shared host): the three old tests took 1.4 s summed. The new test takes
0.5 s.

**Validation:**
- `go test ./coderd -run '^TestPatchChatChildArchive$' -count=10`: pass
- the same run with `-race -count=3`: pass
- `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the
pre-commit hook passed

**Stack:** these two PRs share coderd servers across the copy-pasted
chatstate endpoint tests.

1. #30941: queue and invalid-state tables
2. #30956 (this PR): child archive tests on one server

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 15:01:03 +00:00
Michael Suchacz 300f73b05a test(coderd/x/chatd): cover advisor eligibility in the tool policy table (#30990)
`TestBuildTurnEnvironmentToolPolicy` ran every row with the advisor
experiment off and had no general sub-agent row, so only end-to-end
tests checked advisor eligibility and the tools that only root chats
get. This PR adds those checks to the table and deletes nothing; the PRs
above it delete the end-to-end tests.

- The rows run on a server with `ExperimentChatAdvisor`; the new
`RootAdvisorOff` row uses a second server without it. The stored advisor
config says `Enabled: true`, which must not matter: the experiment is
the only gate (`codersdk/chats.go:1277`).
- `Root` now wants the advisor, its guidance, and the five workspace and
five sub-agent tools, and rejects `propose_plan`. The new `GeneralChild`
row rejects all of those and `ask_user_question`. The plan and Explore
rows reject the advisor.
- Every row checks the guidance and the exclusive tool set: only the
advisor when the row wants it, otherwise empty.

### Why it is safe

The rows pass on `main` (`e53cfef8643`), which now includes #30911. Each
of 15 mutants of `turn_environment.go` fails a row:

| Mutant | Row that fails |
| --- | --- |
| Advisor gate ignores the experiment, the root check, plan mode, or
Explore mode | `RootAdvisorOff`, `GeneralChild`, `PlanRoot`,
`ExploreRoot` in that order |
| No advisor guidance, no advisor tool, or no exclusive set | `Root` |
| Root-only tools in every chat, or in none | `GeneralChild`, or `Root`,
`RootAdvisorOff`, `PlanRoot` |
| `ask_user_question` in standard root turns, or in child turns |
`Root`, or `GeneralChild` |
| `propose_plan` in every turn | `Root` |
| Plan children get `write_file`, or plan turns drop `read_file` |
`PlanChild` |
| Plan turns drop approved MCP tools | `PlanRoot` |

The deletion PRs above map each deleted assertion to these rows. Under
the plan and Explore gate mutants, the plan filter and the Explore
allowlist still drop the advisor tool, so those rows fail on the new
guidance and exclusive set checks.

### Review focus

Both servers are built once and never changed, and each row creates its
own chat, so the rows stay parallel.

### Timing

From 5 alternating runs, the table took 0.29 s (median) before this PR
and 0.28 s after.

### Validation

- `go test ./coderd/x/chatd/ -run '^TestBuildTurnEnvironmentToolPolicy$'
-count=10`, and with `-race -count=3`: pass
- `go test -overlay` mutant runs: results above
- the pre-commit hook (gen, fmt, lint, slim build) passed

### Stack

The stack moves advisor eligibility and the root versus child tool split
into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end
tests that only checked them, finishing #30868. #30911 has merged, so
the stack now starts at `main`.

1. #30990 Advisor and general child rows in the tool policy table (this
PR)
2. #30991 Remove the end-to-end advisor gating tests
3. #30992 Remove the end-to-end root and child tool list tests
4. #30993 Fold the duplicate advisor scenarios

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 14:55:55 +00:00
Michael Suchacz cfddedb95c test(coderd): run the TestPostChats model and org rejections on one server (#30975)
`TestPostChats` started a full coderd and AI Bridge daemon for each of
its 34 subtests. This PR adds a `Rejects` table on one shared server and
moves the 9 model and organization rejection subtests into it: the
non-default org model cases, disabled, provider-disabled and denied
model configs, `NilOrganizationID`, and `NonMemberOrganization`. Each
case creates its own state in `prepare` and returns the caller.

Four rejection subtests keep their own servers because they need or
change state that the cases share: `MissingDefaultModelConfig` needs a
default org with no model, `ProviderDisabledDefaultModelRejected`
disables the default model's provider,
`DeniedSameOrganizationDefaultIsRejected` adds a second default model to
the org, and `AgentsAccessDefaultRole` rewrites org roles.

### Why it is safe

- Cases keep the old subtest names, callers, status, and message checks,
and now also check the exact `Detail` (empty where the old subtests did
not check it).
- I mutated 11 lines in `postChats` and its model helpers and ran the
old and new test files against each one. The old file caught 8 and the
new file catches the same 8, each in the case that owns it. The 3
mutants that both survive return the same response through another
check: dbauthz hides other-org configs from members, and the provider
status check repeats the provider-enabled check.

### Review focus

Cases run in parallel against one deployment. Each case writes only to
its own new orgs, users, providers, or non-default configs. No case
changes the default model, its provider, or member roles.

### Timing

From 5 alternating runs, the moved subtests took 3.12 s summed (median);
the table setup plus its 9 cases take 0.59 s.

### Validation

- `go test ./coderd -run '^TestPostChats$' -count=3`: pass
- the same run with `-race`: pass
- `go test -overlay` mutant runs against the old and new test files:
results above
- `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the
pre-commit hook passed

### Stack

The stack runs every isolated `TestPostChats` rejection case on one
shared server instead of one server per case.

1. #30975 Model and organization rejection cases (this PR)
2. #30976 Workspace, request input, and MCP server rejection cases

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 14:55:19 +00:00
Michael Suchacz 5a1a0594c4 test(coderd): share one server across the chat message pagination tests (#30965)
`TestGetChatMessages_Pagination` started a coderd server with its own
database in each of its ten leaves, although the leaves differ only in
cursors and their own chat rows. This PR builds the client, database,
owner, and chat model once in the parent. The six successful-page leaves
become one table (options, expected ID positions, `HasMore`, queued
count), and the two malformed `after_id` leaves become another. The
transposed or equal cursor case and the burst walk stay separate
subtests, and every subtest keeps its name.

**Why it is safe:** every leaf still creates its own chat, messages, and
queued message, and every request and query is scoped to that chat. No
leaf changes users, roles, models, or deployment values. I ran 24
mutants of `getChatMessages` and its two paginated queries (limit+1 and
`HasMore`, truncation, ASC dispatch, queued suppression, `after_id`
parsing, the transposed check, cursor comparison, and ordering) against
the old and the new test with `go test -overlay`. The new test fails on
all 20 mutants that the old test fails on, in the same leaves. It also
fails on the two mutants that drop the `chat_id` filter, which the old
test missed because each leaf had its own database. Two mutants survive
both tests: the DESC path fetching `limit` rows instead of `limit+1`,
and `HasMore` using `>=`. No test on `main` covers them, and this PR
does not add coverage.

**Review focus:** the shared database interleaves message IDs across
leaves. Assertions use only the IDs that each leaf's `seedChat`
returned, so interleaving cannot change a result for a correct handler.
`AfterIDAtOrAboveMaxReturnsEmpty` now seeds five messages instead of
three, like the other page cases, and still sets `after_id` to the last
ID.

**Timing** (prebuilt test binaries, `-test.parallel 4`, median of 5
alternating runs on a shared host): binary wall time went from 1.21 s to
0.72 s. Leaf times summed went from 3.89 s to 0.39 s, plus 0.48 s for
the one shared server, and coderd boots went from 10 to 1.

**Validation:**
- `go test ./coderd -run '^TestGetChatMessages_Pagination$' -count=10`:
pass
- the same run with `-race -count=2`: pass
- `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the
pre-commit hook passed

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 14:16:18 +00:00
Michael Suchacz 83cdc8e346 test(coderd): table the chatstate queue and invalid-state endpoint tests (#30941)
Replaces nine copy-pasted endpoint tests in
`coderd/exp_chats_chatstate_test.go` with two table tests that each
share one coderd server. `TestChatQueueEndpointErrors` turns the four
queue delete and promote tests into rows.
`TestInvalidChatStateEndpoints` turns the two shared invalid-state
response tests into rows and holds the three reconcile cases as
subtests. Every old case stays a parallel subtest with its own chat, and
the file starts 13 coderd servers instead of 20.

**Why it is safe:** each subtest sends the same request and makes the
same assertions as the test it replaces. With the old tests compiled
back in through `go test -overlay`, each of 10 production mutants failed
exactly the old test that guarded the line and the subtest that replaces
it:

| Mutant | Failed, old and new |
|---|---|
| queue delete or promote returns 409 for an unknown ID, or 404 for an
empty queue (4 mutants) | the matching `Missing` or `EmptyQueue` case |
| send or tool results skip `writeChatInvalidState` (2 mutants) | the
matching `ReturnsSharedResponse` case |
| reconcile changes its not-invalid message |
`ReconcileNotInvalidReturnsConflict` |
| reconcile returns the old chat, or drops the default `last_error` (2
mutants) | `ReconcileSucceeds` |
| the chat URL parameter maps a missing chat to 500 |
`ReconcileNotFound` |

**Review focus:** subtests now share a server, user, and model config.
Each subtest creates its own chat and reads only that chat, and
`withChatWorkerDisabled` stays on, so no worker moves a chat between
steps.

**Timing** (`-count=1 -v -p 4 -parallel 4`, median of 5 paired runs on a
shared host): the nine old tests took 3.8 s summed. The two new tests
take 0.9 s.

**Validation:**
- `go test ./coderd -run
'^(TestChatQueueEndpointErrors|TestInvalidChatStateEndpoints)$'
-count=10`: pass
- the same run with `-race -count=3`: pass
- `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the
pre-commit hook passed

**Stack:** these two PRs share coderd servers across the copy-pasted
chatstate endpoint tests.

1. #30941 (this PR): queue and invalid-state tables
2. #30956: child archive tests on one server

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 14:14:35 +00:00
Michael Suchacz cc51592c6f test(coderd): replace the plan-mode lock counterexample test (#30921)
Deletes `AuditConcurrentIdenticalPUTsDuplicateWithoutLock` and its
test-only store `lockSwitchChatPlanModeInstructionsStore` from
`TestChatPlanModeInstructions`. That test turned the advisory lock off
inside the fake store and asserted the duplicate audit row that follows,
so it checked the fake's schedule, not `putChatPlanModeInstructions`.
The remaining positive test, `AuditConcurrentIdenticalPUTsSingleEntry`,
now holds the per-setting lock until both PUTs wait on it, so it fails
whenever the handler skips the lock or reads Old before taking it.

**Why it is safe:** mutants of `putChatPlanModeInstructions`, run with
`go test -overlay`:

| Mutant | Deleted test on `main` | `SingleEntry` on `main` |
`SingleEntry` after | `AuditLockFailureRejectsWrite` |
|---|---|---|---|---|
| `AcquireLock` call removed | passed 20 of 20 | failed 2 of 20 | failed
5 of 5 | failed 20 of 20 |
| `AcquireLock` moved after the Old read | passed 20 of 20 | failed 2 of
20 | failed 10 of 10 | passed 20 of 20 |

The deleted test passed on both mutants, so it guarded no handler line.
On `main` the positive test caught a missing lock only when the two PUTs
happened to overlap, and 8 or 16 concurrent PUTs did not raise that
rate. With the lock held, it fails on every run of both mutants and
passed 30 of 30 runs on the real handler, plus 5 under `-race`. The
lock-holding pattern is the one in `coderd/experiments/write_test.go`.

**Review focus:** the `pg_locks` wait counts every waiting advisory lock
in the test database. This subtest creates no chats, so chatd never
requests its admission or heartbeat locks, and the two PUTs are the only
waiters.

**Timing** (`-count=1 -v`, median of 5 paired runs on a shared host):
the deleted subtest took 0.80 s. `SingleEntry` took 0.70 s before and
0.58 s after. The whole `TestChatPlanModeInstructions` took 7.0 s before
and 5.0 s after, though host noise is larger than that gap.

**Validation:**
- `go test ./coderd -run '^TestChatPlanModeInstructions$' -count=1`:
pass
- `go test ./coderd -run
'^TestChatPlanModeInstructions$/^(AuditConcurrentIdenticalPUTsSingleEntry|AuditLockFailureRejectsWrite)$'
-count=30`: pass
- the same `SingleEntry` run with `-race -count=5`: pass
- `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the
pre-commit hook passed

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 13:37:49 +00:00
TJ 4e4a56b665 fix: show configured provider icons and names in AI settings (#31033)
Admin-configured provider icons were ignored on the AI Settings Models
page (model rows, Add model menu, provider filter, model form header and
provider select) and in Agents compaction settings. These views derived
the icon only from the provider type, so a provider like DeepSeek on an
OpenAI-compatible type showed a generic icon even though the Providers
page and chat model selector showed the configured one. They now pass
the configured icon to `ProviderIcon`, which falls back to the type
icon.

The Spend page showed provider types (OpenAI) instead of configured
providers (DeepSeek) because `ListOrganizationAISpendUsers` aggregated
`ai.provider` while its filter matched `ai.provider_name`. It now
aggregates `provider_name`, and the page resolves names to display names
and icons from the AI Gateway providers list, which it shares with the
provider filter through one query. `OrganizationAISpendUser.providers`
now holds provider names; records from before configured names existed
have the type as their name, so they render as before.

AI Gateway Sessions views have the same type-versus-name issue and are
left for a separate fix.

**Note:** the Spend page resolves provider display names and icons from
`/aibridge/providers`, which requires deployment-wide read access
(`viewAnyAIBridgeInterception`). Owners and Auditors see the custom
display name and icon; Template Admins, User Admins, Org Admins, Org
Auditors and Org User Admins see the provider name rendered as a type
without the icon. Revisiting that endpoint's permissions is tracked in
AIGOV-726.

Refs CODAGT-1421

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

- Root cause: callers rendered `<ProviderIcon provider={type} />`
without the descriptor's `icon`; nothing was stale.
- Spend page provider metadata is fetched only for viewers who can
already use the provider filter (`viewAnyAIBridgeInterception`); other
viewers see names formatted like provider types.
- Extended `ProvidersBadge` with an optional `providersByName` map
instead of adding a Spend-specific badge, so the Sessions fix can reuse
it.
- Removed `providerTypeByIDFromUserConfigs`, which became unused once
compaction settings used `providerInfoByIDFromUserConfigs`.
- Visual coverage is in Storybook stories (ModelRow, ModelForm,
UserCompactionThresholdSettings, SpendPage) per the repo's FE1 rule.

</details>

---

_Generated by Coder Agents on behalf of @tracyjohnsonux._
2026-10-26 13:26:38 +00:00
Spike Curtis 9fe52826da feat: send include_related from WorkspaceByOwnerAndName options (#29908)
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._
2026-10-26 12:59:53 +01:00
Susana Ferreira 15a5844253 feat: add cost to AI Gateway session threads API (#30509)
## Description

Exposes cost data on the AI Gateway session threads endpoint (`GET
/api/v2/aibridge/sessions/{session_id}`), so the session page can show
cost alongside token usage. Backend only, the UI changes for AIGOV-600
will follow separately.

## Changes

- Add `cost_micros` and `has_unpriced_usage` to
`AIBridgeSessionThreadsTokenUsage`, populated for the session summary,
each thread, and each agentic action.
- Compute the session summary cost in `ListAIBridgeSessions`, next to
the existing session token sums, so tokens and cost come from the same
rows.
- Add `priced_model`, the model and per-token prices used for pricing,
to `AIBridgeThread` for the root interception (the prompt) and to each
`AIBridgeAgenticAction` for that interception, since requests in a
thread may be priced as different models. Nil when not priced.
- Update frontend mocks for the new required fields.

Related to AIGOV-600

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-10-26 10:01:50 +00:00
Sas Swart 946c2f0e04 feat: resolve orgs from workspace session tokens in AI Gateway requests (#30902)
Add an AI Gateway org resolver at the coderd IsAuthorized boundary,
detect workspace session tokens, load the workspace org, validate the
user is still a member of that org, reject missing workspaces or invalid
membership, and return the resolved org in IsAuthorizedResponse while
leaving it unused by downstream policy. Include tests for successful
workspace-token resolution, missing workspace rejection, invalid org
membership rejection, and compatibility with the existing ServeHTTP
flow.

Fixes AIGOV-714
2026-10-26 11:40:51 +02:00
Michael Suchacz 9f2389a908 refactor(coderd/x/chatd): derive the BYOK auth header from the AI Gateway client choice (#30979)
`fantasyConfigForAIBridge` picked the fantasy client for an AI Gateway
route, and `aiGatewayRequestFormatForProviderType` mapped the same
provider type and model again, only to choose `X-Api-Key` or
`Authorization: Bearer` for a user's own key. This PR moves the client
choice into `aibridgeClientProvider` and passes its result to
`aiGatewayProviderAuthForUser`, so the header follows the client. It
deletes the request-format enum, the mapper, the mapper's test, and the
superseded `TestNewModelAttribution`.

## Why it is safe

- `aibridgeClientProvider` is the old `fantasyConfigForAIBridge` switch
without the base URL. `TestAIBridgeProviderFormatMapping` (12 rows,
unchanged) still pins the client and base URL; the mapper test's 9 rows
are a subset of them.
- The mapper returned the Anthropic format for exactly the inputs that
get the Anthropic client, so no header changes.
`TestAIGatewayProviderAuthForUser` and the #30978 subtest pin the
header.
- `TestNewModelAttributionImmutablePerRequest` covers both workspace
bindings that `TestNewModelAttribution` checked, plus the API key ID,
also without a database.
- Mutants through `go test -overlay` each fail a remaining test: every
arm of `aibridgeClientProvider` and the base URL check; an auth switch
keyed on `openai`, an auth case matching `openai-compat` instead of
`anthropic`, and a dropped model ID at the `resolveAIGatewayRoute` call;
the workspace check, the workspace ID copy, and an empty API key ID. A
garbage copy fails to build, so the overlay applies.
- `rg -n 'aiGatewayRequestFormat' .` finds nothing.

## Review focus

Only the Anthropic client gets `X-Api-Key`; `openai` and `openai-compat`
keep `Authorization: Bearer`, as the old default format gave them. Only
the #30978 subtest catches an auth switch keyed on `openai`.

## Validation

- `go test ./coderd/x/chatd/... -count=1 -p 4 -parallel 4`: pass.
- 12 mutants: each fails a remaining test.
- `make pre-commit`: pass.

## Stack

This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.

1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 09:37:12 +00:00
Michael Suchacz 707d373a76 test(coderd/x/chatd): cover BYOK header choice for Bedrock and OpenAI-compatible routes (#30978)
`TestResolveModelRouteForConfigAIGatewayProviderAuth` gains one subtest
that pins which header carries a user's own provider key on two more
routes: `X-Api-Key` for an Anthropic model on a Bedrock provider, and
`Authorization: Bearer` for an OpenAI-compatible provider. The next
layer rewrites how chatd picks that header, and until now no test failed
when the call site dropped the model ID. This test-only layer is the
characterization test for that rewrite, so it adds lines instead of
removing them.

## Why it is needed

- `resolveAIGatewayRoute` passes the model ID to
`aiGatewayRequestFormatForProviderType`, and only the Bedrock arm reads
it. A mutant that passes `""` instead passed all of `go test
./coderd/x/chatd/`: no chatd test resolved a BYOK route for a Bedrock
provider, and `TestAIGatewayRequestFormatForProviderType` calls the
classifier directly.
- With this subtest, that mutant fails on the Bedrock row (`X-Api-Key`
expected, `Authorization` sent). A mutant that maps the classifier's
default arm to the Anthropic format fails on the OpenAI-compatible row.
A garbage copy of `model_routing_aibridge.go` fails to build, so the
`-overlay` applies.

## Review focus

Today the OpenAI-compatible row takes the same default arm as the OpenAI
`UserKey` subtest. The next layer keys the header on the client family
(`anthropic`, `openai`, `openai-compat`), and this row fails if that
switch matches only `openai`.

## Validation

- `go test ./coderd/x/chatd/ -run
'^TestResolveModelRouteForConfigAIGatewayProviderAuth$' -count=1`: pass.
- Both mutants above, through `go test -overlay`: fail the new subtest.
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass.
- `make pre-commit`: pass.

## Stack

This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.

1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 09:24:50 +00:00
Michael Suchacz 231537da8b refactor(coderd/x/chatd): drop transport branches only direct clients used (#30966)
`Model.AcceptsFilePartMediaType`, `BetaHeadersFromCallConfig`, and
`chatopenai.TransportFor` still had branches for the Azure, Bedrock,
Google, OpenRouter, and Vercel clients. Production has built none of
those clients since #30929, so the branches never ran. This PR deletes
them and their test rows.

## Why it is safe

- `AcceptsFilePartMediaType` and `TransportFor` switch on the built
client's `Provider()`, which is `anthropic`, `openai`, or
`openai-compat` (see #30958). `BetaHeadersFromCallConfig` receives
`anthropic` (`thinking_binding.go`) or the gateway's provider hint
(`model_routing_aibridge.go`), which is one of the same three.
- The deleted rows of `TestAcceptsFilePartMediaType`,
`TestTransportFor`, and `TestBetaHeadersFromCallConfig` used the deleted
provider names. The remaining rows fail on a mutant of each rewritten
line: the Responses check in `TransportFor`, the provider check in
`BetaHeadersFromCallConfig`, Anthropic `text/*` acceptance (what the
Bedrock rows also checked), and the SVG rejection (`anthropic-svg` still
checks what `google-svg` did). Garbage copies of both files fail to
build, so the overlays apply.
- `ToolResultMediaOmission` and `InlineImageCapBytes` keep their
provider lists, because they read the configured provider behind the
OpenAI-compatible client.

## Review focus

Azure providers already reach the model through the OpenAI-compatible
client, which always uses Chat Completions. The deleted Azure arm of
`TransportFor` only described the direct Azure client.

This PR also edits `coderd/x/chatd/ARCHITECTURE.md`, section "OpenAI
transport selection": in the paragraph that began "Azure is deliberately
exempt", "`TransportFor` has no Azure case, because" replaces the first
two sentences and the opening "The exemption is narrower than it
appears," of the third; the rest of that paragraph is unchanged.

## Validation

- `go test ./coderd/x/chatd/chatprovider/...
./coderd/x/chatd/chatopenai/...`: pass.
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass.
- Mutants through `go test -overlay`: all 4 fail the named rows.
- `make pre-commit`: pass.

## Stack

This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.

1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 09:12:30 +00:00
Michael Suchacz 17c7fe9632 refactor(coderd/x/chatd/chatprovider): drop provider options only direct clients read (#30958)
After #30929, `chatprovider` still converted Google, OpenRouter, and
Vercel model-config options into fantasy provider options, and
`applyReasoningEffort` still had Azure, Bedrock, Google, OpenRouter, and
Vercel arms. No client that production builds reads any of them. This PR
deletes the three option converters and those five effort arms.

## Why it is safe

- `fantasyConfigForAIBridge` builds only the `anthropic`, `openai`, or
`openai-compat` client, so `model.Provider()` never matched the deleted
arms.
- Each fantasy client reads only `ProviderOptions[<its own name>]`
(chatd never renames the compat client), so the `google`, `openrouter`,
and `vercel` entries were never sent. Pinned Gemini thinking still
reaches Google through the compat `extra_body` path.
- The deleted tests (`TestProviderOptionsForCall_GoogleThinkingConfig`
and the Google, OpenRouter, and Vercel rows of
`TestApplyReasoningEffort`) used those provider names, so they tested
deleted code. The Gemini helpers they reached keep dedicated tests,
which fail on mutants of the Gemini 3 version gate, the clamp
comparison, the medium level mapping, the `GoogleThinkingLevelFromChat`
normalization, and the compat `extra_body` assignment.
- Two new cases close gaps the deleted rows left:
`TestProviderOptionsForCall_GoogleThinkingConfigSkipsNonCompatClients`
fails when the compat provider check becomes `!= ""`, and a pre-Gemini-3
`medium` row in `TestGoogleCompatReasoningEffort` fails when that arm
returns `high`. Both mutants passed before.
- The two Bedrock rows of `ClampsNoneForClaude55Models` now use the
Anthropic transport with the same `global.anthropic.*` IDs, which the
gateway sends to that transport. Changing `strings.Contains` to
`strings.HasPrefix` in `anthropicReasoningEffort` fails them.
- `rg -n
'googleProviderOptionsFromChatConfig|openRouterProviderOptionsFromChatConfig|vercelProviderOptionsFromChatConfig'
.`: no matches.

## Review focus

Chat debug runs record a lower `provider_option_count` for configs that
set Google, OpenRouter, or Vercel options, because those unread entries
are no longer built.

## Validation

- `go test ./coderd/x/chatd/chatprovider/...
./coderd/x/chatd/chatopenai/...`: pass.
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass.
- Mutants through `go test -overlay`: all 11 fail the named tests, and
garbage copies fail to build.
- `make pre-commit`: pass.

## Stack

This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.

1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 08:56:27 +00:00
Michael Suchacz cdc914108c refactor(coderd/x/chatd): drop the remaining direct provider clients (#30929)
After #30928, `chatprovider.ModelFromConfig` still built direct Azure,
Google, OpenRouter, and Vercel clients. The AI Gateway path never asks
for them, because `fantasyConfigForAIBridge` sends those provider types
through the OpenAI-compatible client. This PR deletes those four arms
and their missing-key error cases, the per-provider region plumbing that
only the deleted Bedrock client read, and `ProviderAPIKeys.Empty`, which
has no callers left.

## Why it is safe

- The only production caller of `ModelFromConfig` passes a hint from
`fantasyConfigForAIBridge` (see #30928), and no test builds these four
clients.
- Region flowed from `ConfiguredProvider.Region` through
`ResolveUserProviderKeys` into `ProviderAPIKeys.RegionByProvider`, and
only the Bedrock arm read it. The gateway reads Bedrock and Claude
Platform regions from the provider settings itself
(`aibridgedserver.go`).
- `chatd.go` still marks Claude Platform on AWS as supporting ambient
credentials.
`TestResolveQuickgenModel_TitleGenerationOverrideAmbientCredentials`
fails when that flag is forced to false.
- `Empty` lost its last production caller when direct chat routing was
removed (#26862). Its only test checked the region term.
- Deleted tests (`TestProviderAPIKeysEmpty_RegionCountsAsConfigured`,
`TestResolveUserProviderKeys_PreservesProviderRegions`, the
`DisabledProviderRegionsRemoved` prune row) checked region and `Empty`
code that is gone. One also checked that a keyless Bedrock provider is
available; `TestResolveUserProviderKeys` still fails when the Bedrock
ambient case or the empty-key rule in `setResolvedProviderAPIKey` is
mutated.
- `rg -n 'RegionByProvider|setRegion|keys\.Region\(|\.Empty\(\)'
coderd/x/chatd` finds nothing.

## Review focus

The `aiProviderConfigFromKeys` hunk in `chatd.go`, the only change
outside `chatprovider`: it drops the region reads and keeps the ambient
credential flag.

## Validation

- `go test ./coderd/x/chatd/chatprovider/...
./coderd/x/chatd/chatopenai/...`: pass.
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass.
- `go build ./...` and `go vet` on every package that imports
`chatprovider`: pass.
- `make pre-commit`: pass.

## Stack

This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.

1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-26 08:45:02 +00:00