mirror of
https://github.com/coder/coder.git
synced 2026-11-24 21:48:40 +08:00
c20de5038c32bdb267cf045e2ee5cc9aa992e693
4973
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
cdac1d08cb |
refactor(coderd): move chat model ACL handlers onto the shared ACL helpers (#31015)
Moves the chat model ACL handlers onto the organization ACL helpers in `coderd/mcp_acl.go`, which MCP server configs and organization skills already share. It deletes the model copies of the user and group resolvers, the member count query, the list of available principals, the organization and duplicate ID checks, and the role update loop: 30 lines added, 321 removed. Two shared helpers change: - `resolveACLUsers` and `resolveACLGroups` pass each stored ACL entry to the callback, so the model ACL reads each role from it. - `resolveACLGroups` takes an organization ID. The model ACL passes its organization, so groups from other organizations stay hidden. MCP server configs and organization skills pass `uuid.Nil`, which keeps every organization, as today. **What changes:** successful responses stay the same. On error paths, a stored key that is not a UUID is skipped without a warning log (`PATCH` validation rejects such keys), `500` details use the shared texts (`get ACL users` instead of `hydrate chat model ACL users`), duplicate ID errors come back in the same `400` as the other validation errors because the check now runs inside the write transaction, and a failed membership lookup skips the group check. **Why it is safe:** `TestChatModelACL` checks that groups from other organizations stay hidden, and `TestChatModelACLValidationIsAtomic` covers the duplicate check. I ran 9 mutants of the changed lines with `go test -overlay`: ignore the organization in `resolveACLGroups` or pass `uuid.Nil` from each handler, drop the stored entry given to either callback, report zero members, and apply group roles to users or user roles to groups. The tests fail on each. **Review focus:** `uuid.Nil` means every organization in `resolveACLGroups`, as it does in `GetGroups`. Validation: on `main` and on this branch, `go test ./coderd -run '(?i)acl|mcp|skill' -count=1` passes (24 tests, 62 with subtests) and `go test ./enterprise/coderd -run '(?i)acl|mcp|skill|TestEnterpriseAuditLogs' -count=1` passes (9 tests, 46 with subtests). The pre-commit hook passed (`make gen`, formatting, golangci-lint, slim build). ## Stack This stack moves the chat, chat project, and chat model ACL handlers onto the organization ACL helpers that MCP server configs and organization skills share, and deletes their copies. Successful ACL responses do not change. 1. #31014 Pin member counts and user details in chat and project ACL reads 2. #31015 Move chat model ACL handlers onto the shared ACL helpers 3. #31016 Move chat and chat project ACL reads onto the shared helpers > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
d46a94770b |
test(coderd): pin member counts and user details in chat and project ACL reads (#31014)
Adds five assertions to `TestChatProjectSharing` and `TestChatACLSharingLifecycle`. It is the test-first layer for the refactor above it, so it adds 8 test lines and removes none. **Why it is needed:** the next layers move the chat and chat project ACL reads onto the shared resolvers in `coderd/mcp_acl.go`, which also replaces the per-group member count query of the project read with one batched query. No test checked a group's member count or any user field other than the ID in those reads, so a wrong count or a dropped username would still pass. The new assertions check that: - the project ACL lists the `Everyone` group with 3 members and a custom group with 1, - the project and chat ACL users carry their usernames. **Proof:** the tests pass on `main` and on this branch. I ran 5 mutants of the `main` read code with `go test -overlay`: report a zero member count, count the members of the wrong group, count system users, and return only the user ID in the project read and in the chat read. Each mutant fails these tests and passes the tests on `main`. Validation: `go test ./coderd -run '^(TestChatProjectSharing|TestChatACLSharingLifecycle)$' -count=1` passes, and the pre-commit hook passed (`make gen`, formatting, golangci-lint over every package, and the slim build). ## Stack This stack moves the chat, chat project, and chat model ACL handlers onto the organization ACL helpers that MCP server configs and organization skills already share, and deletes their copies. ACL responses do not change. 1. #31014 Pin member counts and user details in chat and project ACL reads 2. #31015 Move chat model ACL handlers onto the shared ACL helpers 3. #31016 Move chat and chat project ACL reads onto the shared helpers > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
55573833d0 |
fix(coderd/database): lock the workspaces row when claiming a prebuild (#31518)
`ClaimPrebuiltWorkspace` locked the `workspace_prebuilds` view with `FOR UPDATE ... SKIP LOCKED`, but the view is built from CTEs, so nothing got locked. Concurrent claims picked the same prebuild and the losers got a 409 (a customer saw 28 of 30 fail). This locks the `workspaces` row directly (`FOR NO KEY UPDATE SKIP LOCKED`), rechecks owner and deleted on it, and checks eligibility with per-workspace index lookups instead of the views. It uses `=` instead of `IN` so one claim can't take two prebuilds, filters on the preset's template so other templates' prebuilds aren't scanned, and claims oldest first so prebuilds are used before they hit the preset TTL. Query-only, no migration, applies cleanly to release/2.38. Builds on #31468 by Kevin Ha (Canva). Benchmarks (Postgres 17, 20k users, 320k builds, 600 ready prebuilds): ~12 ms per claim (was ~640 ms), and 500 concurrent claims got distinct prebuilds in ~1.5 s. Known limitations: - Each claim still checks every prebuild of the preset's template (other presets included) before sorting. That's a few ms at hundreds of prebuilds per template. - Pre-existing: a reconciler delete during a claim can still 409. Follow-up is a `deleting_at` marker the claim skips. --------- Co-authored-by: Kevin Ha <kevinh@canva.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b0a571888c |
refactor(coderd/x/chatd): validate model overrides once (#31347)
`SendMessage`, `EditMessage` and `EditQueuedMessage` validate a requested model config once, before hooks and the chat transaction. Model config writes serialize on an organization advisory lock that chat transactions do not take, so a second check under the chat row lock could not stop a concurrent disable. If the config is disabled after the check, the turn runs on the organization default model. Fallback resolution stays in the transaction because it reads the locked chat. Refs CODAGT-971 |
||
|
|
f8a138065d |
refactor(coderd/x/chatd): link files inside message transitions (#31353)
`Tx.SendMessage`, `Tx.EditMessage` and `Tx.EditQueuedMessage` take `FileIDs` and `MaxFileLinks`, as `CreateChatInput` does, and call `LinkFiles` themselves, so a link failure rolls back the whole message write. `store_chat_attachment.go` keeps its direct call because it links a file without a message transition. Refs CODAGT-971 |
||
|
|
c3436cb3e0 |
fix(coderd/x/chatd): keep wait_agent waiting on a paused child (#29292)
`wait_agent` treated every status except `running` and `interrupting` as done, so a paused child returned its last assistant message as its final report while a queued message was still under edit. A paused child is not done: `wait_agent` keeps waiting, and on timeout returns `status: "paused"` with `timed_out: true`. The `wait_agent` and `list_agents` descriptions say a paused timeout is expected. Closes CODAGT-1026 Refs CODAGT-971 |
||
|
|
c0f7663e95 |
feat: support editing queued chat messages (#29215)
The owner of a chat can edit a queued message through
`PATCH /api/v2/chats/{chat}/queue/{queuedMessage}`. chatd never sends
a row under edit (`editing_since`): rows ahead of it still send in
order, and a turn that ends at it puts the chat in the new `paused`
status. Ending the head's edit, deleting it, or promoting a queued row
continues the chat. Interrupting sends still run ahead of the queue.
The chat state machine classifies a queue whose head is under edit as
its own sub-state (R1P, I1P, A1P, E1P, XE1P, P), so every path to
`paused` is in the transition matrix. A chat whose family has a paused
member cannot be archived, and auto-archive skips that family. Queue
edit and delete are owner-only, because both can send the next message
with the owner's credentials.
`ChatQueuedMessage` gains `editing_since` and `reasoning_effort`, and
`ChatStatus` gains `paused`.
Closes CODAGT-1028
Refs CODAGT-971
|
||
|
|
5baa8eff01 |
feat: price AI Gateway token usage with the request organization (2/2) (#31121)
Cost looks up model prices site-wide only, so an organization's own prices never apply, even though #31118 now stores the request organization on each interception. Pass the interception's stored organization to `GetAIModelPriceForProvider`. The lookup already falls back from the organization's price to the site-wide custom price, then to the price book. An interception without an organization (old rows, old gateways) uses only site-wide prices, as before. | Stored org | Org price | Site-wide custom | Price used | |---|---|---|---| | none | any | any | site-wide custom, then price book | | B | live | any | B's price | | B | soft-deleted or absent | present | site-wide custom | | B | absent | absent | price book, or NULL cost | Remove `TODO(AIGOV-716)`. Make `TestRecordTokenUsageAuthorized` store an organization and assert that its price wins under the strict authorizer. Part of AIGOV-716. Stacked on #31120. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
15365c69cf |
feat: use the resolved organization for AI Gateway budgets and cost (1/2) (#31120)
`IsAuthorized` resolves the workspace organization, but uses it only to
reject requests; nothing downstream reads it. The budget check and cost
each resolve the group site-wide, so a user working in an org B
workspace can be billed in org A, and no interception records its
organization.
Resolve the request organization once, in `IsAuthorized`. A workspace
session token resolves to the workspace's organization (source
`workspace`). Any other request, including chatd requests until
AIGOV-713, resolves to the organization of the user's site-wide
effective group (source `effective_group`). Return the source in
`IsAuthorizedResponse`.
Have aibridged pass the organization to `IsBudgetExceeded`, which
resolves the budget inside it, and stamp the organization and source on
`RecordInterception`. Resolve cost's effective group inside the
organization stored on the interception. When there is no organization,
behave site-wide as before.
Move `resolveOrganization` and the workspace checks into
`orgresolver.go`, and leave a slot for the chat organization
(AIGOV-713). Bump the aibridged API to v1.6, adding
`IsAuthorizedResponse.organization_source` and
`IsBudgetExceededRequest.organization_id`.
aibridged checks only the shape of the organization (both fields or
neither, and a valid non-nil UUID), not the source value. That lets a
newer coderd add a source without breaking older gateways.
Behaviour changes to review:
- Spend follows the workspace's organization. A user whose budgets are
all in org A has no limit in an org B workspace if B has none.
- A database error while resolving the organization now returns 403 from
`IsAuthorized`, instead of 500 from `IsBudgetExceeded`.
- Requests without a workspace make up to three extra budget queries in
`IsAuthorized`.
- The user spend status endpoint (`GET /api/v2/users/{user}/ai/spend`)
stays site-wide, so it can disagree with where a request was charged.
The org-aware price lookup follows in #31121.
Part of AIGOV-716. Stacked on #31119.
---
*This PR was generated by Coder Agents on behalf of @SasSwart.*
|
||
|
|
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. |
||
|
|
08a10228db |
refactor(coderd/x/chatd): inline the model config provider identity (#31000)
This PR deletes `modelConfigProviderIdentity` and its test table; both callers now use `AIProviderID.UUID.String()` directly. The helper fell back to the provider type name for model configs without an `ai_provider_id`. It changes no behavior, because no such config reaches either caller: the `chat_model_configs_ai_provider_required_when_active` check constraint allows a NULL `ai_provider_id` only on deleted configs, and both callers reject such a config before they read the identity. - Turn preparation resolves the chat's config through `gatewayProviderForConfig`, which returns "AI Gateway routing requires AI provider metadata" for a config without a provider ID. - History sanitization resolves each row's origin config through `resolveNormalizedProviderForModelConfig`, which returns `sql.ErrNoRows`. The sanitizer treats that origin as unavailable and strips the row's provider-specific state (fail closed), as before. **Why it is safe** The deleted table tested the helper. Its live contract is that identity is the provider instance UUID, so two providers of the same type are distinct. I mutated the two inlined lines and ran `./coderd/x/chatd/` with `go test -overlay`. The tests catch all three mutants: - Turn target identity set to the provider type: `TestActiveServer_AnthropicProviderToolPreRequestGuard`, `TestOpenAIResponsesFullReplayPairsReasoningAndWebSearch` and others fail. - Origin identity set to the normalized type: the same tests fail. - Both sites set to the type, so they agree: `TestOpenAIResponsesReasoningNotReplayedAfterModelConfigChange/ProviderMoved` and `TestProviderSwitchSanitizesAndRestoresPEToolHistory` fail. `git grep modelConfigProviderIdentity` finds no references left in the repository, including `site/`, `enterprise/`, `cli/` and `docs/`. **Review focus** `sanitizeForeignProviderStateRows` now discards the normalized provider name that `resolveModelConfigAndNormalizedProvider` returns. It still calls that function, because the function also checks that the config is enabled and its provider is valid. **Validation** - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: ok - `go vet ./coderd/x/chatd/` and `golangci-lint run --fix=false ./coderd/x/chatd/...`: clean - pre-commit hook: passed **Stack** This stack retires chatd compatibility paths for chat data that older Coder versions stored. 1. #30996 stamp chat message fixtures with the current content version 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 (this PR) 5. #31005 retire the `close_agent` tool alias > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
ea79a9885a |
fix: return a partial page from read_file instead of an error (#31470)
Closes CODAGT-435 When a `read_file` response would go over 32 KB, the agent returned an error and no content, telling the model to "Read less at a time using offset and limit parameters". That's most source files over about 32 KB, so the model would lose a turn on each one just to pick a smaller range. #22400 made these hard errors on purpose, so the model wouldn't answer from partial data, but most of the prior art I looked at (pi-mono, Gemini CLI, opencode, Cline) just returns what fits and says where to continue. I think that handles the partial data concern better, as the model is told exactly which lines it has. So, the agent now ends the page at whichever comes first of `limit`, 2000 lines, 32 KB, or the end of the file, and returns it as a success. `workspacetools.ReadFile` then adds a `note` to any page that stops before the end of the file, so the chat tool and the MCP tool both get it. Reading `agent/agentfiles/files.go` with no `offset` or `limit` used to error, and now gives 956 lines with: > Showing lines 1-956 of 1576. To read more, call this tool again with offset=957. The issue suggested returning a chunk plan (e.g. `[[0,200],[200,600],...]`) instead. The model needs one call per page either way, and a chunk list would depend on the current limits and line lengths, whereas the next offset is just `offset + lines_read`. A `limit` over 2000 is now clamped rather than erroring, and `total_lines` no longer counts a trailing newline as an extra line, since the note's maths depends on it. I also dropped the "use offset and limit to read a portion" hint from the 1 MB error, as that check runs before `offset` and `limit` are applied. Workspaces running an older agent will keep returning the error until their agent is updated. I tested this on a dev deployment through Coder Agents, asking Claude Haiku 4.5 and GPT-4.1 mini to read a 108 KB and a 118 KB file (3000 and 3200 lines) using only `read_file`, then report the last line. Both followed the note through to the end of the file (Haiku in 4 calls, GPT-4.1 mini in 5) and got the last line right, whereas on `main` the first call just errors. `coder_workspace_read_file` over MCP gives the same note. The only odd behaviour I saw was Haiku once skipping straight to the end of a file when the prompt only asked about the last line, which I think is on the model rather than the tool. |
||
|
|
0a737cd857 |
refactor(coderd)!: retire the V0 chat message content decoder (#30998)
This PR breaks compatibility with chat messages stored in the legacy content format (`chat_messages.content_version = 0`). No release stored such messages, because Coder Agents (#22290) and `content_version` (#23042) first shipped together in v2.32.0. Only deployments that ran a preview build of `main` between 2026-02-27 and 2026-03-13 (in practice, dogfood) have them: migration 000434 (#23042) stamped every row that existed then with version 0, and nothing converts them later. The PR deletes the legacy decoder from `chatprompt`: `ContentVersionV0`, `parseLegacyContent` and its per-role parsers, the fantasy envelope detector `isFantasyEnvelopeFormat`, `ExtractFileID`, and the legacy tool-row type `toolResultRaw`. Coder Agents is experimental (`coderd/x`), so we drop legacy persisted shapes and the helpers that parse them outright instead of carrying a migration. What happens to those messages: `ParseContent` now returns `unsupported content version 0`. Throwaway API tests on this head show the effect on a chat with version 0 rows: - `GET /api/v2/chats/{chat}/messages` returns 200, but the version 0 messages have no content. - A send to a waiting or errored chat, and an edit, first parse the last assistant message (for an edit, the last one before the edited message) to cancel its pending tool calls. If it is version 0, they return 500 (`Failed to create chat message.` or `Failed to edit chat message.`, detail `execute transaction: parse assistant message: unsupported content version 0`). By code reading, promote does the same. - Otherwise they return 200, and an edit deletes the edited message and every later one. If a version 0 row remains before the new message, the turn fails in the worker (`build chat prompt: unsupported content version 0`) and the chat goes to error. - Recovery: editing the first user message deletes it and every later row, so a new turn runs; another send alone leaves the chat in error. Chats created through the API on those preview builds cannot recover this way: each starts with its system prompt stored as a version 0 row, which no edit deletes, so their users must start a new chat. Chats with only version 1 rows do not change. **Why it is safe** - New content is always written as `CurrentContentVersion` (1), and `content_version` is `NOT NULL` with no default, so no new row gets version 0. - The layer below removed the tests of the legacy encodings. This PR handles the last version 0 test cases. It moves the six cases of current-format parts in `TestParseContent_BackwardCompat` to version 1 rows in `TestParseContent_V1`, and their checks do not change. It deletes the version 0 malformed-input cases of `TestParseContent_ErrorPaths`; the version 1 cases with the same input stay. Every mutant that `main` catches, out of the 17 listed in #30996, is still caught on this head. - `git grep` for each removed symbol across the repository, including `site/`, `enterprise/`, `cli/`, `docs/` and `scripts/`, finds nothing on this head. Before this PR, the only hit outside `chatprompt.go` was `coderd/exp_chats_test.go`, which now writes the version as a literal `0`. That test checks that the SQL `jsonb_typeof` guard skips scalar JSON rows. **Review focus** Version 0 rows now take the existing `unsupported content version` branch of `ParseContent`; the PR adds no new error path. **Validation** - `go test ./coderd/x/chatd/... ./coderd/database/db2sdk/ -count=1 -p 4 -parallel 4`: ok - `go test ./coderd/ ./enterprise/coderd/ -run '(?i)chat|agent|mcp|skill' -count=1 -p 4 -parallel 4`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: 0 issues; pre-commit hook: passed - Throwaway API tests (not committed) of GET, send and edit with version 0 rows: results above **Stack** This stack retires chatd compatibility paths for chat data that older Coder versions stored. 1. #30996 stamp chat message fixtures with the current content version 2. #30997 drop tests of the legacy content codec 3. #30998 retire the V0 chat message content decoder (this PR) 4. #31000 inline the model config provider identity 5. #31005 retire the `close_agent` tool alias > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
e973f00480 |
test(coderd/x/chatd/chatprompt): drop tests of the legacy content codec (#30997)
This PR deletes the tests of the legacy chat message encodings (plain strings, fantasy envelopes and legacy tool rows, all stored with `content_version` 0), and the test-only writers that built those rows (`MarshalContent` and `MarshalToolResult` in `export_test.go`). It changes tests only. The next layer removes the legacy decoder that these tests cover. **Why it is safe** Deleted tests that covered only the legacy format: - The legacy cases of `TestParseContent_BackwardCompat`: legacy system strings, fantasy envelopes and legacy tool rows. Its six cases of current-format parts in version 0 rows stay, because they need no legacy writer. The next layer moves them to version 1 rows. - `TestInjectFileID_StripsInlineData`: the test-only `MarshalContent` writer. - `TestSDKPartsNeverProduceFantasyEnvelopeShape`: the invariant behind `isFantasyEnvelopeFormat`, the legacy format detector. - `TestParseContent_ErrorPaths/unknown_role`: the role switch in the legacy decoder. The V1 decoder has no role switch. The version 0 malformed-input cases of this test stay, because they need no legacy writer. The next layer deletes them with the decoder. Deleted tests that also covered current behavior, checked with mutants of `chatprompt.go`: - `TestConvertMessagesWithFiles_BackwardCompat` (file ID resolution): dropping resolved file data, or not collecting user file IDs, still fails more than 10 remaining tests, including `TestConvertMessagesWithFiles_ResolvesFileData`. - `TestProviderMetadataRoundTrip` (provider metadata becomes provider options): dropping the conversion still fails `TestConvertMessagesWithFiles_Conversation` and `TestAssistantWriteRoundTrip`. - `TestProviderExecutedResult_LegacyToolRow` (provider-executed results in legacy tool rows are dropped before replay): keeping provider-executed results in `injectMissingToolUses` still fails `TestInjectMissingToolUses_DropsProviderExecutedOrphans` and `TestInjectMissingToolUses_DropsOnlyProviderExecutedMessage`. The 17 mutants from the layer below give the same result here as on that layer. **Review focus** The `export_test.go` deletion. `MarshalToolResult` uses `toolResultRaw`, which the next layer deletes, so the writer goes first. **Validation** - `go test ./coderd/x/chatd/chatprompt/ -count=1`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: 0 issues - pre-commit hook: passed **Stack** This stack retires chatd compatibility paths for chat data that older Coder versions stored. 1. #30996 stamp chat message fixtures with the current content version 2. #30997 drop tests of the legacy content codec (this PR) 3. #30998 retire the V0 chat message content decoder 4. #31000 inline the model config provider identity 5. #31005 retire the `close_agent` tool alias > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
31b8fd1b88 | feat: graduate the chat advisor from experiments (#31414) | ||
|
|
48a3d3ff12 |
fix: keep OpenAI web searches in later turns (#31355)
OpenAI chats dropped every earlier web search from the next request with store false, so on later turns the model said it made no tool calls. Fantasy replayed a search only as an item_reference, which OpenAI cannot resolve for an unstored item. The fantasy pin moves to coder_2_33 with coder/fantasy#78, which sends a search inline as an id-less web_search_call, rebuilt from its result metadata, whenever it does not go back as an item_reference. With store true it also covers searches from an unstored response, as when a chat moves to a stored model config or a zero data retention org, and searches with no reasoning before them. The model gets the action it took, not the page contents, which OpenAI does not keep for references either. TestChatOpenAIResponsesWebSearch now sends a second turn and asserts the exact inline item for each action shape through the chat API and chatd's prompt builder. The fake OpenAI server accepts inline searches without an id, returns OpenAI's 404 for references to items it served with store false, and sends sources only on search actions. The tests' reference checks now also catch references without a type, which openai-go omits. Relates to CODAGT-1482 |
||
|
|
1acacc9c30 | feat: graduate MCP tool search from experiments (#31327) | ||
|
|
846daa80e4 | fix(coderd/x/chatd): add ACP subagent prompt guidance (#31498) | ||
|
|
5c691c82c9 |
chore: refresh AI model price book (#31474)
## Price book changes 19 models added, 27 models removed, 37 models changed. <details> <summary>Added</summary> - azure/gpt-6.1-terra - bedrock/au.anthropic.claude-sonnet-5-5 - bedrock/global.openai.gpt-6.1-terra - bedrock/openai.gpt-6.1-terra - bedrock/us.openai.gpt-6.1-terra - copilot/gpt-6.1-terra - openai/gpt-6.1-terra - openrouter/liquid/lfm-2.5-2.6b - openrouter/minimax/minimax-m3.1-flash - openrouter/moonshotai/kimi-k3.1-pro - openrouter/openai/gpt-6.1-terra - openrouter/openai/gpt-6.1-terra-pro - openrouter/particle-ai/particle-1 - openrouter/prism-ml/ternary-bonsai-2-9b - vercel/moonshotai/kimi-k3.1-pro - vercel/moonshotai/kimi-k3.1-pro-highspeed - vercel/openai/gpt-6.1-terra - vercel/openai/gpt-6.1-terra-fast - vercel/particle/particle-1 </details> <details> <summary>Removed</summary> - azure/claude-opus-4-1 - azure/deepseek-r1 - copilot/mai-code-1-flash-picker - google/gemini-3-pro-image-preview - google/gemini-3.1-flash-image-preview - openrouter/arcee-ai/trinity-large-thinking - openrouter/ibm-granite/granite-4.0-h-micro - openrouter/minimax/minimax-m3.1-flash:free - openrouter/nvidia/nemotron-3-super-120b-a12b:free - openrouter/openai/gpt-3.5-turbo - openrouter/openai/gpt-3.5-turbo-instruct - openrouter/openai/gpt-4-turbo - openrouter/openai/gpt-5.2-chat - openrouter/openai/o1 - openrouter/openai/o1-pro - openrouter/openai/o3-mini - openrouter/openai/o3-mini-high - openrouter/openai/o4-mini - openrouter/openai/o4-mini-high - openrouter/qwen/qwen3-next-80b-a3b-thinking - vercel/openai/gpt-3.5-turbo - vercel/openai/gpt-4-turbo - vercel/openai/gpt-4.1-nano-fast - vercel/openai/gpt-image-1 - vercel/openai/o4-mini-fast - vercel/spacexai/grok-4.1-fast-non-reasoning - vercel/spacexai/grok-4.1-fast-reasoning </details> <details> <summary>Changed</summary> - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4.1-flash - openrouter/google/gemini-3.8-flash - openrouter/google/gemma-3-4b-it - openrouter/ibm-granite/granite-4.2-8b - openrouter/meta-llama/llama-3.2-3b-instruct - openrouter/minimax/minimax-m2.5 - openrouter/mistralai/mistral-small-3.2-24b-instruct - openrouter/moonshotai/kimi-k2.7-code - openrouter/moonshotai/kimi-k3 - openrouter/nousresearch/hermes-4-405b - openrouter/nvidia/nemotron-3-nano-30b-a3b - openrouter/openai/gpt-4.1-nano - openrouter/qwen/qwen3-30b-a3b-instruct-2507 - openrouter/qwen/qwen3.5-122b-a10b - openrouter/qwen/qwen3.5-27b - openrouter/qwen/qwen3.5-9b - openrouter/qwen/qwen3.6-27b - openrouter/qwen/qwen3.6-35b-a3b - openrouter/qwen/qwen3.8-27b - openrouter/reflection/beam-1.0-501b-a23b - openrouter/xiaomi/mimo-v2.5 - openrouter/xiaomi/mimo-v2.5-pro - openrouter/z-ai/glm-4.6 - openrouter/z-ai/glm-4.6v - openrouter/z-ai/glm-5.2 - openrouter/z-ai/glm-5.3 - openrouter/z-ai/glm-5.3-flash - openrouter/~deepseek/deepseek-flash-latest - openrouter/~deepseek/deepseek-pro-latest - openrouter/~moonshotai/kimi-latest - openrouter/~openai/gpt-terra-latest - openrouter/~z-ai/glm-flash-latest - openrouter/~z-ai/glm-latest - vercel/amazon/nova-2-lite - vercel/minimax/minimax-m3.1-flash - vercel/openai/gpt-4.1-nano </details> ## Review notes Regenerated by `make gen/aibridge-prices` from the live [models.dev](https://models.dev) catalog. Both artifacts come from one snapshot, so they ship together: - `coderd/aibridge/prices/data/prices.json` - `site/src/modules/aiModels/knownModels/knownModelsGenerated.json` These are customer-visible cost numbers taken from upstream data, so this PR is never merged automatically. The summary above lists what moved; check the diff for exact figures before approving. Opened automatically by the [aigateway-prices-refresh workflow](https://github.com/coder/coder/actions/runs/40846801723). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
d1f308d9f3 |
feat: let organization members turn off organization skills in chats (#31134)
## Stack Organization skills load into every member's Coder Agents chats in their organization, with no way for a member to opt out. This stack adds a per-organization setting that lets members turn them off for their own chats, bottom to top: 1. **#31134** data model, API, and chatd (this PR) 2. #31135 admin and member controls in the dashboard, the `/` menu, and docs ## What changes Organizations get `members_can_disable_skills`, off by default. Users who can update organization skills change it with `PUT /api/experimental/organizations/{organization}/skill-settings`, which writes an organization audit entry. Anyone who can read the organization can `GET` it. While the setting is on, each member saves their own choices with `PATCH /api/experimental/organizations/{organization}/members/{user}/skill-preferences`: `all_skills_disabled` (a master switch that also covers skills created later) and `skills`, a sparse map from skill ID to on or off. `GET` returns the setting, the master switch, and `disabled_skill_ids`. The routes follow the personal-settings rules: without `read_personal` or `update_personal` on that user the caller gets 404, a PATCH while the setting is off gets 403, and a key that is not an organization skill that member can read gets a 400 that names the key. The check runs as the member, not the caller, so an owner or user admin editing someone else's choices is held to that member's skills. Turning the setting off keeps the choices but ignores them. Migration 000636 adds the column and two tables keyed by organization membership. Both cascade when the membership goes away, and the per-skill table also cascades when the skill is deleted, so a recreated skill loads by default. chatd reads the preferences as the chat owner when it builds the skill index and when it loads a body for `read_skill` or for a structured skill invocation (#30861). A skill the member turned off is left out of the index, and both loads report it as not found, including later in a running chat. If the preferences cannot be read, turn preparation fails, as it already does when the skill metadata cannot be read. Older migration tests created organizations with `dbgen.Organization` and `GetDefaultOrganization`, which now select the new column before it exists, so they insert organizations with raw SQL instead. ## Review focus - Authorization in `coderd/organizationskillpreferences.go` and the five new dbauthz methods (`read_personal` and `update_personal` on the user, `organization_skill` update for the setting). - `GetOrganizationSkillMemberPreferencesRow.Excludes` is the one rule chatd applies; #31135 mirrors it in `activeOrganizationSkills`. ## Testing - Go tests cover the queries and cascades, dbauthz, both routes (including the audit diff and each 400 case), and chatd (index, `read_skill`, skill invocations, master switch, a change during a chat). Each new test fails with its code path removed. - Remote dogfood UAT (10 scenarios, real model) passed on the pre-split branch head `186c28d81ab`, which has the same code except the fix below. It found one issue: two spellings of one skill ID with opposite values stored a random result. The PATCH now rejects every aliased key with a 400. A second run on the stack's top head at the time, `718dd6d1bd1`, passed: every aliased form returns 400 and stores nothing, and chats leave out a skill the member turned off, including in `read_skill`. - Polish and the test audit stayed inside the implementation diff. No new dependencies. - Rebased on main as one commit. The migration is now 000636, after main's 000634 and 000635. Every organization skill load passes the chat owner, including main's skill invocation path, so `/skill` invocations honor the opt-out too. The model's skill index leaves out a skill that is not model-invocable or that the member turned off. Apart from that, the diff is unchanged. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
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.
|
||
|
|
eb38759fda |
feat: limit effective group resolution to an organization (#31119)
AI budget resolution searches all of a user's groups across every organization. Whichever group wins determines the organization. #31120 needs to resolve inside a known organization, and it needs to know which organization site-wide resolution picked. Add an `organizationID uuid.NullUUID` argument to `budget.ResolveUserAIBudget` and `budget.ResolveUserEffectiveGroup`. When it is set, count only that organization's override, group budgets and Everyone group. An organization that is unknown, deleted or that the user is not a member of resolves to nothing. When it is null, resolve exactly as before. Return the winning group's organization in `budget.EffectiveGroup.OrganizationID`. Read the override through a new resolution-only query, `GetUserAIBudgetOverrideWithOrganization`, so that the CRUD query `GetUserAIBudgetOverride` and the admin endpoints stay untouched. Add a nullable `organization_id` filter to `GetHighestGroupAIBudgetByUser` and `GetUserEveryoneFallbackGroup`. Every caller passes null, so behaviour is unchanged. There is no migration and no proto change. Scoping to an organization can lift a limit: a user capped in org B has no limit in org A if A has no budgets. AIGOV-711 intends this, and it takes effect in #31120. Part of AIGOV-715. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
a512a7f060 |
fix(coderd/nats): log embedded server messages with slog (#31013)
Route embedded NATS server logs through Coder's slog logger by installing a `natsserver.Logger` adapter with `SetLoggerV2` before starting the server. Add coverage for severity mapping, formatting, startup logging, and debug filtering, and allow expected NATS errors in the existing failure-path and teardown tests. Refs GRU-98. <details> <summary>Implementation decisions</summary> - Preserve the caller's logger fields and add the `server` logger name. - Let slog filter debug output; leave protocol and system-account tracing disabled to avoid logging message payloads. - Map NATS fatal messages to slog `Critical` so adding logging does not introduce process termination. - Restrict test log allowances to the embedded server's expected errors rather than ignoring all error logs. </details> Generated by Coder Agents on behalf of @spikecurtis. |
||
|
|
f10eabbb0c |
fix: confine read_skill_file reads to the skill directory (#31462)
> Xum opened this PR for Mike.
`read_skill_file` checked the requested path lexically, then read
`<skill dir>/<path>` through the agent's general file reader, which
follows symlinks. A supporting file that is a symlink to a file outside
the skill directory returned that file's contents to the model.
The agent's `read-file` endpoint now accepts an optional `root`
parameter. With it, the agent opens `root` with Go's `os.OpenRoot`,
refuses it if `root` itself is a symlink, and opens the file with
`Root.Open`, which follows symlinks only while they stay beneath `root`
and refuses absolute symlinks. `os.Root` opens one path component at a
time relative to the directory it already holds and resolves each
symlink itself, so a file swapped for a symlink during the walk cannot
slip through. `codersdk` adds `AgentConn.ReadFileInRoot`, and
`read_skill_file` reads supporting files through it. Reads without
`root` are unchanged.
- Relative symlinks that never leave the skill directory still work.
Absolute symlinks, and links that climb out of the directory, are
refused. Refusal messages never name the link target.
- The agent refuses a `root` that is itself a symlink, because
`os.OpenRoot` follows it: a skill directory replaced with a symlink to
`/etc` would otherwise become `/etc`. It compares the opened directory
with an `Lstat` of `root`, so a swap between the two calls is also
refused. Symlinks in the parent directories of `root` still work.
- Agents older than this change reject the `root` parameter, so
`read_skill_file` fails closed in a workspace until it restarts with the
new agent.
- Not in this PR: the agent's `resolve-path` endpoint joins a relative
link target to the parent path before resolving the parent's own
symlinks, so it can return the wrong file. Plan path checks still use
it; skill reads no longer do.
Fixes CODAGT-1496
## Testing
- New tests: `TestReadFileInRoot` (handler, real symlinks),
`TestReadFileInRootSwap` (swaps `root` for a symlink while reads run),
`TestReadFileInRootRegularDirectory` (no symlinks, so it also runs on
Windows), `TestAgentConnReadFileInRoot` (SDK over tailnet against the
real handler), `TestReadSkillFileTool/AgentRefusalIsToolError`. The
refusal tests fail when the protection is removed (plain open instead of
`os.Root`, no check that `root` is not a symlink, SDK joining root and
path, or the tool dropping the agent error). Without the `root` check,
`TestReadFileInRootSwap` returned outside bytes in 45 of 500 reads.
- Remote dogfood UAT passed on
|
||
|
|
2255794d65 | feat: add response_size_bytes metric to chatd (#29816) | ||
|
|
7f6ce9c8ab |
test(coderd): stamp chat message fixtures with the current content version (#30996)
Chat prompt tests built most of their stored-message fixtures in the legacy content format (`content_version` 0), so they exercised the legacy decoder instead of the current one. This PR changes tests only: it stamps those fixtures with `ContentVersionV1` and builds them with `MarshalParts`, so they keep passing after the legacy decoder is removed later in this stack. Tests of the version 0 decoder itself keep their version 0 rows until the layers above remove that decoder. **Why it is safe** - `mustMarshalContent` and `mustMarshalToolResult` now build current parts (`PartFromContent`, `ChatMessageToolResult`) and encode them with `MarshalParts`, the production write path. - `TestMixedFormatConversation` becomes `TestConvertMessagesWithFiles_Conversation` and uses current-format rows only. - `TestParseContent_BackwardCompat` does not change. Migration 000434 stamped every existing row with version 0, so its six cases of current-format parts in version 0 rows still cover the version 0 heuristics. #30998 moves those six cases to version 1 rows when it removes that decoder. - `TestProviderExecutedResult_LegacyToolRow` calls the legacy writers (`MarshalContent`, `MarshalToolResult`) directly, so its provider-executed tool row still goes through the legacy tool-row decoder. - `TestParseContent_ErrorPaths` runs its malformed-input cases on version 1 rows, and runs the same input on version 0 rows of each role (`v0/<role>/malformed_json`), so a version 0 parser that accepts malformed content still fails the suite. #30998 deletes the version 0 cases with that decoder. - I ran the 17 mutants listed below, each a `go test -overlay` edit of the current decode and prompt-conversion code in `chatprompt.go`, against the `chatprompt` and `db2sdk` tests on `main` and on this branch. Every mutant `main` catches is still caught. Two more are caught here: mutant 3, because `TestParseContent_ErrorPaths/system/malformed_json` used to hit the legacy system decoder, and mutant 14, by the new JSON `null` case of `TestConvertMessagesWithFiles_NormalizesAssistantToolCallInput`. Mutants 4 and 8 survive those tests on both. The `chatd` test `TestOrganizationSkillsFollowChatOwnerAccess` catches mutant 4, so 8 is an existing gap. - Mutants of the version 0 decoder fail on `main` and on this branch: version 0 assistant or user rows always take the envelope path, their current-format parts are dropped, legacy tool rows lose `provider_executed`, or a version 0 parser accepts malformed JSON. - With the version 0 case removed from `ParseContent` by an overlay, only tests of version 0 rows fail. #30997 deletes them, except the six `TestParseContent_BackwardCompat` cases, which #30998 moves, and the version 0 cases of `TestParseContent_ErrorPaths`, which #30998 deletes. <details> <summary>The 17 mutants</summary> 1. `ParseContent` returns no parts for a V1 row. 2. V1 decoding skips NUL restoration (`decodeNulInParts`). 3. The V1 parse error says "decode" instead of "parse". 4. Tool error string extraction is off (`toolResultPartToMessagePart`). Only a `chatd` test catches it. 5. Tool call input is dropped. 6. Tool call `ProviderExecuted` is dropped when reading. 7. Resolved file data is dropped. 8. The file media type fallback is dropped (`partsToMessageParts`). Survives. 9. User file IDs are not collected for resolution. 10. Text provider metadata is dropped. 11. File reference text is replaced by the raw content. 12. System messages are dropped. 13. Tool call `ProviderExecuted` is dropped when writing (`PartFromContent`). 14. `normalizeToolCallInput` keeps a JSON `null` input instead of `{}`. Survives on `main` only. 15. Text tool result `ProviderExecuted` is dropped. 16. Tool result IDs are dropped. 17. Assistant file IDs are resolved like user file IDs. </details> **Review focus** The rewritten conversation test in `chatprompt_test.go`. It checks the same prompt shape as before, but every row is in the current format. In the same file, `TestProviderExecutedResult_LegacyToolRow` keeps its legacy rows, `TestParseContent_ErrorPaths` checks malformed input on both content versions, and the input normalization table gains a JSON `null` case. The other changed test files only switch fixtures to the current format: `coderd/x/chatd/chatprompt/file_inline_test.go` (+4/-16), `coderd/database/db2sdk/db2sdk_test.go` (+11/-13), `coderd/x/chatd/message_conversion_test.go` (+3/-2) and `coderd/x/chatd/quickgen_internal_test.go` (+1). **Validation** - `go test ./coderd/x/chatd/... ./coderd/database/db2sdk/ -count=1 -p 4 -parallel 4`: ok - `go vet` on the touched packages and `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/...`: clean - pre-commit hook: passed **Stack** This stack retires chatd compatibility paths for chat data that older Coder versions stored. 1. #30996 stamp chat message fixtures with the current content version (this PR) 2. #30997 drop tests of the legacy content codec 3. #30998 retire the V0 chat message content decoder 4. #31000 inline the model config provider identity 5. #31005 retire the `close_agent` tool alias > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
0fd07754f5 |
fix(coderd/httpmw): anchor CSRF exemption patterns (#31125)
fix(httpmw): restrict CSRF exemptions to intended routes CSRF exemptions used shell-style patterns evaluated as unanchored regexes, allowing unintended cookie-authenticated routes to bypass protection. This enabled CSRF against role-management routes containing `derp` and dev container recreate/delete endpoints. - Anchor exemptions to their intended routes or subtrees. - Remove the broad workspace-agent exemption, duplicate first-user entry, and obsolete `/api/v2/scim` pattern. - Preserve intended exemptions and requests without session cookies, keeping agents, proxies, provisioners, and SCIM providers unaffected. - Add regression tests for unintended matches, legitimate exemptions, requests without session cookies, and rejection of a cross-origin request to a formerly exempt route. Validation: `go test ./coderd/httpmw/ -count=1`, `go vet`, and `golangci-lint run ./coderd/httpmw/...` pass. Backports: Omit the doubled-leading-slash test on branches without #29798. Refs [PLAT-733](https://linear.app/codercom/issue/PLAT-733) |
||
|
|
bb8912dc46 |
fix: wait for full completion before asserting in tests (#30885)
Fixes the `TestServer_Metrics/Forwarding` flake reported in [PLAT-609](https://linear.app/codercom/issue/PLAT-609/flake-testserver-metricsforwarding) and, in addition, other defects similar to it. ## Testing defects ### The Original `TestServer_Metrics/Forwarding` waited for `batches_dropped_total` and then asserted on `logs_dropped_total`. The forwarder updates those two counters separately, on adjacent lines, so a read between them sees the first updated and the second not. CI caught exactly that window: expected 2, actual 0 at `proxy_test.go:780`. Each counter is atomic on its own, so the race detector reports nothing. ### The Additional The fallacy of the original is a _de facto_ assumption that sequential updates are atomic as a group. The defect arose from not taking into account that they are atomic individually. The test asserted before the work was completed. A repo-wide sweep for related metrics written together found similar mistakes in other tests: - Live races: all three phases of `TestServer_Metrics/Forwarding` and `TestServer_Metrics/BufferFull` in `agent/boundarylogproxy`, and `TestMetadataBatcher_DropsWhenFull`, which waited for the update channel to empty although the final flush runs after that. - Correct only because of the current implementation's ordering: `TestMetrics_TokenUseCount` in `aibridge`, four tests in `coderd/agentapi/metadatabatcher`, and `TestAgentStatsSessionCounts` in `coderd/prometheusmetrics`. These pass today but would start failing if the code under test reordered its work. ## Fixes All tests the sweep found were fixed. Each test now waits for every value it asserts before asserting it. Where a value is already non-zero from earlier work, or legitimately zero, the wait is for the final value rather than for a change, and several tests use `require.EventuallyWithT` so the wait and the assertion are one step. Two Forwarding phases gain assertions on values they already waited for: `batches_dropped_total == 1` in phase 1, and the reporter's recorded request count in phase 2. Two phases of `TestAgentStatsSessionCounts` assert that the counts did not change. No wait on an unchanged value can show that the collection cycle ran, so they keep waiting on the execution histogram, and a comment at that wait names the dependency. Each fix was checked by temporarily blocking or reordering the code under test between the relevant writes: the old test failed on every run and the new one passed. ## Documentation As a guard against recurrence of defects of this kind, we add the following documentation targeted mostly at agents. The material in `TESTING.md` provides guidance about how to write such a test correctly in the first place. That in `AGENT_FAILURES.md` describes how to recognize the symptoms of this class of test failure, should they arise. - `.claude/docs/TESTING.md`: new section "Wait for Full Completion before Asserting", covering waits on one value with assertions on another, Prometheus metrics in particular, and assertions that nothing changed. - `.claude/docs/AGENT_FAILURES.md`: a catalog entry for the symptom. - `coderd/coderdtest/promhelp`: doc comments noting that each helper call is a separate gather. Generated with Claude Code under the direction of @eric-hughes-coder. |
||
|
|
296da93f6b |
fix(coderd/idpsync): Group sync may only add users to groups of the syncing org (#30706)
Group sync settings can contain group IDs that belong to another organization or that no longer exist. At login, `SyncGroups` passed mapped IDs straight through to `InsertUserGroupsByID`, which has no organization filter, so the settings for one organization could cause a user to be added to a group in a different organization. `SyncGroups` now partitions each organization's expected groups with `PartitionOutInvalidSettings` and only syncs those inside the organization. Groups in another organization, and IDs that match no group, are dropped and reported with one warning per kind. Login and the rest of the sync proceed. Generated by Claude Code under the direction of @eric-hughes-coder. |
||
|
|
161b7233d9 |
feat(coderd): store the organization on AI Gateway interceptions (#31118)
Adds `organization_id` (FK to `organizations`, `ON DELETE RESTRICT`) and `organization_source` (new enum: `workspace`, `chatd`, `effective_group`) to `aibridge_interceptions`, with a check constraint that keeps them set or unset together. Cost and pricing run later, in `RecordTokenUsage`, so they need the organization that AIGOV-716a resolves once per request stored on the interception row. `RecordInterceptionRequest` gains `organization_id` (18) and `organization_source` (19), and the aibridged API moves to v1.5. `RecordInterception` stores a valid pair; any other combination is logged as a warning and stored as NULLs, so a gateway bug never turns into an HTTP 500 for the user. A well-formed ID for an organization that does not exist fails on the FK, like an unknown `initiator_id`. Nothing sends the fields yet, so behaviour is unchanged until AIGOV-716a. **Malformed values are stored as empty, not rejected.** A failed `RecordInterception` returns HTTP 500 to the user, so the server logs a warning and stores NULLs instead. The one exception is a well-formed ID for an organization that does not exist: the foreign key rejects it, the same as an unknown `initiator_id` today. Part of AIGOV-712 *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
50b7c04398 |
refactor(coderd/x/chatd/chattest): drop write-only fake state and share the shape check (#30950)
The OpenAI and Anthropic fakes stored each request in a `request` field
under a mutex that nothing read, and kept the `httptest.Server` in a
field that only their constructors used. This PR deletes both fields,
the mutex and its lock blocks. It also merges the three copies of the
response-shape switch into one `responseShapeError` helper, and the two
copies of the OpenAI request decode into `decodeOpenAIRequest`.
**Why it is safe**
- Nothing read `request`, so dropping it and its mutex changes no
behavior.
- `responseShapeError` returns the same four strings, byte for byte, in
the same order. Each writer still checks `resp.Error` first, writes the
same plain-text 500 with `http.Error`, and keeps its own serializers.
The layer below pins the "both" and "empty" errors, and the existing
mismatch tests pin the other two: removing any case from the helper
fails one of them.
- `decodeOpenAIRequest` returns the read or decode error unwrapped, so
the 400 body is unchanged, and `handleResponses` still runs
`ValidateResponsesAPIInput` before the handler. It sets `RawBody` after
decoding, as both copies did, so the field comment no longer claims it
is set before.
**Review focus**
The writers now use `switch msg := responseShapeError(...); { case msg
!= "": ... }`, which leaves the streaming and non-streaming cases as
they were.
**Validation**
- `go test ./coderd/x/chatd/chattest/ -count=1`: ok before and after
- `go test -race ./coderd/x/chatd/chattest/ -count=1`: ok
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: ok before and
after
- `go vet ./coderd/x/chatd/chattest/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues
- pre-commit hook: passed
**Stack**
The stack makes the chattest fake tests fail on wrong output, then drops
the fakes' write-only state and shares their response-shape check.
1. #30948 table the OpenAI fake positive tests and fail on error streams
2. #30949 pin the fake response-shape errors
3. #30950 drop write-only fake state and share the shape check (this PR)
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
ae6013f9d5 |
refactor(coderd/x/chatd): extract the recording multipart parser and table its tests (#30954)
The bounded multipart loop in `stopAndStoreRecording` (part cap, per-type size limits, the empty, duplicate and unknown-part skips, and partial results on read errors) could only be tested through a PostgreSQL-backed server and an agent mock. This PR moves the loop unchanged into `readRecordingParts` and replaces five tests (`TestStopAndStoreRecording_Oversized`, `_OversizedThumbnail`, `_DuplicatePartsIgnored`, `_Empty` and `_UnknownPartIgnored`) with one table test, `TestReadRecordingParts`, that streams parts through a pipe. **Why it is safe** - The loop body moves as is: same `maxParts`, limits, messages and skip rules. The caller still reads parts only after the workspace lookup and stores the video before the thumbnail. The kept `TestStopAndStoreRecording_*` tests still cover storage. - The table asserts exact video and thumbnail bytes for every case the deleted tests covered. The unknown part now comes first, so it reaches the unknown-type branch. New rows cover the part cap, a duplicate thumbnail, video and thumbnail parts above the 1 MB unknown-type limit, a video above the thumbnail limit, a thumbnail at exactly the thumbnail limit, a read error and a canceled context. - I ran 14 mutants of the guarded lines with `go test -overlay`: the size check; each per-type limit raised by one or dropped, and the video limit set to the thumbnail limit; the empty check; both duplicate checks; the unknown-type branch; the part cap raised and lowered; the context check; and the read-error branch. The deleted tests caught 2 and the table catches all 14. Only `VideoAboveThumbnailLimit` catches the video limit set to the thumbnail limit. Storage checks the file bytes, so it rejected the deleted tests' zero-filled and empty fixtures whether or not the parser accepted them. - The latest commit adds `ThumbnailAtLimit`. With `go test -overlay`, it catches two more mutants that the rest of the table misses: the size check changed from `>` to `>=`, and the thumbnail limit lowered by one byte. No row sends a video of exactly `workspacesdk.MaxRecordingSize` bytes, because that needs another 100 MB part, so a video limit lowered by one byte still passes. **Review focus** The `break` and `continue` paths now end at `return videoData, thumbnailData` instead of falling into the storage code. The canceled-context and read-error rows cover both. **Validation** - `go test ./coderd/x/chatd/ -run 'TestStopAndStoreRecording|TestWaitAgent|TestReadRecordingParts|TestRecordingBoundary' -count=1 -p 4 -parallel 4`: ok, and ok with `-race` - `go test -race ./coderd/x/chatd/ -run '^TestReadRecordingParts$' -count=10`: ok - `go vet ./coderd/x/chatd/`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/`: 0 issues - pre-commit hook: passed **Stack** The stack moves the recording response parsing out of `stopAndStoreRecording` into two functions with table tests, and drops seven PostgreSQL-backed parse tests. 1. #30953 extract the recording boundary parser and table its tests 2. #30954 extract the recording multipart parser and table its tests (this PR, +202/-277 in 2 files) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
9848c41100 |
test(coderd): run the advisor config tests on one server (#30986)
Folds the one-server `TestChatAdvisorConfig_*` tests in
`coderd/exp_chats_test.go` into one `TestChatAdvisorConfig`, whose
subtests share one coderd server. The advisor config tests start 2
servers instead of 10, and the file loses 23 lines. The PR changes only
tests.
**Why it is safe:** each old test is now a subtest with the same
assertions.
- Each subtest that changes the advisor configuration restores the
default (`{}`) in `t.Cleanup`, so no subtest depends on the ones before
it. The subtests also pass with `GetDefault` moved last and with the
whole order reversed (`go test -overlay`). Without the restore,
`GetDefault` fails when moved last.
- `TestChatAdvisorConfig_EnabledReflectsExperiment` stays a separate
test, because it needs its own deployment values.
- `RoundTripZeroValues` is dropped. Its four lines (write zero values,
read, check for no error, expect `{Enabled: true}`) are also in
`OverwriteClearsPreviousValues`.
Seven handler mutants (`go test -overlay` on `coderd/exp_chats.go`) fail
the old tests and the folded test, in the matching subtest: `GET`
inverting `enabled`, `PUT` without its authorization check, accepting
`-1` uses, dropping `max_output_tokens`, skipping a zero-value write,
`GET` ignoring corrupt JSON, and `GET` rejecting unknown JSON keys.
**Review focus:** the shared server. The subtests share one advisor
configuration row, so they do not call `t.Parallel()`, and the function
carries `//nolint:tparallel,paralleltest`, like
`TestChatOperationalSettingsAuditDeniedWrites`.
Validation: `go test ./coderd -run '^TestChatAdvisorConfig' -count=3
-race` passes, and the pre-commit hook passed.
## Stack
This stack removes the deprecated advisor config request fields, then
runs the advisor config tests on one server.
1. #30982 Remove the deprecated advisor config request fields
2. #30986 Run the advisor config tests on one server
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
3cc2861fc4 |
test(coderd/x/chatd/chattest): pin the fake response-shape errors (#30949)
No test reached the "handler returned both streaming and non-streaming
responses" and "handler returned empty response" branches of the
chattest fakes, and the next PR in the stack rewrites them. This PR adds
`TestFakeResponseShapeErrors`, which posts to the OpenAI
`/chat/completions`, OpenAI `/responses` and Anthropic `/v1/messages`
fakes with a handler that returns both response shapes or neither, and
checks the 500 status and the exact error body. It is the test-first
layer for that rewrite, so it adds 77 lines and deletes none.
**Why it is safe**
- Test only, and it passes on `main`.
- I deleted each of the six cases in turn with `go test -overlay`. Each
mutant fails exactly its own row, and the rest of the package still
passes on all six, so no other test covered these branches.
**Review focus**
The test sends plain `net/http` requests with a `{}` body, so it asserts
the fake's own output (`http.Error` writes the message and a newline)
with no provider SDK in between.
**Validation**
- `go test ./coderd/x/chatd/chattest/ -run TestFakeResponseShapeErrors
-count=1 -v`: all six rows pass
- `go vet ./coderd/x/chatd/chattest/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues
- pre-commit hook: passed
**Stack**
The stack makes the chattest fake tests fail on wrong output, then drops
the fakes' write-only state and shares their response-shape check.
1. #30948 table the OpenAI fake positive tests and fail on error streams
2. #30949 pin the fake response-shape errors (this PR)
3. #30950 drop write-only fake state and share the shape check
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
b32aff6a5c |
test(coderd/x/chatd/chatprompt): table the media codec matrix in memory (#30946)
This PR finishes moving the tool result codec cases out of PostgreSQL. `MediaResultCarriesPromotedAttachmentMetadata`, `MediaResultUsesMatchingAttachmentMetadata` and `MediaResultWithText` become rows of `TestMediaToolResultConversion`: `wantStored` pins the persisted result JSON, and `wantMedia` pins Data, MediaType and Text. `TestMediaToolResultRoundTrip` keeps one PostgreSQL round trip, for the media tool pair, on a smaller fixture. The PR also deletes `TestToolResultAntivenom/ValidMediaResultRoundTrips`, whose Data, MediaType and Text checks `MediaResultWithText` covers through the full conversion path. The malformed-input antivenom cases stay, because they bypass storage on purpose. **Why it is safe** - Every moved assertion is kept, and the attachment rows now compare the whole persisted JSON instead of four fields. - #30945 lists the 24 mutants of `chatprompt.go` that I ran with `go test -overlay` against the tests on `main`, on #30945 and on this PR. They cover the media fields, media `ProviderExecuted` and `ToolCallID`, attachment selection and mirroring, and the write-path flags. Every mutant that `main` catches, this PR catches too. - One gap is unchanged: no test on `main` or in this stack pins error precedence when a result sets both IsError and IsMedia. - The trimmed fixture drops only rows the remaining round trip does not need (the org membership, the explicit chat provider, and unused message and model fields). **Review focus** The `wantStored` literals for the two attachment rows, and the trimmed database fixture. **Validation** - `go test ./coderd/x/chatd/chatprompt/ -count=1 -p 4 -parallel 4`: ok on `main` and on this PR - `go vet ./coderd/x/chatd/chatprompt/`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/`: 0 issues - pre-commit hook: passed **Stack** The stack moves the tool result codec matrix out of PostgreSQL and keeps one storage round trip. 1. #30945 table the text and error tool result rows in memory 2. #30946 table the media codec matrix in memory (this PR) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
7dee434315 |
test(coderd/x/chatd): fold taskTestFixture into workerTestFixture (#30924)
`taskTestFixture` in `tasks_test.go` repeated `workerTestFixture` field for field, with the same seed rows, and carried its own copies of five chat setup helpers, `publishChatUpdate` and two message builders. This PR deletes the fixture and the copies and moves the 39 task, hook and turn-trace tests that built it onto `workerTestFixture` and the shared helpers. It also drops the fixture's API key row and the `apiKeyID` parameter of `userTextMessage`, which nothing read. **Why it is safe** The copies differed from the shared helpers in two ways, and both are kept: - **Clearing the recorder.** The copies cleared the recording pubsub after setup, and `interruptChat` cleared it before interrupting, so assertions on published events see only what the code under test published. `workerTestFixture.pubsub` is now that recorder (from the layer below), and the shared helpers clear it at the same points. No worker test reads the fixture recorder's events, so the extra clears do not change them. - **The deadline argument.** The task copy of `forceExecutionState` took an explicit requires-action deadline. `forceExecutionStateWithDeadline` takes it as a pointer (nil keeps the current one) for `setRequiresActionDeadline` and the one call that cleared an expired deadline. The other three callers passed an empty deadline for chats that never had one, so they call `forceExecutionState`. The rest of the move keeps the old behavior: - `startRealTaskWorker` now starts from `testOptions`, which holds the same values. It unsets the recording task starter so the worker builds its real one, as before. - No chatd code reads the fixture's API key. The synthetic gateway key is looked up by its own token name. After the change, `rg 'taskTestFixture|taskUserTextMessage|taskAssistantToolCallMessage|f\.apiKey' coderd/ enterprise/` finds nothing. **Review focus** The `clear()` placement in `helpers_test.go`. Setup helpers clear when they finish, and `interruptChat` clears before it runs. **Validation** Same commands as the layer below: the 142 top-level tests in the ten files listed there, run from `go test -c ./coderd/x/chatd/` binaries (plain and `-race`) with `-test.count=1 -test.parallel 4`. | Head | Plain | `-race` | |---|---|---| | `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races | | this PR | 142 passed | 142 passed, no data races | The pre-commit hook passed. **Stack** The stack folds the task test fixture into the shared worker test fixture. 1. #30923 reuse `recordingPubsub` in the task test fixture 2. #30924 fold `taskTestFixture` into `workerTestFixture` (this PR) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
b54f7de4c6 | feat: graduate chat projects out of the chat-projects experiment (#31354) | ||
|
|
71cd5e67b3 |
chore!: remove the deprecated advisor config request fields (#30982)
Removes the two deprecated advisor model fields, `model_config_id` and
`reasoning_effort`, from `UpdateAdvisorConfigRequest`. It also removes
the `400` that `PUT /api/experimental/chats/config/advisor` returned
when a client still sent them, and the clamp of negative stored limits
in the matching `GET`. `make gen` drops the fields from
`site/src/api/typesGenerated.ts`.
**Behavior change, approved by Mike:** a `PUT` that still sends
`model_config_id` or `reasoning_effort` now succeeds, and the endpoint
ignores both fields, because `httpapi.Read` ignores unknown JSON fields.
Before, it failed with `400` and named `PUT
/api/v2/organizations/{organization}/chats/model-overrides/advisor`,
which has set the advisor model since #28442. Nothing in this repository
sends the fields: the settings page sends only the two limits, and no
CLI command uses the request type.
**Why removing the clamp is safe:** `putChatAdvisorConfig` is the only
production writer of `agents_advisor_config`, and it has rejected
negative limits since #24621 added the endpoint, in the same commit as
the clamp. No migration writes this key. So a stored limit is never
negative.
- Deleted tests: `TestChatAdvisorConfig_StaleModelWriteRejected` (the
removed `400`) and `TestChatAdvisorConfig_ClampsNegativeStoredValues`
(the removed clamp).
- `TestChatAdvisorConfig_IgnoresLegacyReasoningEffort` stays. Migration
000583 left old advisor blobs as they were, so upgraded databases can
still hold the legacy key, and the test covers how `GET` reads them.
**Review focus:** the behavior change, for any client outside this
repository that still sends the deprecated fields to this experimental
endpoint.
Validation: `go test ./coderd -run '^TestChatAdvisorConfig' -count=1`
passes (10 tests), `go vet ./coderd ./codersdk` is clean, and the
pre-commit hook passed (`make gen`, formatting, golangci-lint over every
package, and the slim build).
## Stack
This stack removes the deprecated advisor config request fields, then
runs the advisor config tests on one server.
1. #30982 Remove the deprecated advisor config request fields
2. #30986 Run the advisor config tests on one server
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
9ede7ceed6 |
refactor(coderd/x/chatd): extract the recording boundary parser and table its tests (#30953)
`stopAndStoreRecording` parsed the recording response's Content-Type
inline and logged through a local `warn` closure that copied three
recording fields into every call. This PR moves the parse into
`recordingBoundary`, replaces the closure with `p.logger.With(...)`, and
replaces the two PostgreSQL-backed tests
`TestStopAndStoreRecording_MalformedContentType` and `_MissingBoundary`
with a table test, `TestRecordingBoundary`. The layer above extracts the
multipart parts loop the same way.
**Why it is safe**
- Warning messages and fields are unchanged: `With` puts its fields
before the per-call fields, as the closure did. One log line changes:
the debug line "skipping unknown part content type" now also carries the
recording, parent chat and workspace IDs.
- The caller still checks the header before the workspace lookup and
returns an empty result on failure.
- The deleted tests checked only that the result was empty. With an
empty body, that result is the same whether or not the parse-error or
missing-boundary branch runs, so both tests passed when I disabled those
branches with `go test -overlay`. `TestRecordingBoundary` asserts the
boundary, the ok flag and the exact warning, and fails on both mutants.
**Review focus**
`if !ok { return result }` in `stopAndStoreRecording`. No test pins it.
Falling through on an empty body returns the same empty result; it
differs only in that it also runs the workspace lookup
(`GetWorkspaceByID`) and logs a second warning, `error reading next
multipart part`. So the line needs a reading check.
**Validation**
- `go test ./coderd/x/chatd/ -run
'TestStopAndStoreRecording|TestWaitAgent|TestRecordingBoundary' -count=1
-p 4 -parallel 4`: ok
- `go vet ./coderd/x/chatd/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/`: 0 issues
- pre-commit hook: passed
**Stack**
The stack moves the recording response parsing out of
`stopAndStoreRecording` into two functions with table tests, and drops
seven PostgreSQL-backed parse tests.
1. #30953 extract the recording boundary parser and table its tests
(this PR)
2. #30954 extract the recording multipart parser and table its tests
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
8bafa8de62 |
test(coderd/x/chatd/chattest): table the OpenAI fake positive tests and fail on error streams (#30948)
The six OpenAI fake positive tests in `openai_test.go` become three table tests, `TestOpenAI_StreamingText`, `TestOpenAI_NonStreamingText` and `TestOpenAI_ToolCalls`, each with a Completions API row and a Responses API row. The rows also check more than the old tests did: streaming rows fail on any error part and assert the exact text deltas, and non-streaming rows assert the returned text. The old Responses streaming test passed on a stream that held only an error, and both non-streaming tests checked only `NoError` and `NotNil`. **Why it is safe** - Every old assertion maps to a row: the exact deltas, one tool execution, the follow-up request after it, `NoError` and `NotNil`. - I ran 12 mutants of the fake with `go test -overlay`. Seven pass the old test that targets the mutated behavior and fail the new rows: an error-only Responses stream, an error part after the Completions text, an error instead of `response.completed`, empty non-streaming text in either format, and doubled or dropped Responses deltas. The other five (an error-only Completions stream, doubled Completions deltas, a truncated `OpenAITextChunks`, and a dropped tool call in either format) fail both the old tests and the new rows. - The fake is unchanged; the stronger checks pass on `main`. **Review focus** The Responses streaming row now uses the same two-choice text chunks as the Completions row, so both formats share one expected delta list. **Validation** - `go test ./coderd/x/chatd/chattest/ -count=1`: ok - `go vet ./coderd/x/chatd/chattest/`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues - pre-commit hook: passed **Stack** The stack makes the chattest fake tests fail on wrong output, then drops the fakes' write-only state and shares their response-shape check. 1. #30948 table the OpenAI fake positive tests and fail on error streams (this PR) 2. #30949 pin the fake response-shape errors 3. #30950 drop write-only fake state and share the shape check > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
fa7ed93ffe |
test(coderd/x/chatd/chatprompt): table the text and error tool result rows in memory (#30945)
`TestMediaToolResultRoundTrip` wrote a chat and two messages to PostgreSQL for every tool result codec case, although the read policy under test (`toolResultPartToMessagePart`) is pure. This PR moves the eight text-fallback and error cases into `TestMediaToolResultConversion`, an in-memory table, and deletes their database subtests: `TextResultStaysText`, `MissingMimeTypeStaysText`, `MissingDataStaysText`, `ErrorResultStaysError`, `NonMediaResultTypeStaysText` and the three `IsMediaTrueBut*` cases. The table encodes the same assistant tool call and tool result with `MarshalParts` and `CurrentContentVersion`, then runs `ConvertMessagesWithFiles`. The layer above moves the media rows. **Why it is safe** - Every row keeps its assertions. Each row also gains checks for role, part count, `ToolCallID` and `ProviderExecuted=false`, and text rows compare the output to a literal with `JSONEq`. `ErrorResultStaysError` compares the whole error message, and `IsMediaTrueButMissingMimeType` carries valid base64, so it fails on the `mime_type` check itself rather than in the base64 branch. - I ran 24 mutants of `chatprompt.go` with `go test -overlay` against the tests on `main`, on this PR and on #30946 (list below). Every mutant that `main` catches, this PR catches too. Three that survive on `main` fail here, and one (IsMedia winning over IsError) survives everywhere. <details><summary>Mutants (main / this PR / #30946)</summary> - Survive on `main`, caught here and in #30946: no `mime_type` check; placeholder for every IsMedia text fallback; error-string extraction disabled. - Survives on all three: IsMedia wins over IsError. - Caught on all three: IsMedia gate always on; gate always off; no data check; unmarshal failure treated as media; error branch disabled; media Text, MediaType or Data dropped; `ProviderExecuted` forced true for media, text or error results; text or media `ToolCallID` dropped; base64 check skipped; first attachment chosen regardless of media type; attachment file ID not mirrored; write path drops the media flag, the error flag or the media text; error message replaced. - A garbage copy of `chatprompt.go` fails to build under each overlay, so the overlay applies. </details> **Review focus** The shared assertions in the table loop. The rows also stop passing through PostgreSQL, whose jsonb normalizes key order, whitespace, number forms and escapes, so production decodes different bytes than these rows feed in, with the same meaning. The deleted subtests and the new rows both compare with `JSONEq`, and the round trip the stack keeps covers media results only. **Validation** - `go test ./coderd/x/chatd/chatprompt/ -count=1 -p 4 -parallel 4`: ok on `main` and on this PR - `go vet ./coderd/x/chatd/chatprompt/`: ok - `golangci-lint run --fix=false ./coderd/x/chatd/chatprompt/`: 0 issues - pre-commit hook: passed **Stack** The stack moves the tool result codec matrix out of PostgreSQL and keeps one storage round trip. 1. #30945 table the text and error tool result rows in memory (this PR) 2. #30946 table the media codec matrix in memory > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
f0b6bf12ac |
test(coderd/x/chatd): reuse recordingPubsub in the task test fixture (#30923)
`tasks_test.go` kept its own copy of the recording pubsub, `taskRecordingPubsub` (59 lines), next to `recordingPubsub` in `helpers_test.go`. This PR adds the three things the copy had (`clear`, a `published` snapshot and an `onPublish` hook) to `recordingPubsub`, points the task fixture at it, and deletes the copy. The task fixture now reaches the raw pubsub through the embedded field, so its `rawPS` field goes too. **Why it is safe** - The added methods behave like the copy's: `onPublish` runs outside the lock and before the inner `Publish`, `clear` drops the recorded events, and `published` returns a copy taken under the lock. It replaces the copy's `events()`, which would collide with the existing `events` field. - `recordingPubsub` embeds the full `dbpubsub.Pubsub`, so subscriptions reach the same inner pubsub the copy forwarded `SubscribeWithErr` to. Servers built by the task helpers still get the raw pubsub. - `watchEvents` is the existing `recordingPubsub` method. It filters the same way the copy did, reading under the lock instead of from a snapshot. - After the change, `rg 'taskRecordingPubsub|taskPublishedEvent|rawPS' coderd/` finds nothing. **Review focus** The turn-trace tests set `f.pubsub.onPublish` while holding `f.pubsub.mu`. Both names are unchanged, and `Publish` still reads the hook under that lock. **Validation** I built the package test binary with `go test -c ./coderd/x/chatd/` (and with `-race`). Ten files use either fixture: `tasks_test.go`, `hooks_internal_test.go`, `turn_trace_internal_test.go` and the seven `workerTestFixture` files. I ran the 142 top-level tests in the ten files with `-test.count=1 -test.parallel 4`. | Head | Plain | `-race` | |---|---|---| | `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races | | this PR | 142 passed | 142 passed, no data races | The pre-commit hook passed. **Stack** The stack folds the task test fixture into the shared worker test fixture. 1. #30923 reuse `recordingPubsub` in the task test fixture (this PR) 2. #30924 fold `taskTestFixture` into `workerTestFixture` > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
36bccbf08b |
fix(coderd): reject overflowing workspace TTL values (#31329)
Workspace create and TTL update pass the requested `ttl_ms` to `validWorkspaceTTLMillis`, which multiplied it by `time.Millisecond` before it checked the bounds. Values outside the `int64` nanosecond range wrapped around: `18446744133710` ms and `-18446744013709` ms both became about one minute, so the API accepted them and stored a one-minute TTL instead of returning a validation error. The helper now rejects negative values with the minimum error and values above 30 days with the maximum error before it converts to a `time.Duration`. The maximum check compares whole minutes to match the existing round down to the minute, so inputs that do not overflow keep their current result. Two new `TestWorkspaceUpdateTTL` rows send these values. Without the fix both fail with `An error is expected but got nil.` (the endpoint returns 204); with the fix both get the expected validation error. Related to #31036, which fixes the same overflow in the chat workspace TTL setting. > Xum, an AI agent, opened this PR for @ibetitsmike. |
||
|
|
c8ed6f6cb2 |
test(coderd/x/chatd): assert the compaction debug run finishes (#31328)
Follow-up to #31087. `TestActiveServer_CompactionModelOverride` checked only that the compaction debug run exists and records the override model, so a regression that left the run `in_progress` still passed. The four `summary routes to the override model` subtests now also assert that the run's status is `completed` and that `finished_at` is set. Mutation check, with `go test -p 2 -parallel 4 -count=1 -run '^TestActiveServer_CompactionModelOverride$' ./coderd/x/chatd/`: - Finalize timeout set to `time.Nanosecond` in `startCompactionDebugRun` (`chatloop/compaction.go`), the mutant found in the #31087 review: the old test passes all 13 subtests while it logs four `failed to finalize debug run` warnings. With this change, the four routing subtests fail with `expected: "completed"`, `actual: "in_progress"`. - `finishDebugRun(err)` removed from the `generateCompactionSummary` defer: the same four subtests fail in the same way. - Production code restored: all 13 subtests pass, and the four routing subtests also pass with `-count=5`. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
a3fb196ce4 |
fix(coderd/x/chatd): replace interrupted ACP tool output (#31362)
When interruption arrives after `acp_wait_agent` publishes its result
but before the step commits, the model can receive the user's full
sub-agent transcript, including reasoning.
Keep a list of tools whose buffered output is replaced for the model on
interruption, initially `acp_wait_agent`. Preserve the transcript for
the user and give the model `{"error":"tool call was interrupted"}`. A
completed answer may need to be collected by calling the wait tool
again.
Alternative to #31345.
|
||
|
|
7283fff69f | fix(coderd/database/pubsub): close listener before waiting on latency probe (#31317) | ||
|
|
1a9d5b28ba |
fix: keep ACP harness context synchronized (#31351)
ACP harness resources bypass context drift detection, but only MCP resources were live-synced into bound chats. Later ACP discoveries, capability updates, probe errors, and removals could therefore leave chat context stale without offering a refresh. Extend the existing live-sync query to include ACP harnesses and publish context updates for affected chats while keeping instructions and skills pinned. Depends on #31350. This PR contains the ongoing synchronization change; #31350 fixes initial probe ordering. |
||
|
|
2116682e61 |
fix(coderd): reject overflowing chat workspace TTL values (#31036)
`PUT /api/v2/chats/config/workspace-ttl` converted `workspace_ttl_ms` to a `time.Duration` before it checked the 30-day maximum. A value whose nanosecond count overflows `int64` wraps into range: `18446744133710` ms becomes about one minute, passes both range checks, and is stored. This PR checks the maximum on the millisecond value, before the conversion. **Why it is safe:** for every value that does not overflow, `req.WorkspaceTTLMillis > ttlMaximum.Milliseconds()` is the same test as `d > ttlMaximum`, and it writes the same `400` message. `TestChatWorkspaceTTL` already pins the boundary: exactly 30 days is accepted and 721 hours is rejected. A mutant that rejects exactly 30 days fails it. **Red test:** `TestChatWorkspaceTTL` now sends `18446744133710` ms and expects a `400` and an unchanged stored value. On `main` the handler accepts the value: ```text coderd: PUT path=/api/v2/chats/config/workspace-ttl status_code=204 exp_chats_test.go:17412: Error: An error is expected but got nil. --- FAIL: TestChatWorkspaceTTL ``` **Review focus:** the order of the checks. The maximum now runs on milliseconds before the conversion; the one-minute minimum still runs on the converted duration, which is safe once the maximum has passed. #31018 moved this handler onto the shared `putChatOperationalSetting` helper and kept the maximum check after the conversion, so the overflow is still live on `main`. This branch merges `main` and moves that check to the front of the handler's validation closure, next to the negative check. Validation: `go test ./coderd -run '^TestChatWorkspaceTTL$' -count=1` fails against `main`'s handler as above and passes on this branch. On this branch, `go test ./coderd -run '^(TestChatPersonalModelOverridesAdminSettings|TestChatComputerUseProvider|TestChatDebugLoggingSettings|TestChatWorkspaceTTL|TestChatRetentionDays.*|TestChatDebugRetentionDays|TestChatAutoArchiveDays|TestAuditedChatOperationalSettingWrite.*|TestChatOperationalSettingsAuditDeniedWrites)$' -count=1` passes (12 tests, 35 with subtests) and `go test ./enterprise/coderd -run '^TestChatOperationalSettingsAudit$' -count=1` passes (17 with subtests). `go vet ./coderd/` is clean, and `make pre-commit` passed (`make gen`, formatting, golangci-lint, slim build). > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
0b8d9135ae |
refactor(coderd): drop pass-through chat message conversion wrappers (#31023)
Deletes six helpers in `coderd/exp_chats.go` that only forwarded to `db2sdk` or the store: `convertChatMessage`, `convertChatMessages`, `convertChatQueuedMessage`, `convertChatQueuedMessagePtr`, `convertChatQueuedMessages`, and `lookupEnabledChatModelConfigByID`. Their callers now call `db2sdk.ChatMessage`, `db2sdk.ChatQueuedMessages`, and `GetEnabledChatModelConfigByID` directly, and convert message lists with `slice.List`. This includes the `getChatAttachments` call site that #31140 added on `main`. It adds 9 lines and removes 47. **Why it is safe:** each call site now runs the function the wrapper called. `slice.List` and `db2sdk.ChatQueuedMessages` return an empty, non-nil slice for no rows, as the wrappers did, so empty lists still encode as `[]`. A repository-wide search finds no other references to the deleted names. **Review focus:** the two pointer results use `new(db2sdk.ChatMessage(...))` and `new(db2sdk.ChatQueuedMessage(...))`, the Go 1.26 form of `new` that takes an expression. `coderd/provisionerdaemons.go` already uses it. #29662 edits the same `ChatMessagesResponse` literal in `getChatMessages`, so the two conflict in that one hunk. Validation: on `main` and on this branch, `go test ./coderd -run '^(TestPostChatMessages.*|TestGetChatMessages_.*|TestPatchChatMessage|TestChatMessageWithFile.*|TestDeleteChatQueuedMessage|TestPromoteChatQueuedMessage|TestQueuedMessageWithoutOverrideCapturesEnqueueTimeModel|TestSendMessage.*|TestSubsequentSendWithoutOverrideUsesPersistedModel|TestChatModelOverrides)$' -count=1` passes (20 tests, 149 with subtests). The pre-commit hook passed (`make gen`, formatting, golangci-lint, slim build). > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
67d586bb13 |
refactor(coderd): share the chat prompt length check (#31020)
Five `PUT` handlers wrote the same `400` when the sanitized text is longer than the deployment's prompt byte limit: the deployment system prompt, the organization system prompt, plan mode instructions, the user custom prompt, and chat project instructions. This PR moves that check into `api.writePromptTooLongError`, which takes the sanitized text and each handler's message. It adds 16 lines and removes 28, and drops two comments that only said the limits match. Each handler still reads its body and calls `codersdk.SanitizePromptText` itself, because it keeps using the sanitized text. Moving the sanitize call into the helper would not remove any more lines: each call site would still need the sanitized value and the early return. **Why it is safe:** the messages, the detail text, and the limit are unchanged. I ran 6 mutants with `go test -overlay`: reject a text of exactly the limit, change the message or the detail in the helper, and change the project instructions, custom prompt, and plan mode messages at their call sites. The tests fail on each. **Review focus:** the boolean result. `true` means the helper wrote the `400`, and every call site returns on it. Validation: on `main` and on this branch, `go test ./coderd -run '^(TestChatLimitsFromDeploymentConfig|TestChatProjectInstructions|TestChatSystemPrompt|TestChatPlanModeInstructions)$' -count=1` passes (4 tests, 68 with subtests) and `go test ./enterprise/coderd -run '^(TestOrganizationChatSystemPrompt|TestChatProjectInstructionsUpdateOnlyRole|TestChatProjectInstructionsAudit)$' -count=1` passes (3 tests, 14 with subtests). The pre-commit hook passed (`make gen`, formatting, golangci-lint, slim build). > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |