mirror of
https://github.com/coder/coder.git
synced 2026-11-22 11:28:40 +08:00
34ef30ee90271258f18a080b008cc368f736ab80
4902
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
34ef30ee90 | fix: harden chat workspace file upload input validation (#30184) | ||
|
|
1aff810443 |
chore: sync fantasy with upstream v0.45.5 (#31288)
Moves the fantasy pin to the tip of `coder_2_33` (`85ffbbe`). That commit is coder/fantasy#72, which merges 87 upstream charmbracelet/fantasy commits, v0.40.0 to v0.45.5. Between the two pins 117 files change. Upstream's own v0.40.0 to v0.45.5 change, without tests, testdata, examples, `go.sum` and the kronk provider, is 43 files, +2271/−928. ## What reaches chatd chatd builds only the `anthropic`, `openai` and `openaicompat` fantasy clients (`chatprovider.ModelFromConfig`); other vendors reach it through the AI Gateway on one of those. So the upstream changes to the Google, Vercel, OpenRouter, Bedrock, Azure and kronk providers, and to the `fantasy.Agent` loop and its retries, do not run in chatd. These do: - **Chat Completions and openaicompat streams** keep reasoning on batched and DeepSeek-shaped chunks, keep `finish_reason: length` when tool calls are truncated, and stop sending empty reasoning fields. openaicompat drops assistant turns that hold only reasoning. - **Token usage.** When an OpenAI-shaped backend reports reasoning tokens apart from completion tokens (reasoning larger than output), output tokens now include them, so that backend's reported output tokens and cost rise. OpenAI's own shape, where reasoning is a subset, is unchanged. - **Responses.** A content-filtered turn no longer reads as a tool-call turn. - **Context overflow.** Baseten, Fireworks and Parasail prompt-length errors set `ContextTooLargeErr`, which compaction acts on. - **Anthropic.** Tool calls whose content block never closes are reported. For Claude 5 models, thinking defaults to `display: "summarized"` when the chat config sets none; a configured display still wins. `TestThinkingDropBlockModel_RetriesWithEffort` now expects the field in the retry body. - **Anthropic keepalives.** Fantasy forwards `message_start`, `message_delta` and unknown events as content-free `keepalive` parts. The first one arrives before any model output, so this PR makes `ttft_seconds` and the `time_to_first_token` stage skip them, as they skip warnings. They still reset the stream silence guard. `processStepStream` ignores them, and the debug recorder counts them in its part count but records no content. - **Tool-result media** now goes through upstream's shared `ToolRunBuffer`, which replaces coder/fantasy#64 and does the same thing. #72 keeps coder's anthropic-sdk-go and openai-go forks, Go 1.26 and kronk v1.31.5, so upstream's SDK and Go moves do not come along. `go mod tidy` raises the modules fantasy v0.45.5 requires, among them otel exporters v1.47, the AWS SDK, `google.golang.org/api` v0.307 and go-openapi v1. All are upgrades. The `go.mod` comment now names #72 as the upstream sync. coder/coder#29861 stacks on this PR to pin coder/fantasy#62. <details> <summary>Verification</summary> - `go build ./...`. - `go test` passes on every package that imports fantasy (`coderd/x/chatd/...`), and `go test ./coderd -run 'TestChat|TestExpChat|TestMCP|TestAIBridge'` passes. - `TestGuardedStreamTTFTStage/WarningsAndKeepalivesThenContentObservesOnce` fails without the TTFT change (TTFT observed 0s instead of 1s) and passes with it. - `make pre-commit` passes. The generated Prometheus docs pick up the metric help change. Not verified against live backends in this PR: the stream fixes, the token usage change and the context-overflow patterns have no coder test against a real provider. coder/fantasy#72 reports a local chatd run against the AI Gateway on Anthropic, Responses, OpenAI Chat and openaicompat. </details> > 🤖 This PR was created with the help of Coder Agents, and _will be_ reviewed by a human. 🏂🏻 |
||
|
|
a33af01605 |
refactor(coderd/x/chatd/chatloop): create the compaction debug run through StartRun (#31087)
Compaction was the last debug-run caller that did by hand what `chatdebug.Service.StartRun` does: insert the run on a detached context with a 5 second limit, rebuild the run context, and finalize it with `ClassifyError`. This PR moves `startCompactionDebugRun` onto `StartRun` and deletes `compactionDebugCreateRunTimeout`. #30934 moved the other callers; compaction waited for #30766, which has merged. **Why it is safe:** - The first commit changes only the test, renamed from `TestStartCompactionDebugRun_DoesNotReportDebugErrors` to `TestStartCompactionDebugRun`. It now asserts the whole inserted row: kind `compaction`, status `in_progress`, the parent run's root chat, parent chat and trigger message, the summary model's provider, model, model config and history tip when the caller sets them and the parent run's otherwise, and no summary. It also asserts the returned run context and the `completed` and `interrupted` finalize statuses. It passes on the old code and on the new code. - On the old code, 16 mutants (wrong kind or status, a dropped parent field, an ignored override or fallback, a seeded summary, a wrong run context field, a wrong finalize status) all fail the new test. Before this PR, the chatloop tests caught 1 of them and `TestActiveServer_CompactionModelOverride` 3 more (kind, model and model config); the other 12 passed both. On the new code, all 13 mutants of the `StartRun` call fail the test. - `StartRun` keeps the rest: a failed insert returns the caller's context and a no-op finalizer, the insert ignores the caller's cancellation, and the run still finalizes through `FinalizeRun` with its default 5 second limit. `TestService_StartRun` pins the first two. A nil seed summary still stores no summary, because `nullJSON` maps a nil map to SQL NULL. **Review focus:** log output. The old code discarded create and finalize errors. `StartRun` logs them at Warn as `failed to create debug run` and `failed to finalize debug run`, like the other callers. A debug failure still never fails compaction. Validation: - `go test -count=1 ./coderd/x/chatd/chatloop/...` passes, and so does `go test -race` on the compaction debug tests. - `go test -count=1 -p 2 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `go test -count=1 -parallel 4 -run 'Debug|Compact' ./coderd/x/chatd/`: the same 53 tests pass before and after. - `go vet` is clean on both packages, and the pre-commit hook, which runs `paralleltestctx`, passed on both commits. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
514f23979a |
feat: honor disable-model-invocation in skill frontmatter (#31147)
Extends #30882's `model_invocable` semantics to workspace skills and to stored skills created through the API. Claude Code and Xum let skill authors set `disable-model-invocation: true` in SKILL.md frontmatter, so agents never pick the skill on their own and it runs only when a person invokes it. Coder Agents honored the key only when someone imported a SKILL.md file while adding a project skill (#30884). ## What changes - **Workspace skills:** when the pinned SKILL.md sets the key to the YAML boolean `true`, chatd leaves the skill out of `<available-skills>` before merging sources, so a listed skill with the same name keeps its bare name, and `read_skill` reports it as not found. The skill stays in the `/` menu, and invoking it still loads its body. `read_skill_file` serves its supporting files under the bare name or `workspace/<name>` and refuses its `SKILL.md` (case-insensitive, after `path.Clean`). Skills without the key behave as on the base. - **Invoked workspace skills:** invoking a workspace skill now stores the pinned skill directory on the invocation part, and the prompt renders it as `dir` on `<invoked-skill>`, escaped as an attribute value. Before, only `read_skill` gave the model a skill's directory, and it refuses a hidden skill, so a hidden skill could not run the scripts it bundles. The part also stores the chat's workspace, and the prompt shows `dir` only while the chat stays bound to it, as it does for workspace file references. This changes #30861's invocation code. Hook payloads drop the directory and its workspace like the body, and API responses strip both. - **Stored skills:** a create request whose content sets the key and that omits `model_invocable` stores `model_invocable = false`. An explicit value wins, and PATCH is unchanged. This covers personal, organization, and project skills, which share `createSkill`. - `workspacesdk.SkillDisablesModelInvocation` reads the key. The `CreateSkillRequest.ModelInvocable` doc comment, the generated API docs, and `extending-agents.md` (the SKILL.md format, a new "Turn off automatic use" section, and the notes on the skill index, the skill tools, and aliases) describe the new behavior. ## Follow-ups - The personal and organization skill editors have no "Agents can use it automatically" switch yet. Only the project editor from #30884 has one. ## Testing - Go tests cover the parser, the turn's skill index and aliases, `read_skill`, `read_skill_file`, invocation of a hidden skill and the directory it carries (attribute escaping, no directory after the chat changes workspace, no directory in hook payloads), and the create default for personal and organization skills. Each new test fails when its code path is removed. - Remote dogfood UAT with a real model failed rounds 1 to 3. Rounds 1 and 2 found the hidden SKILL.md still readable through `read_skill_file` by symlinks and stale pins, plus a bare-name lookup bug and a docs gap that round 2 fixed. Round 3 found that the content check added against those bypasses refused a listed skill's file whose own frontmatter sets the key. After round 3 we narrowed the rule to the hidden skill's `SKILL.md` path. The key decides what agents are offered (the index and `read_skill`), not which files they can read: `read_file` and `execute` already open any workspace file, so a content check in `read_skill_file` protected nothing and kept producing edge cases. - Round 4 passed on `c9ff25dc29f`. Later commits added a behavior-neutral cleanup (`cd617533c2e`), one test case from the test audit (`044c1e6e23a`), and a comment fix (`9ec3768b18b`), which passed validation without another UAT round. Round 5 passed on `2b518c6c2b1`, which adds the skill directory. A real model ran hidden skills' scripts from the `dir` on `<invoked-skill>`, including directories whose paths contain `&`, `'`, `"`, `<` and `>`, and API responses carried no directory. Merging main after #30884 landed (`2d7d3cb9674`) did not change this PR's diff, so UAT was not rerun. `8f043b2a342`, which shows the directory only while the chat stays bound to the skill's workspace, has Go tests but no UAT round. - The doc-check skill ran in author self-check mode on `2d7d3cb9674`, and `27de7f5c6d7` fixes its findings: the skill index sentence said every skill is listed, the stored-skill sentence claimed any project editor import honors the key and presented the API default as fixed, the API path came before the UI path, and some wording broke the docs style rules. The fix is docs-only, so UAT was not rerun. - Polish and the test audit stayed inside the implementation diff. No new dependencies. - Codex review found no major issues on `9ec3768b18b`, then raised one P2 on the same head when the PR was marked ready: an invoked hidden skill gets no skill directory. A probe confirmed it, and `2b518c6c2b1` fixes it. Its earlier finding on that head (honor `CODER_AGENT_EXP_SKILL_META_FILE`) was refuted, because the pinned skill snapshot always reads `SKILL.md`. Both threads are resolved, and Codex found no major issues on `2b518c6c2b1` or on the merge `2d7d3cb9674`. - On `27de7f5c6d7`, Codex raised two P2s. One was confirmed: an invoked skill's directory stayed in the prompt after the chat moved to another workspace, which a prompt test showed on that head, and `8f043b2a342` fixes it. The other was declined: on Windows, `scripts\..\SKILL.md` gets past the `SKILL.md` check in `read_skill_file`, but that check is not an access boundary (`read_file` opens any path), and Windows has more aliases (`SKILL.md.`, `SKILL.md::$DATA`, `SKILL~1.MD`) that normalizing backslashes would not stop. On `8f043b2a342`, Codex asked to bind the directory to the workspace build instead. That was declined: every workspace start is a new build with new agent IDs, so the directory would drop after each stop and start, and the pinned body and the live files can diverge without a rebuild anyway, as they do for `read_skill`. A later request on that head asked to limit a hidden skill's `read_skill_file` access to invocations in the current workspace. That was declined too: `read_skill_file` resolves names against the current pin for listed skills on main as well, and the key decides which skills agents are offered, not which files they can read. All four threads are resolved. `a697dcd927f` adds the `format:"uuid"` tag that `TestSDKFieldsFormatted` requires on the new field, and Codex found no major issues on `a697dcd927f`. `ae70b2c533f` is docs-only: it applies the doc-check suggestion to say that an invoked skill's directory is included only while the chat stays in that workspace. The author doc-check self-check found no blocking findings on it, and Codex found no major issues on `ae70b2c533f`. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. --------- Co-authored-by: Jaayden Halko <jaayden.halko@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
1e0a481a60 |
fix: retry workspace quota commits with jittered backoff (#31207)
Bursts of builds for the same user and org (usually autostarts) can hit serialization failures in `CommitQuota`. `InTx` only retried those 3 times back-to-back, so once retries ran out the build failed outright. `CommitQuota` stays `SERIALIZABLE` and now gets up to 10 retries with full-jitter exponential backoff (50ms base, 2s cap, about 11s of backoff at most). These builds aren't interactive, so a longer wait is a better trade than a failed build. The wait respects the request context and happens between transactions, so nothing holds a connection while it sleeps. Each attempt also resets its results now, so a rolled-back attempt can't leak `Ok: true` into the response. The retry settings are opt-in fields on `database.TxOptions` (`SerialMaxAttempts` and `BeforeSerialRetry`). Every other `InTx` caller keeps the default 3 attempts with no delay. Since this touches `coderd/database/db.go`, it'll need a look from a `coderd/database` owner. This replaces #30126 with the simpler approach Spike and I landed on. If we still see failures after this ships, the next step is making autostart replica-aware so a single replica handles each user, rather than adding locking here. Fixes [CORE-198](https://linear.app/codercom/issue/CORE-198) |
||
|
|
7e9735c4ec |
refactor: share the session app fold rule and method derivation (#31028)
Ingest, the template insights API, and the Prometheus metric now use one rule to fold apps and one rule to derive each app's connection method. The method is derived from the app name, not stored. Every current reporter's app name implies its method. - Add codersdk.SessionAppMethod: reconnecting_pty and port_forwarding keep their own method, and every other app name is ssh. It replaces the private helper in coderd/insights.go. - Add codersdk.FoldUnregisteredSessionApps, the fold rule that GetTemplateInsights already applies in SQL. Registered apps, unknown, and overflow keep their entries, and so do the 64 busiest other apps. Ties break by app name in byte order, and the rest add up under overflow. - Ingest uses the shared rule instead of capSessionCounts. Registered apps and unknown no longer fold, and at most 64 unregistered app names keep their entries. Refs #31012, CLIENT-1062 |
||
|
|
e75885a37e |
feat: add ACP subagent waiting and transcript streaming (#30560)
Add `acp_wait_agent` to stream ACP transcripts, including reasoning and nested tool activity, to users while returning the subagent's text response to the parent model. Reconnect dropped streams from their transcript cursor, preserve running sessions on wait timeout or cancellation, and persist separate user-visible and model-visible results. Depends on #31022. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
8fd94eba27 |
feat: add tools to start, message, and interrupt ACP agents (#31022)
Add tools to spawn, message, and interrupt workspace-local ACP agents when the `chat-acp-subagents` experiment is enabled. Derive harness choices and configuration validation from the chat's pinned context, and deduplicate session creation and prompt submission across retries. Depends on #30831. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
457d777af1 |
fix(coderd/x/chatd/toolschema): traverse schema branches (#31128)
Tool input validation skipped properties declared inside composed schemas, allowing case-variant keys to bypass ambiguity checks. Traverse `anyOf`, `oneOf`, and `allOf` branches when checking nested objects, arrays, and free-form map values, while preserving exact property matches. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
9cda919eb1 |
test(coderd/x/chatd): fold the duplicate advisor scenarios (#30993)
Two end-to-end advisor scenarios repeated other tests. This PR moves their unique checks into tests that stay and deletes them. - `TestAdvisorGating_RootChat` replayed the advisor and `read_file` batch of the `mixed exclusive and local tools commit policy errors` subtest. Its exact two-call count moves into that subtest, which already checks that `read_file` never runs and both stored errors. Its check that the first request carries the advisor guidance moves into `TestAdvisorHappyPath_RootChat`; the `Root` row (#30990) checks the advisor tool and the guidance in the turn environment. - The `solo exclusive tool executes` subtest is a subset of `TestAdvisorHappyPath_RootChat`, which now also checks the stored advisor result. ### Why it is safe | Deleted assertion | Remaining check | | --- | --- | | Exactly two streamed calls | the mixed local subtest: `>= 2` became `== 2` | | Advisor offered | `Root` row (turn environment), and `TestAdvisorHappyPath_RootChat` now checks that the first request lists `advisor` | | Guidance in the first request | happy path test, new check | | Advisor and skipped tool errors sent back | the mixed local subtest (stored errors), `TestExclusiveToolPolicy_MixedBatchErrors` (text) | | Solo: stored result is not an error and holds the reply | happy path test, new checks | | Solo: three streamed calls | happy path test waits for the same three | | Mutant | Fails before | Fails after | | --- | --- | --- | | Exclusive batch check off | both mixed subtests, `RootChat` | both mixed subtests | | No exclusive tool set | both mixed subtests, `RootChat`, `Root` row | both mixed subtests, `Root` row | | Advisor runs, then the batch is rejected | `RootChat` only | the mixed local subtest | | Advisor result marked as an error | provider executed subtest, solo | provider executed subtest, happy path | | Advisor result replaced with `{}` | solo, happy path | happy path | | Guidance dropped from the request (`generation.go:898`) | `RootChat` only | happy path | Only an exact count sees the nested advisor call of the third mutant, so the count moves instead of going away. Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1 -p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that all runs at #30990 reach is also reached at #30993. The other differences are blocks that some runs of the same head reach and others miss, mostly error paths that depend on timing, so one run per head can show them as lost or gained. ### Review focus The subtest reads the count after the chat reaches `waiting`, and its fake model server counts only streamed requests, so title requests do not change it. ### Timing From 10 runs, the two deleted scenarios took 0.83 s summed (median per test). ### Validation - `go test ./coderd/x/chatd/ -run '^(TestActiveServer_ExclusiveToolPolicy|TestAdvisorHappyPath_RootChat)$' -count=10`, and with `-race -count=3`: pass - `go test ./coderd/x/chatd/...`: pass - `go test -overlay` mutant runs of the whole `./coderd/x/chatd/` package before and after this PR: results above - the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table 2. #30991 Remove the end-to-end advisor gating tests 3. #30992 Remove the end-to-end root and child tool list tests 4. #30993 Fold the duplicate advisor scenarios (this PR) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
c78ceccfaa |
test(coderd/x/chatd): remove end-to-end root and child tool list tests (#30992)
This PR deletes three end-to-end checks of model request tool lists (309 lines); the rows from #30990 check the same lists on the turn environment. The plan child tail also proved that a follow-up message without `PlanMode` keeps the stored plan mode. The plan rows of `TestBuildTurnEnvironmentToolPolicy` now send that follow-up and check the stored plan mode, so clearing it in `SendMessage` fails the table. - `TestSubagentChatExcludesWorkspaceProvisioningTools` booted coderd with a provisioner and AI Bridge to compare root and child tool names. - The plan child tail of `TestActiveServer_BasicAssistantGenerationAndPromptPreparation` checked `read_file` and `write_file`. Its only helper, `createPlanSubagentChatWithHistory`, goes too. - `TestPlanModeRootChatApprovedExternalMCPToolInvocation` is the first half of `TestPlanModeRootChatApprovedExternalMCPWorkflowCanReachProposePlan`, with the same three checks. ### Why it is safe Each mutant of `turn_environment.go` below failed the deleted check and fails the remaining one: | Deleted assertion | Remaining check | Mutant | | --- | --- | --- | | Root has the five workspace and five sub-agent tools | `Root` | root-only tools in no chat | | Standard root has no `ask_user_question` or `propose_plan` | `Root` | either tool added there | | Child has no workspace, sub-agent, or `ask_user_question` tools | `GeneralChild` | root-only tools or `ask_user_question` in children | | Plan child has `read_file` and no `write_file` | `PlanChild` | each flipped | | Plan root offers the approved MCP tool, ends `waiting`, and sends the result to the next call | the workflow test, and `PlanRoot` | approved MCP tools dropped | The split reads only `ParentChatID`, `Mode`, and `PlanMode` from the chat row (`turn_environment.go:258-261`), so a table child made with `chatstate.CreateChat` gets the tools of a `spawn_agent` child made with `chatstate.CreateChatWithID`. The `TestSpawnAgent_*` tests cover spawning. The deleted sub-agent test replied with an escaped NUL sequence but never checked the stored reply; `TestNulEscapeRoundTrip/BackslashU0000Text` covers that text. Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1 -p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that all runs at #30990 reach is also reached at #30993. The other differences are blocks that some runs of the same head reach and others miss, mostly error paths that depend on timing, so one run per head can show them as lost or gained. ### Timing From 10 runs, the two deleted tests took 1.14 s summed (median per test). The basic test went from 0.51 s to 0.41 s (median of 5). ### Validation - `go test -overlay` mutant runs of the whole `./coderd/x/chatd/` package before and after this PR: results above - `go vet ./coderd/x/chatd/`: clean; the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table 2. #30991 Remove the end-to-end advisor gating tests 3. #30992 Remove the end-to-end root and child tool list tests (this PR) 4. #30993 Fold the duplicate advisor scenarios > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
ac62f2e760 |
test(coderd/x/chatd): remove the end-to-end advisor gating tests (#30991)
`TestAdvisorGating_ExperimentDisabled`, `_ChildChat`, `_PlanMode`, and `_ExploreSubagent` each started Postgres, an active server, and a fake model server for one chat turn, only to check that the request had no advisor tool and, except for `_ExperimentDisabled`, no advisor guidance. The rows from #30990 check the same absence in the turn environment, so this PR deletes the four tests (353 lines). To keep one request-level check, `TestComputerUseSubagentToolsAndModel` now also checks that its child's first streamed request has no `advisor` tool and no guidance block. ### Why it is safe Each test guarded one condition of the advisor gate (`turn_environment.go:291`). Removing the condition failed the test and fails its row: | Deleted test | Its assertions | Row | Gate mutant | | --- | --- | --- | --- | | `_ExperimentDisabled` | No advisor tool with the experiment off and a stored config that says enabled | `RootAdvisorOff` (same config) | experiment check removed | | `_ChildChat` | No advisor tool or guidance in a chat with a parent | `GeneralChild`, the computer use test | root check removed | | `_PlanMode` | Same, in a plan mode root chat | `PlanRoot` | plan check removed | | `_ExploreSubagent` | Same, in an Explore chat | `ExploreRoot` | Explore check removed | The rows read the turn environment, not the request. A mutant that adds the guidance to every request (`generation.go:898`) failed `_ChildChat`, `_PlanMode`, and `_ExploreSubagent` and passes every row; it fails the computer use test. `_ExploreSubagent` made an Explore root chat (`isExploreSubagentMode` matches any Explore chat); `ExploreChild` also rejects the advisor. `_ExperimentDisabled` enabled every other known experiment, but the gate reads only `ExperimentChatAdvisor`. Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1 -p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that all runs at #30990 reach is also reached at #30993. The other differences are blocks that some runs of the same head reach and others miss, mostly error paths that depend on timing, so one run per head can show them as lost or gained. ### Timing From 10 runs, the four tests took 1.25 s summed (median per test). ### Validation - `go test -overlay` mutant runs of the whole `./coderd/x/chatd/` package before and after this PR: results above - `go test ./coderd/x/chatd/ -run '^TestComputerUseSubagentToolsAndModel$' -count=10`, and with `-race -count=3`: pass - `go vet ./coderd/x/chatd/`: clean; the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table 2. #30991 Remove the end-to-end advisor gating tests (this PR) 3. #30992 Remove the end-to-end root and child tool list tests 4. #30993 Fold the duplicate advisor scenarios > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
56fe6ec5e3 |
test(coderd): run the TestPostChats workspace, input, and MCP rejections on one server (#30976)
This PR moves the remaining 9 isolated rejection subtests of `TestPostChats` into the shared `Rejects` table from the previous PR: the 4 workspace cases, `EmptyText`, `UnsupportedPartType`, `RejectsInvalidReasoningEffort`, and the cross-org and third-org MCP server cases. Each one no longer starts its own coderd and AI Bridge daemon. `MCPServerIDsDisabledConfigRejected` keeps its own server: after the create rejection it sends a message on a chat it creates, which a single-request case cannot express. ### Why it is safe - Cases keep the old subtest names, callers, status, and message checks, and now also check the exact `Detail`. The reasoning-effort case compares the full detail instead of two substrings. - I mutated 12 lines in `postChats` and its workspace, input, effort, and MCP helpers and ran the old and new test files against each one. The old file caught 10 and the new file catches the same 10, each in the case that owns it, plus a detail-text mutant the old file missed. The one mutant both survive (reading the workspace as system) returns the same response from the SSH check. ### Review focus The workspace cases now run with the shared default model present. `postChats` rejects them before it resolves a model, so the model does not change their result. `EmptyText` and `UnsupportedPartType` run in an organization without a model, so they still prove that input is rejected before model resolution: moving the input check after it fails both. The MCP cases add their configs to orgs that no other case reads, or to the default org with `default_off`, where no other case passes MCP IDs. ### Timing From 5 alternating runs, the moved subtests took 2.83 s summed (median); their 9 cases take 0.27 s on the shared server. For the whole stack, `go test` reports 1.96 s instead of 3.19 s for the package. ### Validation - `go test ./coderd -run '^TestPostChats$' -count=3`: pass - the same run with `-race`: pass - `go test -overlay` mutant runs against the old and new test files: results above - `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the pre-commit hook passed ### Stack The stack runs every isolated `TestPostChats` rejection case on one shared server instead of one server per case. 1. #30975 Model and organization rejection cases 2. #30976 Workspace, request input, and MCP server rejection cases (this PR) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
f34aaeb017 |
test(coderd): share one server across the chat child archive tests (#30956)
Merges `TestPatchChatArchiveChildRejected`, `TestPatchChatUnarchiveChildRejected`, and `TestPatchChatArchiveRootRollsBackWhenChildCannotArchive` in `coderd/exp_chats_chatstate_test.go` into `TestPatchChatChildArchive`. Each old test started its own coderd server and built the same root and child family. The new subtests share one server and a `createFamily` helper that takes the child statuses, and each subtest still builds its own family. The file starts 11 coderd servers instead of 13. **Why it is safe:** each subtest makes the same requests and the same status and archive-state assertions as the test it replaces. With the old tests compiled back in through `go test -overlay`, both production mutants failed the old tests that guarded the line and the subtests that replace them: | Mutant | Failed, old and new | |---|---| | a child archive or unarchive returns 409 instead of 400 | `ArchiveChildRejected`, `UnarchiveChildRejected` | | the family cascade ignores a child's `SetArchived` error | `RootArchiveRollsBackWhenChildCannotArchive` | **Review focus:** the subtests share a server, user, and model config. Each one builds its own root and children and checks only those rows, and `withChatWorkerDisabled` stays on. **Timing** (`-count=1 -v -p 4 -parallel 4`, median of 5 paired runs on a shared host): the three old tests took 1.4 s summed. The new test takes 0.5 s. **Validation:** - `go test ./coderd -run '^TestPatchChatChildArchive$' -count=10`: pass - the same run with `-race -count=3`: pass - `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the pre-commit hook passed **Stack:** these two PRs share coderd servers across the copy-pasted chatstate endpoint tests. 1. #30941: queue and invalid-state tables 2. #30956 (this PR): child archive tests on one server > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
300f73b05a |
test(coderd/x/chatd): cover advisor eligibility in the tool policy table (#30990)
`TestBuildTurnEnvironmentToolPolicy` ran every row with the advisor experiment off and had no general sub-agent row, so only end-to-end tests checked advisor eligibility and the tools that only root chats get. This PR adds those checks to the table and deletes nothing; the PRs above it delete the end-to-end tests. - The rows run on a server with `ExperimentChatAdvisor`; the new `RootAdvisorOff` row uses a second server without it. The stored advisor config says `Enabled: true`, which must not matter: the experiment is the only gate (`codersdk/chats.go:1277`). - `Root` now wants the advisor, its guidance, and the five workspace and five sub-agent tools, and rejects `propose_plan`. The new `GeneralChild` row rejects all of those and `ask_user_question`. The plan and Explore rows reject the advisor. - Every row checks the guidance and the exclusive tool set: only the advisor when the row wants it, otherwise empty. ### Why it is safe The rows pass on `main` (`e53cfef8643`), which now includes #30911. Each of 15 mutants of `turn_environment.go` fails a row: | Mutant | Row that fails | | --- | --- | | Advisor gate ignores the experiment, the root check, plan mode, or Explore mode | `RootAdvisorOff`, `GeneralChild`, `PlanRoot`, `ExploreRoot` in that order | | No advisor guidance, no advisor tool, or no exclusive set | `Root` | | Root-only tools in every chat, or in none | `GeneralChild`, or `Root`, `RootAdvisorOff`, `PlanRoot` | | `ask_user_question` in standard root turns, or in child turns | `Root`, or `GeneralChild` | | `propose_plan` in every turn | `Root` | | Plan children get `write_file`, or plan turns drop `read_file` | `PlanChild` | | Plan turns drop approved MCP tools | `PlanRoot` | The deletion PRs above map each deleted assertion to these rows. Under the plan and Explore gate mutants, the plan filter and the Explore allowlist still drop the advisor tool, so those rows fail on the new guidance and exclusive set checks. ### Review focus Both servers are built once and never changed, and each row creates its own chat, so the rows stay parallel. ### Timing From 5 alternating runs, the table took 0.29 s (median) before this PR and 0.28 s after. ### Validation - `go test ./coderd/x/chatd/ -run '^TestBuildTurnEnvironmentToolPolicy$' -count=10`, and with `-race -count=3`: pass - `go test -overlay` mutant runs: results above - the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table (this PR) 2. #30991 Remove the end-to-end advisor gating tests 3. #30992 Remove the end-to-end root and child tool list tests 4. #30993 Fold the duplicate advisor scenarios > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
cfddedb95c |
test(coderd): run the TestPostChats model and org rejections on one server (#30975)
`TestPostChats` started a full coderd and AI Bridge daemon for each of its 34 subtests. This PR adds a `Rejects` table on one shared server and moves the 9 model and organization rejection subtests into it: the non-default org model cases, disabled, provider-disabled and denied model configs, `NilOrganizationID`, and `NonMemberOrganization`. Each case creates its own state in `prepare` and returns the caller. Four rejection subtests keep their own servers because they need or change state that the cases share: `MissingDefaultModelConfig` needs a default org with no model, `ProviderDisabledDefaultModelRejected` disables the default model's provider, `DeniedSameOrganizationDefaultIsRejected` adds a second default model to the org, and `AgentsAccessDefaultRole` rewrites org roles. ### Why it is safe - Cases keep the old subtest names, callers, status, and message checks, and now also check the exact `Detail` (empty where the old subtests did not check it). - I mutated 11 lines in `postChats` and its model helpers and ran the old and new test files against each one. The old file caught 8 and the new file catches the same 8, each in the case that owns it. The 3 mutants that both survive return the same response through another check: dbauthz hides other-org configs from members, and the provider status check repeats the provider-enabled check. ### Review focus Cases run in parallel against one deployment. Each case writes only to its own new orgs, users, providers, or non-default configs. No case changes the default model, its provider, or member roles. ### Timing From 5 alternating runs, the moved subtests took 3.12 s summed (median); the table setup plus its 9 cases take 0.59 s. ### Validation - `go test ./coderd -run '^TestPostChats$' -count=3`: pass - the same run with `-race`: pass - `go test -overlay` mutant runs against the old and new test files: results above - `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the pre-commit hook passed ### Stack The stack runs every isolated `TestPostChats` rejection case on one shared server instead of one server per case. 1. #30975 Model and organization rejection cases (this PR) 2. #30976 Workspace, request input, and MCP server rejection cases > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
5a1a0594c4 |
test(coderd): share one server across the chat message pagination tests (#30965)
`TestGetChatMessages_Pagination` started a coderd server with its own database in each of its ten leaves, although the leaves differ only in cursors and their own chat rows. This PR builds the client, database, owner, and chat model once in the parent. The six successful-page leaves become one table (options, expected ID positions, `HasMore`, queued count), and the two malformed `after_id` leaves become another. The transposed or equal cursor case and the burst walk stay separate subtests, and every subtest keeps its name. **Why it is safe:** every leaf still creates its own chat, messages, and queued message, and every request and query is scoped to that chat. No leaf changes users, roles, models, or deployment values. I ran 24 mutants of `getChatMessages` and its two paginated queries (limit+1 and `HasMore`, truncation, ASC dispatch, queued suppression, `after_id` parsing, the transposed check, cursor comparison, and ordering) against the old and the new test with `go test -overlay`. The new test fails on all 20 mutants that the old test fails on, in the same leaves. It also fails on the two mutants that drop the `chat_id` filter, which the old test missed because each leaf had its own database. Two mutants survive both tests: the DESC path fetching `limit` rows instead of `limit+1`, and `HasMore` using `>=`. No test on `main` covers them, and this PR does not add coverage. **Review focus:** the shared database interleaves message IDs across leaves. Assertions use only the IDs that each leaf's `seedChat` returned, so interleaving cannot change a result for a correct handler. `AfterIDAtOrAboveMaxReturnsEmpty` now seeds five messages instead of three, like the other page cases, and still sets `after_id` to the last ID. **Timing** (prebuilt test binaries, `-test.parallel 4`, median of 5 alternating runs on a shared host): binary wall time went from 1.21 s to 0.72 s. Leaf times summed went from 3.89 s to 0.39 s, plus 0.48 s for the one shared server, and coderd boots went from 10 to 1. **Validation:** - `go test ./coderd -run '^TestGetChatMessages_Pagination$' -count=10`: pass - the same run with `-race -count=2`: pass - `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the pre-commit hook passed > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
83cdc8e346 |
test(coderd): table the chatstate queue and invalid-state endpoint tests (#30941)
Replaces nine copy-pasted endpoint tests in `coderd/exp_chats_chatstate_test.go` with two table tests that each share one coderd server. `TestChatQueueEndpointErrors` turns the four queue delete and promote tests into rows. `TestInvalidChatStateEndpoints` turns the two shared invalid-state response tests into rows and holds the three reconcile cases as subtests. Every old case stays a parallel subtest with its own chat, and the file starts 13 coderd servers instead of 20. **Why it is safe:** each subtest sends the same request and makes the same assertions as the test it replaces. With the old tests compiled back in through `go test -overlay`, each of 10 production mutants failed exactly the old test that guarded the line and the subtest that replaces it: | Mutant | Failed, old and new | |---|---| | queue delete or promote returns 409 for an unknown ID, or 404 for an empty queue (4 mutants) | the matching `Missing` or `EmptyQueue` case | | send or tool results skip `writeChatInvalidState` (2 mutants) | the matching `ReturnsSharedResponse` case | | reconcile changes its not-invalid message | `ReconcileNotInvalidReturnsConflict` | | reconcile returns the old chat, or drops the default `last_error` (2 mutants) | `ReconcileSucceeds` | | the chat URL parameter maps a missing chat to 500 | `ReconcileNotFound` | **Review focus:** subtests now share a server, user, and model config. Each subtest creates its own chat and reads only that chat, and `withChatWorkerDisabled` stays on, so no worker moves a chat between steps. **Timing** (`-count=1 -v -p 4 -parallel 4`, median of 5 paired runs on a shared host): the nine old tests took 3.8 s summed. The two new tests take 0.9 s. **Validation:** - `go test ./coderd -run '^(TestChatQueueEndpointErrors|TestInvalidChatStateEndpoints)$' -count=10`: pass - the same run with `-race -count=3`: pass - `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the pre-commit hook passed **Stack:** these two PRs share coderd servers across the copy-pasted chatstate endpoint tests. 1. #30941 (this PR): queue and invalid-state tables 2. #30956: child archive tests on one server > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
cc51592c6f |
test(coderd): replace the plan-mode lock counterexample test (#30921)
Deletes `AuditConcurrentIdenticalPUTsDuplicateWithoutLock` and its test-only store `lockSwitchChatPlanModeInstructionsStore` from `TestChatPlanModeInstructions`. That test turned the advisory lock off inside the fake store and asserted the duplicate audit row that follows, so it checked the fake's schedule, not `putChatPlanModeInstructions`. The remaining positive test, `AuditConcurrentIdenticalPUTsSingleEntry`, now holds the per-setting lock until both PUTs wait on it, so it fails whenever the handler skips the lock or reads Old before taking it. **Why it is safe:** mutants of `putChatPlanModeInstructions`, run with `go test -overlay`: | Mutant | Deleted test on `main` | `SingleEntry` on `main` | `SingleEntry` after | `AuditLockFailureRejectsWrite` | |---|---|---|---|---| | `AcquireLock` call removed | passed 20 of 20 | failed 2 of 20 | failed 5 of 5 | failed 20 of 20 | | `AcquireLock` moved after the Old read | passed 20 of 20 | failed 2 of 20 | failed 10 of 10 | passed 20 of 20 | The deleted test passed on both mutants, so it guarded no handler line. On `main` the positive test caught a missing lock only when the two PUTs happened to overlap, and 8 or 16 concurrent PUTs did not raise that rate. With the lock held, it fails on every run of both mutants and passed 30 of 30 runs on the real handler, plus 5 under `-race`. The lock-holding pattern is the one in `coderd/experiments/write_test.go`. **Review focus:** the `pg_locks` wait counts every waiting advisory lock in the test database. This subtest creates no chats, so chatd never requests its admission or heartbeat locks, and the two PUTs are the only waiters. **Timing** (`-count=1 -v`, median of 5 paired runs on a shared host): the deleted subtest took 0.80 s. `SingleEntry` took 0.70 s before and 0.58 s after. The whole `TestChatPlanModeInstructions` took 7.0 s before and 5.0 s after, though host noise is larger than that gap. **Validation:** - `go test ./coderd -run '^TestChatPlanModeInstructions$' -count=1`: pass - `go test ./coderd -run '^TestChatPlanModeInstructions$/^(AuditConcurrentIdenticalPUTsSingleEntry|AuditLockFailureRejectsWrite)$' -count=30`: pass - the same `SingleEntry` run with `-race -count=5`: pass - `go vet ./coderd` and `golangci-lint run ./coderd/...`: clean; the pre-commit hook passed > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
4e4a56b665 |
fix: show configured provider icons and names in AI settings (#31033)
Admin-configured provider icons were ignored on the AI Settings Models
page (model rows, Add model menu, provider filter, model form header and
provider select) and in Agents compaction settings. These views derived
the icon only from the provider type, so a provider like DeepSeek on an
OpenAI-compatible type showed a generic icon even though the Providers
page and chat model selector showed the configured one. They now pass
the configured icon to `ProviderIcon`, which falls back to the type
icon.
The Spend page showed provider types (OpenAI) instead of configured
providers (DeepSeek) because `ListOrganizationAISpendUsers` aggregated
`ai.provider` while its filter matched `ai.provider_name`. It now
aggregates `provider_name`, and the page resolves names to display names
and icons from the AI Gateway providers list, which it shares with the
provider filter through one query. `OrganizationAISpendUser.providers`
now holds provider names; records from before configured names existed
have the type as their name, so they render as before.
AI Gateway Sessions views have the same type-versus-name issue and are
left for a separate fix.
**Note:** the Spend page resolves provider display names and icons from
`/aibridge/providers`, which requires deployment-wide read access
(`viewAnyAIBridgeInterception`). Owners and Auditors see the custom
display name and icon; Template Admins, User Admins, Org Admins, Org
Auditors and Org User Admins see the provider name rendered as a type
without the icon. Revisiting that endpoint's permissions is tracked in
AIGOV-726.
Refs CODAGT-1421
<details>
<summary>Decision log</summary>
- Root cause: callers rendered `<ProviderIcon provider={type} />`
without the descriptor's `icon`; nothing was stale.
- Spend page provider metadata is fetched only for viewers who can
already use the provider filter (`viewAnyAIBridgeInterception`); other
viewers see names formatted like provider types.
- Extended `ProvidersBadge` with an optional `providersByName` map
instead of adding a Spend-specific badge, so the Sessions fix can reuse
it.
- Removed `providerTypeByIDFromUserConfigs`, which became unused once
compaction settings used `providerInfoByIDFromUserConfigs`.
- Visual coverage is in Storybook stories (ModelRow, ModelForm,
UserCompactionThresholdSettings, SpendPage) per the repo's FE1 rule.
</details>
---
_Generated by Coder Agents on behalf of @tracyjohnsonux._
|
||
|
|
9fe52826da |
feat: send include_related from WorkspaceByOwnerAndName options (#29908)
Stacked on #29855. Wires `WorkspaceOptions.IncludeRelated` through `codersdk.Client.WorkspaceByOwnerAndName`. The method now applies `params.asRequestOption()` (matching `Client.Workspace`), so the `include_related` query parameter is sent to the server. Previously it only forwarded `include_deleted` and silently dropped `IncludeRelated`. - `include_deleted` behavior is unchanged: `asRequestOption` sets it when true; the server treats an omitted value the same as `false`. - Updated the `TemplateOnly` and `LatestBuildOnly` subtests of `TestWorkspaceByOwnerAndNameIncludeRelated` to drive narrowing through the SDK method and its options, exercising the wiring end to end. Option-level encoding is already covered by `TestWorkspaceOptionsAsRequestOption`. _This PR was created by Coder Agents on behalf of @spikecurtis._ |
||
|
|
15a5844253 |
feat: add cost to AI Gateway session threads API (#30509)
## Description
Exposes cost data on the AI Gateway session threads endpoint (`GET
/api/v2/aibridge/sessions/{session_id}`), so the session page can show
cost alongside token usage. Backend only, the UI changes for AIGOV-600
will follow separately.
## Changes
- Add `cost_micros` and `has_unpriced_usage` to
`AIBridgeSessionThreadsTokenUsage`, populated for the session summary,
each thread, and each agentic action.
- Compute the session summary cost in `ListAIBridgeSessions`, next to
the existing session token sums, so tokens and cost come from the same
rows.
- Add `priced_model`, the model and per-token prices used for pricing,
to `AIBridgeThread` for the root interception (the prompt) and to each
`AIBridgeAgenticAction` for that interception, since requests in a
thread may be priced as different models. Nil when not priced.
- Update frontend mocks for the new required fields.
Related to AIGOV-600
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
|
||
|
|
946c2f0e04 |
feat: resolve orgs from workspace session tokens in AI Gateway requests (#30902)
Add an AI Gateway org resolver at the coderd IsAuthorized boundary, detect workspace session tokens, load the workspace org, validate the user is still a member of that org, reject missing workspaces or invalid membership, and return the resolved org in IsAuthorizedResponse while leaving it unused by downstream policy. Include tests for successful workspace-token resolution, missing workspace rejection, invalid org membership rejection, and compatibility with the existing ServeHTTP flow. Fixes AIGOV-714 |
||
|
|
9f2389a908 |
refactor(coderd/x/chatd): derive the BYOK auth header from the AI Gateway client choice (#30979)
`fantasyConfigForAIBridge` picked the fantasy client for an AI Gateway route, and `aiGatewayRequestFormatForProviderType` mapped the same provider type and model again, only to choose `X-Api-Key` or `Authorization: Bearer` for a user's own key. This PR moves the client choice into `aibridgeClientProvider` and passes its result to `aiGatewayProviderAuthForUser`, so the header follows the client. It deletes the request-format enum, the mapper, the mapper's test, and the superseded `TestNewModelAttribution`. ## Why it is safe - `aibridgeClientProvider` is the old `fantasyConfigForAIBridge` switch without the base URL. `TestAIBridgeProviderFormatMapping` (12 rows, unchanged) still pins the client and base URL; the mapper test's 9 rows are a subset of them. - The mapper returned the Anthropic format for exactly the inputs that get the Anthropic client, so no header changes. `TestAIGatewayProviderAuthForUser` and the #30978 subtest pin the header. - `TestNewModelAttributionImmutablePerRequest` covers both workspace bindings that `TestNewModelAttribution` checked, plus the API key ID, also without a database. - Mutants through `go test -overlay` each fail a remaining test: every arm of `aibridgeClientProvider` and the base URL check; an auth switch keyed on `openai`, an auth case matching `openai-compat` instead of `anthropic`, and a dropped model ID at the `resolveAIGatewayRoute` call; the workspace check, the workspace ID copy, and an empty API key ID. A garbage copy fails to build, so the overlay applies. - `rg -n 'aiGatewayRequestFormat' .` finds nothing. ## Review focus Only the Anthropic client gets `X-Api-Key`; `openai` and `openai-compat` keep `Authorization: Bearer`, as the old default format gave them. Only the #30978 subtest catches an auth switch keyed on `openai`. ## Validation - `go test ./coderd/x/chatd/... -count=1 -p 4 -parallel 4`: pass. - 12 mutants: each fails a remaining test. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
707d373a76 |
test(coderd/x/chatd): cover BYOK header choice for Bedrock and OpenAI-compatible routes (#30978)
`TestResolveModelRouteForConfigAIGatewayProviderAuth` gains one subtest that pins which header carries a user's own provider key on two more routes: `X-Api-Key` for an Anthropic model on a Bedrock provider, and `Authorization: Bearer` for an OpenAI-compatible provider. The next layer rewrites how chatd picks that header, and until now no test failed when the call site dropped the model ID. This test-only layer is the characterization test for that rewrite, so it adds lines instead of removing them. ## Why it is needed - `resolveAIGatewayRoute` passes the model ID to `aiGatewayRequestFormatForProviderType`, and only the Bedrock arm reads it. A mutant that passes `""` instead passed all of `go test ./coderd/x/chatd/`: no chatd test resolved a BYOK route for a Bedrock provider, and `TestAIGatewayRequestFormatForProviderType` calls the classifier directly. - With this subtest, that mutant fails on the Bedrock row (`X-Api-Key` expected, `Authorization` sent). A mutant that maps the classifier's default arm to the Anthropic format fails on the OpenAI-compatible row. A garbage copy of `model_routing_aibridge.go` fails to build, so the `-overlay` applies. ## Review focus Today the OpenAI-compatible row takes the same default arm as the OpenAI `UserKey` subtest. The next layer keys the header on the client family (`anthropic`, `openai`, `openai-compat`), and this row fails if that switch matches only `openai`. ## Validation - `go test ./coderd/x/chatd/ -run '^TestResolveModelRouteForConfigAIGatewayProviderAuth$' -count=1`: pass. - Both mutants above, through `go test -overlay`: fail the new subtest. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
231537da8b |
refactor(coderd/x/chatd): drop transport branches only direct clients used (#30966)
`Model.AcceptsFilePartMediaType`, `BetaHeadersFromCallConfig`, and `chatopenai.TransportFor` still had branches for the Azure, Bedrock, Google, OpenRouter, and Vercel clients. Production has built none of those clients since #30929, so the branches never ran. This PR deletes them and their test rows. ## Why it is safe - `AcceptsFilePartMediaType` and `TransportFor` switch on the built client's `Provider()`, which is `anthropic`, `openai`, or `openai-compat` (see #30958). `BetaHeadersFromCallConfig` receives `anthropic` (`thinking_binding.go`) or the gateway's provider hint (`model_routing_aibridge.go`), which is one of the same three. - The deleted rows of `TestAcceptsFilePartMediaType`, `TestTransportFor`, and `TestBetaHeadersFromCallConfig` used the deleted provider names. The remaining rows fail on a mutant of each rewritten line: the Responses check in `TransportFor`, the provider check in `BetaHeadersFromCallConfig`, Anthropic `text/*` acceptance (what the Bedrock rows also checked), and the SVG rejection (`anthropic-svg` still checks what `google-svg` did). Garbage copies of both files fail to build, so the overlays apply. - `ToolResultMediaOmission` and `InlineImageCapBytes` keep their provider lists, because they read the configured provider behind the OpenAI-compatible client. ## Review focus Azure providers already reach the model through the OpenAI-compatible client, which always uses Chat Completions. The deleted Azure arm of `TransportFor` only described the direct Azure client. This PR also edits `coderd/x/chatd/ARCHITECTURE.md`, section "OpenAI transport selection": in the paragraph that began "Azure is deliberately exempt", "`TransportFor` has no Azure case, because" replaces the first two sentences and the opening "The exemption is narrower than it appears," of the third; the rest of that paragraph is unchanged. ## Validation - `go test ./coderd/x/chatd/chatprovider/... ./coderd/x/chatd/chatopenai/...`: pass. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - Mutants through `go test -overlay`: all 4 fail the named rows. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
17c7fe9632 |
refactor(coderd/x/chatd/chatprovider): drop provider options only direct clients read (#30958)
After #30929, `chatprovider` still converted Google, OpenRouter, and Vercel model-config options into fantasy provider options, and `applyReasoningEffort` still had Azure, Bedrock, Google, OpenRouter, and Vercel arms. No client that production builds reads any of them. This PR deletes the three option converters and those five effort arms. ## Why it is safe - `fantasyConfigForAIBridge` builds only the `anthropic`, `openai`, or `openai-compat` client, so `model.Provider()` never matched the deleted arms. - Each fantasy client reads only `ProviderOptions[<its own name>]` (chatd never renames the compat client), so the `google`, `openrouter`, and `vercel` entries were never sent. Pinned Gemini thinking still reaches Google through the compat `extra_body` path. - The deleted tests (`TestProviderOptionsForCall_GoogleThinkingConfig` and the Google, OpenRouter, and Vercel rows of `TestApplyReasoningEffort`) used those provider names, so they tested deleted code. The Gemini helpers they reached keep dedicated tests, which fail on mutants of the Gemini 3 version gate, the clamp comparison, the medium level mapping, the `GoogleThinkingLevelFromChat` normalization, and the compat `extra_body` assignment. - Two new cases close gaps the deleted rows left: `TestProviderOptionsForCall_GoogleThinkingConfigSkipsNonCompatClients` fails when the compat provider check becomes `!= ""`, and a pre-Gemini-3 `medium` row in `TestGoogleCompatReasoningEffort` fails when that arm returns `high`. Both mutants passed before. - The two Bedrock rows of `ClampsNoneForClaude55Models` now use the Anthropic transport with the same `global.anthropic.*` IDs, which the gateway sends to that transport. Changing `strings.Contains` to `strings.HasPrefix` in `anthropicReasoningEffort` fails them. - `rg -n 'googleProviderOptionsFromChatConfig|openRouterProviderOptionsFromChatConfig|vercelProviderOptionsFromChatConfig' .`: no matches. ## Review focus Chat debug runs record a lower `provider_option_count` for configs that set Google, OpenRouter, or Vercel options, because those unread entries are no longer built. ## Validation - `go test ./coderd/x/chatd/chatprovider/... ./coderd/x/chatd/chatopenai/...`: pass. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - Mutants through `go test -overlay`: all 11 fail the named tests, and garbage copies fail to build. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
cdc914108c |
refactor(coderd/x/chatd): drop the remaining direct provider clients (#30929)
After #30928, `chatprovider.ModelFromConfig` still built direct Azure, Google, OpenRouter, and Vercel clients. The AI Gateway path never asks for them, because `fantasyConfigForAIBridge` sends those provider types through the OpenAI-compatible client. This PR deletes those four arms and their missing-key error cases, the per-provider region plumbing that only the deleted Bedrock client read, and `ProviderAPIKeys.Empty`, which has no callers left. ## Why it is safe - The only production caller of `ModelFromConfig` passes a hint from `fantasyConfigForAIBridge` (see #30928), and no test builds these four clients. - Region flowed from `ConfiguredProvider.Region` through `ResolveUserProviderKeys` into `ProviderAPIKeys.RegionByProvider`, and only the Bedrock arm read it. The gateway reads Bedrock and Claude Platform regions from the provider settings itself (`aibridgedserver.go`). - `chatd.go` still marks Claude Platform on AWS as supporting ambient credentials. `TestResolveQuickgenModel_TitleGenerationOverrideAmbientCredentials` fails when that flag is forced to false. - `Empty` lost its last production caller when direct chat routing was removed (#26862). Its only test checked the region term. - Deleted tests (`TestProviderAPIKeysEmpty_RegionCountsAsConfigured`, `TestResolveUserProviderKeys_PreservesProviderRegions`, the `DisabledProviderRegionsRemoved` prune row) checked region and `Empty` code that is gone. One also checked that a keyless Bedrock provider is available; `TestResolveUserProviderKeys` still fails when the Bedrock ambient case or the empty-key rule in `setResolvedProviderAPIKey` is mutated. - `rg -n 'RegionByProvider|setRegion|keys\.Region\(|\.Empty\(\)' coderd/x/chatd` finds nothing. ## Review focus The `aiProviderConfigFromKeys` hunk in `chatd.go`, the only change outside `chatprovider`: it drops the region reads and keeps the ambient credential flag. ## Validation - `go test ./coderd/x/chatd/chatprovider/... ./coderd/x/chatd/chatopenai/...`: pass. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - `go build ./...` and `go vet` on every package that imports `chatprovider`: pass. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
766a0eb918 |
refactor(coderd/x/chatd/chatprovider): drop the direct Bedrock client (#30928)
`chatprovider.ModelFromConfig` builds the fantasy client for every chat
model call. Production reaches it only through the in-process AI
Gateway, where `fantasyConfigForAIBridge` asks for the Anthropic,
OpenAI, or OpenAI-compatible client, never Bedrock. This PR deletes the
direct Bedrock client that `ModelFromConfig` could still build,
`ProviderAllowsAmbientCredentials` and the API key bypass it fed, and
the tests that drove that client.
## Why it is safe
- Outside tests, `rg -n 'chatprovider\.ModelFromConfig\(' coderd
enterprise cli scaletest aibridge` finds one caller, `newLanguageModel`
in `model_routing_aibridge.go`. It passes the hint and placeholder key
from `fantasyConfigForAIBridge`, which sends Bedrock providers through
the Anthropic or OpenAI client by model ID. The gateway signs Bedrock
requests itself (`aibridge/intercept/awssig`).
- `ProviderAllowsAmbientCredentials` had one caller, the key check in
`ModelFromConfig`. The gateway path always sets the placeholder key, so
the check becomes `apiKey == ""`.
- The deleted tests (3 of 4 `TestModelFromConfig_Bedrock` subtests,
`...BedrockStripsAnthropicHeaders`, `...BedrockStreamingHeaders`,
`...BedrockBetaExtraHeader`, two helpers) each built the direct Bedrock
client, so they guarded deleted code.
- The OpenAI and Anthropic rows of the surviving subtest,
`NonBedrockStillRequiresAPIKey`, move into
`TestModelFromConfig_MissingAPIKey`. Its new `bedrock` row pins the
generic error message that a deleted subtest checked. These mutants all
fail it: no empty-key check, a changed generic message, a nil error from
the generic arm. A garbage copy of the file fails to build, so the
`-overlay` applies.
## Review focus
Ambient credentials still decide provider availability in
`ResolveUserProviderKeys`. Only the client-side bypass goes away.
## Validation
- `go test ./coderd/x/chatd/chatprovider/...
./coderd/x/chatd/chatopenai/...`: pass.
- `go test ./coderd/x/chatd/ -run
'AIBridge|AIGateway|Model|Provider|Bedrock|Quickgen|Title|Subagent' -p 4
-parallel 4`: pass.
- `make pre-commit`: pass.
## Stack
This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.
1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
9edb2e388d |
feat: enable Coder.USSpelling Vale rule (#30790)
Depends on #30782. Adds `Coder.USSpelling` at `warning` severity. The rule flags an `-ise` family (`organise`, `initialise`, `authorisation`) and a list of British spellings (`behaviour`, `labelled`, `cancelled`, `analogue`, `whilst`, and others) and suggests the US form. It covers `docs/**` except `docs/.style/style-guide/**` and the generated `docs/reference/{api,cli}/*.md` pages. Baseline: 13 findings before cleanup, 0 after. The first commit fixes 11 of them: 10 in hand-written pages and 1 in the Prometheus metrics table, which comes from metric help text. Two findings sit in generated reference pages, which `.vale.ini` excludes for this rule: the CLI alias `favourite` and `amongst` in a Go comment from a vendored dependency (the DERP map schema). The metric help text comes from `querymetrics.go`, so the fix lands there and in `generated_metrics` and `prometheus.md`. Known false positive: Vale doesn't skip bold text, so a UI label in bold that keeps British spelling is flagged. The rule comment and the guide footer say to use a code span for such a label. Linear: DOCS-1280 <details> <summary>Decision log</summary> - **Rule type**: `substitution`, so each message names the US form. The `-ise` family can't name a specific replacement, so it suggests "the -ize form". - **`cancelled`**: the guide's "Use US spelling" section lists `canceled` and `canceling`. The rule flags the double-l verb forms and leaves `cancellation` alone, which Merriam-Webster spells with one `l`. - **Exceptions**: Vale applies an exception to the matched word, so each is anchored with `^` and `$` and case-insensitive. The list covers `-wise` words and stems for `advise`, `advertise`, `exercise`, `promise`, `premise`, `compromise`, `surprise`, `comprise`, `concise`, `precise`, `revise`, `supervise`, `televise`, `devise`, `improvise`, `franchise`, `merchandise`, `disguise`, `despise`, `paradise`, `cruise`, `noise`, `raise`, `rise`, `wise`, and others, each with the endings `e`, `es`, `ed`, `ing`, `er`, and `ers`. The `mise` tool is excepted by name. - **Extra British spellings** beyond the guide table: other doubled-`l` verbs (`signalled`, `levelled`), `metre`, `litre`, `fibre`, `theatre`, `calibre`, `offence`, `pretence`, `analyse`, `judgement`, `acknowledgement`, `ageing`, `artefact`, `sceptic`, `aluminium`, `practise`, `enrol`, `fulfil`, `instil`, `skilful`. None appears in the corpus today. - **Generated pages**: excluded for `docs/reference/{api,cli}/*.md`, as `Coder.UnitSpacing` does. Changing the `favourite` alias would change CLI behavior, and the `amongst` comment isn't ours to edit. - **Prometheus doc**: edited by hand with matching table padding because `go run ./scripts/metricsdocgen` already rewrites the whole table on the base branch, independent of this change. Test cases, run with `vale --config` against fixtures that are not committed, in LF and CRLF: - Positive: `organise`, `initialise`, `authorise`, `customisation`, `authorisation`, `organisations`, `Organised`, `initialising`, `recogniser`, `customisable`, every explicit list entry, and capitalized forms. - Negative: `advise`, `exercise`, `otherwise`, `Enterprise`, `premise`, `compromise`, `promise`, `surprise`, `precise`, `concise`, `expertise`, `revising`, `supervising`, `improvising`, `raise`, `noise`, `cruise`, `franchise`, `merchandise`, `disguise`, `despise`, `paradise`, `appraise`, `sunrise`, `arise`, `liaise`, `clockwise`, `cancellation`, `canceled`, `mise`. - Skipped: words in code spans and fenced code blocks, such as `cancelled`. - LF and CRLF results are identical. Checks: `vale --output=line docs/` reports 0 `Coder.USSpelling` findings, `make lint/style-claims` passes, and the pre-commit hooks pass on both commits. </details> *Generated by [Coder Agents](https://coder.com/docs/ai-coder/agents) on behalf of @nickvigilante.* |
||
|
|
3c36790c86 |
fix(coderd/x/chatd): coalesce deltas when persisting interrupted turns (#29661)
An interrupted turn was stored with one ChatMessagePart per streamed delta, while a completed turn gets one part per block. One 28,539 character interrupted response became 3,987 parts and 1 MB of JSON, and a /messages page with such turns reached 11.7 MB. Whitespace-only deltas were separate parts too, and prompt replay skips whitespace-only parts, so words and paragraphs ran together in the next turn's prompt. Adjacent deltas of the same type are now joined into one part. A text run ends at another part type, a tool result or a narration change. A reasoning run ends where CreatedAt, the block's start time, changes. Adjacent text blocks still merge because text deltas have no block identity. Rows already stored are not rewritten. |
||
|
|
c4d76a4009 |
feat: add skill action and automatic-use settings (#30882)
Adds two per-skill settings that the project skills UI will expose next: - `action` marks a project skill to show as an action button above project chat composers. A `skills_action_project_only` check keeps it to project skills; the personal and organization routes reject `action` with 400. - `model_invocable` (default true, every stored source) controls automatic use. When it's false the skill is left out of `<available-skills>` and `read_skill` reports it as not found, but a structured skill invocation (a chip from the `/` menu or an action) still loads it, as long as the skill is enabled and the chat owner can read it. Workspace skills always count as model-invocable. Migration 000625 adds both columns with defaults, so existing skills keep today's behavior. The list, get, insert and update queries, `codersdk.SkillMetadata` and the create/update requests carry both fields, and the audit table tracks them. `coderd/x/chatd/ARCHITECTURE.md` gets TODO notes for the author. **NOTE**: the migration adds two columns with constant defaults and a CHECK constraint to `skills`. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 👈 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
9b8d880d63 |
fix: exempt service accounts from user dormancy (#30824)
Closes CODAGT-1344 The Slack bot for Coder Agents (CODAGT-1098) runs inside coderd and acts as a service account that an admin picks. It creates chats and sends messages as that account through Go calls, not HTTP requests. Two dormancy rules break it: 1. **New service accounts start dormant.** The CLI and the web "Create user" page send no status, and `InsertUser` falls back to `dormant`. So the bot's account is dormant from the start. 2. **Accounts go dormant after 90 days without a "last seen" update.** Only the API key middleware updates `last_seen_at`, and only on HTTP requests. The bot never sends any, so its account goes dormant on day 90, even if people use the bot every day. A chat owner must be active, so once the bot's account is dormant, every Slack mention fails. Any other in-process integration that acts as a service account has the same problem. Dormancy does nothing useful for service accounts: - It exists to free license seats, and service accounts never take a license seat (#24401, #27279). - It isn't a lock. Any API request activates a dormant account again. - System users already skip the dormancy job for the same reason. So this PR: - creates service accounts as active when the request doesn't set a status, - rejects an explicit dormant status for a service account with a 400, - skips service accounts in the dormancy job, the same way it already skips system users. Side effects: a service account that nobody uses for 90 days now stays active. That has no effect on license seats. If the account has ever sent traffic through AI Gateway, it also keeps its AI Governance seat until an admin suspends or deletes it. That matters less than it sounds: AI Governance is now included with Premium rather than sold per seat (#27545), so the seat only counts on a license that still has an AI Governance seat limit, and there it only feeds the seat-limit warning. The dormancy job also no longer writes "marked dormant" audit entries for service accounts. I've left existing dormant service accounts alone rather than adding a migration. An admin can activate one, and any API request from it activates it too. --- _This PR description was written by Coder Agents._ |
||
|
|
15a160aec9 |
feat: serve internal MCP servers to chats in process (#29828)
This lets coderd give a chat MCP tools that it serves itself, in process. The first user will be an in-process integration, say a Slack bot. Nothing uses it yet. coderd now takes a list of internal MCP servers when it's built, each with a slug and a `ServerForChat` function. At every step, chatd asks each one for a server for the chat and connects to it over an in-memory transport, so the server knows which chat it's serving without any headers. Nothing is stored on the chat, so the public API doesn't change, and the chat owner can't remove an internal server. As only coderd can add one, internal servers ignore the `chat-inline-mcp-servers` experiment and the `--disable-chat-caller-supplied-tools` kill switch. Their tools come straight after the built-in tools, so they win any name clash with admin, workspace or caller tools. Admin and workspace tools now follow the same first-wins rule, so the model never sees two tools with the same name. If `ServerForChat` returns an error, we fail the turn, as we do when any other read during turn setup fails. I've put this on top of #30730 and #30731 in the stack. It doesn't need anything from them, but the Slack bot needs all three. |
||
|
|
9d5f0cd3c0 |
refactor(coderd): share chat updates with in-process callers (#30731)
An in-process caller (say, a Slack bot) also needs to unarchive a chat before it sends to it, so this adds `api.UpdateChatAsUser` next to the send and interrupt functions from #30730. Like those, it's a Go method rather than an endpoint, and nothing calls it yet. It runs with the given user's own roles, so it can only do what that user could already do with `PATCH /api/v2/chats/{chat}`. Rather than a narrow unarchive helper, it shares the whole `PATCH` handler body. The handler validates every field before it applies any of them, so a narrow copy would just duplicate that logic. It writes the same audit entry as the endpoint, and the endpoint's behaviour doesn't change. |
||
|
|
d8a78b28fd |
refactor(coderd): share chat sends and interrupts with in-process callers (#30730)
This follows on from #30027, which added `api.CreateChatAsUser`, and does the same for sending a message to a chat and interrupting it. These aren't new endpoints, they're Go methods for code running inside coderd (say, a Slack bot) that needs to keep a conversation going in a chat it created, without an API key. Nothing calls them yet. We'll move the bodies of `POST /api/v2/chats/{chat}/messages` and `POST /api/v2/chats/{chat}/interrupt` into functions that both the handlers and `api.SendChatMessageAsUser` / `api.InterruptChatAsUser` call. The caller passes a user ID, and the call runs with that user's own roles, so it can't do anything that user couldn't already do over the API. The endpoints' behaviour doesn't change. |
||
|
|
837c2e1af1 |
feat(coderd): price token usage with organization prices (#30719)
Prices token usage by the most specific match: the organization's price for the configured provider, then a site-wide custom price, then the price book. The requested model is still preferred over the model the provider reports. - `GetAIModelPriceForProvider` replaces `GetAIModelPriceByProviderModel`, which is removed. It is one `UNION ALL` of primary-key lookups, ordered by requested model first, then by specificity. dbauthz checks `ResourceAiModelPrice`, scoped to the org when one is given. - `coderd/aibridge/prices` tests read seeded prices through `GetAIModelPrices`. Interceptions don't carry an organization yet, so `resolveTokenUsageCost` passes none and only site-wide prices apply at runtime for now (AIGOV-716). Org matching is covered by database tests with explicit org IDs. For the same reason, the unpriced-models report still counts only site-wide prices. **Used later:** prices set through the API in #30720 take effect here once interceptions carry an organization. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
da78c88100 |
feat(coderd): add queries for organization AI model prices (#30718)
Adds the store queries for organization AI model prices in `ai_model_configs`, with authorization. They cover basic CRUD on one price, keyed by `(organization_id, provider_id, model)`. - `GetOrganizationAIProviderModelPrice` reads one price. - `UpsertOrganizationAIProviderModelPrice` sets one price, with typed params. It rewrites an existing row only when a price differs, so `updated_at` records the last change. - `DeleteOrganizationAIProviderModelPrice` soft deletes one price. Reads and upserts only match live rows, so setting a price after a delete inserts a new live row. All three authorize against `ResourceAiModelPrice.InOrg(org)`. The new `AiModelPriceInOrg` case in `TestRolePermissions` pins that only owners and org admins pass. A TODO in dbauthz notes that this should become a resource for AI Governance model config. Each query has its own test. The upsert tests cover that identical prices leave `updated_at` unchanged, that changed prices advance it, and that an empty model is rejected. **Used later:** #30719 seeds its lookup tests with the upsert. #30720 serves all three through the org price API. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
30499fdcfa |
fix(coderd/aibridged): allow evicted bridges ten minutes to drain (#30830)
AI Gateway evicts cached request bridges after 15 minutes and currently gives in-flight requests only five seconds to finish, cutting off otherwise healthy model calls and streams. Give evicted bridges up to ten minutes to drain without changing the cache TTL. New acquisitions use a replacement bridge while the retired one drains. Pool shutdown retains a five-second cancellation grace period for cached and already-retired bridges, even when an acquisition is blocked initializing MCP connections. Requests still running at the drain deadline are cancelled. Refs [AIGOV-672](https://linear.app/codercom/issue/AIGOV-672/aibridged-15-minute-bridge-ttl-cancels-in-flight-ai-gateway-requests). The separate acquisition/admission race tracked in [AIGOV-609](https://linear.app/codercom/issue/AIGOV-609) is outside this change. --- Created by OpenCode on behalf of @dannykopping. |
||
|
|
04d7d4da9c |
chore: refresh AI model price book (#31162)
## Price book changes 26 models added, 8 models removed, 56 models changed. <details> <summary>Added</summary> - azure/deepseek-v4.1-flash - google/gemini-pro-latest - openrouter/deepseek/deepseek-v4.1-flash-1017 - openrouter/elorian/glimpse - openrouter/inception/mercury-3 - openrouter/meta/muse-spark-open - openrouter/minimax/minimax-m3.1-flash:free - openrouter/moondream/moondream3-preview - openrouter/moondream/moondream3.1-9b-a2b - openrouter/nvidia/nemotron-3.5-super-vl - openrouter/nvidia/nemotron-3.5-super-vl:free - openrouter/recursive/flint-v1.0:free - openrouter/reflection/beam-1.0-501b-a23b - openrouter/unbiased/pareto-26.10 - openrouter/xingchen-agi/xing4.0-29b-a4b:free - vercel/deepseek/deepseek-v4.1-flash-1017 - vercel/deepseek/deepseek-v4.1-flash-1017-fast - vercel/elorian/glimpse - vercel/inception/mercury-3 - vercel/meta/muse-spark-open - vercel/minimax/minimax-m3.1-flash - vercel/nvidia/nemotron-3.5-super-vl - vercel/reflection/beam - vercel/reflection/beam-free - vercel/scaledown/scaledown-extract-1 - vercel/scaledown/scaledown-summarize-1 </details> <details> <summary>Removed</summary> - openai/gpt-5.2-chat-latest - openai/gpt-5.3-chat-latest - openrouter/anthropic/claude-sonnet-4 - openrouter/deepseek/deepseek-r1 - openrouter/microsoft/wizardlm-2-8x22b - openrouter/sao10k/l3.3-euryale-70b - openrouter/unbiased/pareto-26.10-preview - vercel/anthropic/claude-sonnet-4 </details> <details> <summary>Changed</summary> - azure/gpt-5 - azure/gpt-5-codex - azure/gpt-5-mini - azure/gpt-5-nano - azure/gpt-5.2 - azure/gpt-5.6-sol - openrouter/deepseek/deepseek-chat - openrouter/deepseek/deepseek-v3.2 - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4.1-flash - openrouter/google/gemini-3.8-flash - openrouter/google/gemma-3-27b-it - openrouter/google/gemma-3-4b-it - openrouter/meta-llama/llama-3.2-3b-instruct - openrouter/meta-llama/llama-3.3-70b-instruct - openrouter/meta-llama/llama-4-scout - openrouter/mistralai/mistral-large-4-0 - openrouter/mistralai/mistral-small-3.2-24b-instruct - openrouter/moonshotai/kimi-k3 - openrouter/nvidia/nemotron-3-super-120b-a12b - openrouter/qwen/qwen3-30b-a3b-instruct-2507 - openrouter/qwen/qwen3-next-80b-a3b-instruct - openrouter/qwen/qwen3.5-122b-a10b - openrouter/qwen/qwen3.5-27b - openrouter/qwen/qwen3.5-35b-a3b - openrouter/qwen/qwen3.5-9b - openrouter/qwen/qwen3.6-27b - openrouter/qwen/qwen3.6-35b-a3b - openrouter/qwen/qwen3.8-27b - openrouter/stepfun/step-5-preview - openrouter/upstage/solar-pro4 - openrouter/xiaomi/mimo-v2.5 - openrouter/xiaomi/mimo-v2.5-pro - openrouter/z-ai/glm-4.6 - openrouter/z-ai/glm-4.7 - openrouter/z-ai/glm-5.1 - 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/~deepseek/deepseek-v4-flash-latest - openrouter/~moonshotai/kimi-latest - openrouter/~unbiased/pareto-latest - openrouter/~z-ai/glm-flash-latest - openrouter/~z-ai/glm-latest - vercel/arcee-ai/trinity-large-thinking - vercel/deepseek/deepseek-v4.1-flash - vercel/meta/llama-3.3-70b - vercel/meta/llama-4-maverick - vercel/meta/llama-4-scout - vercel/mistral/ministral-3b - vercel/mistral/ministral-8b - vercel/mistral/mistral-large-4 - vercel/stepfun/step-5-preview - vercel/xiaomi/mimo-v2.5 </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/39752842140). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
39c4bd6ced |
refactor(coderd/x/chatd): drop the unused runnerCtx from the runner debug turn (#31010)
Deletes `runnerDebugTurn.runnerCtx` and the context parameter of `newRunnerDebugTurn`. The field's only reader was the `LaunchRunHeartbeat` call in `ensureLocked`, which #30988 deleted with the run heartbeats, so nothing has read it since. **Why it is safe:** the constructor set the field and no code read it. The debug turn still uses the context of each call to `Ensure`, `Context` and `Finalize`, which this PR does not change. `runner.go` and 10 tests stop passing a context, and four of those tests drop the `context.WithCancel` that they created only for this parameter. Validation: - `go build ./coderd/x/chatd/...` and `go vet ./coderd/x/chatd/...` pass. - The 25 chatd debug-run tests, `TestRecordGenerationFinishFailure`, `TestSessionStartDispatchFailureFinishesGeneration` and `TestStartGeneration_CancelsDeletedToolCallsOnAgent` pass under `-race`. - `golangci-lint run --fix=false ./coderd/x/chatd/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. This PR: Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
98104d10fe |
chore(coderd/database): drop the chat debug stale-sweep indexes (#31009)
Drops `idx_chat_debug_runs_stale` and `idx_chat_debug_steps_stale`, the partial `updated_at` indexes that migration 000468 added for the `FinalizeStaleChatDebugRows` query. #30995 deleted that query, so nothing reads these indexes, but every debug run and step write still updates them. **Why it is safe:** no remaining query can use them. A partial index on `updated_at WHERE finished_at IS NULL` only serves queries that filter on `finished_at IS NULL`, and the one query that still does, the `locked_run` CTE in `InsertChatDebugStep`, finds the run by primary key. `DeleteOldChatDebugRuns` filters on `updated_at` alone and uses `idx_chat_debug_runs_updated_at` from migration 000487, which stays. The down migration recreates both indexes as 000468 defined them. **Review focus:** the migration number. 000632 follows `main`'s newest migration, 000631 from #31059. If `main` gains another migration first, this one moves to the next free number. Validation: - `make gen` changes only `dump.sql`, which loses the two `CREATE INDEX` lines. The renumber to 000632 leaves it unchanged. - `go test -count=1 ./coderd/database/migrations/` passes on this branch, where `main`'s 000631 and this 000632 both apply. The run includes `TestMigrate/UpDownUp` (every migration up, down and up again) and `TestMigrationChain`. - The pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. This PR: Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
e3657389bb |
refactor(coderd/x/chatd/chatdebug): delete the process-global step counters (#31008)
Deletes chatdebug's process-global step counters: the `stepCounters` and `runRefCounts` maps, `refCountMu`, `trackRunRef`, `releaseRunRef`, `nextStepNumber`, `syncStepCounter` and `CleanupStepCounter`, the `runtime.AddCleanup` hook that `ContextWithRun` registered for every run context, and the two `CleanupStepCounter` calls in `FinalizeRun`. Since #31007 the database numbers steps, so no production code reads them. **Why it is safe:** after #31007 no production code reads the counters. Production code only maintained them: `ContextWithRun` registered a reference for every run context and `FinalizeRun` called `CleanupStepCounter`, and this PR removes both. A search of `coderd/` and `enterprise/` for the deleted names finds nothing now. The deleted tests covered only the deleted code: `TestNextStepNumber_Concurrent` and `TestSyncStepCounter_AdvancesCounter` checked counter values, and the three garbage-collection tests in `context_internal_test.go` checked that a counter lives until the last `RunContext` for its run is collected. The 20 `t.Cleanup(func() { CleanupStepCounter(runID) })` lines go with them. `TestReuseStep_PreservesExistingHolder` and `TestBeginStepReuseStep` stay. The `FinalizeRun` doc comment no longer mentions the counter. **Review focus:** `ContextWithRun` is now a plain `context.WithValue`. Code that copies a `RunContext`, such as `runnerDebugTurn.contextLocked`, no longer affects anything, because no state is tied to the struct's lifetime. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `go test -count=1 -run Debug ./coderd/x/chatd/` (19 tests) passes, and the 25 chatd debug-run tests pass under `-race` (`go test -race -run '^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$' ./coderd/x/chatd/`). - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. This PR: Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
f69b98abfc |
fix(coderd): ignore retired OAuth2 scopes such as task:* (#31117)
Closes CODAGT-1422 After upgrading to v2.38, Coder Agents can't connect to Coder's own MCP server if its MCP server config was created before the upgrade. When an admin creates an OAuth2 MCP server config without any scopes, we save the authorization server's entire `scopes_supported` list and send it on every connect. Before v2.38 that list included the `task:*` scopes, which #28750 removed. Since #28178, `/oauth2/authorize` rejects the whole request if it names a scope outside the catalog, so connecting fails with: ``` 'task:*': unknown or unsupported scope ``` The issue suggests a migration that strips `task:*` from `mcp_server_configs`, but I don't think that's the right fix. We can't backport it to 2.38, as `main` already has migrations past the last one on `release/2.38`. A config with only `task:*` scopes would be left with none, and requesting no scope gets you `coder:all`. The column also holds scopes for third-party MCP servers. Any other OAuth2 client that cached the old `scopes_supported` would also stay broken, as would every client the next time we remove a scope. To fix, we'll retire removed scopes rather than delete them. There's now a small list of retired scope names next to the scope catalog, and the authorization server drops those names from a request and grants the rest. RFC 6749 §3.3 lets the server ignore part of the requested scope, and the token response already returns the scope that was issued. Names that were never in the catalog are still rejected, and so is a request of only retired names, so it can't widen into a broader default grant (e.g. `coder:all`). Existing configs then connect without anyone editing them. If we'd assumed from the start that scopes get removed, we'd have retired them rather than deleted them, and that's all this does. It fixes the cause rather than the one MCP config symptom, it's code only so it cherry-picks cleanly onto `release/2.38`, and the next removed scope just moves into the retired list. Third-party MCP servers that remove a scope will still break Agents the same way, since our MCP client saves the authorization server's `scopes_supported` instead of following the MCP spec's scope selection. I've left that for a follow-up. |
||
|
|
ffd24861a1 |
feat: send skill invocations as structured message parts (#30861)
Adds a structured `skill-invocation` chat part so a user message can carry an explicit skill. chatd loads that exact skill when the message is sent and puts its body into the user's prompt, so the skill always applies instead of relying on the model to notice it in `<available-skills>`. The composer chip that sends these parts comes in the next PR. - codersdk: a `skill-invocation` input part and message part with `skill_source` (`personal`, `org`, `project`, `workspace`) and `skill_name`. The resolved body is stored on the part as internal `skill_body`; it's hidden from TypeScript and stripped from every API response. - coderd rejects an unknown source or an invalid name with 400. - chatd resolves each invocation on create, send and edit with the chat owner's permissions, through the same loaders as `read_skill`: stored skills by source and name (project skills through the chat's project, with the root chat fallback for subagents) and workspace skills from the pinned context snapshot. The body is saved at send time so past turns show what the model received. A missing, disabled or unreadable skill rejects the send with 400 "Skill project/triage is not available." - The prompt renders a line saying the user invoked the skill, followed by `<invoked-skill name="project/triage">` with the sanitized body. Titles and hook prompt text show the invocation as `/project/triage`. - The site only gets no-op cases so the regenerated types compile. `coderd/x/chatd/ARCHITECTURE.md` gets a TODO for the author. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 👈 - #30880 - #30881 - #30882 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
cc66f30a19 |
fix(coderd/webpush): bound push response body read and add client timeout (#31129)
fix(webpush): bound response sizes and request duration Prevent push endpoints chosen by users from causing unbounded response buffering or indefinite waits. Cap response body reads at 64 KiB and configure the default HTTP client with a 64 KiB header limit and a 30-second timeout covering the full exchange, including body reads. Document that replacement clients passed to `WithHTTPClient` must set their own timeout. Add regression tests for endless success/error bodies, oversized headers, stalled servers, and the default client limits. Refs [PLAT-729](https://linear.app/codercom/issue/PLAT-729/security-fixcoderdwebpush-bound-response-body-read-and-add-client) |
||
|
|
c61d842b9c |
feat: show available ACP harnesses in chat context (#31059)
Expose discovered ACP harnesses in the chat context resource inventory when the `chat-acp-subagents` experiment is enabled, including configuration paths and resource status. Persist ACP harness resources from agent context snapshots and update the SDK and generated API types. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
3216580614 |
feat: load project skills in chats (#30838)
Chats that belong to a chat project now get the project's skills, next to personal, organization and workspace skills. They show up in the model's skill list, load through `read_skill`, and appear in a "Project skills" group in the `/` menu. - `coderd/x/skills` adds the `project` source. `MergeSkills` now takes a list of sources in merge order (personal, organization, project, workspace). Bare names stay bare unless two sources share a name, in which case they get `project/<name>` style aliases. - chatd loads project skills only when the chat owner owns the project or the project is shared with them. Role grants don't count. This is the same `usableChatProject` check that project instructions and memory use, and one check per turn covers both instructions and skills. Disabled skills are skipped. A failed load logs a warning and the turn continues without them. Subagents use their root chat's project; that lookup is now a helper shared with project instructions. - The site loads project skills for the composer on the project page and in project chats, behind the `chat-projects` experiment. `/clear` and `/compact` defer to a project skill with the same name, as they already do for other sources. When the user can't use the project, the site treats it as no project skills, like chatd, so those commands keep working and the `/` menu shows no retry prompt for project skills. That covers a 403 or 404 from the project skills request and a project missing from the user's project list, which holds only owned and shared projects, so an administrator role that can read the project doesn't count. Other failures are retried and leave the list unknown. A cached project list is also unknown while it refetches or after a failed refetch, so a share revoked since it was cached keeps those commands pending instead of deferring to stale project skills. - Docs gain a "Project skills" section in the extending agents page. `coderd/x/chatd/ARCHITECTURE.md` gains a paragraph on project skills. Dogfood UAT on this branch passed: project skills appear in the project page `/` menu and in project chats, `read_skill` loads them, disabled and deleted skills report not found, chats outside the project don't see them, and a subagent gets them through its root chat. The site reads project skills from the chat's own `project_id`, so subagent chats show them in the composer once sub-chats carry their root's project (#30683). | Project page `/` menu | `read_skill` in a project chat | | --- | --- | | <img alt="Project skills group in the project page slash menu" src="https://raw.githubusercontent.com/coder/coder/assets/pr-30838-project-skills/pr/project-page-slash-menu.png" width="600" /> | <img alt="read_skill loading a project skill in a project chat" src="https://raw.githubusercontent.com/coder/coder/assets/pr-30838-project-skills/pr/project-chat-read-skill.png" width="600" /> | Stack (merge top to bottom): - #30838 👈 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 - #30884 - #31122 |
||
|
|
ffc6aac6a8 |
test(coderd/x/chatd/chatdebug): check the run-summary query boundary (#30973)
Replaces the last Postgres-backed run-summary subtests with mock tests of the `AggregateRunSummary` boundary and one extended Postgres test. This deletes `MultipleStepsSumTokens` and the helpers `createTestStep`, `updateTestStepWithUsage` and `updateTestStepWithFullUsage`. **Why it is safe:** - `NilRunID` now runs against a mock with no expectations, so any query fails it, and checks that the base map comes back unchanged. - The new `QueryAsChatdReturnsError` checks that the read runs as the chatd actor and that the query error is returned. - `RecomputesHasErrorAndCompletedEndpointLabel` now inserts step 2 before step 1 and compares the whole summary read through the real query: five token sums, `has_error`, the endpoint label and the seeded `first_message`. With the table from #30972, it covers every assertion of `MultipleStepsSumTokens`. - Of the same 42 `summary.go` mutants, the tests now kill 34 (`main` kills 22, #30972 kills 31). The new kills are the nil run ID return value, a swallowed query error and a read without the chatd actor. The 8 survivors are equivalent or only change logging. - Mutants of the `GetChatDebugStepsByRunID` SQL that order by `started_at` alone or reverse the order fail the Postgres test. Dropping the `ORDER BY` survives: Postgres reads these rows through the unique `(run_id, step_number)` index, which already returns them in step order. - No references to the removed helpers remain. **Review focus:** the setup order in `RecomputesHasErrorAndCompletedEndpointLabel`. Step 2 is inserted first, so the expected label holds only if the query orders by `step_number`. Since #31007, `CreateStep` numbers steps itself, so the test inserts both rows through the store with explicit step numbers. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack makes the debug run-summary reduction database-free and replaces its Postgres fixtures with literal rows. 1. #30972 Replace run-summary Postgres subtests with literal rows 2. #30973 Check the run-summary query boundary > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
5c9815b474 |
refactor(coderd/x/chatd/chatdebug): replace run-summary Postgres subtests with literal rows (#30972)
Moves the post-query reduction in `chatdebug.(*Service).AggregateRunSummary` into a private `summarizeRunSteps` method and tests it with table cases over literal `database.ChatDebugStep` rows. This deletes the 11 Postgres-backed subtests of `TestService_AggregateRunSummary` whose assertions the table covers; each one built its own database. **Why it is safe:** - The moved body is unchanged apart from `return result`. `AggregateRunSummary` still owns the nil run ID check, the chatd-authorized read and the error return. - Every assertion of the removed subtests maps to a table row that compares the whole output map, so absent keys are checked too. Each row also checks that the base map is not mutated. - `NilRunID`, `RecomputesHasErrorAndCompletedEndpointLabel` and `MultipleStepsSumTokens` stay on Postgres here; #30973 replaces them. - I ran 42 mutants of `summary.go` with `go test -overlay`: `main`'s tests kill 22, this PR's tests kill 31, including all 22. The new kills cover JSON null and empty error payloads, error payloads on completed steps, malformed usage and attempts, empty paths, first-match selection and caller map mutation. Of the 11 survivors, 3 are query-boundary mutants that `main` also misses (#30973 kills them) and 8 are equivalent or only change logging. **Review focus:** `summarizeRunSteps` in `summary.go`. The moved block should match `main` apart from the return statement. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack makes the debug run-summary reduction database-free and replaces its Postgres fixtures with literal rows. 1. #30972 Replace run-summary Postgres subtests with literal rows 2. #30973 Check the run-summary query boundary > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |