mirror of
https://github.com/coder/coder.git
synced 2026-11-25 14:28:37 +08:00
feea5ab959f59cd2135443ed2a0c19bf7643db8f
10
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
acbcd0e807 |
fix(coderd/x/chatd): remember quickgen parameter rejections per model (#31493)
On Claude Opus 5.5, chat title generation and the turn-status label each made four upstream requests, three of them rejected with a 400. The temperature retry in `generateQuickgenObject` called `generateObject` again, which restarted from the forced tool call the model had already rejected. Each turn left about six `bad_request` rows in `aibridge_interceptions` and added 1.5 to 3.5 seconds of latency. This replaces the per-call fallbacks with `quickgenParamModel`, a wrapper applied in `resolveModelCall`. It falls back to plain JSON text when the model rejects the forced `tool_choice`, drops `temperature` when the model rejects it, and records each rejection in a replica-wide `sync.Map` keyed by AI provider ID, model, and parameter, following the existing `thinkingDropBlock` map. Entries expire after 6 hours so a provider that starts accepting a parameter again is picked up without a restart. Only quickgen calls `GenerateObject`, so chat turns are unaffected. | Opus 5.5 | Before | First job per replica (and after expiry) | Later jobs | |---|---|---|---| | Title / status label | 4 (3 rejected) | 3 (2 rejected) | 1 | | Summary | 2 (1 rejected) | 2 (1 rejected) | 1 | Rejections are still detected by matching `tool_choice` or `temperature` in a 400 body, as before. A false match now persists for the TTL on that replica rather than one job; the worst case is text mode or no temperature for that model. Closes [CODAGT-1411](https://linear.app/codercom/issue/CODAGT-1411/quickgen-side-jobs-make-3-rejected-requests-per-run-on-claude-opus-55) <details> <summary>Decision log</summary> - Opus 5.5 reports one rejected parameter per 400, so a job that knows nothing yet needs 3 requests; the issue's "2 requests" target for the minimal fix isn't reachable. - A per-job flag (first iteration) only got jobs to 3 requests. Sharing rejections across jobs gets steady state to 1 without a hardcoded model list, which wouldn't match gateway aliases such as Bedrock IDs anyway. - Per-replica memory over a database column or admin setting: no migration, no request-path writes, self-healing via TTL. Each replica pays the learning cost once per model per TTL window. - Keyed by provider ID plus model so the same model name behind different providers is learned independently. </details> > Generated by Coder Agents on behalf of @deansheather. |
||
|
|
3697bb38ce |
feat!: choose the computer use model per organization (#31300)
> [!NOTE]
> Xum opened this PR for Mike (Coder agent). Mike reviews it before
merge.
Fixes CODAGT-1472.
Computer use now runs on a chat model that each organization picks.
Before, it ran a fixed model on the first enabled AI provider of a
deployment-wide provider type, sorted by name. On dogfood that
provider's key is rejected, so every computer use subagent failed.
## What changed
- **Setting.** A new `computer_use` organization model override, set in
the **Computer use** row of **Organization settings** on the Coder
Agents admin page. Without an override, computer use runs on the
organization's default model. If the chosen model is disabled, deleted,
or unusable for the chat owner, computer use falls back to the default
model, as other overrides do. It also falls back when the chosen model
moves to an AI provider that is not Anthropic or OpenAI, and the row
then says that the saved model is ignored.
- **API.** `PUT
/api/v2/organizations/{organization}/chats/model-overrides/computer_use`
returns 404 while the `chat-virtual-desktop` experiment is off, and 400
unless the model's AI provider type is Anthropic or OpenAI.
- **chatd.** The `computer_use` subagent runs on that model, and the
computer tool flavor follows the model's provider type. OpenAI computer
use always uses the Responses API, so a model that sets
`use_responses_api: false` gets a configuration error. When no usable
model exists, `computer_use` is unavailable, and the reason says whether
a saved computer use model was skipped and why the default model cannot
be used. The default model is read under the chat owner's model ACLs, as
chat turns do.
- **UI.** The row lists only enabled Anthropic and OpenAI models. A
warning icon with the tooltip "Make sure that the selected model
supports computer use." appears when the model in effect (the selected
one, or the default) is not on a curated list of canonical model IDs
known to accept the computer tool (`knownComputerUseModels` in
`knownModels/catalog.ts`, exact match only). It also appears when the
model's AI provider type is OpenAI and its **Use Responses API**
override is Off, because OpenAI computer use needs the Responses API.
The warning does not block saving. I built the list from a live probe on
2026-10-26 that sent each Anthropic and OpenAI model one request with
the computer tool.
- **Docs.** `virtual-desktop.md`, `models.md`, `organizations.md`, and
`architecture.md` describe the new setting, and chatd's
`ARCHITECTURE.md` describes the computer use model routing.


## Breaking change
This removes the deployment-wide computer use provider setting
(`agents_computer_use_provider`), its experimental `GET`/`PUT
/api/experimental/chats/config/computer-use-provider` endpoints (shipped
since v2.35), the Virtual desktop settings card, and its audit field.
Migration 000635 deletes the stored value. After the upgrade, computer
use runs on each organization's default model until an admin picks a
computer use model. Computer use subagents created before the upgrade
keep the model they inherited from their parent chat, so a follow-up
message to one of them can fail; a new computer use subagent uses the
organization's computer use model. Telemetry now reports the
per-organization overrides instead of the provider, and `null` when it
cannot read them.
## Testing
- `make pre-commit` passes. `go test` passes for `./coderd/x/chatd/...`,
`./coderd/database/migrations/`, and the targeted coderd, telemetry,
dbauthz, enterprise audit, and codersdk tests. Vitest and the touched
Storybook stories pass.
- Each new Go test fails when its target behavior is removed from
production code.
- Remote dogfood UAT ran on an isolated Coder instance built from the PR
head, with real Anthropic and OpenAI models:
- 110234e: the row with the experiment on and off, the picker, the
warning icon cases, save and clear, the 400 for other provider types,
which model and computer tool each computer use subagent used
(Anthropic, OpenAI, default, and disabled override), a real desktop
session on an Anthropic and an OpenAI model, the unavailable reasons,
the upgrade through migration 000634, and the removed endpoints.
- 09ce818: an override whose model moved to an unsupported AI provider.
- 7925be9: the alert for a moved and a disabled override, and a computer
use subagent on an Anthropic model.
- 2a01eaf: the row, and computer use subagents on the override and on
the default model.
- 47f5bd1: the warning icon for an OpenAI model with **Use Responses
API** set to Off, On, and Default. With Off, a computer use subagent on
that model fails with a configuration error before any provider request.
With Default, it runs with the computer tool through the Responses API.
- 81d33b4: the unavailable reasons for a disabled override, a cleared
override, and missing credentials, and a computer use subagent on an
Anthropic override. This round found that the docs named the wrong
section of the model form for **Use Responses API**. aeb3d02 fixes that
step, and a re-read of the docs against the recorded UI passed.
|
||
|
|
3576e04e2d |
fix(coderd/x/chatd): keep the chat output cap on compaction summaries (#31042)
Compaction summaries asked the provider for 1.5 times the model's configured output cap. When an admin adds a known model, the form fills `max_output_tokens` with the provider maximum, 128,000 for `claude-opus-5-5`, so each summary request sent `max_tokens: 192000`. Anthropic rejected it with HTTP 400 (`max_tokens: 192000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5-5`), so compaction failed and the chat could not shrink its context. `compactionSummaryCall` now keeps the chat call's cap. The 50% headroom came from #28886, which accepted the overshoot for caps set at a provider ceiling as a tradeoff. With catalog defaults, that case is the common one. `GenerateCompaction` still lowers the cap to the remaining context window when that is smaller. Closes [CODAGT-1428](https://linear.app/codercom/issue/CODAGT-1428). The ticket also shows "Your input exceeds the context window" on a summary request. That is a separate failure, which #30766 handles (merged after the ticket was filed), so this PR does not change it. **Tests** - New `TestActiveServer_ManualCompaction/summary keeps the configured output cap`: a 128,000 cap reaches both the chat turn and the summary request unchanged. On the old code it fails with `expected: 128000 actual: 192000`. - `TestBuildTurnEnvironmentClampsRequestedReasoningEffortToMax` and the compaction hook tests now expect the unchanged default cap (32,000 instead of 48,000). #30942 rewrites the first test and keeps a `3 * defaultChatMaxOutputTokens / 2` expectation, so whichever PR merges second drops that factor. **Validation** - `go test ./coderd/x/chatd/ ./coderd/x/chatd/chatloop/ -count=1`: passes - `make pre-commit`: passes - Remote dogfood UAT against `claude-opus-5-5` with a 128,000 cap: on `main`, manual, automatic, and compaction-model-override summaries asked for 192,000 tokens and failed with the 400 above. On this branch, all 16 summary requests (the same flows plus an unset cap and a small context window) succeeded, and none asked for more than its configured cap. Chat turn `max_tokens` was the same on both. UAT ran on `9230a6e9fa1`; the head `3633adef53e` only adds a comment edit. - No new dependencies. The polish pass and the test audit changed no files. - Codex review on `3633adef53e`: no findings. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
b2c8798e0e |
fix: replay stateless OpenAI reasoning across chat turns (#30298)
OpenAI Responses chats default to `store=false`, and chatd only replayed reasoning as an `item_reference`, which needs provider-side storage. Reasoning was therefore dropped between tool steps and turns, so reasoning models lost their chain of thought mid-task. This pins coder/fantasy `coder_2_33` at 6ba8681, which includes fantasy #63 (and #64, #65, and #66). #63 captures each completed reasoning item (ID, `encrypted_content`, summary) and replays it in full regardless of `store`. In chatd: - Every Responses call requests `reasoning.encrypted_content`. The `store` default and configured includes are unchanged, and Chat Completions requests are untouched. - Prompt rebuilds keep reasoning parts without visible text when they carry finalized encrypted state, so reasoning survives durable history and coderd restarts. - The provider-switch sanitizer also strips OpenAI reasoning from history produced by a different or unknown provider instance, since reasoning IDs and encrypted content only resolve where they were issued. - A compaction model override on a different provider instance, or with a different model, gets a compaction prompt without the chat's OpenAI reasoning. - Each saved reasoning part records the provider instance, model, and credential (the deployment's or the user's personal API key) that produced it, and the sanitizer keeps it only when all three match the current turn, because another model, or the organization behind another credential, can reject the encrypted content. Switching models, adding or removing a personal key, or editing a config's model or provider drops the earlier reasoning; switching back restores it. The record is never returned by the API. Reasoning saved before this change has no record and follows its model config. - If OpenAI rejects replayed reasoning it cannot decrypt (`invalid_encrypted_content`), for example after the deployment's key is replaced with one from another organization, the request is retried once without reasoning, and the reasoning that step produces is saved with the provider's next rejection epoch. Epochs are kept separately for each provider, model, and credential. Later steps and turns leave out reasoning from earlier epochs, on any replica and after restarts, so only the first request after the change is rejected and newer reasoning keeps replaying. A retried step that returns no reasoning saves its epoch on its first part. The advisor's prompt never includes OpenAI reasoning, as on `main`. ## Testing Rebased onto main at |
||
|
|
e988ddb11d |
feat: trace chatd provider stages and count only output parts as first token (#29770)
**TL;DR:** Traces the model provider call: a `stream` stage, a nested `time_to_first_token` stage, and one `provider_attempt` per HTTP round trip, labelled with provider type and model. Behavior change: `coderd_chatd_ttft_seconds` now counts only a real output part as the first token, so error, warning, and finish parts no longer count. Instruments the provider call. **Stream and time to first token.** `GenerateAssistant` records a `stream` stage from stream open to close and a nested `time_to_first_token` stage. The TTFT window closes once, on the first streamed output part: any part other than warnings, finish, or error, including start markers such as `text_start`. A closed window observes the stage and the pre-existing `coderd_chatd_ttft_seconds` with the same elapsed time. A failed open, an error part, or a release without an output part ends the TTFT span with the error (a silence timeout is classified as such) and observes nothing. The `stream` span ends once, with the error `GenerateAssistant` returns, so content-filter and no-output attempts end errored. Failed `stream` windows are observed like successful ones. The attempt is released before the stream span ends, so the TTFT window always falls inside its stream. The compaction summary stream passes a nil tracer, so it records neither. Without #29771, production emits only `provider_attempt`; #29771 passes the tracer to `GenerateAssistant`. **Provider attempts.** The provider HTTP transport is wrapped in `stageSpanRoundTripper`, which emits one `provider_attempt` stage per round trip, so retries each get a span. The span closes on response headers; a status >= 400 marks it errored without changing what the client sees. `resolveModelCall` resolves the `StageModel` (wire provider, configured `provider_type`, model, effective reasoning effort) and threads it to the transport, so span attributes and labels match the call. `provider_type` is read from `ai_providers.type`, so types outside the fantasy set (copilot) keep their configured name. `chatd.New` builds the tracer with the server clock. **Behavior change to `coderd_chatd_ttft_seconds`:** only an output part counts as a first token. Error parts no longer close the window as a success, and warnings and finish parts are skipped; the help text says so. `StageSpan.End` returns the span's elapsed window, which `ttft_seconds` observes. Callers pass `Stages` and `StageModel` through `GenerateAssistantOptions`; a nil tracer discards (TTFT still records `ttft_seconds`). `Server` gains the `stages` tracer and a `TracerProvider` option, wired from `coderd`. <details> <summary>Review decisions</summary> - Start markers close the TTFT window: they are the first sign the model is producing output, and waiting for a delta would fold hidden reasoning time into TTFT. - Failed `stream` and `provider_attempt` windows are observed: that time was spent. TTFT is the exception because a first token that never arrived has no duration. - `http_host` was dropped from `provider_attempt`; every request goes through the local AI Gateway transport, so it was constant. - The advisor tool's nested model call is intentionally not instrumented as `stream`/TTFT. </details> Supersedes #28970 and #28971. 🤖 This PR was generated by Coder Agents on behalf of @jscottmiller. |
||
|
|
0e9337c215 |
fix: retry Anthropic thinking binding errors with drop_block (#29792)
Closes CODAGT-1141
Opus 5.5 and Fable 5.1 bind each signed thinking block to the exact
prefix it was created under. chatd rebuilds the system prompt and tools
from live state before every model call, so if that state changes
mid-turn (e.g. after `start_workspace`), the replayed block no longer
matches and Anthropic returns a 400, which we treated as non-retryable:
```
messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation...
```
To fix, we'll do what Anthropic recommends: on that 400, retry once with
`thinking.block_binding.prefix_mismatch_behavior: "drop_block"` and the
`thinking-binding-controls-2026-08-01` beta, then send both upfront for
that provider and model once the retry succeeds. That's only a hint,
since BYOK users on the same provider can have different keys, so if a
request with `drop_block` gets a 400 we retry once without it and clear
the hint. The retry wraps the model itself, so compaction and the
advisor get it too. The hint is in-memory, so a restart costs one extra
400 per model on each replica. Chats that never hit the error are
unchanged.
aibridge's InvokeModel path was stripping the beta and deleting
`block_binding`, so it now forwards both or neither, for any model. It
also renames the field to `mismatch_behavior`, since that's what Bedrock
calls it, and only some regions accept the Anthropic name.
Always sending `drop_block` would change bytes on working chats, and AWS
doesn't document Mantle support for the beta. Dropping stale thinking
client-side means guessing what the server will reject (the signature is
opaque, and enforcement depends on the model and account), so it would
still need the retry. The proper fix is an append-only prefix, but
that's a much bigger change, and it would also still need this retry.
Mantle does accept the beta, at least for Opus 5.5 on us-east-1 (see
testing below).
<details>
<summary>Testing</summary>
I tested this manually on `9c2b4d6` with `develop.sh`, using Opus 5.5 on
Bedrock Mantle us-east-1 via the dogfood AI Gateway, with a small
logging proxy in front to record the beta header and `block_binding` on
each request. The direct Anthropic API doesn't enforce the binding for
our account, so I couldn't reproduce it there.
To trigger it, I just asked the agent to reason about something, create
a workspace from the `docker` template and run a command in it, all in
one turn. On the merge base, the turn fails with the 400 above as soon
as the workspace is created. On this branch there's one 400, the
`drop_block` retry succeeds, the turn finishes with no error in the UI,
and every request after that sends `drop_block` upfront:
```
status=400 beta="" block_binding=""
status=200 beta="thinking-binding-controls-2026-08-01" block_binding={"prefix_mismatch_behavior":"drop_block"}
status=200 beta="thinking-binding-controls-2026-08-01" block_binding={"prefix_mismatch_behavior":"drop_block"}
```
The chat that failed on the merge base also recovers once it's continued
on this branch, and a restart costs one extra 400 as expected. I also
had the proxy reject any request with `drop_block`, to mimic a BYOK key
without the beta, and the retry without it succeeded and cleared the
hint, so the next chat didn't send it.
I didn't test the InvokeModel path, since I don't have AWS credentials
for it.
</details>
|
||
|
|
e35cbe2a7f |
fix(coderd/x/chatd): stream compaction summaries (#28886)
Chats could get permanently stuck once their context crossed the compaction threshold on adaptive-thinking Claude models: every compaction attempt failed with `compaction produced an empty summary`, and both automatic and manual compaction take the same path, so the chat could never recover. ## Problem `compactionSummaryCall` deliberately set `MaxOutputTokens = nil` because the summary request was non-streaming and the Anthropic SDK rejects non-streaming requests whose `max_tokens` implies a completion longer than ten minutes. But a nil cap makes fantasy's Anthropic provider silently default to 4096 output tokens, and adaptive-thinking Claude models can spend that entire budget on a thinking block, leaving zero summary text. ## Fix - Stream the compaction summary request. Streaming lifts the Anthropic SDK's non-streaming duration restriction, which was the only reason the cap was nil'd. - Keep the resolved output cap (32k default) on the summary call instead of nil'ing it. - When the summary comes back empty with truncation evidence (length finish reason, or reasoning with no text), fail with `compaction summary was truncated at the output token cap` instead of the generic empty-summary error, so the next occurrence is attributable at a glance. Unit tests cover text-block joining and the truncation classification; the compaction e2e fixtures now serve streamed summaries and assert the summary request streams with `max_tokens: 32000`. Dogfood UAT on a deployment built from this branch verified manual compaction with Claude Opus 5 (adaptive thinking, twice, with reload persistence) and an OpenAI regression chat. > 🤖 Opened by [Xum](https://mux.coder.com) on behalf of @ibetitsmike. |
||
|
|
e258526959 |
fix(coderd/x/chatd): coerce Bedrock reasoning summaries to auto (#29229)
## Why
Bedrock Mantle's OpenAI Responses endpoint rejects `reasoning.summary`
values other than `auto` with HTTP 400 (`Unsupported parameter:
'reasoning.summary' is not supported with the 'openai.gpt-5.6-sol'
model`). chatd forwards `provider_options.openai.reasoning_summary` from
the model config unchanged, so every chat turn and quickgen title call
through a Bedrock model config carrying `concise`/`detailed` fails. On
dogfood this produced 43 user-visible "chat generation failed" errors
and 118 title-generation failures in one day; five Bedrock configs still
carry `detailed`.
## What
`resolveModelCall` now coerces
`provider_options.openai.reasoning_summary` to `auto` for Bedrock
providers whose model uses the OpenAI wire format (non-`anthropic.`
model IDs), before per-call provider options are built. Mantle accepts
`auto` (it returns no summaries today, but encrypted reasoning
continuity keeps working). Coercing instead of dropping keeps one config
portable between Bedrock and direct OpenAI, and summaries start flowing
if AWS adds support. Anthropic models on Bedrock and every non-Bedrock
provider are untouched. Only the derived provider options see the
coerced value; the resolved call config keeps the configured one, so
computer-use rerouting to direct OpenAI is unaffected. A TODO item in
`coderd/x/chatd/ARCHITECTURE.md` marks the section for the human author,
per the chatd guardrail.
## Validation
- `TestAIGatewayModelBedrockReasoningSummary` drives the real
`resolveModelCall` path (newModel + ProviderOptionsForCall) with a
request-capturing transport: Bedrock + `openai.gpt-5.6-luna` with
`detailed` sends `"summary":"auto"`; Bedrock + Anthropic and direct
OpenAI are unchanged. `TestBedrockReasoningSummary` covers the helper
table. Red-green: removing the resolver call or the helper body fails
the body assertion (`expected "auto", actual "detailed"`).
- `go test ./coderd/x/chatd/ -run 'TestAIGateway|Bedrock'`, `go test
./coderd/x/chatd/chatprovider/...`, `golangci-lint run
./coderd/x/chatd/...` (0 issues), `make pre-commit`.
- Remote dogfood UAT (Coder Agents) against a mock Bedrock upstream and
the real OpenAI gateway: Bedrock `openai.gpt-5.6-luna` configs with
`detailed`/`concise`/odd-cased values send `"summary":"auto"` and
complete chats and titles; direct OpenAI keeps `detailed` with visible
summaries; Bedrock Anthropic requests gain no OpenAI fields. UAT ran on
the first head (
|
||
|
|
ac824cd235 |
chore(coderd): remove dead code from chatd (#29008)
Removes production code in `coderd/x/chatd` that nothing reaches, the tests that only existed to exercise it, and option/config fields that callers filled in but chatd never read. No runtime behaviour changes; the only edits outside `coderd/x/chatd` drop the now-nonexistent fields at their three call sites (`coderd/coderd.go`, `coderd/exp_chats.go`, `coderd/coderdtest`). Net: 42 files, +147 / -1065. Verification method for every item: `golang.org/x/tools/cmd/deadcode` (with and without `-test`) rooted at `cmd/coder`, `enterprise/cmd/coder` and every package that imports chatd; a `go/packages` pass counting `TypesInfo.Uses` per declared type, const, var, field and method across the same roots, split into test and non-test use sites, plus a read-vs-write split for struct fields; `rg` over the whole repo including `site/src` for json tag names; then `go build ./...`, `go vet ./coderd/x/chatd/...`, `golangci-lint run ./coderd/x/chatd/... ./coderd/ ./coderd/coderdtest/`, and `go test ./coderd/x/chatd/...` (all 20 packages) locally. <details> <summary>Evidence per deletion</summary> | Removed | What it was | Why unused | |---|---|---| | `subagent.go` `resolveConfiguredModelOverride`, `parseModelOverride`, `parsedModelOverride` (~135 lines) + `TestResolveConfiguredModelOverride_*`, `TestParseModelOverride` | raw-string model override resolver | Only callers were its two tests; production resolves overrides through `resolveOrganizationModelOverride` (`title_override.go`, `compaction_override.go`, `subagent.go`). | | `chatd.go` `removeSkillIndexMessages`, `isSkillIndexMessage` + `TestSkillIndexRefreshReplacesStaleAliases` | skill-index refresh helpers | Zero production references; the test simulated a refresh path no production code performs. | | `chatd.go` `chatMessage`, `newChatMessage`, `withCreatedBy`, `appendMessageFields`, `BuildSingleChatMessageInsertParams` (~90 lines) | insert-params builder | Exported, but every caller was a `chatd_test` file (6 sites). Replaced by a 25-line `singleChatMessageInsertParams` helper in `chatd_helpers_test.go`. | | `chatd.go` `Server.closeInflightAdmission` | one-line wrapper around `inflightClosed.Store(true)` | Single call site (`Close`); inlined. | | `chatd.go` `Server.workerID`, `instructionLookupTimeout`, `pendingChatAcquireInterval`, `maxChatsPerAcquire`, `chatHeartbeatInterval` | Server struct fields | Assigned in `New` and never read anywhere (the values reach the worker through `chatWorkerOptions`, not these fields). | | `Config.InstructionLookupTimeout`, `homeInstructionLookupTimeout`, `coderd.Options.ChatdInstructionLookupTimeout`, `coderdtest.Options.ChatdInstructionLookupTimeout` | timeout plumbing | The value only landed in the dead `Server.instructionLookupTimeout`; no CLI flag sets it and nothing reads it. | | `PromoteQueuedOptions.CreatedBy` | option field | Set by `coderd/exp_chats.go` and three tests, never read in chatd (promotion keeps the queued row's `created_by`). | | `SubmitToolResultsOptions.DynamicTools` | option field | Set by `coderd/exp_chats.go` (which re-read `chat.DynamicTools` just to pass it) and three tests, never read in chatd. | | `attachments.go` `buildAssistantPartsForPersist` (whole file) | assistant part builder | Stale copy left by #26270; production uses `buildAssistantParts` in `message_conversion.go`. Its six tests were retargeted to the live function (now `message_conversion_internal_test.go`) and a dead-copy assertion in `subagent_internal_test.go` was dropped. | | `chatloop.RunOptions` (94 lines) | old loop options struct | Only two of 23 fields were ever populated, for one internal call to `prepareMessagesForRequest`, which now takes `model, logger` directly and no longer returns the ignored canonical slice. `GenerateAssistantOptions` / `ExecuteLocalToolsOptions` are the live types. | | `chatloop.ErrDynamicToolCall`, `ErrStopAfterTool`, `PendingToolCall`, `PersistedStep.PendingDynamicToolCalls` | dynamic-tool exit protocol | Zero references outside their declarations (one stale comment in `chatdebug/service.go` updated). | | `chatloop.CompactionOptions.Persist`, `.OnError` | callbacks | `Persist` had zero references; `OnError` was set only by two tests that asserted it was never invoked. | | `chatloop` `stepResult.shouldContinue` + its computation | flag | Written once, never read. | | `chatloop.StateWaiting` | metric label const | Zero references. | | `generation.go` `generationOutcome.InsertedMessages`, `runnerActionMessage` | outcome field | Built on every commit, never read. | | `chatstate` `ExecutionState.IsArchived`, `AllOwnershipStates`, `OwnershipState`/`StateU`/`StateO`, `TransitionAcquire` | state-machine leftovers | Zero references (the ownership consts became dead once `AllOwnershipStates` went). | | `chatstate` `ExecutionState.QueueNonEmpty` | predicate | Only referenced by the test asserting its own table; the sibling `IsRunnable` check in that test is kept. | | `chatdebug.Attempt.RetryClassification`, `.RetryDelayMs` | json fields | Never assigned anywhere, `omitempty`, and `retry_classification`/`retry_delay_ms` do not appear in `site/src` or `typesGenerated.ts`. | | `chatdebug.RunContext.Kind`, `StepContext.HistoryTipMessageID`, `RecorderOptions.Provider`/`.Model`, `stepHandle.opts`/`.usage`/`.err` | context/handle fields | Written (from `chatd.go`, `chatloop/compaction.go`, `modelcall.go`, `recorder.go`) and never read. The DB run row keeps its own `kind` column. | | `chatprovider.MergeProviderAPIKeys` + `TestMergeProviderAPIKeys_PreservesProviderRegions` | key merge | Superseded by `ResolveUserProviderKeys`, whose region test already covers the same behaviour. | | `chatprovider` `providerCreationError` | one-line `xerrors.Errorf` wrapper | Single call site; inlined with identical message. | | `chatretry.IsRetryable` | classifier wrapper | Zero references. | | `computeruse.IsTool` + `TestComputerUseTool` | one-line forwarder to `fantasyopenai.IsComputerUseTool` | No production caller; two test assertions now call the fantasy function directly, and the dropped test only asserted the library's own constructor. | | `chatprompt.ToolResultToPart` | one-line forwarder to `codersdk.ChatMessageToolResult` | Single call site; inlined. | | `subagent_catalog.go` `formatSubagentDefinitions` | forwarder with `nil` overrides | Single call site; inlined. | | `worker.go` `chatWorker.chatWorkerID` | getter | Only tests called it; they read `opts.WorkerID` directly now. | | `chattest.AnthropicErrorResponse`, `OpenAIServerErrorResponse`, `ChatMessageWithParts` (`messages.go` removed) | test fixtures | Zero references. | | `chattest` `AnthropicRequest.Options`, `OpenAIRequest.Options` | `json:",inline"` map fields | `encoding/json` has no inline tag (the TODO on each said so); never populated, never read. | </details> <details> <summary>Considered and kept</summary> - `chatstate.CreateChat` (test-only thin wrapper over `insertChat`, production uses `CreateChatWithID`): documented package API with 25 test call sites; not worth the churn. - `chatprompt.MarshalContent` / `MarshalToolResult`: test-only, but they deliberately produce legacy-format DB rows so the read path's legacy handling stays covered. - `chatstate.AllowedExecutionTransitionsFrom` / `AllowedInputStates` / `AllowedExecutionTransitionOutputs`, `chatdebug.StepFromContext`, `WithClock`, `WithStaleThreshold`, `WaitUntilIdleForTest`, `PublishBuffer.BufferedChannels`, `chattool.NewWorkspaceMCPTool`: test seams that tests actively use to reach otherwise unexported state. - `AgentCapacityLimiter` interface (one production implementation): tests inject fakes. - `applyHookResultMessages` / `appendHookResultMessages`: a named pair over one placement enum, both used. - Nil-receiver guards on `*Metrics`, `*Result`, `*streamSyncPoller`, `*runnerDebugTurn`: nil is a supported "disabled" value on those paths. - Tests flagged by heuristics as assertion-light (`TestNopMetrics_DoesNotPanic`, `TestStepHandleFinish_NilHandle`, `TestRetry_OnRetryNilDoesNotPanic`, the `chatstate` synthetic-cancellation tests that assert through helpers): they cover real nil-safety or delegate assertions to helpers; kept. </details> <details> <summary>Out-of-scope findings (not changed here)</summary> - `chatdebug.Service.FinalizeStale` has had no production caller since #26270 removed the background sweep loop; only its tests call it, and comments in `chatd_debug.go` and `database/querier.go` still describe the loop. Deleting it would erase the implementation a fix needs, so it is left for a decision. - `coderd_chatd_chats` (gauge) and `coderd_chatd_stream_buffer_dropped_total` (counter) are registered and documented in `docs/admin/integrations/prometheus.md` but never set or incremented in production; `Metrics.RecordStreamBufferDropped` is test-only. Removing them changes the exported metric set and the docs, so they are left alone. </details> ## Declined review findings None yet. > Xum (AI agent) opened this PR on behalf of @ibetitsmike. |
||
|
|
9168dbf4d3 |
refactor(coderd/x/chatd): unify LLM model-call construction behind a resolver (#28145)
Centralizes every LLM client build in chatd behind one resolver and makes all model calls behave the same, instead of preserving per-flow quirks. ## Why `chatd` built LLM clients in five places (standard turn, compaction override, quickgen, title override, advisor), each repeating config parsing, route resolution, client construction, and debug wrapping with slightly different behavior. An earlier iteration of this PR centralized construction but preserved every historical quirk behind purpose-specific spec constructors and policy flags. Review concluded the quirks themselves were the problem. ## What changed - `Server.resolveModelCall` (`modelcall.go`) is the single pipeline from a `modelCallSpec` to a ready client plus call metadata. Callers build spec literals inline; the only spec fields are data: model source (chat config, explicit config row, or fixed provider/model pair for computer use), requested reasoning effort, chatd-scoped routing, and build options. - Uniform behavior for every call: - Provider options are always derived. Whole-chat summaries, turn status labels, and chat-model compaction summaries previously sent none; they now follow the config like everything else. - `MaxOutputTokens` always defaults to 32k when the config leaves it unset. The compaction summary call nulls the cap after copying the template because it is non-streaming and the Anthropic SDK rejects non-streaming requests whose cap implies a completion over ten minutes. - Debug recording always wraps the client when chat debug is enabled, labeled with the resolved provider/model. The debug-rebuild paths (`manualTitleDebugSpec`, `quickgenDebugSpec`) are deleted; debug helpers now only create and finalize run records, since run association flows through the generate context, not the model. - Clients are always constructed with the configured model string and unmutated route, so AI Gateway validation sees the name exactly as configured. The resolved identity feeds metadata, logs, and debug labels only. - `resolvedModelCall.newCall` / `newObjectCall` are the only production constructors of `fantasy.Call` / `fantasy.ObjectCall`; object calls now carry the config's sampling parameters. - Net: -240 lines. ## Validation - Full `./coderd/x/chatd/...` suite green (PostgreSQL-backed). - Red-green toggles verified for the three key unifications (option derivation, token default, summary cap removal). - ARCHITECTURE.md: prose the refactor made stale is deleted; no new resolver documentation is added. > Mux acted on Mike's behalf for this PR. |