mirror of
https://github.com/coder/coder.git
synced 2026-11-30 01:47:32 +08:00
34ef30ee90271258f18a080b008cc368f736ab80
587
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
1aff810443 |
chore: sync fantasy with upstream v0.45.5 (#31288)
Moves the fantasy pin to the tip of `coder_2_33` (`85ffbbe`). That commit is coder/fantasy#72, which merges 87 upstream charmbracelet/fantasy commits, v0.40.0 to v0.45.5. Between the two pins 117 files change. Upstream's own v0.40.0 to v0.45.5 change, without tests, testdata, examples, `go.sum` and the kronk provider, is 43 files, +2271/−928. ## What reaches chatd chatd builds only the `anthropic`, `openai` and `openaicompat` fantasy clients (`chatprovider.ModelFromConfig`); other vendors reach it through the AI Gateway on one of those. So the upstream changes to the Google, Vercel, OpenRouter, Bedrock, Azure and kronk providers, and to the `fantasy.Agent` loop and its retries, do not run in chatd. These do: - **Chat Completions and openaicompat streams** keep reasoning on batched and DeepSeek-shaped chunks, keep `finish_reason: length` when tool calls are truncated, and stop sending empty reasoning fields. openaicompat drops assistant turns that hold only reasoning. - **Token usage.** When an OpenAI-shaped backend reports reasoning tokens apart from completion tokens (reasoning larger than output), output tokens now include them, so that backend's reported output tokens and cost rise. OpenAI's own shape, where reasoning is a subset, is unchanged. - **Responses.** A content-filtered turn no longer reads as a tool-call turn. - **Context overflow.** Baseten, Fireworks and Parasail prompt-length errors set `ContextTooLargeErr`, which compaction acts on. - **Anthropic.** Tool calls whose content block never closes are reported. For Claude 5 models, thinking defaults to `display: "summarized"` when the chat config sets none; a configured display still wins. `TestThinkingDropBlockModel_RetriesWithEffort` now expects the field in the retry body. - **Anthropic keepalives.** Fantasy forwards `message_start`, `message_delta` and unknown events as content-free `keepalive` parts. The first one arrives before any model output, so this PR makes `ttft_seconds` and the `time_to_first_token` stage skip them, as they skip warnings. They still reset the stream silence guard. `processStepStream` ignores them, and the debug recorder counts them in its part count but records no content. - **Tool-result media** now goes through upstream's shared `ToolRunBuffer`, which replaces coder/fantasy#64 and does the same thing. #72 keeps coder's anthropic-sdk-go and openai-go forks, Go 1.26 and kronk v1.31.5, so upstream's SDK and Go moves do not come along. `go mod tidy` raises the modules fantasy v0.45.5 requires, among them otel exporters v1.47, the AWS SDK, `google.golang.org/api` v0.307 and go-openapi v1. All are upgrades. The `go.mod` comment now names #72 as the upstream sync. coder/coder#29861 stacks on this PR to pin coder/fantasy#62. <details> <summary>Verification</summary> - `go build ./...`. - `go test` passes on every package that imports fantasy (`coderd/x/chatd/...`), and `go test ./coderd -run 'TestChat|TestExpChat|TestMCP|TestAIBridge'` passes. - `TestGuardedStreamTTFTStage/WarningsAndKeepalivesThenContentObservesOnce` fails without the TTFT change (TTFT observed 0s instead of 1s) and passes with it. - `make pre-commit` passes. The generated Prometheus docs pick up the metric help change. Not verified against live backends in this PR: the stream fixes, the token usage change and the context-overflow patterns have no coder test against a real provider. coder/fantasy#72 reports a local chatd run against the AI Gateway on Anthropic, Responses, OpenAI Chat and openaicompat. </details> > 🤖 This PR was created with the help of Coder Agents, and _will be_ reviewed by a human. 🏂🏻 |
||
|
|
a33af01605 |
refactor(coderd/x/chatd/chatloop): create the compaction debug run through StartRun (#31087)
Compaction was the last debug-run caller that did by hand what `chatdebug.Service.StartRun` does: insert the run on a detached context with a 5 second limit, rebuild the run context, and finalize it with `ClassifyError`. This PR moves `startCompactionDebugRun` onto `StartRun` and deletes `compactionDebugCreateRunTimeout`. #30934 moved the other callers; compaction waited for #30766, which has merged. **Why it is safe:** - The first commit changes only the test, renamed from `TestStartCompactionDebugRun_DoesNotReportDebugErrors` to `TestStartCompactionDebugRun`. It now asserts the whole inserted row: kind `compaction`, status `in_progress`, the parent run's root chat, parent chat and trigger message, the summary model's provider, model, model config and history tip when the caller sets them and the parent run's otherwise, and no summary. It also asserts the returned run context and the `completed` and `interrupted` finalize statuses. It passes on the old code and on the new code. - On the old code, 16 mutants (wrong kind or status, a dropped parent field, an ignored override or fallback, a seeded summary, a wrong run context field, a wrong finalize status) all fail the new test. Before this PR, the chatloop tests caught 1 of them and `TestActiveServer_CompactionModelOverride` 3 more (kind, model and model config); the other 12 passed both. On the new code, all 13 mutants of the `StartRun` call fail the test. - `StartRun` keeps the rest: a failed insert returns the caller's context and a no-op finalizer, the insert ignores the caller's cancellation, and the run still finalizes through `FinalizeRun` with its default 5 second limit. `TestService_StartRun` pins the first two. A nil seed summary still stores no summary, because `nullJSON` maps a nil map to SQL NULL. **Review focus:** log output. The old code discarded create and finalize errors. `StartRun` logs them at Warn as `failed to create debug run` and `failed to finalize debug run`, like the other callers. A debug failure still never fails compaction. Validation: - `go test -count=1 ./coderd/x/chatd/chatloop/...` passes, and so does `go test -race` on the compaction debug tests. - `go test -count=1 -p 2 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `go test -count=1 -parallel 4 -run 'Debug|Compact' ./coderd/x/chatd/`: the same 53 tests pass before and after. - `go vet` is clean on both packages, and the pre-commit hook, which runs `paralleltestctx`, passed on both commits. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
514f23979a |
feat: honor disable-model-invocation in skill frontmatter (#31147)
Extends #30882's `model_invocable` semantics to workspace skills and to stored skills created through the API. Claude Code and Xum let skill authors set `disable-model-invocation: true` in SKILL.md frontmatter, so agents never pick the skill on their own and it runs only when a person invokes it. Coder Agents honored the key only when someone imported a SKILL.md file while adding a project skill (#30884). ## What changes - **Workspace skills:** when the pinned SKILL.md sets the key to the YAML boolean `true`, chatd leaves the skill out of `<available-skills>` before merging sources, so a listed skill with the same name keeps its bare name, and `read_skill` reports it as not found. The skill stays in the `/` menu, and invoking it still loads its body. `read_skill_file` serves its supporting files under the bare name or `workspace/<name>` and refuses its `SKILL.md` (case-insensitive, after `path.Clean`). Skills without the key behave as on the base. - **Invoked workspace skills:** invoking a workspace skill now stores the pinned skill directory on the invocation part, and the prompt renders it as `dir` on `<invoked-skill>`, escaped as an attribute value. Before, only `read_skill` gave the model a skill's directory, and it refuses a hidden skill, so a hidden skill could not run the scripts it bundles. The part also stores the chat's workspace, and the prompt shows `dir` only while the chat stays bound to it, as it does for workspace file references. This changes #30861's invocation code. Hook payloads drop the directory and its workspace like the body, and API responses strip both. - **Stored skills:** a create request whose content sets the key and that omits `model_invocable` stores `model_invocable = false`. An explicit value wins, and PATCH is unchanged. This covers personal, organization, and project skills, which share `createSkill`. - `workspacesdk.SkillDisablesModelInvocation` reads the key. The `CreateSkillRequest.ModelInvocable` doc comment, the generated API docs, and `extending-agents.md` (the SKILL.md format, a new "Turn off automatic use" section, and the notes on the skill index, the skill tools, and aliases) describe the new behavior. ## Follow-ups - The personal and organization skill editors have no "Agents can use it automatically" switch yet. Only the project editor from #30884 has one. ## Testing - Go tests cover the parser, the turn's skill index and aliases, `read_skill`, `read_skill_file`, invocation of a hidden skill and the directory it carries (attribute escaping, no directory after the chat changes workspace, no directory in hook payloads), and the create default for personal and organization skills. Each new test fails when its code path is removed. - Remote dogfood UAT with a real model failed rounds 1 to 3. Rounds 1 and 2 found the hidden SKILL.md still readable through `read_skill_file` by symlinks and stale pins, plus a bare-name lookup bug and a docs gap that round 2 fixed. Round 3 found that the content check added against those bypasses refused a listed skill's file whose own frontmatter sets the key. After round 3 we narrowed the rule to the hidden skill's `SKILL.md` path. The key decides what agents are offered (the index and `read_skill`), not which files they can read: `read_file` and `execute` already open any workspace file, so a content check in `read_skill_file` protected nothing and kept producing edge cases. - Round 4 passed on `c9ff25dc29f`. Later commits added a behavior-neutral cleanup (`cd617533c2e`), one test case from the test audit (`044c1e6e23a`), and a comment fix (`9ec3768b18b`), which passed validation without another UAT round. Round 5 passed on `2b518c6c2b1`, which adds the skill directory. A real model ran hidden skills' scripts from the `dir` on `<invoked-skill>`, including directories whose paths contain `&`, `'`, `"`, `<` and `>`, and API responses carried no directory. Merging main after #30884 landed (`2d7d3cb9674`) did not change this PR's diff, so UAT was not rerun. `8f043b2a342`, which shows the directory only while the chat stays bound to the skill's workspace, has Go tests but no UAT round. - The doc-check skill ran in author self-check mode on `2d7d3cb9674`, and `27de7f5c6d7` fixes its findings: the skill index sentence said every skill is listed, the stored-skill sentence claimed any project editor import honors the key and presented the API default as fixed, the API path came before the UI path, and some wording broke the docs style rules. The fix is docs-only, so UAT was not rerun. - Polish and the test audit stayed inside the implementation diff. No new dependencies. - Codex review found no major issues on `9ec3768b18b`, then raised one P2 on the same head when the PR was marked ready: an invoked hidden skill gets no skill directory. A probe confirmed it, and `2b518c6c2b1` fixes it. Its earlier finding on that head (honor `CODER_AGENT_EXP_SKILL_META_FILE`) was refuted, because the pinned skill snapshot always reads `SKILL.md`. Both threads are resolved, and Codex found no major issues on `2b518c6c2b1` or on the merge `2d7d3cb9674`. - On `27de7f5c6d7`, Codex raised two P2s. One was confirmed: an invoked skill's directory stayed in the prompt after the chat moved to another workspace, which a prompt test showed on that head, and `8f043b2a342` fixes it. The other was declined: on Windows, `scripts\..\SKILL.md` gets past the `SKILL.md` check in `read_skill_file`, but that check is not an access boundary (`read_file` opens any path), and Windows has more aliases (`SKILL.md.`, `SKILL.md::$DATA`, `SKILL~1.MD`) that normalizing backslashes would not stop. On `8f043b2a342`, Codex asked to bind the directory to the workspace build instead. That was declined: every workspace start is a new build with new agent IDs, so the directory would drop after each stop and start, and the pinned body and the live files can diverge without a rebuild anyway, as they do for `read_skill`. A later request on that head asked to limit a hidden skill's `read_skill_file` access to invocations in the current workspace. That was declined too: `read_skill_file` resolves names against the current pin for listed skills on main as well, and the key decides which skills agents are offered, not which files they can read. All four threads are resolved. `a697dcd927f` adds the `format:"uuid"` tag that `TestSDKFieldsFormatted` requires on the new field, and Codex found no major issues on `a697dcd927f`. `ae70b2c533f` is docs-only: it applies the doc-check suggestion to say that an invoked skill's directory is included only while the chat stays in that workspace. The author doc-check self-check found no blocking findings on it, and Codex found no major issues on `ae70b2c533f`. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. --------- Co-authored-by: Jaayden Halko <jaayden.halko@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
e75885a37e |
feat: add ACP subagent waiting and transcript streaming (#30560)
Add `acp_wait_agent` to stream ACP transcripts, including reasoning and nested tool activity, to users while returning the subagent's text response to the parent model. Reconnect dropped streams from their transcript cursor, preserve running sessions on wait timeout or cancellation, and persist separate user-visible and model-visible results. Depends on #31022. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
8fd94eba27 |
feat: add tools to start, message, and interrupt ACP agents (#31022)
Add tools to spawn, message, and interrupt workspace-local ACP agents when the `chat-acp-subagents` experiment is enabled. Derive harness choices and configuration validation from the chat's pinned context, and deduplicate session creation and prompt submission across retries. Depends on #30831. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
457d777af1 |
fix(coderd/x/chatd/toolschema): traverse schema branches (#31128)
Tool input validation skipped properties declared inside composed schemas, allowing case-variant keys to bypass ambiguity checks. Traverse `anyOf`, `oneOf`, and `allOf` branches when checking nested objects, arrays, and free-form map values, while preserving exact property matches. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
9cda919eb1 |
test(coderd/x/chatd): fold the duplicate advisor scenarios (#30993)
Two end-to-end advisor scenarios repeated other tests. This PR moves their unique checks into tests that stay and deletes them. - `TestAdvisorGating_RootChat` replayed the advisor and `read_file` batch of the `mixed exclusive and local tools commit policy errors` subtest. Its exact two-call count moves into that subtest, which already checks that `read_file` never runs and both stored errors. Its check that the first request carries the advisor guidance moves into `TestAdvisorHappyPath_RootChat`; the `Root` row (#30990) checks the advisor tool and the guidance in the turn environment. - The `solo exclusive tool executes` subtest is a subset of `TestAdvisorHappyPath_RootChat`, which now also checks the stored advisor result. ### Why it is safe | Deleted assertion | Remaining check | | --- | --- | | Exactly two streamed calls | the mixed local subtest: `>= 2` became `== 2` | | Advisor offered | `Root` row (turn environment), and `TestAdvisorHappyPath_RootChat` now checks that the first request lists `advisor` | | Guidance in the first request | happy path test, new check | | Advisor and skipped tool errors sent back | the mixed local subtest (stored errors), `TestExclusiveToolPolicy_MixedBatchErrors` (text) | | Solo: stored result is not an error and holds the reply | happy path test, new checks | | Solo: three streamed calls | happy path test waits for the same three | | Mutant | Fails before | Fails after | | --- | --- | --- | | Exclusive batch check off | both mixed subtests, `RootChat` | both mixed subtests | | No exclusive tool set | both mixed subtests, `RootChat`, `Root` row | both mixed subtests, `Root` row | | Advisor runs, then the batch is rejected | `RootChat` only | the mixed local subtest | | Advisor result marked as an error | provider executed subtest, solo | provider executed subtest, happy path | | Advisor result replaced with `{}` | solo, happy path | happy path | | Guidance dropped from the request (`generation.go:898`) | `RootChat` only | happy path | Only an exact count sees the nested advisor call of the third mutant, so the count moves instead of going away. Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1 -p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that all runs at #30990 reach is also reached at #30993. The other differences are blocks that some runs of the same head reach and others miss, mostly error paths that depend on timing, so one run per head can show them as lost or gained. ### Review focus The subtest reads the count after the chat reaches `waiting`, and its fake model server counts only streamed requests, so title requests do not change it. ### Timing From 10 runs, the two deleted scenarios took 0.83 s summed (median per test). ### Validation - `go test ./coderd/x/chatd/ -run '^(TestActiveServer_ExclusiveToolPolicy|TestAdvisorHappyPath_RootChat)$' -count=10`, and with `-race -count=3`: pass - `go test ./coderd/x/chatd/...`: pass - `go test -overlay` mutant runs of the whole `./coderd/x/chatd/` package before and after this PR: results above - the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table 2. #30991 Remove the end-to-end advisor gating tests 3. #30992 Remove the end-to-end root and child tool list tests 4. #30993 Fold the duplicate advisor scenarios (this PR) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
c78ceccfaa |
test(coderd/x/chatd): remove end-to-end root and child tool list tests (#30992)
This PR deletes three end-to-end checks of model request tool lists (309 lines); the rows from #30990 check the same lists on the turn environment. The plan child tail also proved that a follow-up message without `PlanMode` keeps the stored plan mode. The plan rows of `TestBuildTurnEnvironmentToolPolicy` now send that follow-up and check the stored plan mode, so clearing it in `SendMessage` fails the table. - `TestSubagentChatExcludesWorkspaceProvisioningTools` booted coderd with a provisioner and AI Bridge to compare root and child tool names. - The plan child tail of `TestActiveServer_BasicAssistantGenerationAndPromptPreparation` checked `read_file` and `write_file`. Its only helper, `createPlanSubagentChatWithHistory`, goes too. - `TestPlanModeRootChatApprovedExternalMCPToolInvocation` is the first half of `TestPlanModeRootChatApprovedExternalMCPWorkflowCanReachProposePlan`, with the same three checks. ### Why it is safe Each mutant of `turn_environment.go` below failed the deleted check and fails the remaining one: | Deleted assertion | Remaining check | Mutant | | --- | --- | --- | | Root has the five workspace and five sub-agent tools | `Root` | root-only tools in no chat | | Standard root has no `ask_user_question` or `propose_plan` | `Root` | either tool added there | | Child has no workspace, sub-agent, or `ask_user_question` tools | `GeneralChild` | root-only tools or `ask_user_question` in children | | Plan child has `read_file` and no `write_file` | `PlanChild` | each flipped | | Plan root offers the approved MCP tool, ends `waiting`, and sends the result to the next call | the workflow test, and `PlanRoot` | approved MCP tools dropped | The split reads only `ParentChatID`, `Mode`, and `PlanMode` from the chat row (`turn_environment.go:258-261`), so a table child made with `chatstate.CreateChat` gets the tools of a `spawn_agent` child made with `chatstate.CreateChatWithID`. The `TestSpawnAgent_*` tests cover spawning. The deleted sub-agent test replied with an escaped NUL sequence but never checked the stored reply; `TestNulEscapeRoundTrip/BackslashU0000Text` covers that text. Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1 -p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that all runs at #30990 reach is also reached at #30993. The other differences are blocks that some runs of the same head reach and others miss, mostly error paths that depend on timing, so one run per head can show them as lost or gained. ### Timing From 10 runs, the two deleted tests took 1.14 s summed (median per test). The basic test went from 0.51 s to 0.41 s (median of 5). ### Validation - `go test -overlay` mutant runs of the whole `./coderd/x/chatd/` package before and after this PR: results above - `go vet ./coderd/x/chatd/`: clean; the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table 2. #30991 Remove the end-to-end advisor gating tests 3. #30992 Remove the end-to-end root and child tool list tests (this PR) 4. #30993 Fold the duplicate advisor scenarios > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
ac62f2e760 |
test(coderd/x/chatd): remove the end-to-end advisor gating tests (#30991)
`TestAdvisorGating_ExperimentDisabled`, `_ChildChat`, `_PlanMode`, and `_ExploreSubagent` each started Postgres, an active server, and a fake model server for one chat turn, only to check that the request had no advisor tool and, except for `_ExperimentDisabled`, no advisor guidance. The rows from #30990 check the same absence in the turn environment, so this PR deletes the four tests (353 lines). To keep one request-level check, `TestComputerUseSubagentToolsAndModel` now also checks that its child's first streamed request has no `advisor` tool and no guidance block. ### Why it is safe Each test guarded one condition of the advisor gate (`turn_environment.go:291`). Removing the condition failed the test and fails its row: | Deleted test | Its assertions | Row | Gate mutant | | --- | --- | --- | --- | | `_ExperimentDisabled` | No advisor tool with the experiment off and a stored config that says enabled | `RootAdvisorOff` (same config) | experiment check removed | | `_ChildChat` | No advisor tool or guidance in a chat with a parent | `GeneralChild`, the computer use test | root check removed | | `_PlanMode` | Same, in a plan mode root chat | `PlanRoot` | plan check removed | | `_ExploreSubagent` | Same, in an Explore chat | `ExploreRoot` | Explore check removed | The rows read the turn environment, not the request. A mutant that adds the guidance to every request (`generation.go:898`) failed `_ChildChat`, `_PlanMode`, and `_ExploreSubagent` and passes every row; it fails the computer use test. `_ExploreSubagent` made an Explore root chat (`isExploreSubagentMode` matches any Explore chat); `ExploreChild` also rejects the advisor. `_ExperimentDisabled` enabled every other known experiment, but the gate reads only `ExperimentChatAdvisor`. Coverage: in 6 runs per head of `go test ./coderd/x/chatd/... -count=1 -p 4 -covermode=set -coverpkg=./coderd/x/chatd/...`, every block that all runs at #30990 reach is also reached at #30993. The other differences are blocks that some runs of the same head reach and others miss, mostly error paths that depend on timing, so one run per head can show them as lost or gained. ### Timing From 10 runs, the four tests took 1.25 s summed (median per test). ### Validation - `go test -overlay` mutant runs of the whole `./coderd/x/chatd/` package before and after this PR: results above - `go test ./coderd/x/chatd/ -run '^TestComputerUseSubagentToolsAndModel$' -count=10`, and with `-race -count=3`: pass - `go vet ./coderd/x/chatd/`: clean; the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table 2. #30991 Remove the end-to-end advisor gating tests (this PR) 3. #30992 Remove the end-to-end root and child tool list tests 4. #30993 Fold the duplicate advisor scenarios > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
300f73b05a |
test(coderd/x/chatd): cover advisor eligibility in the tool policy table (#30990)
`TestBuildTurnEnvironmentToolPolicy` ran every row with the advisor experiment off and had no general sub-agent row, so only end-to-end tests checked advisor eligibility and the tools that only root chats get. This PR adds those checks to the table and deletes nothing; the PRs above it delete the end-to-end tests. - The rows run on a server with `ExperimentChatAdvisor`; the new `RootAdvisorOff` row uses a second server without it. The stored advisor config says `Enabled: true`, which must not matter: the experiment is the only gate (`codersdk/chats.go:1277`). - `Root` now wants the advisor, its guidance, and the five workspace and five sub-agent tools, and rejects `propose_plan`. The new `GeneralChild` row rejects all of those and `ask_user_question`. The plan and Explore rows reject the advisor. - Every row checks the guidance and the exclusive tool set: only the advisor when the row wants it, otherwise empty. ### Why it is safe The rows pass on `main` (`e53cfef8643`), which now includes #30911. Each of 15 mutants of `turn_environment.go` fails a row: | Mutant | Row that fails | | --- | --- | | Advisor gate ignores the experiment, the root check, plan mode, or Explore mode | `RootAdvisorOff`, `GeneralChild`, `PlanRoot`, `ExploreRoot` in that order | | No advisor guidance, no advisor tool, or no exclusive set | `Root` | | Root-only tools in every chat, or in none | `GeneralChild`, or `Root`, `RootAdvisorOff`, `PlanRoot` | | `ask_user_question` in standard root turns, or in child turns | `Root`, or `GeneralChild` | | `propose_plan` in every turn | `Root` | | Plan children get `write_file`, or plan turns drop `read_file` | `PlanChild` | | Plan turns drop approved MCP tools | `PlanRoot` | The deletion PRs above map each deleted assertion to these rows. Under the plan and Explore gate mutants, the plan filter and the Explore allowlist still drop the advisor tool, so those rows fail on the new guidance and exclusive set checks. ### Review focus Both servers are built once and never changed, and each row creates its own chat, so the rows stay parallel. ### Timing From 5 alternating runs, the table took 0.29 s (median) before this PR and 0.28 s after. ### Validation - `go test ./coderd/x/chatd/ -run '^TestBuildTurnEnvironmentToolPolicy$' -count=10`, and with `-race -count=3`: pass - `go test -overlay` mutant runs: results above - the pre-commit hook (gen, fmt, lint, slim build) passed ### Stack The stack moves advisor eligibility and the root versus child tool split into `TestBuildTurnEnvironmentToolPolicy` and deletes the end-to-end tests that only checked them, finishing #30868. #30911 has merged, so the stack now starts at `main`. 1. #30990 Advisor and general child rows in the tool policy table (this PR) 2. #30991 Remove the end-to-end advisor gating tests 3. #30992 Remove the end-to-end root and child tool list tests 4. #30993 Fold the duplicate advisor scenarios > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
9f2389a908 |
refactor(coderd/x/chatd): derive the BYOK auth header from the AI Gateway client choice (#30979)
`fantasyConfigForAIBridge` picked the fantasy client for an AI Gateway route, and `aiGatewayRequestFormatForProviderType` mapped the same provider type and model again, only to choose `X-Api-Key` or `Authorization: Bearer` for a user's own key. This PR moves the client choice into `aibridgeClientProvider` and passes its result to `aiGatewayProviderAuthForUser`, so the header follows the client. It deletes the request-format enum, the mapper, the mapper's test, and the superseded `TestNewModelAttribution`. ## Why it is safe - `aibridgeClientProvider` is the old `fantasyConfigForAIBridge` switch without the base URL. `TestAIBridgeProviderFormatMapping` (12 rows, unchanged) still pins the client and base URL; the mapper test's 9 rows are a subset of them. - The mapper returned the Anthropic format for exactly the inputs that get the Anthropic client, so no header changes. `TestAIGatewayProviderAuthForUser` and the #30978 subtest pin the header. - `TestNewModelAttributionImmutablePerRequest` covers both workspace bindings that `TestNewModelAttribution` checked, plus the API key ID, also without a database. - Mutants through `go test -overlay` each fail a remaining test: every arm of `aibridgeClientProvider` and the base URL check; an auth switch keyed on `openai`, an auth case matching `openai-compat` instead of `anthropic`, and a dropped model ID at the `resolveAIGatewayRoute` call; the workspace check, the workspace ID copy, and an empty API key ID. A garbage copy fails to build, so the overlay applies. - `rg -n 'aiGatewayRequestFormat' .` finds nothing. ## Review focus Only the Anthropic client gets `X-Api-Key`; `openai` and `openai-compat` keep `Authorization: Bearer`, as the old default format gave them. Only the #30978 subtest catches an auth switch keyed on `openai`. ## Validation - `go test ./coderd/x/chatd/... -count=1 -p 4 -parallel 4`: pass. - 12 mutants: each fails a remaining test. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
707d373a76 |
test(coderd/x/chatd): cover BYOK header choice for Bedrock and OpenAI-compatible routes (#30978)
`TestResolveModelRouteForConfigAIGatewayProviderAuth` gains one subtest that pins which header carries a user's own provider key on two more routes: `X-Api-Key` for an Anthropic model on a Bedrock provider, and `Authorization: Bearer` for an OpenAI-compatible provider. The next layer rewrites how chatd picks that header, and until now no test failed when the call site dropped the model ID. This test-only layer is the characterization test for that rewrite, so it adds lines instead of removing them. ## Why it is needed - `resolveAIGatewayRoute` passes the model ID to `aiGatewayRequestFormatForProviderType`, and only the Bedrock arm reads it. A mutant that passes `""` instead passed all of `go test ./coderd/x/chatd/`: no chatd test resolved a BYOK route for a Bedrock provider, and `TestAIGatewayRequestFormatForProviderType` calls the classifier directly. - With this subtest, that mutant fails on the Bedrock row (`X-Api-Key` expected, `Authorization` sent). A mutant that maps the classifier's default arm to the Anthropic format fails on the OpenAI-compatible row. A garbage copy of `model_routing_aibridge.go` fails to build, so the `-overlay` applies. ## Review focus Today the OpenAI-compatible row takes the same default arm as the OpenAI `UserKey` subtest. The next layer keys the header on the client family (`anthropic`, `openai`, `openai-compat`), and this row fails if that switch matches only `openai`. ## Validation - `go test ./coderd/x/chatd/ -run '^TestResolveModelRouteForConfigAIGatewayProviderAuth$' -count=1`: pass. - Both mutants above, through `go test -overlay`: fail the new subtest. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
231537da8b |
refactor(coderd/x/chatd): drop transport branches only direct clients used (#30966)
`Model.AcceptsFilePartMediaType`, `BetaHeadersFromCallConfig`, and `chatopenai.TransportFor` still had branches for the Azure, Bedrock, Google, OpenRouter, and Vercel clients. Production has built none of those clients since #30929, so the branches never ran. This PR deletes them and their test rows. ## Why it is safe - `AcceptsFilePartMediaType` and `TransportFor` switch on the built client's `Provider()`, which is `anthropic`, `openai`, or `openai-compat` (see #30958). `BetaHeadersFromCallConfig` receives `anthropic` (`thinking_binding.go`) or the gateway's provider hint (`model_routing_aibridge.go`), which is one of the same three. - The deleted rows of `TestAcceptsFilePartMediaType`, `TestTransportFor`, and `TestBetaHeadersFromCallConfig` used the deleted provider names. The remaining rows fail on a mutant of each rewritten line: the Responses check in `TransportFor`, the provider check in `BetaHeadersFromCallConfig`, Anthropic `text/*` acceptance (what the Bedrock rows also checked), and the SVG rejection (`anthropic-svg` still checks what `google-svg` did). Garbage copies of both files fail to build, so the overlays apply. - `ToolResultMediaOmission` and `InlineImageCapBytes` keep their provider lists, because they read the configured provider behind the OpenAI-compatible client. ## Review focus Azure providers already reach the model through the OpenAI-compatible client, which always uses Chat Completions. The deleted Azure arm of `TransportFor` only described the direct Azure client. This PR also edits `coderd/x/chatd/ARCHITECTURE.md`, section "OpenAI transport selection": in the paragraph that began "Azure is deliberately exempt", "`TransportFor` has no Azure case, because" replaces the first two sentences and the opening "The exemption is narrower than it appears," of the third; the rest of that paragraph is unchanged. ## Validation - `go test ./coderd/x/chatd/chatprovider/... ./coderd/x/chatd/chatopenai/...`: pass. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - Mutants through `go test -overlay`: all 4 fail the named rows. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
17c7fe9632 |
refactor(coderd/x/chatd/chatprovider): drop provider options only direct clients read (#30958)
After #30929, `chatprovider` still converted Google, OpenRouter, and Vercel model-config options into fantasy provider options, and `applyReasoningEffort` still had Azure, Bedrock, Google, OpenRouter, and Vercel arms. No client that production builds reads any of them. This PR deletes the three option converters and those five effort arms. ## Why it is safe - `fantasyConfigForAIBridge` builds only the `anthropic`, `openai`, or `openai-compat` client, so `model.Provider()` never matched the deleted arms. - Each fantasy client reads only `ProviderOptions[<its own name>]` (chatd never renames the compat client), so the `google`, `openrouter`, and `vercel` entries were never sent. Pinned Gemini thinking still reaches Google through the compat `extra_body` path. - The deleted tests (`TestProviderOptionsForCall_GoogleThinkingConfig` and the Google, OpenRouter, and Vercel rows of `TestApplyReasoningEffort`) used those provider names, so they tested deleted code. The Gemini helpers they reached keep dedicated tests, which fail on mutants of the Gemini 3 version gate, the clamp comparison, the medium level mapping, the `GoogleThinkingLevelFromChat` normalization, and the compat `extra_body` assignment. - Two new cases close gaps the deleted rows left: `TestProviderOptionsForCall_GoogleThinkingConfigSkipsNonCompatClients` fails when the compat provider check becomes `!= ""`, and a pre-Gemini-3 `medium` row in `TestGoogleCompatReasoningEffort` fails when that arm returns `high`. Both mutants passed before. - The two Bedrock rows of `ClampsNoneForClaude55Models` now use the Anthropic transport with the same `global.anthropic.*` IDs, which the gateway sends to that transport. Changing `strings.Contains` to `strings.HasPrefix` in `anthropicReasoningEffort` fails them. - `rg -n 'googleProviderOptionsFromChatConfig|openRouterProviderOptionsFromChatConfig|vercelProviderOptionsFromChatConfig' .`: no matches. ## Review focus Chat debug runs record a lower `provider_option_count` for configs that set Google, OpenRouter, or Vercel options, because those unread entries are no longer built. ## Validation - `go test ./coderd/x/chatd/chatprovider/... ./coderd/x/chatd/chatopenai/...`: pass. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - Mutants through `go test -overlay`: all 11 fail the named tests, and garbage copies fail to build. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
cdc914108c |
refactor(coderd/x/chatd): drop the remaining direct provider clients (#30929)
After #30928, `chatprovider.ModelFromConfig` still built direct Azure, Google, OpenRouter, and Vercel clients. The AI Gateway path never asks for them, because `fantasyConfigForAIBridge` sends those provider types through the OpenAI-compatible client. This PR deletes those four arms and their missing-key error cases, the per-provider region plumbing that only the deleted Bedrock client read, and `ProviderAPIKeys.Empty`, which has no callers left. ## Why it is safe - The only production caller of `ModelFromConfig` passes a hint from `fantasyConfigForAIBridge` (see #30928), and no test builds these four clients. - Region flowed from `ConfiguredProvider.Region` through `ResolveUserProviderKeys` into `ProviderAPIKeys.RegionByProvider`, and only the Bedrock arm read it. The gateway reads Bedrock and Claude Platform regions from the provider settings itself (`aibridgedserver.go`). - `chatd.go` still marks Claude Platform on AWS as supporting ambient credentials. `TestResolveQuickgenModel_TitleGenerationOverrideAmbientCredentials` fails when that flag is forced to false. - `Empty` lost its last production caller when direct chat routing was removed (#26862). Its only test checked the region term. - Deleted tests (`TestProviderAPIKeysEmpty_RegionCountsAsConfigured`, `TestResolveUserProviderKeys_PreservesProviderRegions`, the `DisabledProviderRegionsRemoved` prune row) checked region and `Empty` code that is gone. One also checked that a keyless Bedrock provider is available; `TestResolveUserProviderKeys` still fails when the Bedrock ambient case or the empty-key rule in `setResolvedProviderAPIKey` is mutated. - `rg -n 'RegionByProvider|setRegion|keys\.Region\(|\.Empty\(\)' coderd/x/chatd` finds nothing. ## Review focus The `aiProviderConfigFromKeys` hunk in `chatd.go`, the only change outside `chatprovider`: it drops the region reads and keeps the ambient credential flag. ## Validation - `go test ./coderd/x/chatd/chatprovider/... ./coderd/x/chatd/chatopenai/...`: pass. - `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: pass. - `go build ./...` and `go vet` on every package that imports `chatprovider`: pass. - `make pre-commit`: pass. ## Stack This stack removes provider code that only direct, non-gateway clients used, so `chatprovider` builds just the three clients the AI Gateway path needs; #30979 then derives the BYOK auth header from that same client choice. 1. #30928 Drop the direct Bedrock client 2. #30929 Drop the remaining direct provider clients 3. #30958 Drop provider options only direct clients read 4. #30966 Drop transport branches only direct clients used 5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible routes 6. #30979 Derive the BYOK auth header from the client choice > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
766a0eb918 |
refactor(coderd/x/chatd/chatprovider): drop the direct Bedrock client (#30928)
`chatprovider.ModelFromConfig` builds the fantasy client for every chat
model call. Production reaches it only through the in-process AI
Gateway, where `fantasyConfigForAIBridge` asks for the Anthropic,
OpenAI, or OpenAI-compatible client, never Bedrock. This PR deletes the
direct Bedrock client that `ModelFromConfig` could still build,
`ProviderAllowsAmbientCredentials` and the API key bypass it fed, and
the tests that drove that client.
## Why it is safe
- Outside tests, `rg -n 'chatprovider\.ModelFromConfig\(' coderd
enterprise cli scaletest aibridge` finds one caller, `newLanguageModel`
in `model_routing_aibridge.go`. It passes the hint and placeholder key
from `fantasyConfigForAIBridge`, which sends Bedrock providers through
the Anthropic or OpenAI client by model ID. The gateway signs Bedrock
requests itself (`aibridge/intercept/awssig`).
- `ProviderAllowsAmbientCredentials` had one caller, the key check in
`ModelFromConfig`. The gateway path always sets the placeholder key, so
the check becomes `apiKey == ""`.
- The deleted tests (3 of 4 `TestModelFromConfig_Bedrock` subtests,
`...BedrockStripsAnthropicHeaders`, `...BedrockStreamingHeaders`,
`...BedrockBetaExtraHeader`, two helpers) each built the direct Bedrock
client, so they guarded deleted code.
- The OpenAI and Anthropic rows of the surviving subtest,
`NonBedrockStillRequiresAPIKey`, move into
`TestModelFromConfig_MissingAPIKey`. Its new `bedrock` row pins the
generic error message that a deleted subtest checked. These mutants all
fail it: no empty-key check, a changed generic message, a nil error from
the generic arm. A garbage copy of the file fails to build, so the
`-overlay` applies.
## Review focus
Ambient credentials still decide provider availability in
`ResolveUserProviderKeys`. Only the client-side bypass goes away.
## Validation
- `go test ./coderd/x/chatd/chatprovider/...
./coderd/x/chatd/chatopenai/...`: pass.
- `go test ./coderd/x/chatd/ -run
'AIBridge|AIGateway|Model|Provider|Bedrock|Quickgen|Title|Subagent' -p 4
-parallel 4`: pass.
- `make pre-commit`: pass.
## Stack
This stack removes provider code that only direct, non-gateway clients
used, so `chatprovider` builds just the three clients the AI Gateway
path needs; #30979 then derives the BYOK auth header from that same
client choice.
1. #30928 Drop the direct Bedrock client
2. #30929 Drop the remaining direct provider clients
3. #30958 Drop provider options only direct clients read
4. #30966 Drop transport branches only direct clients used
5. #30978 Cover the BYOK header choice for Bedrock and OpenAI-compatible
routes
6. #30979 Derive the BYOK auth header from the client choice
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
|
||
|
|
3c36790c86 |
fix(coderd/x/chatd): coalesce deltas when persisting interrupted turns (#29661)
An interrupted turn was stored with one ChatMessagePart per streamed delta, while a completed turn gets one part per block. One 28,539 character interrupted response became 3,987 parts and 1 MB of JSON, and a /messages page with such turns reached 11.7 MB. Whitespace-only deltas were separate parts too, and prompt replay skips whitespace-only parts, so words and paragraphs ran together in the next turn's prompt. Adjacent deltas of the same type are now joined into one part. A text run ends at another part type, a tool result or a narration change. A reasoning run ends where CreatedAt, the block's start time, changes. Adjacent text blocks still merge because text deltas have no block identity. Rows already stored are not rewritten. |
||
|
|
c4d76a4009 |
feat: add skill action and automatic-use settings (#30882)
Adds two per-skill settings that the project skills UI will expose next: - `action` marks a project skill to show as an action button above project chat composers. A `skills_action_project_only` check keeps it to project skills; the personal and organization routes reject `action` with 400. - `model_invocable` (default true, every stored source) controls automatic use. When it's false the skill is left out of `<available-skills>` and `read_skill` reports it as not found, but a structured skill invocation (a chip from the `/` menu or an action) still loads it, as long as the skill is enabled and the chat owner can read it. Workspace skills always count as model-invocable. Migration 000625 adds both columns with defaults, so existing skills keep today's behavior. The list, get, insert and update queries, `codersdk.SkillMetadata` and the create/update requests carry both fields, and the audit table tracks them. `coderd/x/chatd/ARCHITECTURE.md` gets TODO notes for the author. **NOTE**: the migration adds two columns with constant defaults and a CHECK constraint to `skills`. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 👈 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
15a160aec9 |
feat: serve internal MCP servers to chats in process (#29828)
This lets coderd give a chat MCP tools that it serves itself, in process. The first user will be an in-process integration, say a Slack bot. Nothing uses it yet. coderd now takes a list of internal MCP servers when it's built, each with a slug and a `ServerForChat` function. At every step, chatd asks each one for a server for the chat and connects to it over an in-memory transport, so the server knows which chat it's serving without any headers. Nothing is stored on the chat, so the public API doesn't change, and the chat owner can't remove an internal server. As only coderd can add one, internal servers ignore the `chat-inline-mcp-servers` experiment and the `--disable-chat-caller-supplied-tools` kill switch. Their tools come straight after the built-in tools, so they win any name clash with admin, workspace or caller tools. Admin and workspace tools now follow the same first-wins rule, so the model never sees two tools with the same name. If `ServerForChat` returns an error, we fail the turn, as we do when any other read during turn setup fails. I've put this on top of #30730 and #30731 in the stack. It doesn't need anything from them, but the Slack bot needs all three. |
||
|
|
39c4bd6ced |
refactor(coderd/x/chatd): drop the unused runnerCtx from the runner debug turn (#31010)
Deletes `runnerDebugTurn.runnerCtx` and the context parameter of `newRunnerDebugTurn`. The field's only reader was the `LaunchRunHeartbeat` call in `ensureLocked`, which #30988 deleted with the run heartbeats, so nothing has read it since. **Why it is safe:** the constructor set the field and no code read it. The debug turn still uses the context of each call to `Ensure`, `Context` and `Finalize`, which this PR does not change. `runner.go` and 10 tests stop passing a context, and four of those tests drop the `context.WithCancel` that they created only for this parameter. Validation: - `go build ./coderd/x/chatd/...` and `go vet ./coderd/x/chatd/...` pass. - The 25 chatd debug-run tests, `TestRecordGenerationFinishFailure`, `TestSessionStartDispatchFailureFinishesGeneration` and `TestStartGeneration_CancelsDeletedToolCallsOnAgent` pass under `-race`. - `golangci-lint run --fix=false ./coderd/x/chatd/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. This PR: Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
e3657389bb |
refactor(coderd/x/chatd/chatdebug): delete the process-global step counters (#31008)
Deletes chatdebug's process-global step counters: the `stepCounters` and `runRefCounts` maps, `refCountMu`, `trackRunRef`, `releaseRunRef`, `nextStepNumber`, `syncStepCounter` and `CleanupStepCounter`, the `runtime.AddCleanup` hook that `ContextWithRun` registered for every run context, and the two `CleanupStepCounter` calls in `FinalizeRun`. Since #31007 the database numbers steps, so no production code reads them. **Why it is safe:** after #31007 no production code reads the counters. Production code only maintained them: `ContextWithRun` registered a reference for every run context and `FinalizeRun` called `CleanupStepCounter`, and this PR removes both. A search of `coderd/` and `enterprise/` for the deleted names finds nothing now. The deleted tests covered only the deleted code: `TestNextStepNumber_Concurrent` and `TestSyncStepCounter_AdvancesCounter` checked counter values, and the three garbage-collection tests in `context_internal_test.go` checked that a counter lives until the last `RunContext` for its run is collected. The 20 `t.Cleanup(func() { CleanupStepCounter(runID) })` lines go with them. `TestReuseStep_PreservesExistingHolder` and `TestBeginStepReuseStep` stay. The `FinalizeRun` doc comment no longer mentions the counter. **Review focus:** `ContextWithRun` is now a plain `context.WithValue`. Code that copies a `RunContext`, such as `runnerDebugTurn.contextLocked`, no longer affects anything, because no state is tied to the struct's lifetime. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `go test -count=1 -run Debug ./coderd/x/chatd/` (19 tests) passes, and the 25 chatd debug-run tests pass under `-race` (`go test -race -run '^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$' ./coderd/x/chatd/`). - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. This PR: Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
ffd24861a1 |
feat: send skill invocations as structured message parts (#30861)
Adds a structured `skill-invocation` chat part so a user message can carry an explicit skill. chatd loads that exact skill when the message is sent and puts its body into the user's prompt, so the skill always applies instead of relying on the model to notice it in `<available-skills>`. The composer chip that sends these parts comes in the next PR. - codersdk: a `skill-invocation` input part and message part with `skill_source` (`personal`, `org`, `project`, `workspace`) and `skill_name`. The resolved body is stored on the part as internal `skill_body`; it's hidden from TypeScript and stripped from every API response. - coderd rejects an unknown source or an invalid name with 400. - chatd resolves each invocation on create, send and edit with the chat owner's permissions, through the same loaders as `read_skill`: stored skills by source and name (project skills through the chat's project, with the root chat fallback for subagents) and workspace skills from the pinned context snapshot. The body is saved at send time so past turns show what the model received. A missing, disabled or unreadable skill rejects the send with 400 "Skill project/triage is not available." - The prompt renders a line saying the user invoked the skill, followed by `<invoked-skill name="project/triage">` with the sanitized body. Titles and hook prompt text show the invocation as `/project/triage`. - The site only gets no-op cases so the regenerated types compile. `coderd/x/chatd/ARCHITECTURE.md` gets a TODO for the author. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 👈 - #30880 - #30881 - #30882 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
c61d842b9c |
feat: show available ACP harnesses in chat context (#31059)
Expose discovered ACP harnesses in the chat context resource inventory when the `chat-acp-subagents` experiment is enabled, including configuration paths and resource status. Persist ACP harness resources from agent context snapshots and update the SDK and generated API types. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
3216580614 |
feat: load project skills in chats (#30838)
Chats that belong to a chat project now get the project's skills, next to personal, organization and workspace skills. They show up in the model's skill list, load through `read_skill`, and appear in a "Project skills" group in the `/` menu. - `coderd/x/skills` adds the `project` source. `MergeSkills` now takes a list of sources in merge order (personal, organization, project, workspace). Bare names stay bare unless two sources share a name, in which case they get `project/<name>` style aliases. - chatd loads project skills only when the chat owner owns the project or the project is shared with them. Role grants don't count. This is the same `usableChatProject` check that project instructions and memory use, and one check per turn covers both instructions and skills. Disabled skills are skipped. A failed load logs a warning and the turn continues without them. Subagents use their root chat's project; that lookup is now a helper shared with project instructions. - The site loads project skills for the composer on the project page and in project chats, behind the `chat-projects` experiment. `/clear` and `/compact` defer to a project skill with the same name, as they already do for other sources. When the user can't use the project, the site treats it as no project skills, like chatd, so those commands keep working and the `/` menu shows no retry prompt for project skills. That covers a 403 or 404 from the project skills request and a project missing from the user's project list, which holds only owned and shared projects, so an administrator role that can read the project doesn't count. Other failures are retried and leave the list unknown. A cached project list is also unknown while it refetches or after a failed refetch, so a share revoked since it was cached keeps those commands pending instead of deferring to stale project skills. - Docs gain a "Project skills" section in the extending agents page. `coderd/x/chatd/ARCHITECTURE.md` gains a paragraph on project skills. Dogfood UAT on this branch passed: project skills appear in the project page `/` menu and in project chats, `read_skill` loads them, disabled and deleted skills report not found, chats outside the project don't see them, and a subagent gets them through its root chat. The site reads project skills from the chat's own `project_id`, so subagent chats show them in the composer once sub-chats carry their root's project (#30683). | Project page `/` menu | `read_skill` in a project chat | | --- | --- | | <img alt="Project skills group in the project page slash menu" src="https://raw.githubusercontent.com/coder/coder/assets/pr-30838-project-skills/pr/project-page-slash-menu.png" width="600" /> | <img alt="read_skill loading a project skill in a project chat" src="https://raw.githubusercontent.com/coder/coder/assets/pr-30838-project-skills/pr/project-chat-read-skill.png" width="600" /> | Stack (merge top to bottom): - #30838 👈 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 - #30884 - #31122 |
||
|
|
ffc6aac6a8 |
test(coderd/x/chatd/chatdebug): check the run-summary query boundary (#30973)
Replaces the last Postgres-backed run-summary subtests with mock tests of the `AggregateRunSummary` boundary and one extended Postgres test. This deletes `MultipleStepsSumTokens` and the helpers `createTestStep`, `updateTestStepWithUsage` and `updateTestStepWithFullUsage`. **Why it is safe:** - `NilRunID` now runs against a mock with no expectations, so any query fails it, and checks that the base map comes back unchanged. - The new `QueryAsChatdReturnsError` checks that the read runs as the chatd actor and that the query error is returned. - `RecomputesHasErrorAndCompletedEndpointLabel` now inserts step 2 before step 1 and compares the whole summary read through the real query: five token sums, `has_error`, the endpoint label and the seeded `first_message`. With the table from #30972, it covers every assertion of `MultipleStepsSumTokens`. - Of the same 42 `summary.go` mutants, the tests now kill 34 (`main` kills 22, #30972 kills 31). The new kills are the nil run ID return value, a swallowed query error and a read without the chatd actor. The 8 survivors are equivalent or only change logging. - Mutants of the `GetChatDebugStepsByRunID` SQL that order by `started_at` alone or reverse the order fail the Postgres test. Dropping the `ORDER BY` survives: Postgres reads these rows through the unique `(run_id, step_number)` index, which already returns them in step order. - No references to the removed helpers remain. **Review focus:** the setup order in `RecomputesHasErrorAndCompletedEndpointLabel`. Step 2 is inserted first, so the expected label holds only if the query orders by `step_number`. Since #31007, `CreateStep` numbers steps itself, so the test inserts both rows through the store with explicit step numbers. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack makes the debug run-summary reduction database-free and replaces its Postgres fixtures with literal rows. 1. #30972 Replace run-summary Postgres subtests with literal rows 2. #30973 Check the run-summary query boundary > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
5c9815b474 |
refactor(coderd/x/chatd/chatdebug): replace run-summary Postgres subtests with literal rows (#30972)
Moves the post-query reduction in `chatdebug.(*Service).AggregateRunSummary` into a private `summarizeRunSteps` method and tests it with table cases over literal `database.ChatDebugStep` rows. This deletes the 11 Postgres-backed subtests of `TestService_AggregateRunSummary` whose assertions the table covers; each one built its own database. **Why it is safe:** - The moved body is unchanged apart from `return result`. `AggregateRunSummary` still owns the nil run ID check, the chatd-authorized read and the error return. - Every assertion of the removed subtests maps to a table row that compares the whole output map, so absent keys are checked too. Each row also checks that the base map is not mutated. - `NilRunID`, `RecomputesHasErrorAndCompletedEndpointLabel` and `MultipleStepsSumTokens` stay on Postgres here; #30973 replaces them. - I ran 42 mutants of `summary.go` with `go test -overlay`: `main`'s tests kill 22, this PR's tests kill 31, including all 22. The new kills cover JSON null and empty error payloads, error payloads on completed steps, malformed usage and attempts, empty paths, first-match selection and caller map mutation. Of the 11 survivors, 3 are query-boundary mutants that `main` also misses (#30973 kills them) and 8 are equivalent or only change logging. **Review focus:** `summarizeRunSteps` in `summary.go`. The moved block should match `main` apart from the return statement. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack makes the debug run-summary reduction database-free and replaces its Postgres fixtures with literal rows. 1. #30972 Replace run-summary Postgres subtests with literal rows 2. #30973 Check the run-summary query boundary > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
82288467d9 | refactor(coderd/x/chatd/chatstate): share one outstanding tool-call scan (#30883) | ||
|
|
eea839ccc4 |
refactor(coderd): number chat debug steps in the database (#31007)
`InsertChatDebugStep` now numbers a step after the run's highest step when the caller passes zero, so chatdebug stops numbering steps in process memory. `CreateStepParams` loses `StepNumber`, `beginStep` no longer calls `nextStepNumber` or `syncStepCounter`, and `CreateStep` replaces its collision retry, which listed the run's steps and bumped the number, with a per-run lock. #31008 deletes the counters, which no production code reads after this PR. **Why it is safe:** Postgres takes the insert's snapshot before the statement waits on the run row, so creates that waited on the same run read the same highest step. `CreateStep` therefore takes `pg_advisory_xact_lock(LockIDChatDebugRunSteps(run))` in its own statement and inserts in the same transaction, so each insert starts after the previous holder committed. The new `TestService_CreateStep_NumbersConcurrentSteps` holds the run row, starts 20 creates, waits until all of them wait on a lock, then commits and checks the numbers 1 to 20. It passes 10 of 10 runs, and fails 10 of 10 with a 10-attempt collision retry in place of the lock. `TestService_CreateStep_RetriesDuplicateStepNumbers` becomes `TestService_CreateStep_NumbersStepsPerRun`, and `TestService_CreateStep_ListRetryErrorWins` goes with the list call it covered. Mutants that fail the chatdebug tests: no lock, the lock outside the transaction, the lock keyed by chat, a constant number, storing the zero, numbering across runs, a nonzero number from `CreateStep`, and an unclassified missing run. One mutant survives and is equivalent: running the insert on `s.db` instead of `tx` inside the same `InTx` callback, because the insert still commits before the transaction releases the lock. Running the insert after the transaction commits fails the new test with a duplicate key. A copy of `service.go` with garbage in it fails to build. **Review focus:** `@step_number` stays as an override. Production passes zero, and the fixtures in `querier_test.go`, `dbauthz_test.go`, `dbpurge_test.go` and `exp_chats_test.go` keep their explicit numbers. No test depends on the override (a mutant that ignores it survives), because every fixture numbers its steps in insert order. Dropping the parameter would touch about 20 fixtures outside chatdebug. The PR removes more than it adds: +179/-233 hand-written lines. The generated `querier.go` and `queries.sql.go` change 15 more. Validation: - `make gen/db` changes only `querier.go` and `queries.sql.go`. - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes, and `go test -count=10 -run TestService_CreateStep ./coderd/x/chatd/chatdebug/` passes all 6 tests 10 of 10 times. - `go test -count=1 -run ChatDebug ./coderd/database/ ./coderd/database/dbpurge/` and `go test -count=1 -run Debug ./coderd/x/chatd/` (19 tests) pass, and the 25 chatd debug-run tests pass under `-race`. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/... ./coderd/database/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. This PR: Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
95e6a73f5c |
refactor(coderd/x/chatd/chatdebug): share one finalize-once lifecycle between the stream wrappers (#30981)
`wrapStreamSeq` and `wrapObjectStreamSeq` each carried a copy of the same finalize-once lifecycle. This PR moves it into a private `streamStep` (the once-only gate and the context safety net) and a `streamOutcome` (finish and error bookkeeping, and the early-stop and missing-finish status rules), and rewrites both wrappers on them. Each wrapper keeps its own part switch and payload type. It also deletes a `stop != nil` check that is never false and a `seq != nil` check that `Stream` and `StreamObject` make before they wrap a sequence. **Why it is safe:** the PR changes no test. #30980 pins both wrappers' status rules, and the chatdebug package and the chatd debug-run tests pass before and after. All 39 mutants of the new lifecycle and of each wrapper's wiring fail the package's tests, and a copy of `model.go` with garbage in it fails to build. One more mutant drops the `finalized` check from the safety net, so a step can be written twice; #30980's race case kills it in 50 of 50 runs without `-race` and in 45 to 49 of 50 with `-race`. Two details keep their values: the response usage normalizes a zero `fantasy.Usage` when no finish part arrived, which gives the same zero value as before, and the summary's error count and last error are copied from `streamOutcome` when the step finalizes instead of being counted inline. **Review focus:** the once-only gate stays per iterator (`streamStep`), not on `stepHandle`, because `stepHandle.finish` lets a retry overwrite an earlier result. `finish` builds the payload only when its call finalizes the step, under the same lock as before. **Moved onto the deletion stack:** #30988 deletes the stream heartbeats, so the merge commit that moved this layer (no force push) also drops them from the new lifecycle: `heartbeatDone`, `startHeartbeat`, the channel close in `finalizeLocked`, both `step.startHeartbeat()` calls and `launchHeartbeat`, and with them the heartbeat blocks in `debugModel.Generate` and `GenerateObject`. The rest of the diff is unchanged. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes before and after. - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/ -run '^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$'`: the same 25 tests pass before and after. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. This PR: Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
01ee3484cc |
test(coderd/x/chatd/chatdebug): table the stream wrapper tests and cover their status rules (#30980)
Replaces five stream wrapper tests with two tables that run every case against both `wrapStreamSeq` and `wrapObjectStreamSeq`. #30981 rewrites both wrappers on one finalize-once lifecycle, and these tests pin what that rewrite must keep. It deletes `TestWrapStreamSeq_CompletedNotDowngradedByCtxCancel`, `TestWrapObjectStreamSeq_CompletedNotDowngradedByCtxCancel`, `TestWrapStreamSeq_DroppedStreamFinalizedOnCtxCancel` and `TestDebugModel_StreamObjectRejectsNilSequence`. - New `TestStreamWrapperStatus` runs 13 cases on each wrapper: a finished stream, a consumer that stops before or after the finish part, a stream that ends without one, an error part with and without an error, an error on a text part, a consumer that stops after an error, a canceled error part, cancellation before the finish part and while the consumer holds it, a dropped stream, and a consumer that stops right after cancellation, which races the context safety net. Each case writes through a recording store and checks that the step is written exactly once, plus its status, finish reason, stored usage (all six token counts, or NULL), error count, last error, and whether the wrapper or the safety net finalized it. - `TestDebugModel_StreamRejectsNilSequence` is now one table over `Stream` and `StreamObject`. - `TestDebugModel_Stream` also checks the streamed text, not only that the response has content. **Why it is safe:** the PR changes only a test file, and the tests pass on the production code of the layer below. To show they can fail, I ran 46 mutants of both wrappers and the nil-sequence checks. The whole package kills 17 of them before this PR and all 46 after it. The 29 it missed include the object wrapper's dropped-stream path, the rule that a stream without a finish part is interrupted, both error-part rules, cancellation while the consumer holds the finish part, text that is never materialized, usage that keeps only the input tokens or is stored without a finish part, and summary metadata on the safety net's write. Two more mutants drop the safety net's `finalized` check, so a step can be written twice. Across repeated batches of 50 runs, the race case kills them in 49 to 50 of 50 without `-race`. Under `-race` the kill rate depends on machine load: batches of 50 ranged from 24 to 46 kills. The unchanged code passes 200 runs with and without `-race`. A copy of `model.go` with garbage in it fails to build, which shows the mutants replaced the real file. **Review focus:** the PR adds 117 more lines than it deletes. It is the test-first layer for #30981, which deletes 65 production lines. **Moved onto the deletion stack:** a merge commit moved this layer onto the updated #30934 without a force push; its only conflict was the test file's import block (#30988 dropped `time` with the heartbeat tests). A second commit adds the audit follow-ups: the recording store, the stored usage check, the race case and the text check. Validation: `go test -race -count=1 ./coderd/x/chatd/chatdebug/...` passes, `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. This PR: Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
e8882b6b51 |
refactor(coderd/x/chatd): create and finalize debug runs through one helper (#30934)
Chat turns, manual titles, automatic titles and turn status labels each created a debug run on a detached, time-bounded context, rebuilt the run context from the row, and finalized the run by hand. This PR adds `chatdebug.Service.BeginRun` and `StartRun` and routes all four through them. It deletes `prepareQuickgenDebugCandidate`, `shortTextCandidate`, `chatdebugRunContext`, `debugCreateRunTimeout` and a literal 5 second insert timeout. - `BeginRun` inserts the run on a context that ignores the caller's cancellation, with a 5 second limit, and builds the `RunContext` from its parameters. Chat turns call it and still finalize in `runnerDebugTurn`. - `StartRun` wraps `BeginRun` for one model call and returns a context that carries the run plus a function that finalizes it from the call's error. Titles and status labels use it. - New `TestService_StartRun` covers a finalized run, a failed insert and a failed finalize with a mock store, including the seed summary that each finalize keeps and the warning that each failure logs. **Why it is safe:** #30933 pins the insert parameters, the run context, the finalize status and summary, and the failed insert for all four call sites. Those tests and the other debug-run, title and quickgen tests pass before and after. `CreateRun` stores its parameters unchanged, so a `RunContext` built from the parameters equals one built from the row. A repo-wide search finds no reference to the deleted symbols. Of 14 mutants of `BeginRun` and `StartRun`, 13 fail `TestService_StartRun`. They drop either failure warning, report a failed insert as success, let the insert inherit the caller's cancellation or lose its deadline, drop the parent chat or the history tip from the run context, drop the seed summary from the insert or the finalize, ignore the call error or the finalize timeout, leave the run out of the returned context, or finalize the wrong run. The survivor shortens the insert limit from 5 seconds to 1. **Review focus:** log output. Create and finalize failures now log through the chatdebug logger as `failed to create debug run` and `failed to finalize debug run`. Before, each call site used its own logger and message. Compaction still creates its debug run by hand, because #30766 changes that code; it can move to `StartRun` after that PR merges. **Moved onto the deletion stack:** a merge commit moved this layer onto the updated #30933 without a force push. It carries one forced change: #30989 removed the `database/sql` import from `chatdebug/service_test.go` with the last test that used it, and `TestService_StartRun` here still uses `sql.NullString`, so the merge adds the import back. The rest of the diff is unchanged. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/ -run '^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$'`: the same 25 tests pass before and after, and again after the move. - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/... ./coderd/x/chatd/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. This PR: Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
a1556f8e62 |
test(coderd/x/chatd): pin the debug runs that turns, titles and status labels record (#30933)
Adds tests that pin what four call sites record when they create and finalize a debug run: chat turns, manual titles, automatic titles and turn status labels. #30934 moves all four onto one helper. Automatic titles and status labels had no debug-run test, and the chat turn and manual title tests checked only some fields. - `TestRunnerDebugTurnEnsureCreatesOnce` now checks every insert parameter, the full `RunContext` the model call sees, and that the insert runs on a context that ignores the caller's cancellation but has a deadline. - New `TestRunnerDebugTurnEnsureCreateFailureDisablesTurn`: a failed insert disables debug for the turn, and the turn does not retry it. - `TestProposeChatTitle_DebugRun` also checks that the run has no trigger message, its model config and model, the seed label in its summary, and that it recorded steps. - New `TestQuickgenDebugRun` covers automatic titles and status labels when the model succeeds, when it fails, and when the insert fails. It checks the insert, the run context and the finalize call. Titles record the configured provider and model; status labels record the resolved ones. - New `TestPrepareManualTitleDebugRunCreateFailure`: when the manual title insert fails, the title call gets no run and finishing does nothing. **Why it is safe:** the PR changes only tests, and they pass on `main`'s production code. To show they can fail, I ran 34 mutants of the four call sites, and 31 fail the new tests. Two survivors change nothing these tests can observe: the seed summary on the manual title insert (finalize rewrites the summary) and the 10 second finalize timeout for titles and labels. This layer does not pin the third: removing `context.WithoutCancel` from the title and label insert in `quickgen.go`. #30934 moves that detach into the shared `BeginRun`, which the chat turn test pins. Validation: `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/ -run '^(TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestQuickgenDebugRun|TestPrepareManualTitleDebugRunCreateFailure)$'` passes on this branch and with `main`'s production code, and the pre-commit hook passed. This layer now sits on #30995 instead of #30932. A merge commit moved it there without a force push, and the layer's own diff is unchanged (same patch-id). The same command and `go test -race ./coderd/x/chatd/chatdebug/...` pass at the new head. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. This PR: Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
367358862b |
refactor: delete chatdebug FinalizeStale and the stale threshold (#30989)
Deletes `chatdebug.Service.FinalizeStale` and everything that existed only for it. Nothing in production calls `FinalizeStale` since #26270, and #30988 removed the heartbeats that kept live runs out of its reach. This is the second of three PRs that delete the stale debug-run sweep. - `chatdebug/service.go`: deletes `FinalizeStale`, `SetStaleAfter`, `DefaultStaleThreshold`, the `staleAfterNanos` field and `WithClock`. The service keeps its real clock for the timestamps it writes. - `chatd.go`: the debug service factory no longer calls `SetStaleAfter(inFlightChatStaleAfter * 3)`. `inFlightChatStaleAfter` stays, because the chat worker uses it. - `chatdebug/types.go`: deletes `EventKindFinalize` and `BroadcastPubsubChannel`. `FinalizeStale` was the only publisher without a chat ID, so `PubsubChannel` loses its `uuid.Nil` branch. Nothing in production subscribes to `chat_debug:*` channels. - Deletes the four `FinalizeStale` service tests, and `TestFinalizeStaleChatDebugRows_TerminalStatusAlignment` together with `codersdk.ChatDebugTerminalStatuses`, which only that test used. The test compared that list with the `NOT IN` lists in `FinalizeStaleChatDebugRows` and nothing else: no other debug query or constraint lists the statuses. The next PR deletes that query. - Comments that named the stale sweep now say what happens instead: `debugCleanupClockSkew`, `errRunFinalized`, `CreateStep`, `UpdateStep`, the `InsertChatDebugStep` and `UpdateChatDebugStep` queries, the edit cleanup in `chat_mutations.go`, the two notes on removed tests in `chatd_internal_test.go`, and four comments in `chatd_test.go`. **Why it is safe:** `FinalizeStale` and `SetStaleAfter` had no production caller other than the factory line this PR removes, and nothing calls `WithClock` after #30988. `make gen/db` changes only the regenerated query comments. #30988 explains why no reader of `updated_at` needs the sweep and why dbpurge cannot delete a live run. **Review focus:** the `debugCleanupClockSkew` comment in `chatd_debug.go`. The value stays `30 * time.Second`. Runs that start inside that buffer survive the fast cleanup; the old comment said the stale sweep would then finalize them, but dbpurge deletes them once they age past the debug retention window. Validation: `make gen/db`, `go build ./...`, and `go vet` on the touched packages. `go test -count=1` passes for `./coderd/x/chatd/chatdebug/...`, `./coderd/x/chatd/ -run 'Debug|EditMessage|ArchiveChat'`, `./coderd/database/ -run 'ChatDebug|TestIsAuthorizedQuery|TestInsertChatMessagesOrderContract|ConnectionLogs'` and `./codersdk/`. The pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. This PR: Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
2397f3953a |
refactor(coderd): delete the chat debug run and step heartbeats (#30988)
Deletes the chat debug heartbeats. Model calls and streams started a goroutine that touched the step and its run on a ticker, and runner debug turns started a second one that touched the run. Both existed so that `FinalizeStale` would not mark a live run as interrupted, but nothing in production calls `FinalizeStale` since #26270. Mike chose to delete the stale sweep as dead code. This PR is the first of three that do it. - `chatdebug/model.go`: `Generate`, `GenerateObject` and both stream wrappers no longer start `launchHeartbeat`. - `active_turn_debug.go`: the runner debug turn no longer starts `LaunchRunHeartbeat`. - `chatdebug/service.go`: deletes `TouchStep`, `TouchRun`, `LaunchRunHeartbeat`, `heartbeatInterval`, and the channel that `SetStaleAfter` closed to wake the heartbeats. The `WithClock` doc no longer names the heartbeat tickers. - Deletes the `TouchChatDebugStepAndRun` and `TouchChatDebugRunUpdatedAt` queries with their dbauthz wrappers and tests, and `TestLaunchHeartbeat`. `TestFinalizeStaleChatDebugRows` now backdates its run with `UpdateChatDebugRun` instead of the deleted test-only query. **Why it is safe:** the heartbeats wrote only `updated_at` on `chat_debug_runs` and `chat_debug_steps`. These read it: | Reader | Why it does not need the heartbeat | |---|---| | `FinalizeStaleChatDebugRows` and the partial indexes `idx_chat_debug_runs_stale` and `idx_chat_debug_steps_stale` | No production caller. The next two PRs delete the query, and #31009 drops the indexes in a migration. | | `DeleteOldChatDebugRuns` (dbpurge) | See the next paragraph. | | `DebugPanel.tsx` run sort | Sorts by `started_at \|\| updated_at`, and `started_at` is `NOT NULL`, so it never falls back to `updated_at`. | | Debug run and step API responses | Return `updated_at` as data. Nothing uses it to decide whether a run is alive. | dbpurge deletes runs whose `updated_at` is older than the debug retention window, whatever their status, and their steps cascade. The window is `agents_chat_debug_retention_days`: 30 days by default, and 0 turns the purge off, so dbpurge never deletes a run that was written in the last day. A run's `updated_at` still moves when the run is created, when each step is inserted (the `InsertChatDebugStep` CTE), and on every run update and finalize. So dbpurge could only delete a live run if one model call plus the tool calls after it ran for more than a day. The runner finalizes its debug run when the runner context ends, a `requires_action` wait times out after 5 minutes (the case `TouchRun` covered), and chatloop aborts a stream that is silent for `--chat-stream-silence-timeout`, 10 minutes by default (0 turns that guard off). Mike accepted the cost: a run or step orphaned by a crashed replica stays `in_progress` until dbpurge deletes it. That is already true on `main`, because nothing runs the sweep. This does not touch the chat worker's `chat_heartbeats` loop that ARCHITECTURE.md describes, and no ARCHITECTURE.md sentence about debug runs becomes false. **Review focus:** nothing uses `WithClock` after this PR, but deleting it here would take this PR past 500 changed lines, so it goes with `FinalizeStale` in the next PR. Validation: `make gen/db`, `go build ./coderd/...`, and `golangci-lint run` on the touched packages (0 issues). `go test -count=1` passes for `./coderd/x/chatd/chatdebug/...`, `./coderd/database/dbauthz/ -run TestMethodTestSuite`, `./coderd/database/ -run ChatDebug`, `./coderd/x/chatd/ -run Debug` and `./coderd/database/dbpurge/`. The pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. This PR: Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
e53cfef864 |
fix(coderd/x/chatd): drop blocked tools from Explore sub-agent turns (#30911)
Explore sub-agents enforced their tool limit in one place. `buildTurnEnvironment` set the turn's active tool list from `allowedExploreToolNames`, but `write_file`, `edit_files`, `attach_file`, `process_list`, and `process_signal` stayed registered. chatloop reads an empty active list as every registered tool (`isToolActive`), and that check decides both which tools the model is offered and which calls run. So a change that dropped or emptied `ActiveTools` before the model call would give those tools to every Explore sub-agent. #30868 lists that change as the one mutant only its removed end-to-end tests caught. Plan mode does not have the gap, because `filterToolsForTurn` also removes blocked tools from the registered set. This PR turns the Explore allowlist into one predicate, `exploreToolAllowed`. Explore children now drop the tools it blocks right after the plan-mode filter, and `allowedExploreToolNames` still builds the active list from the same predicate. The `false` entries in the old map were no-ops, so the predicate lists only the five allowed built-ins. An Explore sub-agent is offered and can call the same tools as before. Root Explore chats and plan mode are unchanged; root Explore chats still rely on the active list alone. Tools that join after the filter keep their current behavior: `appendDynamicTools` returns early for Explore chats, `find_tools` from the deferred MCP search stays active and defers only MCP tools that already pass the allowlist, provider tools are a separate list that is already cut to `web_search` for Explore children, and computer use exists only in computer-use chats. Refs #30867 ## Testing - `TestBuildTurnEnvironmentToolPolicy` now requires every tool registered for an Explore child to be offered. Without the production change, `ExploreChild` and `ExploreChildAfterMCPReplacement` fail with `Should be empty, but was [write_file edit_files attach_file process_list process_signal]`. With it, all rows pass. - A throwaway runtime probe (not committed) ran an Explore child whose fake model calls `write_file` and then `edit_files`, with `ActiveTools` set to nil for Explore chats at the chatloop handoff: | `ActiveTools` set to nil | Before this PR | With this PR | |---|---|---| | At the model call | The model is offered `write_file`, `edit_files`, `attach_file`, `process_list`, and `process_signal` | The model is offered only `read_file`, `execute`, and `process_output` | | At the model call and at tool execution | Both calls run on the workspace agent and return `{"ok": true}` | Both calls fail with `Tool not found`, and the agent gets no write or edit | - `go test ./coderd/x/chatd/...`, `go test ./coderd/ -run '(?i)chat|explore|plan|mcp'`, `go test ./enterprise/coderd/ -run '(?i)chat|explore|plan|mcp'`, and golangci-lint on `coderd/x/chatd` pass. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
3576e04e2d |
fix(coderd/x/chatd): keep the chat output cap on compaction summaries (#31042)
Compaction summaries asked the provider for 1.5 times the model's configured output cap. When an admin adds a known model, the form fills `max_output_tokens` with the provider maximum, 128,000 for `claude-opus-5-5`, so each summary request sent `max_tokens: 192000`. Anthropic rejected it with HTTP 400 (`max_tokens: 192000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5-5`), so compaction failed and the chat could not shrink its context. `compactionSummaryCall` now keeps the chat call's cap. The 50% headroom came from #28886, which accepted the overshoot for caps set at a provider ceiling as a tradeoff. With catalog defaults, that case is the common one. `GenerateCompaction` still lowers the cap to the remaining context window when that is smaller. Closes [CODAGT-1428](https://linear.app/codercom/issue/CODAGT-1428). The ticket also shows "Your input exceeds the context window" on a summary request. That is a separate failure, which #30766 handles (merged after the ticket was filed), so this PR does not change it. **Tests** - New `TestActiveServer_ManualCompaction/summary keeps the configured output cap`: a 128,000 cap reaches both the chat turn and the summary request unchanged. On the old code it fails with `expected: 128000 actual: 192000`. - `TestBuildTurnEnvironmentClampsRequestedReasoningEffortToMax` and the compaction hook tests now expect the unchanged default cap (32,000 instead of 48,000). #30942 rewrites the first test and keeps a `3 * defaultChatMaxOutputTokens / 2` expectation, so whichever PR merges second drops that factor. **Validation** - `go test ./coderd/x/chatd/ ./coderd/x/chatd/chatloop/ -count=1`: passes - `make pre-commit`: passes - Remote dogfood UAT against `claude-opus-5-5` with a 128,000 cap: on `main`, manual, automatic, and compaction-model-override summaries asked for 192,000 tokens and failed with the 400 above. On this branch, all 16 summary requests (the same flows plus an unset cap and a small context window) succeeded, and none asked for more than its configured cap. Chat turn `max_tokens` was the same on both. UAT ran on `9230a6e9fa1`; the head `3633adef53e` only adds a comment edit. - No new dependencies. The polish pass and the test audit changed no files. - Codex review on `3633adef53e`: no findings. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
a86012f82b |
refactor(coderd/x/chatd/chatloop): resolve tool name aliases in one toolBatch method (#30939)
Adds `(*toolBatch).resolve` for the `ToolNameAliases` lookup that `runOne`, `notifyStepToolCallObservers`, `notifyStepToolResultObservers`, and `isSerialToolCall` each repeated. The last three become `toolBatch` methods instead of taking the tool map and the alias map. Where they looked up a tool and then type-asserted it, they now assert on the map value: a missing name gives a nil interface, so the assertion fails as the missing-key check did. It also fixes a latent bug: `runOne` looked up result provider metadata by the name the model sent, while its other lookups use the resolved name, so a runner called by an alias lost its metadata. This cannot happen in production today: the only alias is `close_agent` to `interrupt_agent` (`subagent.go:45`), and only `computer_use.go:112` sets `ResultProviderMetadata`. ## Why it is safe Each mutant below puts the raw name back at one call site, and each fails a test: | Call site | Failing test | |---|---| | `runOne` tool lookup | `TestExecuteSingleTool_ResolvesToolNameAlias` and 5 more | | `runOne` metadata lookup | `TestExecuteLocalTools_ProviderToolRunner` | | `notifyStepToolCallObservers` | `TestExecuteToolsNotifiesStepToolCallObservers` | | `notifyStepToolResultObservers` (either loop) | `TestExecuteToolsNotifiesStepToolResultObservers` | | `isSerialToolCall` | `TestExecuteToolsSerialToolCallOrder` | No test called a serial tool or a provider runner by an alias, so this PR adds one aliased call to `TestExecuteToolsSerialToolCallOrder` and one to `TestExecuteLocalTools_ProviderToolRunner`. With the `chatloop.go` of #30938, the first test still passes, and the second fails because the aliased result has no metadata. ## Validation - `go test -race -count=1 ./coderd/x/chatd/chatloop/` passes on #30938 and here. - `go test -count=1 -p 4 -parallel 4 ./coderd/x/chatd/...` passes here (20 packages). - `golangci-lint run ./coderd/x/chatd/chatloop/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack replaces the 20-parameter `executeTools` and the 15-parameter `executeSingleTool` in `chatloop` with methods on one `toolBatch` type, and resolves tool name aliases in one place. Production behavior does not change. 1. #30937 Cover provider tool runners in `ExecuteLocalTools` 2. #30938 Replace `executeTools` and `executeSingleTool` with `toolBatch` 3. #30939 Resolve tool name aliases in one `toolBatch` method > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
63c116fddd |
refactor(coderd/x/chatd): delete the CompactionOptions and compactionOutcome mirrors (#30984)
Deletes two structs that each repeat another struct field for field. `chatloop.CompactionOptions` repeated 21 fields of `GenerateCompactionOptions`, and `normalizedCompactionGenerateConfig` copied them one by one, so each new option had to be added in three places, as #30766 did for `Logger`. `compactionOutcome` in `chatd` repeated the 11 fields of `chatloop.CompactionResult` only so that `generateCompaction` could convert one into the other. The PR also deletes `TestGenerateCompactionSummaryUsesToolDefinitions`, which repeats `TestGenerateCompactionSummaryPreservesCallOptions`. ## Why it is safe - `publishCompactionError`, `startCompactionDebugRun`, and `generateCompactionSummary` now take `GenerateCompactionOptions`. Every read of the normalized config, in `GenerateCompaction` and in those helpers, uses one of the 21 fields that the copier copied without change. None reads the 7 fields that only `GenerateCompactionOptions` has. - `normalizedCompactionGenerateConfig` applies the same four defaults and the same threshold gate to its parameter, which is already a copy. So `GenerateCompaction` still reports the requested `ThresholdPercent` and `ContextLimit` from its own `opts`. If it read `config.ThresholdPercent` instead, `TestGenerateCompaction_RecordsRequestedTrigger` would fail. - Go allows the `compactionOutcome(outcome)` conversion only because the two structs have identical fields, so `buildCompactionMessagesInput` can hold the `chatloop.CompactionResult` itself. The four `TestBuildCompactionMessages_*` tests that build it keep their assertions. - Six mutants of the summary call each fail the deleted test on #30766: no tools, no call options, no summary prompt, one tool dropped, the caller's history changed, and tool descriptions stripped. The kept test failed only the first five, because its tool had no description. With that description moved into it, the kept test fails all six. - `git grep -w CompactionOptions` and `git grep compactionOutcome` find no matches. ## Review focus `generateCompactionSummary` keeps its `model` and `messages` parameters, so its 15 direct test calls change only the type name. It now also receives `Model` and `Messages` fields with the same values, and it does not read them. ## Validation - `go test -race -count=1 ./coderd/x/chatd/chatloop/` passes. - `go test -count=1 -p 4 -parallel 4 ./coderd/x/chatd/...` passes (20 packages). - `golangci-lint run ./coderd/x/chatd/...` reports 0 issues, and the pre-commit hook passed. ## Stack #30766 has merged, so this PR now targets `main` by itself. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
3df3c03288 |
refactor(coderd/x/chatd): replace executeTools and executeSingleTool with toolBatch (#30938)
Replaces the 20-parameter `executeTools` and the 15-parameter `executeSingleTool` in `chatloop` with methods on an unexported `toolBatch`. `newToolBatch` builds it once from `ExecuteLocalToolsOptions`, `run` replaces `executeTools`, and `runOne` replaces `executeSingleTool`. The 12 internal test calls set only the options they use instead of up to 20 positional arguments. It also deletes two copies: - `executeTools` filtered out provider-executed calls that `ExecuteLocalTools` had already removed. Only the `ExecuteLocalTools` filter remains. - The `runOne` metric defer repeated the body of `recordToolResultMetrics`. It now calls that function. ## Why it is safe - `newToolBatch` builds the tool, runner, and metadata maps with the lines `executeTools` used, and the byte budget as `ExecuteLocalTools` did. `run` drops the empty-batch returns: `ExecuteLocalTools` returns before it when no local call is left. - `recordToolResultMetrics` labels by `result.ToolName`, which `runOne` sets to `tc.ToolName` and never changes. It skips a nil `Metrics`. Production never passes one, because `ExecuteLocalTools` sets `NopMetrics()` first; only the direct test calls, which omit `Metrics`, use that path. - With the duplicate filter gone, removing the remaining `ProviderExecuted` filter fails `TestExecuteLocalTools_ProviderToolRunner` (#30937). The other four mutants from #30937 still fail it here. - `git grep 'executeTools\|executeSingleTool'` finds one comment, in `chatd_test.go`, which this PR updates. ## Review focus The metric defer stays a closure so that it reads `result` when `runOne` returns. ## Validation - `go test -race -count=1 ./coderd/x/chatd/chatloop/` passes on #30937 and here, including the 16 tests that reach this code: `TestExecuteTools*` (5), `TestExecuteSingleTool_*` (5), `TestExecuteLocalTools*` (6). - `TestActiveServer_ToolErrorRecordsMetric`, `TestActiveServer_ToolExecutionAndPolicy`, and `TestProcessChatPanicRecovery` in `./coderd/x/chatd/` pass on #30937 and here. - `golangci-lint run ./coderd/x/chatd/chatloop/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack replaces the 20-parameter `executeTools` and the 15-parameter `executeSingleTool` in `chatloop` with methods on one `toolBatch` type, and resolves tool name aliases in one place. Production behavior does not change. 1. #30937 Cover provider tool runners in `ExecuteLocalTools` 2. #30938 Replace `executeTools` and `executeSingleTool` with `toolBatch` 3. #30939 Resolve tool name aliases in one `toolBatch` method > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
f004c72749 |
test(coderd/x/chatd/chatloop): cover provider tool runners in ExecuteLocalTools (#30937)
Adds `TestExecuteLocalTools_ProviderToolRunner`. No test ran a `ProviderTool` runner (the local half of a provider-defined tool, such as OpenAI computer use) through `ExecuteLocalTools`, so nothing checked runner dispatch, the active-tool exemption for runners, result metadata, or the skip of provider-executed calls. #30938 rewrites that code, so this PR pins the behavior first. The test sends a runner call and a provider-executed `web_search` call. The runner is in neither `Tools` nor `ActiveTools`. The test checks that only the runner call gets a result, and that the result has the runner's output and its `ResultProviderMetadata`. ## Why it can fail Each mutant is `chatloop.go` with one change, run with `go test -overlay`. Each one fails the new test, and all other `chatloop` tests pass with it. | Mutant | New test fails with | |---|---| | Runners are not added to the tool map | `Tool not found: computer` | | Runners are not exempt from the active-tool check | `Tool not active in this turn: computer` | | `ResultProviderMetadata` is not attached | nil metadata | | Provider tools without a runner are not skipped | nil pointer panic | | Both `ProviderExecuted` filters are removed | 2 results | Removing only one of the two `ProviderExecuted` filters, in `ExecuteLocalTools` or in `executeTools`, fails no test, because the other filter still runs. #30938 deletes the one in `executeTools`. `go test ./coderd/x/chatd/` also passes with runners left out of the tool map and the metadata attachment removed. Its subtest `TestActiveServer_ToolExecutionAndPolicy/provider_runner_executes_and_preserves_metadata` replays a stored computer-use call and result; it does not run the runner. ## Validation - `go test -race -count=1 ./coderd/x/chatd/chatloop/` passes. - `golangci-lint run ./coderd/x/chatd/chatloop/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack replaces the 20-parameter `executeTools` and the 15-parameter `executeSingleTool` in `chatloop` with methods on one `toolBatch` type, and resolves tool name aliases in one place. Production behavior does not change. 1. #30937 Cover provider tool runners in `ExecuteLocalTools` 2. #30938 Replace `executeTools` and `executeSingleTool` with `toolBatch` 3. #30939 Resolve tool name aliases in one `toolBatch` method > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
86ea5d4c4e |
ci: bump paralleltestctx to detect timeout contexts used through closures (#31039)
#31011 fixed a flake where a closure in `TestProjectSkillQueries` used the parent test's `testutil.Context` from parallel subtests. Once that deadline passed, the closure's `require.NoError` called `FailNow` on the parent `t`, which panics and takes down the whole `coderd/database` package. `paralleltestctx` only checked direct references to the context, so it missed this. coder/paralleltestctx#6 now follows calls to local closures too. This pins `paralleltestctx` to the current `main` commit, as there's no tag yet. That commit also brings in the outer variable reassignment check from coder/paralleltestctx#4 and the `x/tools` bump from coder/paralleltestctx#5. The closure check flagged the `loadPrompt` helper in `TestMediaToolResultRoundTrip`, so it now makes its own context from the subtest's `t`. The `TestGraph` and `TestRuntimeAudit` fixes for the outer variable check are the same as in #30288, so that PR only needs to repin. |
||
|
|
ea287daf71 |
docs(coderd/x/chatd): resolve ARCHITECTURE.md TODOs for idle chats and workspace files (#30039)
Resolves the four TODO notes that #27079 and #27111 left in `coderd/x/chatd/ARCHITECTURE.md`. Each note pointed at a real change in documented behavior, so each is replaced with a short description that keeps the architectural facts and drops the implementation detail the notes carried (part field lists, the agent upload path, the prompt text format, helper names). - `Create` takes an explicit initial status that defaults to `running`, matching `chatstate.CreateChat`; callers request `waiting` for an idle chat. The execution state diagram gains the `N --> W: Create(waiting)` edge, and the `POST /api/v2/chats` section documents that empty `content` creates an idle chat, so clients can use the chat ID (for example to upload workspace files) before the first turn. The child-chat locking bullet from #30240 now uses the same `Create(initialMessages, initialStatus)` signature. - Files uploaded into the chat's workspace get no file links, so the attachment cap and eviction do not apply to them. A message can reference only a file in the chat's upload directory in the currently bound workspace, and the model gets the reference as text, never the bytes. - `POST /api/v2/chats/{chat}/workspace-files` is owner-only and needs SSH access to the workspace. It uses no transition, rejects archived chats, and works in every other execution state. It prefers the chat's bound agent and otherwise uses the worker's deterministic agent selection without binding the chat. Testing: - Docs-only change, rebased onto `main` at `8245457c8a5`. All four TODO notes were still on `main`, and each statement above was rechecked against the code there. - `make pre-commit-light` passes (markdown format and lint, `typos`, the dash check). `markdownlint-cli2` reports the same 10 pre-existing findings on `main` and on this branch. - The existing tests that pin each documented behavior pass on the rebased head: `TestCreateChat_AllowsNoUserMessages`, `TestCreateChat_RejectsInvalidInitialStatus`, `TestTransitionCreate_NToW`, `TestCreateChatWithoutInitialUserContent`, `TestPostChats_EmptyContent`, `TestWorkspaceFilePartToText`, `TestWorkspaceFilePartToTextStaleWorkspace`, `TestPostChatWorkspaceFile` (including `NotOwner`, `Archived`, `SharedWorkspaceRequiresSSH`), `TestCreateChatMessageWorkspaceFilePartRejectsInvalidPath`, and `TestCreateChatMessageWorkspaceFileWorkspaceValidation`. Review record: - Codex round 1 on `e3c5053`: 3 P2 findings (explicit `Create` status, model sees more than the path, missing owner-only constraint). All confirmed against existing tests and fixed in `41c40a2`. - Codex round 2 on `41c40a2`: 3 P2 findings (SSH requirement, `running` default for the initial status, per-chat reference path rule). All confirmed against existing tests and fixed in `5a55996`. - Codex round 3 on `5a55996`: no findings. - Codex round 4 on `46f94d0`, the head rebased onto `main` (review started by marking the PR ready): no findings. The rebase changed no reviewed text; it only updated the signature in the child-chat bullet that `main` added since. Refs #27079, #27111 > Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike. |
||
|
|
8245457c8a |
fix(coderd/x/chatd): make compaction fit an overflowing context (#30766)
Compaction is the recovery path for a chat near its context window, but its summary request was larger than the turn that overflowed: the whole history plus the tool definitions. Its only fallback, a retry without tools, also missed context-window errors that arrive inside an HTTP 200 stream (OpenAI Responses API, Bedrock Mantle). In the incident behind this PR, one MCP tool result of about 1 MB moved a 1M-token chat from 67% to 92% of its window in one step. After that, every turn and every `/compact` failed with "Your input exceeds the context window of this model." This PR does not try to predict whether the summary request fits. Each time the model rejects it for its size, the next request is thinner: 1. The full request: tool definitions and the whole history. 2. The same history without tool definitions (as before). 3. Tool results longer than 32 KiB cut to 32 KiB, keeping their head and tail. 4. Tool results longer than 4 KiB cut to 4 KiB. A step that would cut nothing is skipped. Only locally executed text and error tool results are cut. User messages, attachments, provider-executed results, and media stay whole. The cuts apply only to the summary request, not to the stored history. Other changes: - **In-stream rejections match.** Fantasy stream errors without a status code and Responses `error` and `response.failed` events now count as size rejections. A Responses error code other than `context_length_exceeded` never matches, so a rate limit stays retryable. Anthropic's "input length and `max_tokens` exceed context limit" also matches. - **A conversation that still does not fit** fails as a non-retryable config error that tells the user how to recover. - **Each rejected summary request is logged at Warn** with its tool count, tool result cap, and the bytes it cut. Not in this PR: counting tool results that arrive after the measured step in the compaction trigger, estimating the summary request before sending it, and a tighter per-result cap for large-window models. Earlier revisions of this branch did these and were dropped for the simpler path above. ## Testing - `go test ./coderd/x/chatd/...` (20 packages), `golangci-lint` on `chatd` and `chatloop`, and the pre-commit hook pass. - The real OpenAI Responses client runs against `httptest` for each in-stream error shape and must retry without tools. - Each of these breaks a test: removing the cut steps, sending a cut that cuts nothing, turning error results into text, cutting provider-executed results, and dropping the in-stream match. > Xum opened this PR on behalf of @ibetitsmike. |
||
|
|
200fa7dea7 |
perf(coderd): bound the initial chat stream snapshot to the client cursor (#29761)
Opening a chat on the Agents page loads its transcript over REST and then connects the chat stream with `after_id` set to the newest loaded message. The first sync of the stream ignores that cursor when it queries the database: it fetches every row of the chat on each connection, and then sends only the rows above `after_id`. The first sync now resolves `after_id` to that message's revision and fetches only rows changed at or after it. The history reset rule is the one on `main` (#29808): the stream resets only when message `after_id` is deleted or missing. A deleted cursor still produces one `history_reset` with the surviving history, because the bounded query includes the cursor row. An unknown ID keeps the full query. A message ID from another chat, live or deleted, is ignored, so the client receives the full history. Live updates after the first sync are unchanged. ## Performance Measured on dogfood's database, which runs `main`, with `EXPLAIN (ANALYZE, BUFFERS, SERIALIZE BINARY)` of the first-sync query. The chats are the 554 chats updated in the past day, picked by row count. `main` starts at revision 0. This PR starts at the revision of the newest live message, which is the `after_id` the web client sends. | Chat (rows) | `main` output | `main` first / repeat run | This PR output | This PR time | |---|---|---|---|---| | p50 (41) | 189 kB | 21.5 ms / 0.6 ms | 1 kB | 0.1 ms | | p90 (351) | 2.0 MB | 163 ms / 7.9 ms | 10 kB | 0.5 ms | | p99 (2,200) | 7.1 MB | 425 ms / 25 ms | 14 kB | 3.0 ms | | Largest (14,746) | 64.9 MB | 4.8 s / 193 ms | 6 kB | 17.6 ms | - Across the 554 chats, the bounded query returns 1 row up to p99 and 5 rows at most. - Both queries visit the same heap pages, because no index covers `revision`. The saving is the TOAST reads, serialization, transfer, and decoding of rows that `main` then discards. Most of `main`'s time is serialization: 153 ms of 193 ms for the largest chat. - The cursor lookup is one primary-key read of about 0.4 ms, so a median chat gains almost no latency. The gain grows with chat size. - Deleted rows are about 0.1% of rows, so they do not change the cost. ## Not changed A tab whose stream was down can miss an edit, then send a message and store the response, so its newest ID is above the edit. On reconnect, message `after_id` is live and the stream sends no reset, so the tab keeps the deleted messages. `main` has done the same since #29808, and this PR does not change it (mafredri's reproduction gives `expected [5 6 7 8], actual [3 4 7 8]` on both). An ID cannot show which edits the client applied. #29662 adds a client-reported version for that. <details> <summary>Delivery record</summary> - Rebased on `main` at `6ebefb83254`, keeping the #29808 reset rule and #30266 read-only snapshot reads. The cursor-bound mock test is part of `TestStreamLoopInitialSyncTombstones`. - Assumption checked on dogfood: no live message has a higher revision than a later message. Messages are only updated to soft-delete them or to set search columns, which the revision trigger ignores. 2,861 rows in 29 recently active chats break it, all created between 2026-06-26 and 2026-07-16 and none since. A client cursor cannot sit before them, because the client sends its newest message. - Local: `go test ./coderd/x/chatd/...`, `go test ./coderd -run '^TestStreamChat$'`, `go test ./coderd/database/dbauthz -run '^TestMethodTestSuite$'`. Mutants of the cursor bound (no `- 1`, no bound, cursor from another chat kept) each fail `TestStreamLoop*`. - Remote UAT before the rebase covered deleted, foreign, and unknown cursors, edits, grouped commits, and reconnects. On a synthetic 5,000-message chat, dial to first snapshot went from 129.6 ms to 15.0 ms. - Codex: [round 1](https://github.com/coder/coder/pull/29761#pullrequestreview-5284702021) and [round 2](https://github.com/coder/coder/pull/29761#pullrequestreview-5284855535) found cross-chat cursor bugs, fixed. Round 3 and the round on `7bed7855e41` found nothing. </details> > Xum opened this PR on behalf of @ibetitsmike. |
||
|
|
dfdd6a59a5 |
feat: move chats between projects through the chat update API (#30894)
`PATCH /api/v2/chats/{chat}` now takes `project_id`. A project ID moves
the chat into that project, and `uuid.Nil` removes it from its project.
**Stack** (moving chats between projects, bottom first):
1. #30893: the move in chatd
2. **This PR**: the chat update API takes `project_id`
3. #30895: **Move to project** in the chat menu
4. #30795: drag a chat onto a project folder in the sidebar
**Why:** #30893 can move a chat family, and the UI layers above need an
endpoint to call.
- A move accepts the same projects as chat creation, through
`validateChatProjectSelection()`, which this PR extracts from
`postChats()` without a change in behavior.
- A project that the chat's owner cannot use gives 404, even for an
admin. The owner must own the project or hold a grant on it
(`chatd.ChatProjectUsableBy`, the check that chat creation uses since
#30439). So an admin cannot put a member's chat into a project that the
member has no access to and expose its memory.
- A child chat, an archived chat or a disabled `chat-projects`
experiment gives 400. A family that is not idle gives 409 ("Cannot move
an active chat. Interrupt or wait for the chat to finish first."). A
project deleted between the check and the move gives 404.
- The move is the last write in `patchChat()`, so a refused move keeps
the earlier writes of the same request, as a refused archive does.
**What to scrutinize:** the access check in
`validateChatProjectSelection()` and the order of the refusals in
`patchChat()` (`coderd/exp_chats.go`).
**Architecture doc:** the `PATCH /api/v2/chats/{chat}` section of
`coderd/x/chatd/ARCHITECTURE.md` lists the `SetProject` states of a move
and its refusals, and no longer says that only an `archived` change
emits transitions.
**Generated** (`make gen`): `coderd/apidoc`,
`docs/reference/api/chats.md`, `docs/reference/api/schemas.md` and
`typesGenerated.ts` come from `UpdateChatRequest.ProjectID` in
`codersdk/chats.go`.
## Testing
- `make pre-commit` passes, and so does `go test ./coderd -run
TestPatchChatProject` (14 subtests).
- `TestPatchChatProject/AnotherOwnersProject` gets 404 for another
user's project, then moves the chat after the project is shared with the
chat's owner. It fails without the access check, and also with an
owner-only check. `MoveBackWaitsForAPendingMove` ends in the wrong
project when the handler skips the move before the lock.
`ActiveFamilyReturnsConflict` checks the 409 for a running, interrupting
or action-waiting root and for a running subagent.
`PublishesProjectChange` and `AuditsTheMove` cover the watch event and
the audit entry.
- Untested: the 404 when the project is deleted between the check and
the move.
> Xum opened this PR on behalf of @ibetitsmike.
|
||
|
|
0968f97a43 |
feat: move a chat family between projects in chatd (#30893)
chatd can now move a root chat, together with its subagent chats, into a project, to another project, or out of its project. Nothing calls this yet. #30894 adds the API. **Stack** (moving chats between projects, bottom first): 1. **This PR**: the move in chatd 2. #30894: `PATCH /api/v2/chats/{chat}` takes `project_id` 3. #30895: **Move to project** in the chat menu 4. #30795: drag a chat onto a project folder in the sidebar **Why:** today a chat keeps the project it was created with. A move must follow the family rules of archiving, because a step that runs during a move would still have the memory tools of the old project. - `chatstate.Tx.SetProject` runs only from W, E0 and E1, like `SetArchived`. `SetFamilyProject()` locks the root row before its subagents, in the same order as archiving, so a busy family gets `ErrTransitionNotAllowed` and nothing changes. - A move to the project the chat is already in changes nothing, even while the chat runs. The check reads the locked root row, so it waits for a move that is still in flight. - Only the root row stores `project_id`, and subagents use the project of the root. After the commit, chatd publishes a new `project_change` watch event for each chat of the family. The move keeps `updated_at`, so lists keep their order. - A root chat outside a project now has an empty memory index. When a chat leaves its project, or its project is deleted, its next turn start commits one memory index update that removes the memories the model saw there. **What to scrutinize:** the lock order and the same-project check under the lock in `SetFamilyProject()` (`chatstate/family.go`), the turn-start condition in `memoryIndexMessage()` (`memory.go`), and whether the `ARCHITECTURE.md` text matches them. **Generated** (`make gen`): `queries.sql.go`, `querier.go`, `dbmock` and `dbmetrics` come from `queries/chats.sql`. `coderd/apidoc`, `docs/reference/api/schemas.md` and `typesGenerated.ts` come from the new watch event kind, which is also why two `chats.test.ts` fixtures gain `project_change: false`. **Architecture doc:** `coderd/x/chatd/ARCHITECTURE.md` lists `SetProject` among the transitions and in the execution state diagram (W, E0 and E1 back to themselves). It also says that a root chat's project can change after creation, and that a moved chat's next turn starts with a memory index update from the old project to the new one. ## Testing - `make pre-commit` passes. `go test` passes for `coderd/x/chatd/chatstate`, `coderd/database/dbauthz` (`TestMethodTestSuite`) and the chatd memory tests. - `TestSetFamilyProjectLocksRootFirst` fails with 55P03 when a subagent row is locked first. `TestSetFamilyProjectKeepsTheCurrentProject` covers the same-project move during a run. The transition matrix test gains `SetProject` cases for W, E0 and E1. - `TestMovedChatUsesNewProject` runs two real turns around a move: the second turn uses the instructions and memories of the new project, and `OutOfProject` fails without the memory index removal. > Xum opened this PR on behalf of @ibetitsmike. |
||
|
|
6ebefb8325 |
feat: add chat project sharing API (#30439)
API for chat project sharing (experiment `chat-projects`). Builds on #30479 (merged). Owners share a project with users, groups, or the whole organization (the Everyone group, ID = organization ID). Chats in a shared project stay private. | Role | Project and instructions | Memories | ACL | Delete | |---------|--------------------------|------------|------|--------| | `use` | read | read/write | read | no | | `admin` | read/write | read/write | edit | no | Only the owner, and administrators whose role grants delete, can delete a project. - **API:** `GET`/`PATCH .../chats/projects/{project}/acl`, same shapes as `/chats/{chat}/acl`, plus SDK methods. Project responses include the caller's `permissions` (`update`, `delete`, `share`); the UI hides edit and delete accordingly. - **Listing:** `GET /chats/projects` returns owned and shared projects. Removes `GetChatProjectsByOwnerID`. - **Chat access:** creating a chat in a project, and loading its memory and instructions on each turn, requires the chat owner to own the project or have an ACL grant (`chatd.ChatProjectUsableBy`). Role grants don't count. If the grant is removed, existing chats lose memory and instructions on their next turn. - **Validation:** users and groups must be in the project's organization; keys must be canonical UUIDs; callers can't change their own role; the owner can't be added. Migration `000624` drops a user's grants when they leave the organization, so rejoining doesn't restore access. - **Instructions:** readers who can't edit get 403 instead of 404, and the UI hides editing. - **Agent prompt:** memories are visible to and editable by sharees, so the agent is told not to save secrets or personal details. Known gap: project deletion still detaches chats, and a sharee's open sidebar keeps showing them until reload. #30683 replaces this. Not included: share notifications, `/acl/available`, sharing UI. <details> <summary>Decision log</summary> - `use` grants memory read/write over HTTP, because agents in a sharee's chats can already write memories. Making the agent read-only for sharees was the alternative (@f0ssel chose sharees changing memories through use). - An administrator with `share` can grant themselves access and then use the project. Accepted to keep access control simple (@f0ssel). </details> > Generated by Coder Agents. |
||
|
|
e254086494 |
fix(coderd/x/chatd/chattool): return database errors from workspace tools (#30822)
Relates to CODAGT-1330 `create_workspace`, `start_workspace` and `stop_workspace` read a fair bit from the database whilst they wait on a build: the chat workspace TTL setting, the workspace's agents, the agent's lifecycle state, and the chat row once the build is done. When one of those reads failed, we'd log it (or just ignore it) and carry on as if it hadn't, e.g. falling back to the template's TTL or leaving out the agent status, and the tool still reported success. A failed write of the new build ID to the chat binding was handled the same way. To fix, we'll return a tool error for those database errors, so the model knows the call failed and can retry. `start_workspace` and `stop_workspace` now also re-bind the chat when its build is stale, so a retried call repairs a binding write that failed. An invalid TTL setting, a workspace with no build yet, and agent selection errors all behave like they do today. A tool error doesn't stop the build. The tools only watch the build and the agent, so the build, the startup scripts and the turn all carry on. If the model calls the tool again, `create_workspace` finds the workspace through the chat binding, which #30663 commits with the workspace, and waits on it again rather than creating a second one. It only creates a replacement if the agent has since disconnected or timed out, like it does today. `start_workspace` just waits on the latest build again, and the other workspace tools find and dial the agent themselves. This follows on from #30663. |
||
|
|
e09407c366 |
fix(coderd): commit chat workspace bindings with dependent state (#30663)
Relates to CODAGT-1330 When a workspace rebuild gives a chat a new agent, chatd saves the new agent binding and then re-pins the chat's context to that agent. These committed separately, and a failed re-pin was just logged. The next turn would see the new agent already bound, so it never re-pinned, and the chat kept injecting the old agent's context. `create_workspace` had a similar problem. It bound the chat to the workspace after the workspace was committed, and if that failed it logged an error and still reported success. The workspace was left orphaned, and the next call would just create another one. To fix, we'll commit the binding and the re-pin in one transaction. `create_workspace` now binds the chat inside the workspace create transaction. I've done this with the unused `postCreateInTX` hook in `createWorkspace`, which I've renamed to `postBuildInTX` and moved after the build insert so it has the build ID. |
||
|
|
096db5de02 |
fix(coderd/x/chatd): return MCP OAuth token database errors (#30662)
Relates to CODAGT-1330 Before chatd connects to MCP servers, it refreshes any expired OAuth tokens. If saving a refreshed token failed, we'd log it and use the new token for that turn only. A failed write when marking a revoked grant for reconnect, and a failed re-read after losing a refresh race, were also just logged, and the turn connected without the token. To fix, we'll return those database errors so the prepare retry runs. A transient error from the OAuth provider still keeps the current token for the turn, like it does today. This doesn't help if the provider already rotated the refresh token and the save fails, since the new token is lost either way. On retry, a provider that rotates tokens rejects the old one and we mark the token for reconnect, which is where we'd end up today anyway, just a turn earlier. |