Commit Graph
4958 Commits
Author SHA1 Message Date
Mathias Fredriksson 48a3d3ff12 fix: keep OpenAI web searches in later turns (#31355)
OpenAI chats dropped every earlier web search from the next request
with store false, so on later turns the model said it made no tool
calls. Fantasy replayed a search only as an item_reference, which
OpenAI cannot resolve for an unstored item.

The fantasy pin moves to coder_2_33 with coder/fantasy#78, which sends
a search inline as an id-less web_search_call, rebuilt from its result
metadata, whenever it does not go back as an item_reference. With
store true it also covers searches from an unstored response, as when a
chat moves to a stored model config or a zero data retention org, and
searches with no reasoning before them. The model gets the action it
took, not the page contents, which OpenAI does not keep for references
either.

TestChatOpenAIResponsesWebSearch now sends a second turn and asserts
the exact inline item for each action shape through the chat API and
chatd's prompt builder. The fake OpenAI server accepts inline searches
without an id, returns OpenAI's 404 for references to items it served
with store false, and sends sources only on search actions. The tests'
reference checks now also catch references without a type, which
openai-go omits.

Relates to CODAGT-1482
2026-10-29 19:50:34 +00:00
Michael Suchacz 1acacc9c30 feat: graduate MCP tool search from experiments (#31327) 2026-10-29 20:32:56 +01:00
Hugo Dutka 846daa80e4 fix(coderd/x/chatd): add ACP subagent prompt guidance (#31498) 2026-10-29 17:30:20 +01:00
cdrciandgithub-actions[bot] 5c691c82c9 chore: refresh AI model price book (#31474)
## Price book changes

19 models added, 27 models removed, 37 models changed.

<details>
<summary>Added</summary>

- azure/gpt-6.1-terra
- bedrock/au.anthropic.claude-sonnet-5-5
- bedrock/global.openai.gpt-6.1-terra
- bedrock/openai.gpt-6.1-terra
- bedrock/us.openai.gpt-6.1-terra
- copilot/gpt-6.1-terra
- openai/gpt-6.1-terra
- openrouter/liquid/lfm-2.5-2.6b
- openrouter/minimax/minimax-m3.1-flash
- openrouter/moonshotai/kimi-k3.1-pro
- openrouter/openai/gpt-6.1-terra
- openrouter/openai/gpt-6.1-terra-pro
- openrouter/particle-ai/particle-1
- openrouter/prism-ml/ternary-bonsai-2-9b
- vercel/moonshotai/kimi-k3.1-pro
- vercel/moonshotai/kimi-k3.1-pro-highspeed
- vercel/openai/gpt-6.1-terra
- vercel/openai/gpt-6.1-terra-fast
- vercel/particle/particle-1
</details>

<details>
<summary>Removed</summary>

- azure/claude-opus-4-1
- azure/deepseek-r1
- copilot/mai-code-1-flash-picker
- google/gemini-3-pro-image-preview
- google/gemini-3.1-flash-image-preview
- openrouter/arcee-ai/trinity-large-thinking
- openrouter/ibm-granite/granite-4.0-h-micro
- openrouter/minimax/minimax-m3.1-flash:free
- openrouter/nvidia/nemotron-3-super-120b-a12b:free
- openrouter/openai/gpt-3.5-turbo
- openrouter/openai/gpt-3.5-turbo-instruct
- openrouter/openai/gpt-4-turbo
- openrouter/openai/gpt-5.2-chat
- openrouter/openai/o1
- openrouter/openai/o1-pro
- openrouter/openai/o3-mini
- openrouter/openai/o3-mini-high
- openrouter/openai/o4-mini
- openrouter/openai/o4-mini-high
- openrouter/qwen/qwen3-next-80b-a3b-thinking
- vercel/openai/gpt-3.5-turbo
- vercel/openai/gpt-4-turbo
- vercel/openai/gpt-4.1-nano-fast
- vercel/openai/gpt-image-1
- vercel/openai/o4-mini-fast
- vercel/spacexai/grok-4.1-fast-non-reasoning
- vercel/spacexai/grok-4.1-fast-reasoning
</details>

<details>
<summary>Changed</summary>

- openrouter/deepseek/deepseek-v4-flash-0731
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/google/gemini-3.8-flash
- openrouter/google/gemma-3-4b-it
- openrouter/ibm-granite/granite-4.2-8b
- openrouter/meta-llama/llama-3.2-3b-instruct
- openrouter/minimax/minimax-m2.5
- openrouter/mistralai/mistral-small-3.2-24b-instruct
- openrouter/moonshotai/kimi-k2.7-code
- openrouter/moonshotai/kimi-k3
- openrouter/nousresearch/hermes-4-405b
- openrouter/nvidia/nemotron-3-nano-30b-a3b
- openrouter/openai/gpt-4.1-nano
- openrouter/qwen/qwen3-30b-a3b-instruct-2507
- openrouter/qwen/qwen3.5-122b-a10b
- openrouter/qwen/qwen3.5-27b
- openrouter/qwen/qwen3.5-9b
- openrouter/qwen/qwen3.6-27b
- openrouter/qwen/qwen3.6-35b-a3b
- openrouter/qwen/qwen3.8-27b
- openrouter/reflection/beam-1.0-501b-a23b
- openrouter/xiaomi/mimo-v2.5
- openrouter/xiaomi/mimo-v2.5-pro
- openrouter/z-ai/glm-4.6
- openrouter/z-ai/glm-4.6v
- openrouter/z-ai/glm-5.2
- openrouter/z-ai/glm-5.3
- openrouter/z-ai/glm-5.3-flash
- openrouter/~deepseek/deepseek-flash-latest
- openrouter/~deepseek/deepseek-pro-latest
- openrouter/~moonshotai/kimi-latest
- openrouter/~openai/gpt-terra-latest
- openrouter/~z-ai/glm-flash-latest
- openrouter/~z-ai/glm-latest
- vercel/amazon/nova-2-lite
- vercel/minimax/minimax-m3.1-flash
- vercel/openai/gpt-4.1-nano
</details>

## Review notes

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

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

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

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

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-29 15:39:30 +00:00
Michael Suchacz d1f308d9f3 feat: let organization members turn off organization skills in chats (#31134)
## Stack

Organization skills load into every member's Coder Agents chats in their
organization, with no way for a member to opt out. This stack adds a
per-organization setting that lets members turn them off for their own
chats, bottom to top:

1. **#31134** data model, API, and chatd (this PR)
2. #31135 admin and member controls in the dashboard, the `/` menu, and
docs

## What changes

Organizations get `members_can_disable_skills`, off by default. Users
who can update organization skills change it with `PUT
/api/experimental/organizations/{organization}/skill-settings`, which
writes an organization audit entry. Anyone who can read the organization
can `GET` it.

While the setting is on, each member saves their own choices with `PATCH
/api/experimental/organizations/{organization}/members/{user}/skill-preferences`:
`all_skills_disabled` (a master switch that also covers skills created
later) and `skills`, a sparse map from skill ID to on or off. `GET`
returns the setting, the master switch, and `disabled_skill_ids`. The
routes follow the personal-settings rules: without `read_personal` or
`update_personal` on that user the caller gets 404, a PATCH while the
setting is off gets 403, and a key that is not an organization skill
that member can read gets a 400 that names the key. The check runs as
the member, not the caller, so an owner or user admin editing someone
else's choices is held to that member's skills. Turning the setting off
keeps the choices but ignores them.

Migration 000636 adds the column and two tables keyed by organization
membership. Both cascade when the membership goes away, and the
per-skill table also cascades when the skill is deleted, so a recreated
skill loads by default.

chatd reads the preferences as the chat owner when it builds the skill
index and when it loads a body for `read_skill` or for a structured
skill invocation (#30861). A skill the member turned off is left out of
the index, and both loads report it as not found, including later in a
running chat. If the preferences cannot be read, turn preparation fails,
as it already does when the skill metadata cannot be read.

Older migration tests created organizations with `dbgen.Organization`
and `GetDefaultOrganization`, which now select the new column before it
exists, so they insert organizations with raw SQL instead.

## Review focus

- Authorization in `coderd/organizationskillpreferences.go` and the five
new dbauthz methods (`read_personal` and `update_personal` on the user,
`organization_skill` update for the setting).
- `GetOrganizationSkillMemberPreferencesRow.Excludes` is the one rule
chatd applies; #31135 mirrors it in `activeOrganizationSkills`.

## Testing

- Go tests cover the queries and cascades, dbauthz, both routes
(including the audit diff and each 400 case), and chatd (index,
`read_skill`, skill invocations, master switch, a change during a chat).
Each new test fails with its code path removed.
- Remote dogfood UAT (10 scenarios, real model) passed on the pre-split
branch head `186c28d81ab`, which has the same code except the fix below.
It found one issue: two spellings of one skill ID with opposite values
stored a random result. The PATCH now rejects every aliased key with a
400. A second run on the stack's top head at the time, `718dd6d1bd1`,
passed: every aliased form returns 400 and stores nothing, and chats
leave out a skill the member turned off, including in `read_skill`.
- Polish and the test audit stayed inside the implementation diff. No
new dependencies.
- Rebased on main as one commit. The migration is now 000636, after
main's 000634 and 000635. Every organization skill load passes the chat
owner, including main's skill invocation path, so `/skill` invocations
honor the opt-out too. The model's skill index leaves out a skill that
is not model-invocable or that the member turned off. Apart from that,
the diff is unchanged.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-29 12:53:50 +00:00
Michael Suchacz 3697bb38ce feat!: choose the computer use model per organization (#31300)
> [!NOTE]
> Xum opened this PR for Mike (Coder agent). Mike reviews it before
merge.

Fixes CODAGT-1472.

Computer use now runs on a chat model that each organization picks.
Before, it ran a fixed model on the first enabled AI provider of a
deployment-wide provider type, sorted by name. On dogfood that
provider's key is rejected, so every computer use subagent failed.

## What changed

- **Setting.** A new `computer_use` organization model override, set in
the **Computer use** row of **Organization settings** on the Coder
Agents admin page. Without an override, computer use runs on the
organization's default model. If the chosen model is disabled, deleted,
or unusable for the chat owner, computer use falls back to the default
model, as other overrides do. It also falls back when the chosen model
moves to an AI provider that is not Anthropic or OpenAI, and the row
then says that the saved model is ignored.
- **API.** `PUT
/api/v2/organizations/{organization}/chats/model-overrides/computer_use`
returns 404 while the `chat-virtual-desktop` experiment is off, and 400
unless the model's AI provider type is Anthropic or OpenAI.
- **chatd.** The `computer_use` subagent runs on that model, and the
computer tool flavor follows the model's provider type. OpenAI computer
use always uses the Responses API, so a model that sets
`use_responses_api: false` gets a configuration error. When no usable
model exists, `computer_use` is unavailable, and the reason says whether
a saved computer use model was skipped and why the default model cannot
be used. The default model is read under the chat owner's model ACLs, as
chat turns do.
- **UI.** The row lists only enabled Anthropic and OpenAI models. A
warning icon with the tooltip "Make sure that the selected model
supports computer use." appears when the model in effect (the selected
one, or the default) is not on a curated list of canonical model IDs
known to accept the computer tool (`knownComputerUseModels` in
`knownModels/catalog.ts`, exact match only). It also appears when the
model's AI provider type is OpenAI and its **Use Responses API**
override is Off, because OpenAI computer use needs the Responses API.
The warning does not block saving. I built the list from a live probe on
2026-10-26 that sent each Anthropic and OpenAI model one request with
the computer tool.
- **Docs.** `virtual-desktop.md`, `models.md`, `organizations.md`, and
`architecture.md` describe the new setting, and chatd's
`ARCHITECTURE.md` describes the computer use model routing.

![The Computer use row with an uncurated model selected shows the
warning icon and its
tooltip](https://github.com/user-attachments/assets/3948d936-5d8f-4ff9-a6de-14094c154dc8)

![The Computer use model picker lists only Anthropic and OpenAI
models](https://github.com/user-attachments/assets/913cd4a0-3cdf-4e5d-b2f9-582b9fca999c)

## Breaking change

This removes the deployment-wide computer use provider setting
(`agents_computer_use_provider`), its experimental `GET`/`PUT
/api/experimental/chats/config/computer-use-provider` endpoints (shipped
since v2.35), the Virtual desktop settings card, and its audit field.
Migration 000635 deletes the stored value. After the upgrade, computer
use runs on each organization's default model until an admin picks a
computer use model. Computer use subagents created before the upgrade
keep the model they inherited from their parent chat, so a follow-up
message to one of them can fail; a new computer use subagent uses the
organization's computer use model. Telemetry now reports the
per-organization overrides instead of the provider, and `null` when it
cannot read them.

## Testing

- `make pre-commit` passes. `go test` passes for `./coderd/x/chatd/...`,
`./coderd/database/migrations/`, and the targeted coderd, telemetry,
dbauthz, enterprise audit, and codersdk tests. Vitest and the touched
Storybook stories pass.
- Each new Go test fails when its target behavior is removed from
production code.
- Remote dogfood UAT ran on an isolated Coder instance built from the PR
head, with real Anthropic and OpenAI models:
- 110234e: the row with the experiment on and off, the picker, the
warning icon cases, save and clear, the 400 for other provider types,
which model and computer tool each computer use subagent used
(Anthropic, OpenAI, default, and disabled override), a real desktop
session on an Anthropic and an OpenAI model, the unavailable reasons,
the upgrade through migration 000634, and the removed endpoints.
- 09ce818: an override whose model moved to an unsupported AI provider.
- 7925be9: the alert for a moved and a disabled override, and a computer
use subagent on an Anthropic model.
- 2a01eaf: the row, and computer use subagents on the override and on
the default model.
- 47f5bd1: the warning icon for an OpenAI model with **Use Responses
API** set to Off, On, and Default. With Off, a computer use subagent on
that model fails with a configuration error before any provider request.
With Default, it runs with the computer tool through the Responses API.
- 81d33b4: the unavailable reasons for a disabled override, a cleared
override, and missing credentials, and a computer use subagent on an
Anthropic override. This round found that the docs named the wrong
section of the model form for **Use Responses API**. aeb3d02 fixes that
step, and a re-read of the docs against the recorded UI passed.
2026-10-29 13:00:05 +01:00
Sas Swart eb38759fda feat: limit effective group resolution to an organization (#31119)
AI budget resolution searches all of a user's groups across every
organization. Whichever group wins determines the organization. #31120
needs to resolve inside a known organization, and it needs to know which
organization site-wide resolution picked.

Add an `organizationID uuid.NullUUID` argument to
`budget.ResolveUserAIBudget` and `budget.ResolveUserEffectiveGroup`.
When it is set, count only that organization's override, group budgets
and Everyone group. An organization that is unknown, deleted or that the
user is not a member of resolves to nothing. When it is null, resolve
exactly as before. Return the winning group's organization in
`budget.EffectiveGroup.OrganizationID`.

Read the override through a new resolution-only query,
`GetUserAIBudgetOverrideWithOrganization`, so that the CRUD query
`GetUserAIBudgetOverride` and the admin endpoints stay untouched. Add a
nullable `organization_id` filter to `GetHighestGroupAIBudgetByUser` and
`GetUserEveryoneFallbackGroup`.

Every caller passes null, so behaviour is unchanged. There is no
migration and no proto change.

Scoping to an organization can lift a limit: a user capped in org B has
no limit in org A if A has no budgets. AIGOV-711 intends this, and it
takes effect in #31120.

Part of AIGOV-715.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-29 12:14:34 +02:00
Spike Curtis a512a7f060 fix(coderd/nats): log embedded server messages with slog (#31013)
Route embedded NATS server logs through Coder's slog logger by
installing a `natsserver.Logger` adapter with `SetLoggerV2` before
starting the server. Add coverage for severity mapping, formatting,
startup logging, and debug filtering, and allow expected NATS errors in
the existing failure-path and teardown tests.

Refs GRU-98.

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

- Preserve the caller's logger fields and add the `server` logger name.
- Let slog filter debug output; leave protocol and system-account
tracing disabled to avoid logging message payloads.
- Map NATS fatal messages to slog `Critical` so adding logging does not
introduce process termination.
- Restrict test log allowances to the embedded server's expected errors
rather than ignoring all error logs.

</details>

Generated by Coder Agents on behalf of @spikecurtis.
2026-10-29 11:05:54 +01:00
Michael SuchaczandEthan Dickson f10eabbb0c fix: confine read_skill_file reads to the skill directory (#31462)
> Xum opened this PR for Mike.

`read_skill_file` checked the requested path lexically, then read
`<skill dir>/<path>` through the agent's general file reader, which
follows symlinks. A supporting file that is a symlink to a file outside
the skill directory returned that file's contents to the model.

The agent's `read-file` endpoint now accepts an optional `root`
parameter. With it, the agent opens `root` with Go's `os.OpenRoot`,
refuses it if `root` itself is a symlink, and opens the file with
`Root.Open`, which follows symlinks only while they stay beneath `root`
and refuses absolute symlinks. `os.Root` opens one path component at a
time relative to the directory it already holds and resolves each
symlink itself, so a file swapped for a symlink during the walk cannot
slip through. `codersdk` adds `AgentConn.ReadFileInRoot`, and
`read_skill_file` reads supporting files through it. Reads without
`root` are unchanged.

- Relative symlinks that never leave the skill directory still work.
Absolute symlinks, and links that climb out of the directory, are
refused. Refusal messages never name the link target.
- The agent refuses a `root` that is itself a symlink, because
`os.OpenRoot` follows it: a skill directory replaced with a symlink to
`/etc` would otherwise become `/etc`. It compares the opened directory
with an `Lstat` of `root`, so a swap between the two calls is also
refused. Symlinks in the parent directories of `root` still work.
- Agents older than this change reject the `root` parameter, so
`read_skill_file` fails closed in a workspace until it restarts with the
new agent.
- Not in this PR: the agent's `resolve-path` endpoint joins a relative
link target to the parent path before resolving the parent's own
symlinks, so it can return the wrong file. Plan path checks still use
it; skill reads no longer do.

Fixes CODAGT-1496

## Testing

- New tests: `TestReadFileInRoot` (handler, real symlinks),
`TestReadFileInRootSwap` (swaps `root` for a symlink while reads run),
`TestReadFileInRootRegularDirectory` (no symlinks, so it also runs on
Windows), `TestAgentConnReadFileInRoot` (SDK over tailnet against the
real handler), `TestReadSkillFileTool/AgentRefusalIsToolError`. The
refusal tests fail when the protection is removed (plain open instead of
`os.Root`, no check that `root` is not a symlink, SDK joining root and
path, or the tool dropping the agent error). Without the `root` check,
`TestReadFileInRootSwap` returned outside bytes in 45 of 500 reads.
- Remote dogfood UAT passed on 132c7bed66 with a real model: allowed
reads (including an in-skill directory symlink followed by `..`),
refused escapes with no outside bytes or target paths in errors, a
30-call symlink swap race with no outside bytes, and an old agent
failing closed. The merge base leaked `/etc/passwd` in the same setup.
Later commits change tests and docs, rewrite agent errors for the model,
and add the `root` symlink check. Unit tests cover those changes; the
UAT did not.
- Cleanup passes stayed inside the implementation diff: polish touched
only `skill_test.go`, and the test audit added only `agentconn_test.go`.
No new dependencies.

---------

Co-authored-by: Ethan Dickson <ethan@coder.com>
2026-10-29 10:18:54 +01:00
Callum Styan 2255794d65 feat: add response_size_bytes metric to chatd (#29816) 2026-10-28 18:35:20 -07:00
Michael Suchacz 7f6ce9c8ab test(coderd): stamp chat message fixtures with the current content version (#30996)
Chat prompt tests built most of their stored-message fixtures in the
legacy content format (`content_version` 0), so they exercised the
legacy decoder instead of the current one. This PR changes tests only:
it stamps those fixtures with `ContentVersionV1` and builds them with
`MarshalParts`, so they keep passing after the legacy decoder is removed
later in this stack. Tests of the version 0 decoder itself keep their
version 0 rows until the layers above remove that decoder.

**Why it is safe**

- `mustMarshalContent` and `mustMarshalToolResult` now build current
parts (`PartFromContent`, `ChatMessageToolResult`) and encode them with
`MarshalParts`, the production write path.
- `TestMixedFormatConversation` becomes
`TestConvertMessagesWithFiles_Conversation` and uses current-format rows
only.
- `TestParseContent_BackwardCompat` does not change. Migration 000434
stamped every existing row with version 0, so its six cases of
current-format parts in version 0 rows still cover the version 0
heuristics. #30998 moves those six cases to version 1 rows when it
removes that decoder.
- `TestProviderExecutedResult_LegacyToolRow` calls the legacy writers
(`MarshalContent`, `MarshalToolResult`) directly, so its
provider-executed tool row still goes through the legacy tool-row
decoder.
- `TestParseContent_ErrorPaths` runs its malformed-input cases on
version 1 rows, and runs the same input on version 0 rows of each role
(`v0/<role>/malformed_json`), so a version 0 parser that accepts
malformed content still fails the suite. #30998 deletes the version 0
cases with that decoder.
- I ran the 17 mutants listed below, each a `go test -overlay` edit of
the current decode and prompt-conversion code in `chatprompt.go`,
against the `chatprompt` and `db2sdk` tests on `main` and on this
branch. Every mutant `main` catches is still caught. Two more are caught
here: mutant 3, because
`TestParseContent_ErrorPaths/system/malformed_json` used to hit the
legacy system decoder, and mutant 14, by the new JSON `null` case of
`TestConvertMessagesWithFiles_NormalizesAssistantToolCallInput`. Mutants
4 and 8 survive those tests on both. The `chatd` test
`TestOrganizationSkillsFollowChatOwnerAccess` catches mutant 4, so 8 is
an existing gap.
- Mutants of the version 0 decoder fail on `main` and on this branch:
version 0 assistant or user rows always take the envelope path, their
current-format parts are dropped, legacy tool rows lose
`provider_executed`, or a version 0 parser accepts malformed JSON.
- With the version 0 case removed from `ParseContent` by an overlay,
only tests of version 0 rows fail. #30997 deletes them, except the six
`TestParseContent_BackwardCompat` cases, which #30998 moves, and the
version 0 cases of `TestParseContent_ErrorPaths`, which #30998 deletes.

<details>
<summary>The 17 mutants</summary>

1. `ParseContent` returns no parts for a V1 row.
2. V1 decoding skips NUL restoration (`decodeNulInParts`).
3. The V1 parse error says "decode" instead of "parse".
4. Tool error string extraction is off (`toolResultPartToMessagePart`).
Only a `chatd` test catches it.
5. Tool call input is dropped.
6. Tool call `ProviderExecuted` is dropped when reading.
7. Resolved file data is dropped.
8. The file media type fallback is dropped (`partsToMessageParts`).
Survives.
9. User file IDs are not collected for resolution.
10. Text provider metadata is dropped.
11. File reference text is replaced by the raw content.
12. System messages are dropped.
13. Tool call `ProviderExecuted` is dropped when writing
(`PartFromContent`).
14. `normalizeToolCallInput` keeps a JSON `null` input instead of `{}`.
Survives on `main` only.
15. Text tool result `ProviderExecuted` is dropped.
16. Tool result IDs are dropped.
17. Assistant file IDs are resolved like user file IDs.

</details>

**Review focus**

The rewritten conversation test in `chatprompt_test.go`. It checks the
same prompt shape as before, but every row is in the current format. In
the same file, `TestProviderExecutedResult_LegacyToolRow` keeps its
legacy rows, `TestParseContent_ErrorPaths` checks malformed input on
both content versions, and the input normalization table gains a JSON
`null` case. The other changed test files only switch fixtures to the
current format: `coderd/x/chatd/chatprompt/file_inline_test.go`
(+4/-16), `coderd/database/db2sdk/db2sdk_test.go` (+11/-13),
`coderd/x/chatd/message_conversion_test.go` (+3/-2) and
`coderd/x/chatd/quickgen_internal_test.go` (+1).

**Validation**

- `go test ./coderd/x/chatd/... ./coderd/database/db2sdk/ -count=1 -p 4
-parallel 4`: ok
- `go vet` on the touched packages and `golangci-lint run --fix=false
./coderd/x/chatd/chatprompt/...`: clean
- pre-commit hook: passed

**Stack**

This stack retires chatd compatibility paths for chat data that older
Coder versions stored.

1. #30996 stamp chat message fixtures with the current content version
(this PR)
2. #30997 drop tests of the legacy content codec
3. #30998 retire the V0 chat message content decoder
4. #31000 inline the model config provider identity
5. #31005 retire the `close_agent` tool alias

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-28 19:45:29 +00:00
Bobby Ho 0fd07754f5 fix(coderd/httpmw): anchor CSRF exemption patterns (#31125)
fix(httpmw): restrict CSRF exemptions to intended routes

CSRF exemptions used shell-style patterns evaluated as unanchored regexes,
allowing unintended cookie-authenticated routes to bypass protection.
This enabled CSRF against role-management routes containing `derp` and
dev container recreate/delete endpoints.

- Anchor exemptions to their intended routes or subtrees.
- Remove the broad workspace-agent exemption, duplicate first-user entry,
  and obsolete `/api/v2/scim` pattern.
- Preserve intended exemptions and requests without session cookies,
  keeping agents, proxies, provisioners, and SCIM providers unaffected.
- Add regression tests for unintended matches, legitimate exemptions,
  requests without session cookies, and rejection of a cross-origin
  request to a formerly exempt route.

Validation: `go test ./coderd/httpmw/ -count=1`, `go vet`, and
`golangci-lint run ./coderd/httpmw/...` pass.

Backports: Omit the doubled-leading-slash test on branches without #29798.

Refs [PLAT-733](https://linear.app/codercom/issue/PLAT-733)
2026-10-28 11:16:55 -07:00
eric-hughes-coder bb8912dc46 fix: wait for full completion before asserting in tests (#30885)
Fixes the `TestServer_Metrics/Forwarding` flake reported in
[PLAT-609](https://linear.app/codercom/issue/PLAT-609/flake-testserver-metricsforwarding)
and, in addition, other defects similar to it.

## Testing defects

### The Original

`TestServer_Metrics/Forwarding` waited for `batches_dropped_total` and
then asserted on `logs_dropped_total`. The forwarder updates those two
counters separately, on adjacent lines, so a read between them sees the
first updated and the second not. CI caught exactly that window:
expected 2, actual 0 at `proxy_test.go:780`. Each counter is atomic on
its own, so the race detector reports nothing.

### The Additional

The fallacy of the original is a _de facto_ assumption that sequential
updates are atomic as a group. The defect arose from not taking into
account that they are atomic individually. The test asserted before the
work was completed. A repo-wide sweep for related metrics written
together found similar mistakes in other tests:

- Live races: all three phases of `TestServer_Metrics/Forwarding` and
`TestServer_Metrics/BufferFull` in `agent/boundarylogproxy`, and
`TestMetadataBatcher_DropsWhenFull`, which waited for the update channel
to empty although the final flush runs after that.
- Correct only because of the current implementation's ordering:
`TestMetrics_TokenUseCount` in `aibridge`, four tests in
`coderd/agentapi/metadatabatcher`, and `TestAgentStatsSessionCounts` in
`coderd/prometheusmetrics`. These pass today but would start failing if
the code under test reordered its work.

## Fixes

All tests the sweep found were fixed. Each test now waits for every
value it asserts before asserting it. Where a value is already non-zero
from earlier work, or legitimately zero, the wait is for the final value
rather than for a change, and several tests use
`require.EventuallyWithT` so the wait and the assertion are one step.
Two Forwarding phases gain assertions on values they already waited for:
`batches_dropped_total == 1` in phase 1, and the reporter's recorded
request count in phase 2.

Two phases of `TestAgentStatsSessionCounts` assert that the counts did
not change. No wait on an unchanged value can show that the collection
cycle ran, so they keep waiting on the execution histogram, and a
comment at that wait names the dependency.

Each fix was checked by temporarily blocking or reordering the code
under test between the relevant writes: the old test failed on every run
and the new one passed.

## Documentation

As a guard against recurrence of defects of this kind, we add the
following documentation targeted mostly at agents. The material in
`TESTING.md` provides guidance about how to write such a test correctly
in the first place. That in `AGENT_FAILURES.md` describes how to
recognize the symptoms of this class of test failure, should they arise.

- `.claude/docs/TESTING.md`: new section "Wait for Full Completion
before Asserting", covering waits on one value with assertions on
another, Prometheus metrics in particular, and assertions that nothing
changed.
- `.claude/docs/AGENT_FAILURES.md`: a catalog entry for the symptom.
- `coderd/coderdtest/promhelp`: doc comments noting that each helper
call is a separate gather.

Generated with Claude Code under the direction of @eric-hughes-coder.
2026-10-28 09:17:10 -06:00
eric-hughes-coder 296da93f6b fix(coderd/idpsync): Group sync may only add users to groups of the syncing org (#30706)
Group sync settings can contain group IDs that belong to another
organization or that no longer exist. At login, `SyncGroups` passed
mapped IDs straight through to `InsertUserGroupsByID`, which has no
organization filter, so the settings for one organization could cause a
user to be added to a group in a different organization.
  
`SyncGroups` now partitions each organization's expected groups with
`PartitionOutInvalidSettings` and only syncs those
inside the organization. Groups in another organization, and IDs that
match no group, are dropped and reported with one
  warning per kind. Login and the rest of the sync proceed.
  
Generated by Claude Code under the direction of @eric-hughes-coder.
2026-10-28 09:13:17 -06:00
Sas Swart 161b7233d9 feat(coderd): store the organization on AI Gateway interceptions (#31118)
Adds `organization_id` (FK to `organizations`, `ON DELETE RESTRICT`) and
`organization_source` (new enum: `workspace`, `chatd`,
`effective_group`) to `aibridge_interceptions`, with a check constraint
that keeps them set or unset together. Cost and pricing run later, in
`RecordTokenUsage`, so they need the organization that AIGOV-716a
resolves once per request stored on the interception row.

`RecordInterceptionRequest` gains `organization_id` (18) and
`organization_source` (19), and the aibridged API moves to v1.5.
`RecordInterception` stores a valid pair; any other combination is
logged as a warning and stored as NULLs, so a gateway bug never turns
into an HTTP 500 for the user. A well-formed ID for an organization that
does not exist fails on the FK, like an unknown `initiator_id`. Nothing
sends the fields yet, so behaviour is unchanged until AIGOV-716a.

**Malformed values are stored as empty, not rejected.** A failed
`RecordInterception` returns HTTP 500 to the user, so the server logs a
warning and stores NULLs instead. The one exception is a well-formed ID
for an organization that does not exist: the foreign key rejects it, the
same as an unknown `initiator_id` today.

Part of AIGOV-712

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-28 10:52:35 +02:00
Michael Suchacz 50b7c04398 refactor(coderd/x/chatd/chattest): drop write-only fake state and share the shape check (#30950)
The OpenAI and Anthropic fakes stored each request in a `request` field
under a mutex that nothing read, and kept the `httptest.Server` in a
field that only their constructors used. This PR deletes both fields,
the mutex and its lock blocks. It also merges the three copies of the
response-shape switch into one `responseShapeError` helper, and the two
copies of the OpenAI request decode into `decodeOpenAIRequest`.

**Why it is safe**

- Nothing read `request`, so dropping it and its mutex changes no
behavior.
- `responseShapeError` returns the same four strings, byte for byte, in
the same order. Each writer still checks `resp.Error` first, writes the
same plain-text 500 with `http.Error`, and keeps its own serializers.
The layer below pins the "both" and "empty" errors, and the existing
mismatch tests pin the other two: removing any case from the helper
fails one of them.
- `decodeOpenAIRequest` returns the read or decode error unwrapped, so
the 400 body is unchanged, and `handleResponses` still runs
`ValidateResponsesAPIInput` before the handler. It sets `RawBody` after
decoding, as both copies did, so the field comment no longer claims it
is set before.

**Review focus**

The writers now use `switch msg := responseShapeError(...); { case msg
!= "": ... }`, which leaves the streaming and non-streaming cases as
they were.

**Validation**

- `go test ./coderd/x/chatd/chattest/ -count=1`: ok before and after
- `go test -race ./coderd/x/chatd/chattest/ -count=1`: ok
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: ok before and
after
- `go vet ./coderd/x/chatd/chattest/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack makes the chattest fake tests fail on wrong output, then drops
the fakes' write-only state and shares their response-shape check.

1. #30948 table the OpenAI fake positive tests and fail on error streams
2. #30949 pin the fake response-shape errors
3. #30950 drop write-only fake state and share the shape check (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-28 00:03:54 +00:00
Michael Suchacz ae6013f9d5 refactor(coderd/x/chatd): extract the recording multipart parser and table its tests (#30954)
The bounded multipart loop in `stopAndStoreRecording` (part cap,
per-type size limits, the empty, duplicate and unknown-part skips, and
partial results on read errors) could only be tested through a
PostgreSQL-backed server and an agent mock. This PR moves the loop
unchanged into `readRecordingParts` and replaces five tests
(`TestStopAndStoreRecording_Oversized`, `_OversizedThumbnail`,
`_DuplicatePartsIgnored`, `_Empty` and `_UnknownPartIgnored`) with one
table test, `TestReadRecordingParts`, that streams parts through a pipe.

**Why it is safe**

- The loop body moves as is: same `maxParts`, limits, messages and skip
rules. The caller still reads parts only after the workspace lookup and
stores the video before the thumbnail. The kept
`TestStopAndStoreRecording_*` tests still cover storage.
- The table asserts exact video and thumbnail bytes for every case the
deleted tests covered. The unknown part now comes first, so it reaches
the unknown-type branch. New rows cover the part cap, a duplicate
thumbnail, video and thumbnail parts above the 1 MB unknown-type limit,
a video above the thumbnail limit, a thumbnail at exactly the thumbnail
limit, a read error and a canceled context.
- I ran 14 mutants of the guarded lines with `go test -overlay`: the
size check; each per-type limit raised by one or dropped, and the video
limit set to the thumbnail limit; the empty check; both duplicate
checks; the unknown-type branch; the part cap raised and lowered; the
context check; and the read-error branch. The deleted tests caught 2 and
the table catches all 14. Only `VideoAboveThumbnailLimit` catches the
video limit set to the thumbnail limit. Storage checks the file bytes,
so it rejected the deleted tests' zero-filled and empty fixtures whether
or not the parser accepted them.
- The latest commit adds `ThumbnailAtLimit`. With `go test -overlay`, it
catches two more mutants that the rest of the table misses: the size
check changed from `>` to `>=`, and the thumbnail limit lowered by one
byte. No row sends a video of exactly `workspacesdk.MaxRecordingSize`
bytes, because that needs another 100 MB part, so a video limit lowered
by one byte still passes.

**Review focus**

The `break` and `continue` paths now end at `return videoData,
thumbnailData` instead of falling into the storage code. The
canceled-context and read-error rows cover both.

**Validation**

- `go test ./coderd/x/chatd/ -run
'TestStopAndStoreRecording|TestWaitAgent|TestReadRecordingParts|TestRecordingBoundary'
-count=1 -p 4 -parallel 4`: ok, and ok with `-race`
- `go test -race ./coderd/x/chatd/ -run '^TestReadRecordingParts$'
-count=10`: ok
- `go vet ./coderd/x/chatd/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack moves the recording response parsing out of
`stopAndStoreRecording` into two functions with table tests, and drops
seven PostgreSQL-backed parse tests.

1. #30953 extract the recording boundary parser and table its tests
2. #30954 extract the recording multipart parser and table its tests
(this PR, +202/-277 in 2 files)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 23:10:37 +00:00
Michael Suchacz 9848c41100 test(coderd): run the advisor config tests on one server (#30986)
Folds the one-server `TestChatAdvisorConfig_*` tests in
`coderd/exp_chats_test.go` into one `TestChatAdvisorConfig`, whose
subtests share one coderd server. The advisor config tests start 2
servers instead of 10, and the file loses 23 lines. The PR changes only
tests.

**Why it is safe:** each old test is now a subtest with the same
assertions.

- Each subtest that changes the advisor configuration restores the
default (`{}`) in `t.Cleanup`, so no subtest depends on the ones before
it. The subtests also pass with `GetDefault` moved last and with the
whole order reversed (`go test -overlay`). Without the restore,
`GetDefault` fails when moved last.
- `TestChatAdvisorConfig_EnabledReflectsExperiment` stays a separate
test, because it needs its own deployment values.
- `RoundTripZeroValues` is dropped. Its four lines (write zero values,
read, check for no error, expect `{Enabled: true}`) are also in
`OverwriteClearsPreviousValues`.

Seven handler mutants (`go test -overlay` on `coderd/exp_chats.go`) fail
the old tests and the folded test, in the matching subtest: `GET`
inverting `enabled`, `PUT` without its authorization check, accepting
`-1` uses, dropping `max_output_tokens`, skipping a zero-value write,
`GET` ignoring corrupt JSON, and `GET` rejecting unknown JSON keys.

**Review focus:** the shared server. The subtests share one advisor
configuration row, so they do not call `t.Parallel()`, and the function
carries `//nolint:tparallel,paralleltest`, like
`TestChatOperationalSettingsAuditDeniedWrites`.

Validation: `go test ./coderd -run '^TestChatAdvisorConfig' -count=3
-race` passes, and the pre-commit hook passed.

## Stack

This stack removes the deprecated advisor config request fields, then
runs the advisor config tests on one server.

1. #30982 Remove the deprecated advisor config request fields
2. #30986 Run the advisor config tests on one server

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 22:51:08 +00:00
Michael Suchacz 3cc2861fc4 test(coderd/x/chatd/chattest): pin the fake response-shape errors (#30949)
No test reached the "handler returned both streaming and non-streaming
responses" and "handler returned empty response" branches of the
chattest fakes, and the next PR in the stack rewrites them. This PR adds
`TestFakeResponseShapeErrors`, which posts to the OpenAI
`/chat/completions`, OpenAI `/responses` and Anthropic `/v1/messages`
fakes with a handler that returns both response shapes or neither, and
checks the 500 status and the exact error body. It is the test-first
layer for that rewrite, so it adds 77 lines and deletes none.

**Why it is safe**

- Test only, and it passes on `main`.
- I deleted each of the six cases in turn with `go test -overlay`. Each
mutant fails exactly its own row, and the rest of the package still
passes on all six, so no other test covered these branches.

**Review focus**

The test sends plain `net/http` requests with a `{}` body, so it asserts
the fake's own output (`http.Error` writes the message and a newline)
with no provider SDK in between.

**Validation**

- `go test ./coderd/x/chatd/chattest/ -run TestFakeResponseShapeErrors
-count=1 -v`: all six rows pass
- `go vet ./coderd/x/chatd/chattest/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack makes the chattest fake tests fail on wrong output, then drops
the fakes' write-only state and shares their response-shape check.

1. #30948 table the OpenAI fake positive tests and fail on error streams
2. #30949 pin the fake response-shape errors (this PR)
3. #30950 drop write-only fake state and share the shape check

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 22:50:09 +00:00
Michael Suchacz b32aff6a5c test(coderd/x/chatd/chatprompt): table the media codec matrix in memory (#30946)
This PR finishes moving the tool result codec cases out of PostgreSQL.
`MediaResultCarriesPromotedAttachmentMetadata`,
`MediaResultUsesMatchingAttachmentMetadata` and `MediaResultWithText`
become rows of `TestMediaToolResultConversion`: `wantStored` pins the
persisted result JSON, and `wantMedia` pins Data, MediaType and Text.
`TestMediaToolResultRoundTrip` keeps one PostgreSQL round trip, for the
media tool pair, on a smaller fixture. The PR also deletes
`TestToolResultAntivenom/ValidMediaResultRoundTrips`, whose Data,
MediaType and Text checks `MediaResultWithText` covers through the full
conversion path. The malformed-input antivenom cases stay, because they
bypass storage on purpose.

**Why it is safe**

- Every moved assertion is kept, and the attachment rows now compare the
whole persisted JSON instead of four fields.
- #30945 lists the 24 mutants of `chatprompt.go` that I ran with `go
test -overlay` against the tests on `main`, on #30945 and on this PR.
They cover the media fields, media `ProviderExecuted` and `ToolCallID`,
attachment selection and mirroring, and the write-path flags. Every
mutant that `main` catches, this PR catches too.
- One gap is unchanged: no test on `main` or in this stack pins error
precedence when a result sets both IsError and IsMedia.
- The trimmed fixture drops only rows the remaining round trip does not
need (the org membership, the explicit chat provider, and unused message
and model fields).

**Review focus**

The `wantStored` literals for the two attachment rows, and the trimmed
database fixture.

**Validation**

- `go test ./coderd/x/chatd/chatprompt/ -count=1 -p 4 -parallel 4`: ok
on `main` and on this PR
- `go vet ./coderd/x/chatd/chatprompt/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack moves the tool result codec matrix out of PostgreSQL and keeps
one storage round trip.

1. #30945 table the text and error tool result rows in memory
2. #30946 table the media codec matrix in memory (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 22:49:11 +00:00
Michael Suchacz 7dee434315 test(coderd/x/chatd): fold taskTestFixture into workerTestFixture (#30924)
`taskTestFixture` in `tasks_test.go` repeated `workerTestFixture` field
for field, with the same seed rows, and carried its own copies of five
chat setup helpers, `publishChatUpdate` and two message builders. This
PR deletes the fixture and the copies and moves the 39 task, hook and
turn-trace tests that built it onto `workerTestFixture` and the shared
helpers. It also drops the fixture's API key row and the `apiKeyID`
parameter of `userTextMessage`, which nothing read.

**Why it is safe**

The copies differed from the shared helpers in two ways, and both are
kept:

- **Clearing the recorder.** The copies cleared the recording pubsub
after setup, and `interruptChat` cleared it before interrupting, so
assertions on published events see only what the code under test
published. `workerTestFixture.pubsub` is now that recorder (from the
layer below), and the shared helpers clear it at the same points. No
worker test reads the fixture recorder's events, so the extra clears do
not change them.
- **The deadline argument.** The task copy of `forceExecutionState` took
an explicit requires-action deadline. `forceExecutionStateWithDeadline`
takes it as a pointer (nil keeps the current one) for
`setRequiresActionDeadline` and the one call that cleared an expired
deadline. The other three callers passed an empty deadline for chats
that never had one, so they call `forceExecutionState`.

The rest of the move keeps the old behavior:

- `startRealTaskWorker` now starts from `testOptions`, which holds the
same values. It unsets the recording task starter so the worker builds
its real one, as before.
- No chatd code reads the fixture's API key. The synthetic gateway key
is looked up by its own token name.

After the change, `rg
'taskTestFixture|taskUserTextMessage|taskAssistantToolCallMessage|f\.apiKey'
coderd/ enterprise/` finds nothing.

**Review focus**

The `clear()` placement in `helpers_test.go`. Setup helpers clear when
they finish, and `interruptChat` clears before it runs.

**Validation**

Same commands as the layer below: the 142 top-level tests in the ten
files listed there, run from `go test -c ./coderd/x/chatd/` binaries
(plain and `-race`) with `-test.count=1 -test.parallel 4`.

| Head | Plain | `-race` |
|---|---|---|
| `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races |
| this PR | 142 passed | 142 passed, no data races |

The pre-commit hook passed.

**Stack**

The stack folds the task test fixture into the shared worker test
fixture.

1. #30923 reuse `recordingPubsub` in the task test fixture
2. #30924 fold `taskTestFixture` into `workerTestFixture` (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 22:48:18 +00:00
Garrett Delfosse b54f7de4c6 feat: graduate chat projects out of the chat-projects experiment (#31354) 2026-10-27 18:18:41 -04:00
Michael Suchacz 71cd5e67b3 chore!: remove the deprecated advisor config request fields (#30982)
Removes the two deprecated advisor model fields, `model_config_id` and
`reasoning_effort`, from `UpdateAdvisorConfigRequest`. It also removes
the `400` that `PUT /api/experimental/chats/config/advisor` returned
when a client still sent them, and the clamp of negative stored limits
in the matching `GET`. `make gen` drops the fields from
`site/src/api/typesGenerated.ts`.

**Behavior change, approved by Mike:** a `PUT` that still sends
`model_config_id` or `reasoning_effort` now succeeds, and the endpoint
ignores both fields, because `httpapi.Read` ignores unknown JSON fields.
Before, it failed with `400` and named `PUT
/api/v2/organizations/{organization}/chats/model-overrides/advisor`,
which has set the advisor model since #28442. Nothing in this repository
sends the fields: the settings page sends only the two limits, and no
CLI command uses the request type.

**Why removing the clamp is safe:** `putChatAdvisorConfig` is the only
production writer of `agents_advisor_config`, and it has rejected
negative limits since #24621 added the endpoint, in the same commit as
the clamp. No migration writes this key. So a stored limit is never
negative.

- Deleted tests: `TestChatAdvisorConfig_StaleModelWriteRejected` (the
removed `400`) and `TestChatAdvisorConfig_ClampsNegativeStoredValues`
(the removed clamp).
- `TestChatAdvisorConfig_IgnoresLegacyReasoningEffort` stays. Migration
000583 left old advisor blobs as they were, so upgraded databases can
still hold the legacy key, and the test covers how `GET` reads them.

**Review focus:** the behavior change, for any client outside this
repository that still sends the deprecated fields to this experimental
endpoint.

Validation: `go test ./coderd -run '^TestChatAdvisorConfig' -count=1`
passes (10 tests), `go vet ./coderd ./codersdk` is clean, and the
pre-commit hook passed (`make gen`, formatting, golangci-lint over every
package, and the slim build).

## Stack

This stack removes the deprecated advisor config request fields, then
runs the advisor config tests on one server.

1. #30982 Remove the deprecated advisor config request fields
2. #30986 Run the advisor config tests on one server

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:51:51 +00:00
Michael Suchacz 9ede7ceed6 refactor(coderd/x/chatd): extract the recording boundary parser and table its tests (#30953)
`stopAndStoreRecording` parsed the recording response's Content-Type
inline and logged through a local `warn` closure that copied three
recording fields into every call. This PR moves the parse into
`recordingBoundary`, replaces the closure with `p.logger.With(...)`, and
replaces the two PostgreSQL-backed tests
`TestStopAndStoreRecording_MalformedContentType` and `_MissingBoundary`
with a table test, `TestRecordingBoundary`. The layer above extracts the
multipart parts loop the same way.

**Why it is safe**

- Warning messages and fields are unchanged: `With` puts its fields
before the per-call fields, as the closure did. One log line changes:
the debug line "skipping unknown part content type" now also carries the
recording, parent chat and workspace IDs.
- The caller still checks the header before the workspace lookup and
returns an empty result on failure.
- The deleted tests checked only that the result was empty. With an
empty body, that result is the same whether or not the parse-error or
missing-boundary branch runs, so both tests passed when I disabled those
branches with `go test -overlay`. `TestRecordingBoundary` asserts the
boundary, the ok flag and the exact warning, and fails on both mutants.

**Review focus**

`if !ok { return result }` in `stopAndStoreRecording`. No test pins it.
Falling through on an empty body returns the same empty result; it
differs only in that it also runs the workspace lookup
(`GetWorkspaceByID`) and logs a second warning, `error reading next
multipart part`. So the line needs a reading check.

**Validation**

- `go test ./coderd/x/chatd/ -run
'TestStopAndStoreRecording|TestWaitAgent|TestRecordingBoundary' -count=1
-p 4 -parallel 4`: ok
- `go vet ./coderd/x/chatd/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack moves the recording response parsing out of
`stopAndStoreRecording` into two functions with table tests, and drops
seven PostgreSQL-backed parse tests.

1. #30953 extract the recording boundary parser and table its tests
(this PR)
2. #30954 extract the recording multipart parser and table its tests

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:51:11 +00:00
Michael Suchacz 8bafa8de62 test(coderd/x/chatd/chattest): table the OpenAI fake positive tests and fail on error streams (#30948)
The six OpenAI fake positive tests in `openai_test.go` become three
table tests, `TestOpenAI_StreamingText`, `TestOpenAI_NonStreamingText`
and `TestOpenAI_ToolCalls`, each with a Completions API row and a
Responses API row. The rows also check more than the old tests did:
streaming rows fail on any error part and assert the exact text deltas,
and non-streaming rows assert the returned text. The old Responses
streaming test passed on a stream that held only an error, and both
non-streaming tests checked only `NoError` and `NotNil`.

**Why it is safe**

- Every old assertion maps to a row: the exact deltas, one tool
execution, the follow-up request after it, `NoError` and `NotNil`.
- I ran 12 mutants of the fake with `go test -overlay`. Seven pass the
old test that targets the mutated behavior and fail the new rows: an
error-only Responses stream, an error part after the Completions text,
an error instead of `response.completed`, empty non-streaming text in
either format, and doubled or dropped Responses deltas. The other five
(an error-only Completions stream, doubled Completions deltas, a
truncated `OpenAITextChunks`, and a dropped tool call in either format)
fail both the old tests and the new rows.
- The fake is unchanged; the stronger checks pass on `main`.

**Review focus**

The Responses streaming row now uses the same two-choice text chunks as
the Completions row, so both formats share one expected delta list.

**Validation**

- `go test ./coderd/x/chatd/chattest/ -count=1`: ok
- `go vet ./coderd/x/chatd/chattest/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack makes the chattest fake tests fail on wrong output, then drops
the fakes' write-only state and shares their response-shape check.

1. #30948 table the OpenAI fake positive tests and fail on error streams
(this PR)
2. #30949 pin the fake response-shape errors
3. #30950 drop write-only fake state and share the shape check

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:50:33 +00:00
Michael Suchacz fa7ed93ffe test(coderd/x/chatd/chatprompt): table the text and error tool result rows in memory (#30945)
`TestMediaToolResultRoundTrip` wrote a chat and two messages to
PostgreSQL for every tool result codec case, although the read policy
under test (`toolResultPartToMessagePart`) is pure. This PR moves the
eight text-fallback and error cases into
`TestMediaToolResultConversion`, an in-memory table, and deletes their
database subtests: `TextResultStaysText`, `MissingMimeTypeStaysText`,
`MissingDataStaysText`, `ErrorResultStaysError`,
`NonMediaResultTypeStaysText` and the three `IsMediaTrueBut*` cases. The
table encodes the same assistant tool call and tool result with
`MarshalParts` and `CurrentContentVersion`, then runs
`ConvertMessagesWithFiles`. The layer above moves the media rows.

**Why it is safe**

- Every row keeps its assertions. Each row also gains checks for role,
part count, `ToolCallID` and `ProviderExecuted=false`, and text rows
compare the output to a literal with `JSONEq`. `ErrorResultStaysError`
compares the whole error message, and `IsMediaTrueButMissingMimeType`
carries valid base64, so it fails on the `mime_type` check itself rather
than in the base64 branch.
- I ran 24 mutants of `chatprompt.go` with `go test -overlay` against
the tests on `main`, on this PR and on #30946 (list below). Every mutant
that `main` catches, this PR catches too. Three that survive on `main`
fail here, and one (IsMedia winning over IsError) survives everywhere.

<details><summary>Mutants (main / this PR / #30946)</summary>

- Survive on `main`, caught here and in #30946: no `mime_type` check;
placeholder for every IsMedia text fallback; error-string extraction
disabled.
- Survives on all three: IsMedia wins over IsError.
- Caught on all three: IsMedia gate always on; gate always off; no data
check; unmarshal failure treated as media; error branch disabled; media
Text, MediaType or Data dropped; `ProviderExecuted` forced true for
media, text or error results; text or media `ToolCallID` dropped; base64
check skipped; first attachment chosen regardless of media type;
attachment file ID not mirrored; write path drops the media flag, the
error flag or the media text; error message replaced.
- A garbage copy of `chatprompt.go` fails to build under each overlay,
so the overlay applies.

</details>

**Review focus**

The shared assertions in the table loop. The rows also stop passing
through PostgreSQL, whose jsonb normalizes key order, whitespace, number
forms and escapes, so production decodes different bytes than these rows
feed in, with the same meaning. The deleted subtests and the new rows
both compare with `JSONEq`, and the round trip the stack keeps covers
media results only.

**Validation**

- `go test ./coderd/x/chatd/chatprompt/ -count=1 -p 4 -parallel 4`: ok
on `main` and on this PR
- `go vet ./coderd/x/chatd/chatprompt/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack moves the tool result codec matrix out of PostgreSQL and keeps
one storage round trip.

1. #30945 table the text and error tool result rows in memory (this PR)
2. #30946 table the media codec matrix in memory

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:49:53 +00:00
Michael Suchacz f0b6bf12ac test(coderd/x/chatd): reuse recordingPubsub in the task test fixture (#30923)
`tasks_test.go` kept its own copy of the recording pubsub,
`taskRecordingPubsub` (59 lines), next to `recordingPubsub` in
`helpers_test.go`. This PR adds the three things the copy had (`clear`,
a `published` snapshot and an `onPublish` hook) to `recordingPubsub`,
points the task fixture at it, and deletes the copy. The task fixture
now reaches the raw pubsub through the embedded field, so its `rawPS`
field goes too.

**Why it is safe**

- The added methods behave like the copy's: `onPublish` runs outside the
lock and before the inner `Publish`, `clear` drops the recorded events,
and `published` returns a copy taken under the lock. It replaces the
copy's `events()`, which would collide with the existing `events` field.
- `recordingPubsub` embeds the full `dbpubsub.Pubsub`, so subscriptions
reach the same inner pubsub the copy forwarded `SubscribeWithErr` to.
Servers built by the task helpers still get the raw pubsub.
- `watchEvents` is the existing `recordingPubsub` method. It filters the
same way the copy did, reading under the lock instead of from a
snapshot.
- After the change, `rg 'taskRecordingPubsub|taskPublishedEvent|rawPS'
coderd/` finds nothing.

**Review focus**

The turn-trace tests set `f.pubsub.onPublish` while holding
`f.pubsub.mu`. Both names are unchanged, and `Publish` still reads the
hook under that lock.

**Validation**

I built the package test binary with `go test -c ./coderd/x/chatd/` (and
with `-race`). Ten files use either fixture: `tasks_test.go`,
`hooks_internal_test.go`, `turn_trace_internal_test.go` and the seven
`workerTestFixture` files. I ran the 142 top-level tests in the ten
files with `-test.count=1 -test.parallel 4`.

| Head | Plain | `-race` |
|---|---|---|
| `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races |
| this PR | 142 passed | 142 passed, no data races |

The pre-commit hook passed.

**Stack**

The stack folds the task test fixture into the shared worker test
fixture.

1. #30923 reuse `recordingPubsub` in the task test fixture (this PR)
2. #30924 fold `taskTestFixture` into `workerTestFixture`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:49:14 +00:00
Michael Suchacz 36bccbf08b fix(coderd): reject overflowing workspace TTL values (#31329)
Workspace create and TTL update pass the requested `ttl_ms` to
`validWorkspaceTTLMillis`, which multiplied it by `time.Millisecond`
before it checked the bounds. Values outside the `int64` nanosecond
range wrapped around: `18446744133710` ms and `-18446744013709` ms both
became about one minute, so the API accepted them and stored a
one-minute TTL instead of returning a validation error.

The helper now rejects negative values with the minimum error and values
above 30 days with the maximum error before it converts to a
`time.Duration`. The maximum check compares whole minutes to match the
existing round down to the minute, so inputs that do not overflow keep
their current result.

Two new `TestWorkspaceUpdateTTL` rows send these values. Without the fix
both fail with `An error is expected but got nil.` (the endpoint returns
204); with the fix both get the expected validation error.

Related to #31036, which fixes the same overflow in the chat workspace
TTL setting.

> Xum, an AI agent, opened this PR for @ibetitsmike.
2026-10-27 20:48:30 +00:00
Michael Suchacz c8ed6f6cb2 test(coderd/x/chatd): assert the compaction debug run finishes (#31328)
Follow-up to #31087. `TestActiveServer_CompactionModelOverride` checked
only that the compaction debug run exists and records the override
model, so a regression that left the run `in_progress` still passed. The
four `summary routes to the override model` subtests now also assert
that the run's status is `completed` and that `finished_at` is set.

Mutation check, with `go test -p 2 -parallel 4 -count=1 -run
'^TestActiveServer_CompactionModelOverride$' ./coderd/x/chatd/`:
- Finalize timeout set to `time.Nanosecond` in `startCompactionDebugRun`
(`chatloop/compaction.go`), the mutant found in the #31087 review: the
old test passes all 13 subtests while it logs four `failed to finalize
debug run` warnings. With this change, the four routing subtests fail
with `expected: "completed"`, `actual: "in_progress"`.
- `finishDebugRun(err)` removed from the `generateCompactionSummary`
defer: the same four subtests fail in the same way.
- Production code restored: all 13 subtests pass, and the four routing
subtests also pass with `-count=5`.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:47:42 +00:00
Hugo Dutka a3fb196ce4 fix(coderd/x/chatd): replace interrupted ACP tool output (#31362)
When interruption arrives after `acp_wait_agent` publishes its result
but before the step commits, the model can receive the user's full
sub-agent transcript, including reasoning.

Keep a list of tools whose buffered output is replaced for the model on
interruption, initially `acp_wait_agent`. Preserve the transcript for
the user and give the model `{"error":"tool call was interrupted"}`. A
completed answer may need to be collected by calling the wait tool
again.

Alternative to #31345.
2026-10-27 19:31:51 +00:00
Michael Suchacz 7283fff69f fix(coderd/database/pubsub): close listener before waiting on latency probe (#31317) 2026-10-27 19:31:36 +01:00
Hugo Dutka 1a9d5b28ba fix: keep ACP harness context synchronized (#31351)
ACP harness resources bypass context drift detection, but only MCP
resources were live-synced into bound chats. Later ACP discoveries,
capability updates, probe errors, and removals could therefore leave
chat context stale without offering a refresh. Extend the existing
live-sync query to include ACP harnesses and publish context updates for
affected chats while keeping instructions and skills pinned.

Depends on #31350. This PR contains the ongoing synchronization change;
#31350 fixes initial probe ordering.
2026-10-27 18:28:16 +00:00
Michael Suchacz 2116682e61 fix(coderd): reject overflowing chat workspace TTL values (#31036)
`PUT /api/v2/chats/config/workspace-ttl` converted `workspace_ttl_ms` to
a `time.Duration` before it checked the 30-day maximum. A value whose
nanosecond count overflows `int64` wraps into range: `18446744133710` ms
becomes about one minute, passes both range checks, and is stored. This
PR checks the maximum on the millisecond value, before the conversion.

**Why it is safe:** for every value that does not overflow,
`req.WorkspaceTTLMillis > ttlMaximum.Milliseconds()` is the same test as
`d > ttlMaximum`, and it writes the same `400` message.
`TestChatWorkspaceTTL` already pins the boundary: exactly 30 days is
accepted and 721 hours is rejected. A mutant that rejects exactly 30
days fails it.

**Red test:** `TestChatWorkspaceTTL` now sends `18446744133710` ms and
expects a `400` and an unchanged stored value. On `main` the handler
accepts the value:

```text
coderd: PUT path=/api/v2/chats/config/workspace-ttl status_code=204
exp_chats_test.go:17412: Error: An error is expected but got nil.
--- FAIL: TestChatWorkspaceTTL
```

**Review focus:** the order of the checks. The maximum now runs on
milliseconds before the conversion; the one-minute minimum still runs on
the converted duration, which is safe once the maximum has passed.

#31018 moved this handler onto the shared `putChatOperationalSetting`
helper and kept the maximum check after the conversion, so the overflow
is still live on `main`. This branch merges `main` and moves that check
to the front of the handler's validation closure, next to the negative
check.

Validation: `go test ./coderd -run '^TestChatWorkspaceTTL$' -count=1`
fails against `main`'s handler as above and passes on this branch. On
this branch, `go test ./coderd -run
'^(TestChatPersonalModelOverridesAdminSettings|TestChatComputerUseProvider|TestChatDebugLoggingSettings|TestChatWorkspaceTTL|TestChatRetentionDays.*|TestChatDebugRetentionDays|TestChatAutoArchiveDays|TestAuditedChatOperationalSettingWrite.*|TestChatOperationalSettingsAuditDeniedWrites)$'
-count=1` passes (12 tests, 35 with subtests) and `go test
./enterprise/coderd -run '^TestChatOperationalSettingsAudit$' -count=1`
passes (17 with subtests). `go vet ./coderd/` is clean, and `make
pre-commit` passed (`make gen`, formatting, golangci-lint, slim build).

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 19:09:38 +01:00
Michael Suchacz 0b8d9135ae refactor(coderd): drop pass-through chat message conversion wrappers (#31023)
Deletes six helpers in `coderd/exp_chats.go` that only forwarded to
`db2sdk` or the store: `convertChatMessage`, `convertChatMessages`,
`convertChatQueuedMessage`, `convertChatQueuedMessagePtr`,
`convertChatQueuedMessages`, and `lookupEnabledChatModelConfigByID`.
Their callers now call `db2sdk.ChatMessage`,
`db2sdk.ChatQueuedMessages`, and `GetEnabledChatModelConfigByID`
directly, and convert message lists with `slice.List`. This includes the
`getChatAttachments` call site that #31140 added on `main`. It adds 9
lines and removes 47.

**Why it is safe:** each call site now runs the function the wrapper
called. `slice.List` and `db2sdk.ChatQueuedMessages` return an empty,
non-nil slice for no rows, as the wrappers did, so empty lists still
encode as `[]`. A repository-wide search finds no other references to
the deleted names.

**Review focus:** the two pointer results use
`new(db2sdk.ChatMessage(...))` and `new(db2sdk.ChatQueuedMessage(...))`,
the Go 1.26 form of `new` that takes an expression.
`coderd/provisionerdaemons.go` already uses it.

#29662 edits the same `ChatMessagesResponse` literal in
`getChatMessages`, so the two conflict in that one hunk.

Validation: on `main` and on this branch, `go test ./coderd -run
'^(TestPostChatMessages.*|TestGetChatMessages_.*|TestPatchChatMessage|TestChatMessageWithFile.*|TestDeleteChatQueuedMessage|TestPromoteChatQueuedMessage|TestQueuedMessageWithoutOverrideCapturesEnqueueTimeModel|TestSendMessage.*|TestSubsequentSendWithoutOverrideUsesPersistedModel|TestChatModelOverrides)$'
-count=1` passes (20 tests, 149 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 17:25:11 +01:00
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