mirror of
https://github.com/coder/coder.git
synced 2026-11-23 20:38:59 +08:00
052d9e840f6a1af14471d908062debfbc884c75c
4873
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
9edb2e388d |
feat: enable Coder.USSpelling Vale rule (#30790)
Depends on #30782. Adds `Coder.USSpelling` at `warning` severity. The rule flags an `-ise` family (`organise`, `initialise`, `authorisation`) and a list of British spellings (`behaviour`, `labelled`, `cancelled`, `analogue`, `whilst`, and others) and suggests the US form. It covers `docs/**` except `docs/.style/style-guide/**` and the generated `docs/reference/{api,cli}/*.md` pages. Baseline: 13 findings before cleanup, 0 after. The first commit fixes 11 of them: 10 in hand-written pages and 1 in the Prometheus metrics table, which comes from metric help text. Two findings sit in generated reference pages, which `.vale.ini` excludes for this rule: the CLI alias `favourite` and `amongst` in a Go comment from a vendored dependency (the DERP map schema). The metric help text comes from `querymetrics.go`, so the fix lands there and in `generated_metrics` and `prometheus.md`. Known false positive: Vale doesn't skip bold text, so a UI label in bold that keeps British spelling is flagged. The rule comment and the guide footer say to use a code span for such a label. Linear: DOCS-1280 <details> <summary>Decision log</summary> - **Rule type**: `substitution`, so each message names the US form. The `-ise` family can't name a specific replacement, so it suggests "the -ize form". - **`cancelled`**: the guide's "Use US spelling" section lists `canceled` and `canceling`. The rule flags the double-l verb forms and leaves `cancellation` alone, which Merriam-Webster spells with one `l`. - **Exceptions**: Vale applies an exception to the matched word, so each is anchored with `^` and `$` and case-insensitive. The list covers `-wise` words and stems for `advise`, `advertise`, `exercise`, `promise`, `premise`, `compromise`, `surprise`, `comprise`, `concise`, `precise`, `revise`, `supervise`, `televise`, `devise`, `improvise`, `franchise`, `merchandise`, `disguise`, `despise`, `paradise`, `cruise`, `noise`, `raise`, `rise`, `wise`, and others, each with the endings `e`, `es`, `ed`, `ing`, `er`, and `ers`. The `mise` tool is excepted by name. - **Extra British spellings** beyond the guide table: other doubled-`l` verbs (`signalled`, `levelled`), `metre`, `litre`, `fibre`, `theatre`, `calibre`, `offence`, `pretence`, `analyse`, `judgement`, `acknowledgement`, `ageing`, `artefact`, `sceptic`, `aluminium`, `practise`, `enrol`, `fulfil`, `instil`, `skilful`. None appears in the corpus today. - **Generated pages**: excluded for `docs/reference/{api,cli}/*.md`, as `Coder.UnitSpacing` does. Changing the `favourite` alias would change CLI behavior, and the `amongst` comment isn't ours to edit. - **Prometheus doc**: edited by hand with matching table padding because `go run ./scripts/metricsdocgen` already rewrites the whole table on the base branch, independent of this change. Test cases, run with `vale --config` against fixtures that are not committed, in LF and CRLF: - Positive: `organise`, `initialise`, `authorise`, `customisation`, `authorisation`, `organisations`, `Organised`, `initialising`, `recogniser`, `customisable`, every explicit list entry, and capitalized forms. - Negative: `advise`, `exercise`, `otherwise`, `Enterprise`, `premise`, `compromise`, `promise`, `surprise`, `precise`, `concise`, `expertise`, `revising`, `supervising`, `improvising`, `raise`, `noise`, `cruise`, `franchise`, `merchandise`, `disguise`, `despise`, `paradise`, `appraise`, `sunrise`, `arise`, `liaise`, `clockwise`, `cancellation`, `canceled`, `mise`. - Skipped: words in code spans and fenced code blocks, such as `cancelled`. - LF and CRLF results are identical. Checks: `vale --output=line docs/` reports 0 `Coder.USSpelling` findings, `make lint/style-claims` passes, and the pre-commit hooks pass on both commits. </details> *Generated by [Coder Agents](https://coder.com/docs/ai-coder/agents) on behalf of @nickvigilante.* |
||
|
|
3c36790c86 |
fix(coderd/x/chatd): coalesce deltas when persisting interrupted turns (#29661)
An interrupted turn was stored with one ChatMessagePart per streamed delta, while a completed turn gets one part per block. One 28,539 character interrupted response became 3,987 parts and 1 MB of JSON, and a /messages page with such turns reached 11.7 MB. Whitespace-only deltas were separate parts too, and prompt replay skips whitespace-only parts, so words and paragraphs ran together in the next turn's prompt. Adjacent deltas of the same type are now joined into one part. A text run ends at another part type, a tool result or a narration change. A reasoning run ends where CreatedAt, the block's start time, changes. Adjacent text blocks still merge because text deltas have no block identity. Rows already stored are not rewritten. |
||
|
|
c4d76a4009 |
feat: add skill action and automatic-use settings (#30882)
Adds two per-skill settings that the project skills UI will expose next: - `action` marks a project skill to show as an action button above project chat composers. A `skills_action_project_only` check keeps it to project skills; the personal and organization routes reject `action` with 400. - `model_invocable` (default true, every stored source) controls automatic use. When it's false the skill is left out of `<available-skills>` and `read_skill` reports it as not found, but a structured skill invocation (a chip from the `/` menu or an action) still loads it, as long as the skill is enabled and the chat owner can read it. Workspace skills always count as model-invocable. Migration 000625 adds both columns with defaults, so existing skills keep today's behavior. The list, get, insert and update queries, `codersdk.SkillMetadata` and the create/update requests carry both fields, and the audit table tracks them. `coderd/x/chatd/ARCHITECTURE.md` gets TODO notes for the author. **NOTE**: the migration adds two columns with constant defaults and a CHECK constraint to `skills`. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 👈 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com> |
||
|
|
9b8d880d63 |
fix: exempt service accounts from user dormancy (#30824)
Closes CODAGT-1344 The Slack bot for Coder Agents (CODAGT-1098) runs inside coderd and acts as a service account that an admin picks. It creates chats and sends messages as that account through Go calls, not HTTP requests. Two dormancy rules break it: 1. **New service accounts start dormant.** The CLI and the web "Create user" page send no status, and `InsertUser` falls back to `dormant`. So the bot's account is dormant from the start. 2. **Accounts go dormant after 90 days without a "last seen" update.** Only the API key middleware updates `last_seen_at`, and only on HTTP requests. The bot never sends any, so its account goes dormant on day 90, even if people use the bot every day. A chat owner must be active, so once the bot's account is dormant, every Slack mention fails. Any other in-process integration that acts as a service account has the same problem. Dormancy does nothing useful for service accounts: - It exists to free license seats, and service accounts never take a license seat (#24401, #27279). - It isn't a lock. Any API request activates a dormant account again. - System users already skip the dormancy job for the same reason. So this PR: - creates service accounts as active when the request doesn't set a status, - rejects an explicit dormant status for a service account with a 400, - skips service accounts in the dormancy job, the same way it already skips system users. Side effects: a service account that nobody uses for 90 days now stays active. That has no effect on license seats. If the account has ever sent traffic through AI Gateway, it also keeps its AI Governance seat until an admin suspends or deletes it. That matters less than it sounds: AI Governance is now included with Premium rather than sold per seat (#27545), so the seat only counts on a license that still has an AI Governance seat limit, and there it only feeds the seat-limit warning. The dormancy job also no longer writes "marked dormant" audit entries for service accounts. I've left existing dormant service accounts alone rather than adding a migration. An admin can activate one, and any API request from it activates it too. --- _This PR description was written by Coder Agents._ |
||
|
|
15a160aec9 |
feat: serve internal MCP servers to chats in process (#29828)
This lets coderd give a chat MCP tools that it serves itself, in process. The first user will be an in-process integration, say a Slack bot. Nothing uses it yet. coderd now takes a list of internal MCP servers when it's built, each with a slug and a `ServerForChat` function. At every step, chatd asks each one for a server for the chat and connects to it over an in-memory transport, so the server knows which chat it's serving without any headers. Nothing is stored on the chat, so the public API doesn't change, and the chat owner can't remove an internal server. As only coderd can add one, internal servers ignore the `chat-inline-mcp-servers` experiment and the `--disable-chat-caller-supplied-tools` kill switch. Their tools come straight after the built-in tools, so they win any name clash with admin, workspace or caller tools. Admin and workspace tools now follow the same first-wins rule, so the model never sees two tools with the same name. If `ServerForChat` returns an error, we fail the turn, as we do when any other read during turn setup fails. I've put this on top of #30730 and #30731 in the stack. It doesn't need anything from them, but the Slack bot needs all three. |
||
|
|
9d5f0cd3c0 |
refactor(coderd): share chat updates with in-process callers (#30731)
An in-process caller (say, a Slack bot) also needs to unarchive a chat before it sends to it, so this adds `api.UpdateChatAsUser` next to the send and interrupt functions from #30730. Like those, it's a Go method rather than an endpoint, and nothing calls it yet. It runs with the given user's own roles, so it can only do what that user could already do with `PATCH /api/v2/chats/{chat}`. Rather than a narrow unarchive helper, it shares the whole `PATCH` handler body. The handler validates every field before it applies any of them, so a narrow copy would just duplicate that logic. It writes the same audit entry as the endpoint, and the endpoint's behaviour doesn't change. |
||
|
|
d8a78b28fd |
refactor(coderd): share chat sends and interrupts with in-process callers (#30730)
This follows on from #30027, which added `api.CreateChatAsUser`, and does the same for sending a message to a chat and interrupting it. These aren't new endpoints, they're Go methods for code running inside coderd (say, a Slack bot) that needs to keep a conversation going in a chat it created, without an API key. Nothing calls them yet. We'll move the bodies of `POST /api/v2/chats/{chat}/messages` and `POST /api/v2/chats/{chat}/interrupt` into functions that both the handlers and `api.SendChatMessageAsUser` / `api.InterruptChatAsUser` call. The caller passes a user ID, and the call runs with that user's own roles, so it can't do anything that user couldn't already do over the API. The endpoints' behaviour doesn't change. |
||
|
|
837c2e1af1 |
feat(coderd): price token usage with organization prices (#30719)
Prices token usage by the most specific match: the organization's price for the configured provider, then a site-wide custom price, then the price book. The requested model is still preferred over the model the provider reports. - `GetAIModelPriceForProvider` replaces `GetAIModelPriceByProviderModel`, which is removed. It is one `UNION ALL` of primary-key lookups, ordered by requested model first, then by specificity. dbauthz checks `ResourceAiModelPrice`, scoped to the org when one is given. - `coderd/aibridge/prices` tests read seeded prices through `GetAIModelPrices`. Interceptions don't carry an organization yet, so `resolveTokenUsageCost` passes none and only site-wide prices apply at runtime for now (AIGOV-716). Org matching is covered by database tests with explicit org IDs. For the same reason, the unpriced-models report still counts only site-wide prices. **Used later:** prices set through the API in #30720 take effect here once interceptions carry an organization. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
da78c88100 |
feat(coderd): add queries for organization AI model prices (#30718)
Adds the store queries for organization AI model prices in `ai_model_configs`, with authorization. They cover basic CRUD on one price, keyed by `(organization_id, provider_id, model)`. - `GetOrganizationAIProviderModelPrice` reads one price. - `UpsertOrganizationAIProviderModelPrice` sets one price, with typed params. It rewrites an existing row only when a price differs, so `updated_at` records the last change. - `DeleteOrganizationAIProviderModelPrice` soft deletes one price. Reads and upserts only match live rows, so setting a price after a delete inserts a new live row. All three authorize against `ResourceAiModelPrice.InOrg(org)`. The new `AiModelPriceInOrg` case in `TestRolePermissions` pins that only owners and org admins pass. A TODO in dbauthz notes that this should become a resource for AI Governance model config. Each query has its own test. The upsert tests cover that identical prices leave `updated_at` unchanged, that changed prices advance it, and that an empty model is rejected. **Used later:** #30719 seeds its lookup tests with the upsert. #30720 serves all three through the org price API. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
30499fdcfa |
fix(coderd/aibridged): allow evicted bridges ten minutes to drain (#30830)
AI Gateway evicts cached request bridges after 15 minutes and currently gives in-flight requests only five seconds to finish, cutting off otherwise healthy model calls and streams. Give evicted bridges up to ten minutes to drain without changing the cache TTL. New acquisitions use a replacement bridge while the retired one drains. Pool shutdown retains a five-second cancellation grace period for cached and already-retired bridges, even when an acquisition is blocked initializing MCP connections. Requests still running at the drain deadline are cancelled. Refs [AIGOV-672](https://linear.app/codercom/issue/AIGOV-672/aibridged-15-minute-bridge-ttl-cancels-in-flight-ai-gateway-requests). The separate acquisition/admission race tracked in [AIGOV-609](https://linear.app/codercom/issue/AIGOV-609) is outside this change. --- Created by OpenCode on behalf of @dannykopping. |
||
|
|
04d7d4da9c |
chore: refresh AI model price book (#31162)
## Price book changes 26 models added, 8 models removed, 56 models changed. <details> <summary>Added</summary> - azure/deepseek-v4.1-flash - google/gemini-pro-latest - openrouter/deepseek/deepseek-v4.1-flash-1017 - openrouter/elorian/glimpse - openrouter/inception/mercury-3 - openrouter/meta/muse-spark-open - openrouter/minimax/minimax-m3.1-flash:free - openrouter/moondream/moondream3-preview - openrouter/moondream/moondream3.1-9b-a2b - openrouter/nvidia/nemotron-3.5-super-vl - openrouter/nvidia/nemotron-3.5-super-vl:free - openrouter/recursive/flint-v1.0:free - openrouter/reflection/beam-1.0-501b-a23b - openrouter/unbiased/pareto-26.10 - openrouter/xingchen-agi/xing4.0-29b-a4b:free - vercel/deepseek/deepseek-v4.1-flash-1017 - vercel/deepseek/deepseek-v4.1-flash-1017-fast - vercel/elorian/glimpse - vercel/inception/mercury-3 - vercel/meta/muse-spark-open - vercel/minimax/minimax-m3.1-flash - vercel/nvidia/nemotron-3.5-super-vl - vercel/reflection/beam - vercel/reflection/beam-free - vercel/scaledown/scaledown-extract-1 - vercel/scaledown/scaledown-summarize-1 </details> <details> <summary>Removed</summary> - openai/gpt-5.2-chat-latest - openai/gpt-5.3-chat-latest - openrouter/anthropic/claude-sonnet-4 - openrouter/deepseek/deepseek-r1 - openrouter/microsoft/wizardlm-2-8x22b - openrouter/sao10k/l3.3-euryale-70b - openrouter/unbiased/pareto-26.10-preview - vercel/anthropic/claude-sonnet-4 </details> <details> <summary>Changed</summary> - azure/gpt-5 - azure/gpt-5-codex - azure/gpt-5-mini - azure/gpt-5-nano - azure/gpt-5.2 - azure/gpt-5.6-sol - openrouter/deepseek/deepseek-chat - openrouter/deepseek/deepseek-v3.2 - openrouter/deepseek/deepseek-v4-flash-0731 - openrouter/deepseek/deepseek-v4.1-flash - openrouter/google/gemini-3.8-flash - openrouter/google/gemma-3-27b-it - openrouter/google/gemma-3-4b-it - openrouter/meta-llama/llama-3.2-3b-instruct - openrouter/meta-llama/llama-3.3-70b-instruct - openrouter/meta-llama/llama-4-scout - openrouter/mistralai/mistral-large-4-0 - openrouter/mistralai/mistral-small-3.2-24b-instruct - openrouter/moonshotai/kimi-k3 - openrouter/nvidia/nemotron-3-super-120b-a12b - openrouter/qwen/qwen3-30b-a3b-instruct-2507 - openrouter/qwen/qwen3-next-80b-a3b-instruct - openrouter/qwen/qwen3.5-122b-a10b - openrouter/qwen/qwen3.5-27b - openrouter/qwen/qwen3.5-35b-a3b - openrouter/qwen/qwen3.5-9b - openrouter/qwen/qwen3.6-27b - openrouter/qwen/qwen3.6-35b-a3b - openrouter/qwen/qwen3.8-27b - openrouter/stepfun/step-5-preview - openrouter/upstage/solar-pro4 - openrouter/xiaomi/mimo-v2.5 - openrouter/xiaomi/mimo-v2.5-pro - openrouter/z-ai/glm-4.6 - openrouter/z-ai/glm-4.7 - openrouter/z-ai/glm-5.1 - openrouter/z-ai/glm-5.2 - openrouter/z-ai/glm-5.3 - openrouter/z-ai/glm-5.3-flash - openrouter/~deepseek/deepseek-flash-latest - openrouter/~deepseek/deepseek-pro-latest - openrouter/~deepseek/deepseek-v4-flash-latest - openrouter/~moonshotai/kimi-latest - openrouter/~unbiased/pareto-latest - openrouter/~z-ai/glm-flash-latest - openrouter/~z-ai/glm-latest - vercel/arcee-ai/trinity-large-thinking - vercel/deepseek/deepseek-v4.1-flash - vercel/meta/llama-3.3-70b - vercel/meta/llama-4-maverick - vercel/meta/llama-4-scout - vercel/mistral/ministral-3b - vercel/mistral/ministral-8b - vercel/mistral/mistral-large-4 - vercel/stepfun/step-5-preview - vercel/xiaomi/mimo-v2.5 </details> ## Review notes Regenerated by `make gen/aibridge-prices` from the live [models.dev](https://models.dev) catalog. Both artifacts come from one snapshot, so they ship together: - `coderd/aibridge/prices/data/prices.json` - `site/src/modules/aiModels/knownModels/knownModelsGenerated.json` These are customer-visible cost numbers taken from upstream data, so this PR is never merged automatically. The summary above lists what moved; check the diff for exact figures before approving. Opened automatically by the [aigateway-prices-refresh workflow](https://github.com/coder/coder/actions/runs/39752842140). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
39c4bd6ced |
refactor(coderd/x/chatd): drop the unused runnerCtx from the runner debug turn (#31010)
Deletes `runnerDebugTurn.runnerCtx` and the context parameter of `newRunnerDebugTurn`. The field's only reader was the `LaunchRunHeartbeat` call in `ensureLocked`, which #30988 deleted with the run heartbeats, so nothing has read it since. **Why it is safe:** the constructor set the field and no code read it. The debug turn still uses the context of each call to `Ensure`, `Context` and `Finalize`, which this PR does not change. `runner.go` and 10 tests stop passing a context, and four of those tests drop the `context.WithCancel` that they created only for this parameter. Validation: - `go build ./coderd/x/chatd/...` and `go vet ./coderd/x/chatd/...` pass. - The 25 chatd debug-run tests, `TestRecordGenerationFinishFailure`, `TestSessionStartDispatchFailureFinishesGeneration` and `TestStartGeneration_CancelsDeletedToolCallsOnAgent` pass under `-race`. - `golangci-lint run --fix=false ./coderd/x/chatd/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. This PR: Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
98104d10fe |
chore(coderd/database): drop the chat debug stale-sweep indexes (#31009)
Drops `idx_chat_debug_runs_stale` and `idx_chat_debug_steps_stale`, the partial `updated_at` indexes that migration 000468 added for the `FinalizeStaleChatDebugRows` query. #30995 deleted that query, so nothing reads these indexes, but every debug run and step write still updates them. **Why it is safe:** no remaining query can use them. A partial index on `updated_at WHERE finished_at IS NULL` only serves queries that filter on `finished_at IS NULL`, and the one query that still does, the `locked_run` CTE in `InsertChatDebugStep`, finds the run by primary key. `DeleteOldChatDebugRuns` filters on `updated_at` alone and uses `idx_chat_debug_runs_updated_at` from migration 000487, which stays. The down migration recreates both indexes as 000468 defined them. **Review focus:** the migration number. 000632 follows `main`'s newest migration, 000631 from #31059. If `main` gains another migration first, this one moves to the next free number. Validation: - `make gen` changes only `dump.sql`, which loses the two `CREATE INDEX` lines. The renumber to 000632 leaves it unchanged. - `go test -count=1 ./coderd/database/migrations/` passes on this branch, where `main`'s 000631 and this 000632 both apply. The run includes `TestMigrate/UpDownUp` (every migration up, down and up again) and `TestMigrationChain`. - The pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. This PR: Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
e3657389bb |
refactor(coderd/x/chatd/chatdebug): delete the process-global step counters (#31008)
Deletes chatdebug's process-global step counters: the `stepCounters` and `runRefCounts` maps, `refCountMu`, `trackRunRef`, `releaseRunRef`, `nextStepNumber`, `syncStepCounter` and `CleanupStepCounter`, the `runtime.AddCleanup` hook that `ContextWithRun` registered for every run context, and the two `CleanupStepCounter` calls in `FinalizeRun`. Since #31007 the database numbers steps, so no production code reads them. **Why it is safe:** after #31007 no production code reads the counters. Production code only maintained them: `ContextWithRun` registered a reference for every run context and `FinalizeRun` called `CleanupStepCounter`, and this PR removes both. A search of `coderd/` and `enterprise/` for the deleted names finds nothing now. The deleted tests covered only the deleted code: `TestNextStepNumber_Concurrent` and `TestSyncStepCounter_AdvancesCounter` checked counter values, and the three garbage-collection tests in `context_internal_test.go` checked that a counter lives until the last `RunContext` for its run is collected. The 20 `t.Cleanup(func() { CleanupStepCounter(runID) })` lines go with them. `TestReuseStep_PreservesExistingHolder` and `TestBeginStepReuseStep` stay. The `FinalizeRun` doc comment no longer mentions the counter. **Review focus:** `ContextWithRun` is now a plain `context.WithValue`. Code that copies a `RunContext`, such as `runnerDebugTurn.contextLocked`, no longer affects anything, because no state is tied to the struct's lifetime. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `go test -count=1 -run Debug ./coderd/x/chatd/` (19 tests) passes, and the 25 chatd debug-run tests pass under `-race` (`go test -race -run '^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$' ./coderd/x/chatd/`). - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. #30934 Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. This PR: Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
f69b98abfc |
fix(coderd): ignore retired OAuth2 scopes such as task:* (#31117)
Closes CODAGT-1422 After upgrading to v2.38, Coder Agents can't connect to Coder's own MCP server if its MCP server config was created before the upgrade. When an admin creates an OAuth2 MCP server config without any scopes, we save the authorization server's entire `scopes_supported` list and send it on every connect. Before v2.38 that list included the `task:*` scopes, which #28750 removed. Since #28178, `/oauth2/authorize` rejects the whole request if it names a scope outside the catalog, so connecting fails with: ``` 'task:*': unknown or unsupported scope ``` The issue suggests a migration that strips `task:*` from `mcp_server_configs`, but I don't think that's the right fix. We can't backport it to 2.38, as `main` already has migrations past the last one on `release/2.38`. A config with only `task:*` scopes would be left with none, and requesting no scope gets you `coder:all`. The column also holds scopes for third-party MCP servers. Any other OAuth2 client that cached the old `scopes_supported` would also stay broken, as would every client the next time we remove a scope. To fix, we'll retire removed scopes rather than delete them. There's now a small list of retired scope names next to the scope catalog, and the authorization server drops those names from a request and grants the rest. RFC 6749 §3.3 lets the server ignore part of the requested scope, and the token response already returns the scope that was issued. Names that were never in the catalog are still rejected, and so is a request of only retired names, so it can't widen into a broader default grant (e.g. `coder:all`). Existing configs then connect without anyone editing them. If we'd assumed from the start that scopes get removed, we'd have retired them rather than deleted them, and that's all this does. It fixes the cause rather than the one MCP config symptom, it's code only so it cherry-picks cleanly onto `release/2.38`, and the next removed scope just moves into the retired list. Third-party MCP servers that remove a scope will still break Agents the same way, since our MCP client saves the authorization server's `scopes_supported` instead of following the MCP spec's scope selection. I've left that for a follow-up. |
||
|
|
ffd24861a1 |
feat: send skill invocations as structured message parts (#30861)
Adds a structured `skill-invocation` chat part so a user message can carry an explicit skill. chatd loads that exact skill when the message is sent and puts its body into the user's prompt, so the skill always applies instead of relying on the model to notice it in `<available-skills>`. The composer chip that sends these parts comes in the next PR. - codersdk: a `skill-invocation` input part and message part with `skill_source` (`personal`, `org`, `project`, `workspace`) and `skill_name`. The resolved body is stored on the part as internal `skill_body`; it's hidden from TypeScript and stripped from every API response. - coderd rejects an unknown source or an invalid name with 400. - chatd resolves each invocation on create, send and edit with the chat owner's permissions, through the same loaders as `read_skill`: stored skills by source and name (project skills through the chat's project, with the root chat fallback for subagents) and workspace skills from the pinned context snapshot. The body is saved at send time so past turns show what the model received. A missing, disabled or unreadable skill rejects the send with 400 "Skill project/triage is not available." - The prompt renders a line saying the user invoked the skill, followed by `<invoked-skill name="project/triage">` with the sanitized body. Titles and hook prompt text show the invocation as `/project/triage`. - The site only gets no-op cases so the regenerated types compile. `coderd/x/chatd/ARCHITECTURE.md` gets a TODO for the author. Stack (merge top to bottom): - #30826 - #30827 - #30838 - #30840 - #30854 - #30855 - #30856 - #30861 👈 - #30880 - #30881 - #30882 - #30884 - #31122 - #31126 --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
cc66f30a19 |
fix(coderd/webpush): bound push response body read and add client timeout (#31129)
fix(webpush): bound response sizes and request duration Prevent push endpoints chosen by users from causing unbounded response buffering or indefinite waits. Cap response body reads at 64 KiB and configure the default HTTP client with a 64 KiB header limit and a 30-second timeout covering the full exchange, including body reads. Document that replacement clients passed to `WithHTTPClient` must set their own timeout. Add regression tests for endless success/error bodies, oversized headers, stalled servers, and the default client limits. Refs [PLAT-729](https://linear.app/codercom/issue/PLAT-729/security-fixcoderdwebpush-bound-response-body-read-and-add-client) |
||
|
|
c61d842b9c |
feat: show available ACP harnesses in chat context (#31059)
Expose discovered ACP harnesses in the chat context resource inventory when the `chat-acp-subagents` experiment is enabled, including configuration paths and resource status. Persist ACP harness resources from agent context snapshots and update the SDK and generated API types. Generated with Codex, carefully reviewed by Hugo. |
||
|
|
3216580614 |
feat: load project skills in chats (#30838)
Chats that belong to a chat project now get the project's skills, next to personal, organization and workspace skills. They show up in the model's skill list, load through `read_skill`, and appear in a "Project skills" group in the `/` menu. - `coderd/x/skills` adds the `project` source. `MergeSkills` now takes a list of sources in merge order (personal, organization, project, workspace). Bare names stay bare unless two sources share a name, in which case they get `project/<name>` style aliases. - chatd loads project skills only when the chat owner owns the project or the project is shared with them. Role grants don't count. This is the same `usableChatProject` check that project instructions and memory use, and one check per turn covers both instructions and skills. Disabled skills are skipped. A failed load logs a warning and the turn continues without them. Subagents use their root chat's project; that lookup is now a helper shared with project instructions. - The site loads project skills for the composer on the project page and in project chats, behind the `chat-projects` experiment. `/clear` and `/compact` defer to a project skill with the same name, as they already do for other sources. When the user can't use the project, the site treats it as no project skills, like chatd, so those commands keep working and the `/` menu shows no retry prompt for project skills. That covers a 403 or 404 from the project skills request and a project missing from the user's project list, which holds only owned and shared projects, so an administrator role that can read the project doesn't count. Other failures are retried and leave the list unknown. A cached project list is also unknown while it refetches or after a failed refetch, so a share revoked since it was cached keeps those commands pending instead of deferring to stale project skills. - Docs gain a "Project skills" section in the extending agents page. `coderd/x/chatd/ARCHITECTURE.md` gains a paragraph on project skills. Dogfood UAT on this branch passed: project skills appear in the project page `/` menu and in project chats, `read_skill` loads them, disabled and deleted skills report not found, chats outside the project don't see them, and a subagent gets them through its root chat. The site reads project skills from the chat's own `project_id`, so subagent chats show them in the composer once sub-chats carry their root's project (#30683). | Project page `/` menu | `read_skill` in a project chat | | --- | --- | | <img alt="Project skills group in the project page slash menu" src="https://raw.githubusercontent.com/coder/coder/assets/pr-30838-project-skills/pr/project-page-slash-menu.png" width="600" /> | <img alt="read_skill loading a project skill in a project chat" src="https://raw.githubusercontent.com/coder/coder/assets/pr-30838-project-skills/pr/project-chat-read-skill.png" width="600" /> | Stack (merge top to bottom): - #30838 👈 - #30854 - #30855 - #30856 - #30861 - #30880 - #30881 - #30882 - #30884 - #31122 |
||
|
|
ffc6aac6a8 |
test(coderd/x/chatd/chatdebug): check the run-summary query boundary (#30973)
Replaces the last Postgres-backed run-summary subtests with mock tests of the `AggregateRunSummary` boundary and one extended Postgres test. This deletes `MultipleStepsSumTokens` and the helpers `createTestStep`, `updateTestStepWithUsage` and `updateTestStepWithFullUsage`. **Why it is safe:** - `NilRunID` now runs against a mock with no expectations, so any query fails it, and checks that the base map comes back unchanged. - The new `QueryAsChatdReturnsError` checks that the read runs as the chatd actor and that the query error is returned. - `RecomputesHasErrorAndCompletedEndpointLabel` now inserts step 2 before step 1 and compares the whole summary read through the real query: five token sums, `has_error`, the endpoint label and the seeded `first_message`. With the table from #30972, it covers every assertion of `MultipleStepsSumTokens`. - Of the same 42 `summary.go` mutants, the tests now kill 34 (`main` kills 22, #30972 kills 31). The new kills are the nil run ID return value, a swallowed query error and a read without the chatd actor. The 8 survivors are equivalent or only change logging. - Mutants of the `GetChatDebugStepsByRunID` SQL that order by `started_at` alone or reverse the order fail the Postgres test. Dropping the `ORDER BY` survives: Postgres reads these rows through the unique `(run_id, step_number)` index, which already returns them in step order. - No references to the removed helpers remain. **Review focus:** the setup order in `RecomputesHasErrorAndCompletedEndpointLabel`. Step 2 is inserted first, so the expected label holds only if the query orders by `step_number`. Since #31007, `CreateStep` numbers steps itself, so the test inserts both rows through the store with explicit step numbers. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack makes the debug run-summary reduction database-free and replaces its Postgres fixtures with literal rows. 1. #30972 Replace run-summary Postgres subtests with literal rows 2. #30973 Check the run-summary query boundary > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
5c9815b474 |
refactor(coderd/x/chatd/chatdebug): replace run-summary Postgres subtests with literal rows (#30972)
Moves the post-query reduction in `chatdebug.(*Service).AggregateRunSummary` into a private `summarizeRunSteps` method and tests it with table cases over literal `database.ChatDebugStep` rows. This deletes the 11 Postgres-backed subtests of `TestService_AggregateRunSummary` whose assertions the table covers; each one built its own database. **Why it is safe:** - The moved body is unchanged apart from `return result`. `AggregateRunSummary` still owns the nil run ID check, the chatd-authorized read and the error return. - Every assertion of the removed subtests maps to a table row that compares the whole output map, so absent keys are checked too. Each row also checks that the base map is not mutated. - `NilRunID`, `RecomputesHasErrorAndCompletedEndpointLabel` and `MultipleStepsSumTokens` stay on Postgres here; #30973 replaces them. - I ran 42 mutants of `summary.go` with `go test -overlay`: `main`'s tests kill 22, this PR's tests kill 31, including all 22. The new kills cover JSON null and empty error payloads, error payloads on completed steps, malformed usage and attempts, empty paths, first-match selection and caller map mutation. Of the 11 survivors, 3 are query-boundary mutants that `main` also misses (#30973 kills them) and 8 are equivalent or only change logging. **Review focus:** `summarizeRunSteps` in `summary.go`. The moved block should match `main` apart from the return statement. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports 0 issues, and the pre-commit hook passed. ## Stack This stack makes the debug run-summary reduction database-free and replaces its Postgres fixtures with literal rows. 1. #30972 Replace run-summary Postgres subtests with literal rows 2. #30973 Check the run-summary query boundary > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. |
||
|
|
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. |
||
|
|
d14631df1a |
feat(coderd/database): add organization AI model config table (#30717)
Adds `ai_model_configs`: an organization's AI Governance configuration for one model on one configured provider. Token prices are its first settings. Migration `000630` is additive and needs no backfill. - Rows are soft deleted with a `deleted` flag. A surrogate `id` is the primary key, and a partial unique index allows one live row per `(organization_id, provider_id, model)`. Cascades on delete of the organization or provider. The organization is a column, as in other organization-scoped tables. - A check constraint rejects an empty model. - Pricing per provider ID is what lets `openai-compat` gateways be priced, and lets providers of the same type have different prices. - Site-wide prices per provider type stay in the existing `ai_model_prices` table, unchanged. Recording which price was used on each token usage record is deferred until its design settles. **Used later:** #30718 adds the queries that read and write the table, and #30719 looks prices up from it. The rest of the diff is generated. --- *This PR was generated by Coder Agents on behalf of @SasSwart.* |
||
|
|
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. |
||
|
|
8b6f209e8f |
refactor: delete the FinalizeStaleChatDebugRows query (#30995)
Deletes the `FinalizeStaleChatDebugRows` query. #30989 deleted `chatdebug.Service.FinalizeStale`, its only caller. This is the last of three PRs that delete the stale debug-run sweep. - Deletes the query from `chatdebug.sql` and regenerates the querier, dbmock and dbmetrics code. `make gen/db` leaves the dbmetrics wrapper of a deleted query behind, so I removed it by hand. - Deletes the dbauthz wrapper and its `TestMethodTestSuite` case, and `TestFinalizeStaleChatDebugRows` from `querier_test.go`. - The `codersdk.ChatDebugStatus` comment no longer names the query. **Why it is safe:** nothing calls the query after #30989. #30988 explains why no reader of the debug `updated_at` columns needs the sweep and why dbpurge cannot delete a live run. **Review focus:** the partial indexes `idx_chat_debug_runs_stale` and `idx_chat_debug_steps_stale` from migration 000468 served only this query. They stay in this PR; #31009, at the top of this stack, drops them in a migration. Validation: `make gen/db` and `go build ./...`. `go test -count=1` passes for `./coderd/database/dbauthz/ -run TestMethodTestSuite`, `./coderd/database/ -run ChatDebug`, `./codersdk/` 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. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. This PR: 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. |
||
|
|
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. |
||
|
|
90a8d51418 |
test(coderd/nats): use a random cluster port in TestPubsub/CloseIdempotent (#31056)
`TestPubsub/CloseIdempotent` in `coderd/nats` flakes in CI with
"embedded nats server not ready within 10s" (for example in
[`test-go-pg-17` on
main](https://github.com/coder/coder/actions/runs/39412671012/job/118594196090)).
It is the only subtest that calls `nats.New` with `nats.Options{}`
directly. With `ClusterPort` unset, `buildServerOptions` falls back to
the fixed production cluster port 6222. Test packages run in parallel,
and `cli` `TestServer/SpammyLogs` runs `coder server --cluster-host
127.0.0.1`, which holds 127.0.0.1:6222. When the route listener cannot
bind, nats-server logs nothing under `NoLog`, and `ReadyForConnections`
waits out the 10 s `readyTimeout`.
The fix gives the subtest `ClusterPort: natsserver.RANDOM_PORT`, the
option the `newPubsub` helper already sets for every other subtest. It
is a one-line, test-only change.
## Testing
- Red on the merge base: with 127.0.0.1:6222 held by a plain listener,
`TestPubsub/CloseIdempotent` fails after 10.01 s with the CI message.
- Green on this branch: with the port held, `go test ./coderd/nats/...`
passes.
- `go test ./coderd/nats/... -count=3` and `make pre-commit` pass.
- Remote dogfood UAT ran on the tested SHA
|
||
|
|
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. |
||
|
|
1a65385a4b |
fix: log workspace shutdown reasons for SSH connections (#30515)
Workspace stops and deletes closed active SSH connections with generic shutdown or process-exit reasons. This obscured the workspace action that ended a connection and made related logs harder to correlate. The agent’s SSH tracking and logging now identify connections closed by the SSH server as server_shutdown, while preserving earlier client or network disconnects. The agent includes the client session ID when available for ordinary sessions and connections used only for port forwarding. Coderd now enriches shutdown reasons when it processes connection reports. It translates server_shutdown into workspace_stopped when the latest build is a running or successful stop or delete requested before the connection closed. Coderd persists the enriched reason and logs the build reason, transition, and build ID alongside the client session ID. Unavailable or unrelated build state retains the generic shutdown reason. The CLI now logs shutdown context once per stop or delete build through its existing workspace watcher. This includes the client session ID when available and preserves the existing graceful SSH shutdown behavior. Regarding the PTY connections, when the agent shut down, the reconnecting PTY server closed each PTY and its attached connections, and the connection handler then returned without an error. The server therefore logged and reported those connections as graceful closes. Its fallback for a forced shutdown reported a free-form reason that coderd did not recognize, so coderd never refined either case into a workspace shutdown. We change the reconnecting PTY server so that it reports any connection that ends after the agent begins shutting down as a server shutdown initiated by the agent, and its log keeps the client session ID. The forced shutdown fallback now reports the same standard reason, which lets coderd translate it into a workspace stop or delete in the connection log, as it already does for SSH. A client that closes its connection before the shutdown still keeps its graceful reason. Regression tests cover shutdown attribution, fallback behavior, CLI logging, and PostgreSQL persistence with and without a client session ID. The test logging helper also synchronizes with cleanup to prevent logging after a test completes - resolves https://linear.app/codercom/issue/CLIENT-665/close-workspace-tunnel-with-a-reason <!-- If you have used AI to produce some or all of this PR, please ensure you have read our [AI Contribution guidelines](https://github.com/coder/coder/blob/main/contributing/AI_CONTRIBUTING.md) before submitting. --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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. |
||
|
|
f4cd0deccb |
feat!: report template insights session usage per app (#29796)
Report template insights session usage per app instead of five fixed family rows, with registry names and icons. - Add per-app rows for reported session apps (VS Code, Cursor, GoLand, Zed, etc.); unused apps are omitted - Replace `type` (`builtin`/`app`) with `method` (`ssh`, `reconnecting_pty`, `port_forwarding`, `workspace_app`); session methods are derived from the app name until #31012 stores them - Add `usage_total_seconds` to count each user's active minutes once, and use it as the UI bar denominator so overlapping apps can exceed 100% - Merge template apps sharing a slug into one row across templates, using the newest display name and icon - Rename Web Terminal slug from `reconnecting-pty` to `reconnecting_pty` - Cap the response at the 64 busiest unregistered apps and fold the rest into "Other apps", flagged with `seconds_is_upper_bound` ("Up to" in the UI) - Add `unknown` and `overflow` accounting rows with explanatory tooltips, and a fallback icon for apps without one - Remove the unused `codersdk.UnionByFamily` helper from the Go SDK BREAKING CHANGE: `report.apps_usage` in `GET /api/v2/insights/templates` no longer returns the fixed five rows, family slugs, or previous display names. Consumers must update. Part of CLIENT-642 Prometheus metrics handled separately in #29906 |
||
|
|
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. |
||
|
|
452654d07f | test(coderd/database): use subtest context in TestProjectSkillQueries (#31011) | ||
|
|
de42c37f76 |
refactor(coderd): share chat creation with in-process callers (#30027)
Right now, the only way to create a chat is through `POST /api/v2/chats`. That's fine for clients, but an integration running inside coderd (say, a Slack bot) would have to store or mint an API key just to call its own server. So, we'll pull chat creation out of the handler into a shared function, and add `api.CreateChatAsUser` for in-process callers. They get the same validation, errors, and audit entry as the endpoint, and the endpoint's behaviour doesn't change. This is the same pattern `chatCreateWorkspace` already uses to let chatd create workspaces as a user. I've also exported the chat daemon for in-process callers. Chat errors are now just values that carry the endpoint's status, message, and cause, so in-process callers can use `errors.As` on them (e.g. to spot a prompt hook denial) rather than decoding an HTTP response. The audit entry is written in the background, as auto-archive already does, rather than through a fake request. As with an API key, a dormant user is activated on use, whilst a suspended or deleted user gets a 403. The PRs above this one do the same for sending, interrupting, and updating chats. |
||
|
|
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. |