Commit Graph
21 Commits
Author SHA1 Message Date
Ethan 5cbf086517 feat: send tool result media to providers like user files (#31383)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
This is the first of four stacked PRs.

Today a PDF in an MCP tool result reaches no provider. On Anthropic we
strip it in chatd. On OpenAI Chat Completions fantasy swaps it for a
"cannot be displayed" note, and on Responses it sends a placeholder that
points at a user message it never sends.

coder/fantasy#73 and coder/fantasy#74 make fantasy convert tool result
media with the converter it already uses for user files: an Anthropic
document inside `tool_result`, an `input_file` inside
`function_call_output` on Responses, and a user file part straight after
the tool message on Chat Completions. Both have merged, and this PR pins
`charm.land/fantasy` to the coder_2_33 tip that has them. Chat
Completions file parts now refuse text files, as Responses already did,
so `AcceptsFilePartMediaType` follows.

The converters take a filename, so an MCP embedded resource blob is now
named after the last element of its URI path, and we store the name with
the tool result so later turns send the same one. OpenAI picks the file
type from the extension, so we append the right one when it's missing or
wrong. We drop names with control characters, as Postgres `jsonb`
rejects NUL, and we redact the name like the rest of the tool response,
since a URI like `https://host/sse/<token>` would otherwise put the
token in the chat history.

There's also a test proving aibridge's Chat Completions re-encode keeps
a user file part, as that's where these PDFs end up.

Anthropic still strips tool result PDFs until the next PR in the stack.
2026-11-11 00:06:40 +11:00
Michael SuchaczandEthan Dickson b6dc7158b4 feat: use the Anthropic computer use toolset for Claude 4.8 and later (#31521)
> Xum acted for Mike: this PR was written and opened by an AI agent on
Mike's behalf.

Computer use subagents on Claude 5.5 models (`claude-opus-5-5`,
`claude-sonnet-5-5`) failed on their first request: these models reject
`computer_20251124` and accept only the GA toolset
`computer_toolset_20260801`.

chatd now picks the Anthropic computer use tool version from the chat's
model with `ComputerUseToolVersionForModel` from coder/fantasy: the
toolset for Claude 4.8 and later, `computer_20251124` for Opus 4.5 to
4.7, Sonnet 4.6 and model IDs it cannot parse, and `computer_20250124`
for Haiku and Sonnet 4.5. Claude Platform on AWS and Amazon Bedrock
offer computer use only through the earlier versions, so an Anthropic
provider configured for either declares `computer_20251124` where the
model would take the toolset. For the toolset, chatd answers like
Anthropic's SDK tool runner: actions answer with text and only
`screenshot` returns an image, `cursor_position` returns the position as
text, `key` honors `repeat` (1 to 100), and zoom is declared disabled
because the agent desktop has no zoom action. The earlier versions still
answer every action with a screenshot.

A step's computer calls run one at a time in call order. For every
Anthropic version, the calls after one that failed, or that was rejected
before it ran (malformed input or a pre_tool_use hook denial), return
`Not executed: an earlier computer action in this turn failed.` without
running, which is the SDK runner's text. The chat loop enforces this
halt, so the computer tool keeps no state between calls. `wait` and
`hold_key` durations are read as seconds (capped at 300).

The frontend marks Claude Opus 5.5 and Sonnet 5.5 as verified for
computer use, and the computer tool row now labels each action ("Left
click", "Type", "Press key") instead of "Screenshot", shows text output,
and shows the error of failed or halted calls inline. The error block is
shared with the write_file and edit_files rows as
`ToolCall.ErrorDetail`.

Uses coder/fantasy#80 and coder/fantasy#82, both merged. `go.mod` pins
the fork to `7882f906a89a`.

<details>
<summary>UAT</summary>

TL;DR: it works. A remote Coder Agents UAT on dogfood passed on
`00143d5b12`, with all model traffic logged through a proxy:

- `claude-opus-5-5`, `claude-sonnet-5-5` and `claude-opus-4-8` declared
`computer_toolset_20260801` with zoom disabled and no beta header.
`claude-opus-4-6` and an unknown model ID declared `computer_20251124`
with the `computer-use-2025-11-24` beta, `claude-haiku-4-5` declared
`computer_20250124`, and a Claude Platform on AWS provider declared
`computer_20251124`. Opus 5.5, Sonnet 5.5, Opus 4.6 and Haiku 4.5 each
completed a desktop task.
- Toolset actions answered with text and only `screenshot` returned an
image. `repeat` 100 ran, 150 failed, and `wait` 400 stopped at 300
seconds.
- A failed call (`repeat` 150 on the toolset, a desktop error on 4.6)
and a pre_tool_use hook denial each halted the rest of the step without
touching the desktop. The next step ran normally.
- The computer tool rows showed action labels, text output and the halt
error. Opus 5.5 and Sonnet 5.5 showed no warning in the computer use
model selector. Switching a chat between 4.6 and 5.5 worked in both
directions.

Not tested: the tool type on Bedrock, and a halt after malformed model
input. Known, unchanged behavior: the desktop reports success for
unknown key names and off-screen coordinates, the model can still emit
`zoom`, which fails, and `scroll` up fails in `agent/x/agentdesktop`
because the negative amount is read as a flag. Both failures halt the
rest of their batch.

</details>

---------

Co-authored-by: Ethan Dickson <ethanndickson@gmail.com>
2026-11-02 21:28:22 +11:00
Michael Suchacz 78fa9a8613 refactor(coderd/x/chatd)!: retire the close_agent tool alias (#31005)
This PR breaks compatibility with chat histories that contain
`close_agent` tool calls, which chats from v2.34 and earlier have.
#26673 (v2.35) renamed `close_agent` to `interrupt_agent` and kept a
hidden alias, so a model that copied the old name from such a history
still interrupted the child. This PR deletes the alias:
`subagentToolNameAliases`, `ExecuteLocalToolsOptions.ToolNameAliases`
with `(*toolBatch).resolve` and its five call sites in `chatloop`, the
alias step in builtin input validation, and the `close_agent` entries in
the unbilled tool set, the plan policy, and the chatprompt lifecycle
list. Coder Agents is experimental (`coderd/x`), and our rule for
experimental persisted data is to drop the legacy shape outright and
delete the code that existed only to support it, instead of carrying it
forward.

What happens to an old chat:

- Replay does not change, because the replay path does not look up tool
names: the model still sees the historical `close_agent` call and its
stored result, and the UI renders them as before. The write path reads a
tool name only to parse `execute` commands and to keep structured error
results from subagent lifecycle tools. Dropping `close_agent` from that
lifecycle list changes nothing, because its calls are now rejected with
a plain-text error.
- If the model calls `close_agent` again, nothing runs and the child
keeps running. The tool result is the error `Tool not active in this
turn: close_agent`, and the model can retry with `interrupt_agent`.

**Why it is safe**

- Deleted alias-only tests:
`TestExecuteSingleTool_ResolvesToolNameAlias`, the
`AliasNamesClassifyAsCalled` billing row, the alias subtest of
`TestPartitionAmbiguousToolCallsGatesOnBuiltins`, the alias loop in
`TestUnbilledSubagentToolNamesMatchCatalog`, and the aliased calls that
#30939 added to `TestExecuteToolsSerialToolCallOrder` and
`TestExecuteLocalTools_ProviderToolRunner`; both tests are back to their
#30938 form.
- `TestExecuteSingleTool_UnknownAliasFallsThrough` is now
`TestExecuteSingleTool_RejectsUnknownTool` and asserts the exact error
above. The observer tests call the tool by its real name.
- Mutants of the active tool check, step observer notification, serial
dispatch, the unbilled set, the plan policy and builtin input validation
each fail a remaining test. Only the deleted alias test caught an empty
name passed to the tool handler; no chatd tool reads that name (MCP
tools use their original name).
- `git grep` finds no use of the removed identifiers and no backend code
that resolves `close_agent`. The rejection test still uses that name as
its input. The frontend keeps its `close_agent` display mapping, which
old histories still use.

**Review focus**

- A rejected `close_agent` call is now billed like any rejected tool
call; the rejection is immediate.
- `ARCHITECTURE.md`, "Generation goroutine": this PR deletes the
sub-bullet that called `close_agent` a deprecated alias of
`interrupt_agent`.
- The `resolved_tool_name` debug log field is gone. It differed from
`tool_name` only for aliased calls, and the alias is gone.

**Validation**

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

**Stack**

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

This PR replaces #31003 and carries its change, adapted to the
`toolBatch` code that #30938 and #30939 merged. Mike chose to keep the
fallbacks that #31001 and #31002 removed, so those two layers and #31003
left the stack.

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

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 02:00:59 +00:00
Michael Suchacz a86012f82b refactor(coderd/x/chatd/chatloop): resolve tool name aliases in one toolBatch method (#30939)
Adds `(*toolBatch).resolve` for the `ToolNameAliases` lookup that
`runOne`, `notifyStepToolCallObservers`,
`notifyStepToolResultObservers`, and `isSerialToolCall` each repeated.
The last three become `toolBatch` methods instead of taking the tool map
and the alias map. Where they looked up a tool and then type-asserted
it, they now assert on the map value: a missing name gives a nil
interface, so the assertion fails as the missing-key check did.

It also fixes a latent bug: `runOne` looked up result provider metadata
by the name the model sent, while its other lookups use the resolved
name, so a runner called by an alias lost its metadata. This cannot
happen in production today: the only alias is `close_agent` to
`interrupt_agent` (`subagent.go:45`), and only `computer_use.go:112`
sets `ResultProviderMetadata`.

## Why it is safe

Each mutant below puts the raw name back at one call site, and each
fails a test:

| Call site | Failing test |
|---|---|
| `runOne` tool lookup | `TestExecuteSingleTool_ResolvesToolNameAlias`
and 5 more |
| `runOne` metadata lookup | `TestExecuteLocalTools_ProviderToolRunner`
|
| `notifyStepToolCallObservers` |
`TestExecuteToolsNotifiesStepToolCallObservers` |
| `notifyStepToolResultObservers` (either loop) |
`TestExecuteToolsNotifiesStepToolResultObservers` |
| `isSerialToolCall` | `TestExecuteToolsSerialToolCallOrder` |

No test called a serial tool or a provider runner by an alias, so this
PR adds one aliased call to `TestExecuteToolsSerialToolCallOrder` and
one to `TestExecuteLocalTools_ProviderToolRunner`. With the
`chatloop.go` of #30938, the first test still passes, and the second
fails because the aliased result has no metadata.

## Validation

- `go test -race -count=1 ./coderd/x/chatd/chatloop/` passes on #30938
and here.
- `go test -count=1 -p 4 -parallel 4 ./coderd/x/chatd/...` passes here
(20 packages).
- `golangci-lint run ./coderd/x/chatd/chatloop/...` reports 0 issues,
and the pre-commit hook passed.

## Stack

This stack replaces the 20-parameter `executeTools` and the 15-parameter
`executeSingleTool` in `chatloop` with methods on one `toolBatch` type,
and resolves tool name aliases in one place. Production behavior does
not change.

1. #30937 Cover provider tool runners in `ExecuteLocalTools`
2. #30938 Replace `executeTools` and `executeSingleTool` with
`toolBatch`
3. #30939 Resolve tool name aliases in one `toolBatch` method

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 09:39:54 +00:00
Michael Suchacz 3df3c03288 refactor(coderd/x/chatd): replace executeTools and executeSingleTool with toolBatch (#30938)
Replaces the 20-parameter `executeTools` and the 15-parameter
`executeSingleTool` in `chatloop` with methods on an unexported
`toolBatch`. `newToolBatch` builds it once from
`ExecuteLocalToolsOptions`, `run` replaces `executeTools`, and `runOne`
replaces `executeSingleTool`. The 12 internal test calls set only the
options they use instead of up to 20 positional arguments.

It also deletes two copies:

- `executeTools` filtered out provider-executed calls that
`ExecuteLocalTools` had already removed. Only the `ExecuteLocalTools`
filter remains.
- The `runOne` metric defer repeated the body of
`recordToolResultMetrics`. It now calls that function.

## Why it is safe

- `newToolBatch` builds the tool, runner, and metadata maps with the
lines `executeTools` used, and the byte budget as `ExecuteLocalTools`
did. `run` drops the empty-batch returns: `ExecuteLocalTools` returns
before it when no local call is left.
- `recordToolResultMetrics` labels by `result.ToolName`, which `runOne`
sets to `tc.ToolName` and never changes. It skips a nil `Metrics`.
Production never passes one, because `ExecuteLocalTools` sets
`NopMetrics()` first; only the direct test calls, which omit `Metrics`,
use that path.
- With the duplicate filter gone, removing the remaining
`ProviderExecuted` filter fails
`TestExecuteLocalTools_ProviderToolRunner` (#30937). The other four
mutants from #30937 still fail it here.
- `git grep 'executeTools\|executeSingleTool'` finds one comment, in
`chatd_test.go`, which this PR updates.

## Review focus

The metric defer stays a closure so that it reads `result` when `runOne`
returns.

## Validation

- `go test -race -count=1 ./coderd/x/chatd/chatloop/` passes on #30937
and here, including the 16 tests that reach this code:
`TestExecuteTools*` (5), `TestExecuteSingleTool_*` (5),
`TestExecuteLocalTools*` (6).
- `TestActiveServer_ToolErrorRecordsMetric`,
`TestActiveServer_ToolExecutionAndPolicy`, and
`TestProcessChatPanicRecovery` in `./coderd/x/chatd/` pass on #30937 and
here.
- `golangci-lint run ./coderd/x/chatd/chatloop/...` reports 0 issues,
and the pre-commit hook passed.

## Stack

This stack replaces the 20-parameter `executeTools` and the 15-parameter
`executeSingleTool` in `chatloop` with methods on one `toolBatch` type,
and resolves tool name aliases in one place. Production behavior does
not change.

1. #30937 Cover provider tool runners in `ExecuteLocalTools`
2. #30938 Replace `executeTools` and `executeSingleTool` with
`toolBatch`
3. #30939 Resolve tool name aliases in one `toolBatch` method

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 09:26:42 +00:00
Michael Suchacz f004c72749 test(coderd/x/chatd/chatloop): cover provider tool runners in ExecuteLocalTools (#30937)
Adds `TestExecuteLocalTools_ProviderToolRunner`. No test ran a
`ProviderTool` runner (the local half of a provider-defined tool, such
as OpenAI computer use) through `ExecuteLocalTools`, so nothing checked
runner dispatch, the active-tool exemption for runners, result metadata,
or the skip of provider-executed calls. #30938 rewrites that code, so
this PR pins the behavior first.

The test sends a runner call and a provider-executed `web_search` call.
The runner is in neither `Tools` nor `ActiveTools`. The test checks that
only the runner call gets a result, and that the result has the runner's
output and its `ResultProviderMetadata`.

## Why it can fail

Each mutant is `chatloop.go` with one change, run with `go test
-overlay`. Each one fails the new test, and all other `chatloop` tests
pass with it.

| Mutant | New test fails with |
|---|---|
| Runners are not added to the tool map | `Tool not found: computer` |
| Runners are not exempt from the active-tool check | `Tool not active
in this turn: computer` |
| `ResultProviderMetadata` is not attached | nil metadata |
| Provider tools without a runner are not skipped | nil pointer panic |
| Both `ProviderExecuted` filters are removed | 2 results |

Removing only one of the two `ProviderExecuted` filters, in
`ExecuteLocalTools` or in `executeTools`, fails no test, because the
other filter still runs. #30938 deletes the one in `executeTools`.

`go test ./coderd/x/chatd/` also passes with runners left out of the
tool map and the metadata attachment removed. Its subtest
`TestActiveServer_ToolExecutionAndPolicy/provider_runner_executes_and_preserves_metadata`
replays a stored computer-use call and result; it does not run the
runner.

## Validation

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

## Stack

This stack replaces the 20-parameter `executeTools` and the 15-parameter
`executeSingleTool` in `chatloop` with methods on one `toolBatch` type,
and resolves tool name aliases in one place. Production behavior does
not change.

1. #30937 Cover provider tool runners in `ExecuteLocalTools`
2. #30938 Replace `executeTools` and `executeSingleTool` with
`toolBatch`
3. #30939 Resolve tool name aliases in one `toolBatch` method

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 11:02:53 +02:00
J. Scott Miller fc0af7fbd8 feat: open a chat_turn span per prompt (#29771)
**TL;DR:** Wraps each prompt in a `chat_turn` root span with every
lifecycle stage parented under it. The span records one outcome per turn
(`completed`, `interrupted`, `error`, `abandoned`), and the new
`coderd_chatd_turn_outcomes_total` counter counts those outcomes. Turns
stay correct when tasks are canceled, replaced, or retried.

Each prompt runs inside a `chat_turn` root span owned by the runner
(`runnerTurnSpan`). The generation step, prepare, MCP connect, stream,
TTFT, provider attempt, commit, thinking, tool call, compaction, and
retry backoff stages are parented under it, activating the stages from
#29770. `chat_turn` spans are standalone roots: the turn runs on a
worker, often on another replica, and no trace context is persisted.

**Lifecycle**

- **Start.** Each generation loop iteration calls `Ensure`, which opens
the turn if none is open and returns a `turnToken`. The span is
backdated to the trigger: the latest of the last user prompt, a dynamic
tool's result message after it, and a pending compaction request. An
`acquisition` stage covers trigger to pickup.
- **Stale trigger / takeover.** A trigger at or before the previous
anchor opens the turn at now with no `acquisition` and counts
`stale_anchor`. A runner that took the chat over from an owner with a
stale heartbeat (`TakenOver`, from acquisition) opens its first turn at
now with no `acquisition`, so the dead owner's run is not reported as
pickup delay.
- **Newer prompt.** `Ensure` on the current turn with a newer trigger
closes it and opens a new one. The closed turn is `abandoned` unless the
task that ran it records an outcome before releasing it.
- **Finish.** After `FinishTurn` or `EnterRequiresAction` commits, the
step calls `Complete`; `Settle` closes the span after the step's own
stage ends, so the finishing step is inside the turn. A chat waiting in
`requires_action` is outside any turn; the generation resumed by its
tool results opens a new one.
- **Emission.** Closing a turn fixes its end time; its span is emitted
once every task that joined it (`Ensure` takes the task ID) has called
`Release`, which `runTask` does after the task returns. A finishing task
whose `FinishTurn` promoted a queued prompt therefore still counts its
turn as `completed` even when the promoted task's `Ensure` runs before
its `Complete`. `End` at runner exit emits whatever is left.
- **Failure.** A step that commits `FinishError`, or fails closed,
invalidates the turn as `error` after the commit. Errors the task runner
retries, including task timeouts, keep the same turn open; an expected,
non-retryable exit records no outcome and leaves the turn open until the
interrupt task, a newer prompt, or runner exit closes it. A canceled
generation task records no outcome and cannot obtain a turn token, so a
replaced task never touches its successor's turn.
- **Interrupt.** The interrupt task marks the open turn `interrupted`
before `FinishInterruption` commits and closes it after. Only a stop (by
the user or a parent agent) is `interrupted`; it ends with unset span
status, since error status is reserved for `error` turns. runner
shutdown, loss of ownership, and message edits close the turn as
`abandoned` with unset status.
- **Promotion.** Every promoting transition (`FinishTurn`,
`FinishInterruption`, a send to an errored chat, `PromoteQueued`)
returns the promoted message's queued time in its result, and one
`recordQueueWait` helper records a standalone `queue_wait` to the
promotion. The promoted turn opens at the promotion time.

`chat_turn` is observed on `coderd_chatd_stage_duration_seconds` only
for completed turns, so the histogram is completed-turn latency; every
turn still emits its span.

`coderd_chatd_turn_outcomes_total{outcome, chat_kind}` counts every
closed turn exactly once (`completed`, `interrupted`, `error`,
`abandoned`), matching the span's `turn_outcome`, under the
`chat-stage-metrics` experiment. Turn time accounting is in draft
#29772.

**Stages and identity**

- `tool_call` is a live stage around each local tool call in `chatloop`;
the tool runs on its context, and it ends errored only when the tool
fails to execute. Calls that never run (inactive, unknown, or rejected
by policy) record no stage.
- `mcp_connect` carries connected and failed server counts and ends
errored only when servers were configured and none connected.
- The compaction stage carries the model that runs the summary.
- `withStageIdentity` puts scope and chat kind on the turn context.
Detached background work runs in `background` scope as its own trace
roots.
- The `advisor` tool's nested model call appears only as its enclosing
`tool_call`.

ARCHITECTURE.md gains a "Lifecycle tracing" section.

<details>
<summary>Review decisions</summary>

- Turn identity stays timestamp-based with targeted fixes (clamped
acquisition, rotation on a newer trigger, invalidate after commit,
fail-closed invalidation, settle closing invalidated turns) plus a
takeover flag; keying turns on message IDs would not detect takeover and
cannot express interrupted/abandoned outcomes.
- Outcome classification: the interrupt task owns `interrupted`, and
cancellation or a fence mismatch alone never records an outcome, so
shutdown, ownership loss, and edits are `abandoned`. Only `error` turns
set error span status. Remaining ordering races between a step and an
interrupt are documented as known limitations in ARCHITECTURE.md.
- Turns are emitted after the tasks that ran them return, not when they
close, so an outcome a replaced task records while unwinding reaches its
own turn; the successor task is not delayed. Chosen over an
after-commit, pre-publish hook on `ChatMachine.Update`, which would fix
only the `FinishTurn` ordering.
- `requires_action` ends the turn rather than pausing it, so `chat_turn`
measures chatd time; a prompt with client tools counts as several turns.
- Promoted turns anchor at promotion time and `queue_wait` is always
standalone, so `chat_turn` never includes time spent queued behind
another turn.
- The former `capacity_wait` stage (#29805) was dropped: it was a
per-worker lower bound, excluded from accounting, and needed its own SQL
and bookkeeping. #29805's remaining helpers are folded into this PR.

</details>

Supersedes #28972, #28973, and #29805.

🤖 This PR was generated by Coder Agents on behalf of @jscottmiller.
2026-09-30 11:53:58 -05:00
Mathias Fredriksson fa5bac6e77 feat: send tool call IDs and cancel unresolved calls on interrupt (#29954)
Retries and replica takeovers ran tool calls again, and an interrupt
recorded the same generic result whether a call had finished, was
still running, or never started.

chatd now derives a tool call ID from the chat, the committed
assistant message, and the provider tool call ID, and sends it with
execute starts, edit_files, and write_file. Every replica and retry
computes the same ID, so the agent returns the first result instead
of running the tool again, and a retried foreground execute waits
only for the rest of its timeout.

On interrupt, chatd cancels the unresolved calls of those tools on
the agent before committing, within 30 seconds, and records what
happened: "tool call was canceled before it ran; no changes were
made", the output of a command canceled while running, or the real
result. The UI shows a canceled command with the existing killed
marker. If the cancel fails, including an old agent's 404, the result
stays the generic interrupted text.

Calls whose provider tool call ID is empty or repeats in the message
get no ID and behave as before.

Fixes CODAGT-757
2026-09-30 14:31:52 +03:00
Michael Suchacz fd5b37576a feat(coderd): record provider response IDs on chat messages (#29763)
Chat messages could only be linked to AI Gateway records per chat, so
nothing recorded which model response produced a given message.

fantasy surfaces the response ID the model endpoint returns on the
stream's finish part: the Anthropic Messages ID as the part ID, and the
OpenAI Responses ID in provider metadata. chatd now stores that ID in
the existing `chat_messages.provider_response_id` column for assistant
steps and the compaction summary row. No migration and no aibridge
changes.

What the stored value is depends on the route:

| Route | Stored value | Joins to |
|---|---|---|
| Anthropic Messages API through the AI Gateway (Anthropic and Bedrock
Claude) | The gateway's interception ID. The gateway replaces the
message ID because injected MCP tool loops can fold several upstream
messages into one response. | `aibridge_interceptions.id` |
| OpenAI Responses API through the AI Gateway | The upstream `resp_` ID,
passed through unchanged | `provider_response_id` on
`aibridge_token_usages`, `aibridge_user_prompts`, and
`aibridge_tool_usages` |
| Direct to the provider | The provider's own ID (`msg_`, `resp_`) |
Nothing in the gateway tables |

To resolve messages to interceptions, then read usage by
`interception_id`:

```sql
SELECT cm.id AS chat_message_id, i.id AS interception_id
FROM chat_messages cm
JOIN aibridge_interceptions i ON i.id::text = cm.provider_response_id
UNION
SELECT cm.id, tu.interception_id
FROM chat_messages cm
JOIN aibridge_token_usages tu ON tu.provider_response_id = cm.provider_response_id;
```

Not covered, and left NULL:
- Partial rows saved on interrupt, because fantasy only reports the ID
in the finish part.
- Chat Completions providers (OpenAI-compatible, OpenRouter, Vercel),
because fantasy does not surface the chunk ID there.
- User, tool, and system rows, and all existing messages.

<details>
<summary>Delivery record</summary>

- `96a896c` replaced the earlier interception-link design (`59fa58f`,
`7f93c18`, `9d04ccd`) in place: the aibridge hook, the
`aibridge_interception_id` column and migration, the message part buffer
tracking, and the `ARCHITECTURE.md` section are all removed. The net
diff against the base touches only `coderd/database` and
`coderd/x/chatd`.
- Local validation on `96a896c`: pre-commit hook green (gen, fmt, lint,
build); `go test ./coderd/x/chatd/... ./coderd/database/` green.
Red-green: removing the finish-part capture fails both new end-to-end
tests (`TestActiveServer_PersistsAnthropicMessageID`,
`TestOpenAIResponsesPersistsProviderResponseID`). CI on `96a896c`:
green.
- Remote UAT round 2 on `96a896c`
([chat](https://dogfood.cdr.dev/agents/75353a23-cd9e-4c81-a99f-472c78f3ba32)):
**FAIL** against this description's earlier claim that every stored ID
joins the gateway usage rows directly. Anthropic rows routed through the
gateway stored the interception ID, so 0 of 18 joined usage rows
directly, while every checked Anthropic row equaled
`aibridge_interceptions.id`. Both OpenAI Responses rows joined directly.
Interrupted partial rows, Chat Completions rows, and user and tool rows
were NULL, with no empty strings or duplicate IDs. Multi-step turns,
manual compaction, edit and regenerate, a provider switch, and a retried
429 behaved as expected. One unattributed anomaly: a single duplicate
user row after interrupt and continue, which did not reproduce and is
outside this diff.
- `2e889ba` corrects the doc comment on
`PersistedStep.ProviderResponseID` and this description to match;
behavior is unchanged. Pre-commit hook and CI green.
- Remote UAT round 3 on `2e889ba` against the corrected contract ([same
chat](https://dogfood.cdr.dev/agents/75353a23-cd9e-4c81-a99f-472c78f3ba32)):
**PASS**. The query above resolved all 40 stamped rows to exactly one
interception from the same chat, with none unresolved. Reading usage by
interception recovered every usage row for 38 of them; the last two
resolved but their usage rows were not counted. Fresh Anthropic and
Responses calls, a seven-step tool turn, manual compaction, an Anthropic
to Responses to Anthropic switch in one chat, and a UI reload behaved as
described, and the NULL cases held. Three interrupt and continue
attempts did not reproduce the round-2 duplicate, so it stays
unattributed. Not tested: gateway-injected MCP tool loops (unreachable
from chatd, whose delegated requests skip the gateway's MCP proxy),
direct Anthropic `msg_` IDs, Bedrock, and threshold-triggered
compaction. Both rounds had a verified isolation proof and a clean
dogfood audit.
- Codex rounds 1 to 3 reviewed the old design. Codex round 4 on
`2e889ba`
([request](https://github.com/coder/coder/pull/29763#issuecomment-5796193371),
13:58Z): no major issues
([result](https://github.com/coder/coder/pull/29763#issuecomment-5796267231),
reviewed commit `2e889ba05c`). No unresolved review threads. Review
passes so far: 4 of 6.
- Final head `2e889ba` is the exact commit remote UAT round 3 and Codex
round 4 covered; required checks green.

</details>

> Xum updated this PR on behalf of @ibetitsmike.
2026-09-23 19:01:24 +02:00
Michael Suchacz 8397680687 fix: keep text and image together in MCP tool results (#29332)
## Problem

MCP tool results that mix text and an image (Playwright's default
`browser_take_screenshot` returns `[text, image]`) were reduced to text
only in both MCP conversion paths, so screenshots never reached the
model. The generic tool renderer also showed media results as a JSON
dump of base64.

## Fix

- `mcpclient` and `chattool`: keep all text plus the first usable binary
item. Error flags survive empty and MIME-less results. Only one binary
payload is represented; additional images are still dropped.
- `chatloop`: at execution time, cap tool media at the 10 MiB attachment
limit and correct or reject declared image types by byte signature
(sniffing, not decoding).
- `chatd` prompt build and `chatprovider`: at generation and compaction,
replace media the destination provider cannot accept with the text plus
an omission note (Anthropic/Bedrock: JPEG, PNG, GIF, WebP under the
inline cap; OpenAI/Azure and Google: their image allowlists, applying
the configured vendor's rules behind `openai-compat`). Persisted history
is unchanged, so the UI keeps the payload and provider switches keep
working.
- `site`: results flagged `is_media` render through `ToolResultMedia`
(image with the existing lightbox, or a short notice for non-image
media, plus the text). Unflagged media-shaped JSON stays in the JSON
viewer.
- `go.mod`: pin [coder/fantasy
`9a3598480a71`](https://github.com/coder/fantasy/commit/9a3598480a71e45901bfcfbf566ffa42c6bbdd63),
main's `a511353f83eb` plus the batch-order fix `460d4fdd113b` (Chat
Completions and compatible transports emit every tool result before
synthetic user images). The fix lives on
`mike/mcp-tool-media-batch-order`; no upstream PR yet.

## Validation

Round 3 dogfood UAT on this head, `522bd76a58a`: **PASS**
([chat](https://dogfood.cdr.dev/agents/5e617636-c6f2-46fc-96e5-97ae35ed822e),
real Playwright MCP, Claude Haiku 4.5 and GPT-4o mini through the AI
gateway). Verified in the UI and on the wire: image plus text render
together, the lightbox opens and closes, both survive a reload; audio
shows a notice instead of base64; media-shaped JSON stays in the JSON
viewer; BMP on OpenAI Responses and Chat Completions reaches the model
as text plus an omission note; SVG and PNG histories switch from
Anthropic to OpenAI; cross-provider compaction through the organization
override works; a result over 10 MiB persists only text plus a note, and
a 5.5 MiB PNG is substituted for Anthropic yet still renders in the UI.
Google is not routable on the dogfood gateway (404), so it was not
exercised. The remote agent's own FAIL was a probe artifact (the code
viewer renders in a shadow root) and was overturned on its screenshots
by the independent runner. Rounds 1 and 2 (`65db84a`, `5001de7`) covered
the same API surface earlier.

Known limits: signature sniffing does not catch a truncated PNG with a
valid header (providers return 400 for it), and only the first binary
item of a result is kept. Pre-existing and out of scope: chatd opens a
new MCP session per generation action, so Playwright's default
per-session browser loses page state between steps (UAT used
`--cdp-endpoint`).

Reviews:

| Review | Head | Outcome |
|---|---|---|
| Codex 1 to 5 | `472914f` to `bcf4c72` | 16 findings (empty binary
promoted over text, no provider caps, SVG on Anthropic, provider-switch
gap, Bedrock labels, unbounded media, unvalidated bytes, renderer
gating, lightbox test), all fixed |
| Codex 6, 7 | `8a9a9e0`, `5001de7` | no major issues; one Responses
audio concern [refuted with a live
probe](https://github.com/coder/coder/pull/29332#discussion_r4018514197)
|
|
[Codex](https://github.com/coder/coder/pull/29332#pullrequestreview-5226106293)
| `83e1a10` | two P2s refuted with serializer captures
([MIME](https://github.com/coder/coder/pull/29332#discussion_r4029188332),
[advisor](https://github.com/coder/coder/pull/29332#discussion_r4029160781));
[reassessment](https://github.com/coder/coder/pull/29332#issuecomment-5702295886)
clean |
| Codex | `522bd76` | [no major
issues](https://github.com/coder/coder/pull/29332#issuecomment-5713663081)
on the rewritten tests |
| @DanielleMaywood | `472914f`, `5001de7` | renderer restructure and
explicit audio mapping done; lazy slice cloning removed; two threads
left open for her re-check |

Local pre-push hooks were skipped per Mike's instruction; CI is the
gate.

> Xum acted on Mike's (@ibetitsmike) behalf to create this PR.
2026-09-17 15:09:19 +02:00
Michael Suchacz 0362e5386c fix(coderd/x/chatd/chatloop): tell the model to gather context before retrying an exclusive tool (#29281)
When the model batches `advisor` (an exclusive tool) with other tool
calls, every call in the batch is rejected and the `advisor` result only
says to retry with `advisor` alone. That nudges the model toward
re-calling `advisor` immediately, even when the sibling calls were there
to gather context for it.

Extend the message so the model is told to run the other tools first
when it still needs their output, then retry with only the exclusive
tool call.

Generated by Coder Agents on behalf of @ibetitsmike.
2026-09-15 17:02:48 +02:00
Jaayden Halko b428c8feb6 feat(coderd): bill completed local tool batches in agent runtime (#28360)
**Stack**: #28359 → **#28360 (this PR)** → #28361 → #28362

## Summary

Completed local tool batches now count toward Coder Agent runtime
(`chat_messages.runtime_ms`, the source of truth for
`hb_agent_runtime_v1`), excluding sub-agent orchestration tools to avoid
double counting, and without multiplying runtime for parallel tool
calls.

Second of a four-PR stack splitting #28211. Stacked on #28359. Refs
CODAGT-928
(https://linear.app/codercom/issue/CODAGT-928/track-local-tool-execution-for-agent-runtime).

## Problem

Agent runtime previously measured only model invocation wall clock
(stream open to fully consumed). Time spent executing local tools
between steps, including file operations, terminal commands, workspace
provisioning, and MCP tools, was deliberately excluded, which
undercounts the product definition of "actively processing a task".

Naive inclusion has two hazards: a batch of parallel tool calls would
bill N windows for one wall-clock wait, and `wait_agent` would re-bill
child agents that already bill their own model and tool time.

## Fix

Each completed local tool batch bills one window: the union of the
billed tools' execution intervals, persisted as `runtime_ms` on a
dedicated usage record appended after the batch's tool-result rows. The
record is a tool-role message with `visibility='model'`, so it never
reaches the API, SSE, or clients, and prompt replay drops it because its
single internal `tool-batch-usage` part converts to no provider content.
Its content carries an audit payload (`billed_ms`, `billed_calls`) so
the billed window is inspectable after the fact; real tool-result rows
never carry batch-level runtime. Concurrent calls all start at batch
start, so 5 parallel 10s reads bill 10s, not 50s; serial calls
(`SerialToolCalls`) count only from their own launch, so unbilled waits
before them do not count.

Sub-agent orchestration tools (`spawn_agent`, `wait_agent`,
`message_agent`, `interrupt_agent`, `list_agents`,
`list_subagent_models`, plus the deprecated `close_agent` alias) never
extend the window: every chat, including children, applies the same
rules to its own runtime, so a parent's `wait_agent` window would double
count. A lone `wait_agent` bills 0 and appends no usage record;
`execute` 10s in parallel with `wait_agent` 60s bills 10s. A test pins
the unbilled set to the registered sub-agent tool catalog so they cannot
drift.

`GetTotalChatMessageRuntimeMsInRange` already sums `runtime_ms`
role-agnostically, so the usage record is picked up with no schema,
query, or cron changes.

Client-executed dynamic tools, external agents, parked/idle time, and
retry backoff remain unbilled. Interrupted batches still bill only the
model window; the rest of the stack adds partial-window billing via the
same usage record.

`ExecuteLocalToolsOptions` also gains an optional `ToolBillingRecorder`
(`RecordStart`/`RecordComplete`) observing per-occurrence dispatch-order
execution stamps. This PR wires no recorder; the next PR in the stack
connects it to the message part buffer for interrupt billing.

**NOTE**: Reported agent runtime (`hb_agent_runtime_v1`) increases from
deploy forward. There is no backfill and no feature flag.
2026-08-25 16:40:41 +07:00
Michael Suchacz 7724ee281a feat: defer MCP tool schemas behind a find_tools search (#28225)
## Summary

When the `mcp-tool-search` experiment is enabled, chatd stops inlining
connected MCP tool schemas into every generation. It instead exposes a
built-in `find_tools` tool whose description carries a compact catalog
of the deferred tools, and only ships full JSON schemas for tools the
model has activated by searching or by calling them directly.

Closes [CODAGT-760](https://linear.app/coder/issue/CODAGT-760).

## Problem

Tool-heavy agent configurations (GitHub, Linear, Notion, and dev-tooling
MCP servers) inline over 100k tokens of tool schema definitions into
every generation. Initial uncached requests reached ~216k tokens with
time-to-first-token close to nine minutes, while the model typically
invokes only a handful of tools per turn.

## How it works

- `decideMCPToolSearch` defers external and workspace `.mcp.json` MCP
tools whenever the experiment is enabled. Native, dynamic, provider,
skill, and transport tools are never deferred.
- `find_tools` embeds a server-grouped catalog in its tool description
(degrading to names-only, then counts-only, then a constant-size summary
past a context-scaled size cap) and scores keyword matches across tool
names, descriptions, parameter schemas, and server metadata. Queries can
scope to one server with a `server:` prefix, and exact `names` arguments
always activate.
- Activation state is ephemeral: it is re-derived each generation from
surviving chat history (`find_tools` results and direct calls to
deferred tools), so activations naturally lapse when compaction
summarizes them away. Aggregate activated schema weight is capped at 10%
of the context window, shedding the least recently activated schemas
first; `find_tools` shares that budget across parallel calls in one
step. No new persistence.
- Deferred tools stay registered for execution, so the model can call a
cataloged tool directly without searching first; the schema is activated
for subsequent steps.
- Fail-open: the experiment being disabled, an empty candidate set, or
an MCP tool named `find_tools` all disable deferral, leaving today's
behavior byte-identical on the wire.
- Prometheus counters/histograms track `find_tools` calls, matches,
activations, and deferred token weight.
- The conversation timeline renders `find_tools` calls with a collapsed
search summary and expandable match list, falling back to the generic
renderer on malformed payloads.

## Validation

- Unit tests for the catalog, matcher, experiment-gated decision, and
activation derivation; end-to-end chatd generation tests covering
search-then-call, direct-call activation, experiment-off wire parity,
compaction lapse, and subagent tool gating.
- Storybook interaction tests for the timeline rendering and
malformed-payload fallback.
- Remote dogfood UAT on dev.coder.com passed: deferral with a real MCP
server and Anthropic model, direct calls without prior search,
activation persistence across turns, experiment-off parity, and clean
UI/console.

> Disclosure: Mux (AI agent) authored this PR on Mike's behalf.
2026-08-18 19:12:47 +02:00
Mathias Fredriksson 59fcc9c0ad feat: improve sub-agent orchestration tools (#26673)
Tool errors caused orchestrators to abandon spawned agents. Bare error
responses and the close_agent name framed delegation as one-shot: one
transient failure or timeout ended the work, and the orchestrator had no
way to recover or reuse agents.

Renames close_agent to interrupt_agent with a hidden backward-compatible
alias. wait_agent and message_agent return structured payloads instead
of bare errors, so the orchestrator can retry after a timeout, recover
from an error status, or redirect an idle agent. Adds list_agents so
orchestrators can rediscover spawned agents. Adds root-only
orchestration guidance for error recovery.
2026-06-26 13:41:43 +03:00
Kyle Carberry 32217259b7 feat: cap tool output to fit the model context window (#26637)
## Problem

Local tool results were persisted and replayed to the model verbatim,
with no size cap. A single oversized result, most often a multi-megabyte
response from an MCP tool, overflows the prompt on the next request.
Every retry rebuilds the same history and fails the same way, leaving
the chat wedged in `error`. Auto-compaction is reactive (token usage is
only known after a response), so it can't catch a single result that
blows the very next request.

## Fix

Cap every locally-executed tool result at its single choke point,
`executeSingleTool` in `chatloop`, so the cap covers built-in tools,
**global (deployment-pinned) MCP**, **workspace MCP**, and provider
runners uniformly. Because this runs before the result is published to
the live stream and before it is committed, the SSE preview, the
persisted message, and the model replay all see the same bounded output.

The budget is token-aware: a single tool result may use at most half the
model's context window (`~4 bytes/token`), with a `16KB` floor and a
`64KB` default when the window is unknown. Truncation keeps the head and
tail of the output and replaces the middle with a marker telling the
model how much was removed and to narrow its query; it is UTF-8 safe and
never exceeds the budget. Binary media `Data` is passed through
untouched (only the text payload is bounded).

A `coderd_chatd_tool_result_truncated_total{provider,model,tool_name}`
counter and a warning log record each truncation.

## Out of scope

- Provider-executed results (e.g. web search) arrive via the stream, not
`executeSingleTool`.
- Dynamic/external tool results submitted through the `/tool-results`
API are validated as JSON elsewhere.
- Cumulative growth across many results is still handled by context
compaction; this change only bounds any single result.

<details>
<summary>Implementation notes</summary>

- New `coderd/x/chatd/chatloop/tooltruncate.go`:
`toolResultByteBudget(contextLimitTokens)` and
`truncateToolResultText(text, maxBytes)` (pure, unit-tested).
- `chatloop.go`: added `ContextLimit` to `ExecuteLocalToolsOptions`;
threaded a computed byte budget through `executeTools` into
`executeSingleTool`, where `resp.Content` is capped for the text,
media-text, and error branches.
- `generation.go`: passes `ContextLimit: prepared.ContextLimitFallback`
(the model's configured context limit).
- `metrics.go`: new `ToolResultTruncatedTotal` counter +
`RecordToolResultTruncated`.
- Tunable knobs live as constants in `tooltruncate.go`
(`toolResultContextDivisor = 2`, `bytesPerTokenEstimate`,
`minToolResultBytes`, `defaultToolResultBytes`).

Verified: `go build ./coderd/x/chatd/...`, `go test
./coderd/x/chatd/chatloop/...`, and the `chatd` test binary compiles.

</details>

---

Resolves CODAGT-678

Generated by Coder Agents on behalf of @kylecarbs.
2026-06-24 09:16:38 -06:00
Cian Johnston 21a2652343 fix(coderd/x/chatd): show correct provider and clean detail for Bedrock errors (#26338)
## Problem
Bedrock errors (routed through aibridge) showed the wrong provider
("Anthropic ...")
and a doubly-wrapped detail string instead of the clean message.

## Fix (chatd only)
- **Provider label:** thread the configured provider to error
classification via
`GenerateAssistantOptions.ErrorProvider`. Transport provider still
drives prompt
  prep, sanitization, and metric labels (unchanged).
- **Detail:** unwrap the SDK transport wrapper (`METHOD "URL": NNN
{body}`) to surface
the inner message; handles top-level `{"message":...}` and nested
`{"error":{"message":...}}`.

## Notes
- Surfacing a top-level `message` now applies to all providers
(intentional; nested wins when both present).
- The advisor path keeps the transport label; accepted as-is (it returns
`err.Error()`, not the classification).
- Fixes display in chatd only; the wrapper originates in aibridge (out
of scope here).

🤖 Generated by Coder Agents.
2026-06-16 11:14:37 +01:00
Hugo Dutka 4debd23cbb fix: chatd refactor (#26270)
Implements the chatd stabilization RFC.

Combines:
- https://github.com/coder/coder/pull/25908
- https://github.com/coder/coder/pull/25923
- https://github.com/coder/coder/pull/26109
- https://github.com/coder/coder/pull/26110
- https://github.com/coder/coder/pull/26111
- https://github.com/coder/coder/pull/26112
2026-06-12 13:33:12 +02:00
Ethan 3ab1323bc9 fix!: rename chat stream silence timeout error (#25973)
Renames the Agents chat stream-silence error from `startup_timeout` to
`stream_silence_timeout` now that the timeout applies to any gap between
provider stream parts, not just first-token startup.

Updates the SDK enum, generated API docs/types, chat error copy, and
Agents UI stories/status labels so the user-facing wording describes a
stalled provider response instead of startup delay.

> **Breaking change:** This is a very minor breaking change for the
Coder Agents API: the public chat error kind enum no longer includes
`startup_timeout`, so clients matching that specific value should handle
`stream_silence_timeout` instead.
2026-06-04 18:36:02 +10:00
Ethan becc858fa8 fix(coderd/x/chatd): retry provider stream cancellations (#26010)
Closes CODAGT-541.

## Problem

An Agents chat stream could die with a terminal `context cancelled`
error and surface to the user as a permanent chat failure, even when no
context in our process had actually been canceled. The cancellation was
a provider-returned error value (HTTP/2 RST_STREAM mid-body surfacing as
`context.Canceled` from Go's net/http2), not a real caller cancel.

The chain that produced the bug:

- fantasy passed the provider's `context.Canceled` through unchanged.
- `chaterror.Classify` short-circuited any `errors.Is(err,
context.Canceled)` (or `"context canceled"` text) as terminal generic,
before checking HTTP status codes or other retry signals.
- `chatretry.Retry` did not retry.
- The frontend rendered `type:"error"` and the chat was dead.

The same short-circuit also masked retryable 5xx responses whose
underlying transport error happened to wrap `context.Canceled`.

## Approach

`context.Canceled` has no inherent intent. The same error value can mean
a user pressing Stop, a server shutdown, the silence guard firing, or a
provider-side stream reset. The only layer that can disambiguate is the
one holding both the returned error and the caller context. That is
`chatretry`.

This PR centralizes the policy there and keeps `chaterror` context-free.

## Changes

`coderd/x/chatd/chaterror/classify.go`

- Add `ErrProviderTransportReset` sentinel to explicitly mark
provider-side stream cancellations.
- Remove the broad `context.Canceled` / `"context canceled"`
short-circuit so status codes and other retry signals can win.
- Classify `ErrProviderTransportReset` (with no status code) as a
retryable timeout.
- Keep a fallback that classifies bare `context.Canceled` as
terminal-generic when no other signal is present, so legitimate caller
cancels still terminate cleanly.

`coderd/x/chatd/chatretry/chatretry.go`

- Add `contextError(ctx)` that returns `context.Cause(ctx)` when set,
falling back to `ctx.Err()`, so caller-owned cancel causes
(`ErrInterrupted`, `errStreamSilenceTimeout`, server shutdown sentinels)
propagate cleanly out of the retry loop.
- Add `classifyProviderAttemptError(err)` that wraps a bare
`context.Canceled` in `ErrProviderTransportReset` and reclassifies.
Errors that already classify as retryable or carry a status code are
left alone.
- Restructure `Retry` so the policy is explicit and readable: check
caller cancellation before attempting, run the attempt, check caller
cancellation again before normalizing the provider error, then classify
and retry.

## End-to-end behavior

- Provider returns `context.Canceled` while caller context is healthy:
classified as a retryable timeout, retried, the user sees a brief
`type:"retry"` event and the chat continues.
- User presses Stop: `contextError(ctx)` returns `ErrInterrupted`. Retry
stops. `chatloop` flushes partial content and persists.
- Stream-silence guard fires: `attemptCtx` is canceled with
`errStreamSilenceTimeout`, `guardedStream` produces a classified
retryable error, retry proceeds normally on the still-alive parent.
- Server shutdown: parent context's cause propagates out, retry stops.
2026-06-04 12:52:37 +10:00
Ethan 7e2f7198dd fix(coderd/x/chatd/chatloop): use stream silence timeout (#25782)
Replaces the 60 second first-token timeout in the chat loop with a 10
minute stream-silence timeout.

Previously, the guard bounded only the gap before the first stream part.
Once any part arrived the attempt could hang indefinitely if the
provider stopped streaming without closing the connection, and even
normal long-running responses could be killed after 60 seconds if the
provider was slow to emit the first token.

The guard now arms when a model attempt opens its stream, resets on
every received stream part, and fires after 10 minutes of complete
silence. The existing retry path still handles the timeout, and the
public `startup_timeout` error kind is preserved to avoid API and
frontend churn.

10 minutes matches the default request timeout used by the Anthropic and
OpenAI Python SDKs.


Closes CODAGT-493
2026-05-28 21:02:40 +10:00
Ethan c650aabbef chore: standardize on *_internal_test.go for white-box tests (#25601)
My agent added `//nolint:testpackage` to a test file on one of my PRs.
Again. This PR cleans it up across the entire repo and updates the
in-repo conventions so future agents stop doing it.

The repo already has a precedent for white-box tests that need to touch
unexported symbols: `*_internal_test.go` (145+ existing files). The
`testpackage` linter's default `skip-regexp` exempts that filename
suffix, so the `//nolint:testpackage` directive is unnecessary in every
case where someone reached for it. This PR renames 51 such files to
`*_internal_test.go` via `git mv` so blame and history follow, and
strips the dead directive from 2 files that were already correctly named
(`coderd/oauth2provider/authorize_internal_test.go`,
`coderd/x/chatd/advisor_internal_test.go`).

`.claude/docs/TESTING.md` now documents the rule explicitly under *Test
Package Naming*, which is imported into the root `AGENTS.md` via
`@.claude/docs/TESTING.md`. The rule: prefer `package foo_test`; if you
need internal access, rename the file to `*_internal_test.go` rather
than adding a nolint directive.
2026-05-22 20:24:38 +10:00