Commit Graph
4855 Commits
Author SHA1 Message Date
Jaayden Halko 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
2026-10-21 19:47:50 +07:00
Michael Suchacz 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.
2026-10-21 11:20:12 +00:00
Michael Suchacz 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.
2026-10-21 10:13:45 +00:00
Michael Suchacz 82288467d9 refactor(coderd/x/chatd/chatstate): share one outstanding tool-call scan (#30883) 2026-10-21 10:34:57 +02:00
Michael Suchacz 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.
2026-10-21 08:23:28 +00:00
Michael Suchacz 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.
2026-10-21 07:45:19 +00:00
Sas Swart 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.*
2026-10-21 06:17:12 +00:00
Michael Suchacz 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.
2026-10-21 05:03:58 +00:00
Michael Suchacz 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.
2026-10-20 22:11:25 +00:00
Michael Suchacz 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.
2026-10-20 21:43:20 +00:00
Michael Suchacz 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.
2026-10-20 21:10:40 +00:00
Michael Suchacz 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.
2026-10-20 20:54:18 +00:00
Michael Suchacz 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.
2026-10-20 20:32:25 +00:00
Michael Suchacz 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.
2026-10-20 20:10:13 +02:00
Michael Suchacz 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 451c4ecd16 and passed. It
repeated red and green with 127.0.0.1:6222 and 0.0.0.0:6222 held, ran
`-count=5` with no port held, and showed that an overlay whose second
`Close` returns an error makes the subtest fail, so it still checks
idempotent `Close`.

Polish and the test audit made no changes, so both stayed inside the
implementation diff (`coderd/nats/pubsub_test.go`).

Draft #30759 carries the same one-line edit as a drive-by, so whichever
lands second merges cleanly.

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

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

## Why it is safe

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

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

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

## Validation

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

## Stack

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

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

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

It also deletes two copies:

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

## Why it is safe

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

## Review focus

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

## Validation

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

## Stack

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

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

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

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

## Why it can fail

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

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

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

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

## Validation

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

## Stack

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

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

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 11:02:53 +02:00
Ethan 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.
2026-10-20 15:41:25 +11:00
Michael Suchacz 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.
2026-10-20 01:48:51 +02:00
Michael Suchacz 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.
2026-10-20 00:30:05 +02:00
Faur Ioan-AurelandClaude Opus 5.5 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>
2026-10-19 23:06:41 +03:00
Michael Suchacz 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.
2026-10-19 19:15:56 +02:00
Ehab Younes 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
2026-10-19 17:59:18 +03:00
Michael Suchacz 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.
2026-10-19 14:01:11 +00:00
Michael Suchacz 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.
2026-10-19 12:38:17 +00:00
Garrett Delfosse 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.
2026-10-19 11:32:26 +00:00
Jaayden Halko 452654d07f test(coderd/database): use subtest context in TestProjectSkillQueries (#31011) 2026-10-19 19:05:27 +08:00
Ethan 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.
2026-10-19 14:37:36 +11:00
Ethan 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.
2026-10-19 14:02:47 +11:00
Ethan e09407c366 fix(coderd): commit chat workspace bindings with dependent state (#30663)
Relates to CODAGT-1330

When a workspace rebuild gives a chat a new agent, chatd saves the new
agent binding and then re-pins the chat's context to that agent. These
committed separately, and a failed re-pin was just logged. The next turn
would see the new agent already bound, so it never re-pinned, and the
chat kept injecting the old agent's context.

`create_workspace` had a similar problem. It bound the chat to the
workspace after the workspace was committed, and if that failed it
logged an error and still reported success. The workspace was left
orphaned, and the next call would just create another one.

To fix, we'll commit the binding and the re-pin in one transaction.
`create_workspace` now binds the chat inside the workspace create
transaction. I've done this with the unused `postCreateInTX` hook in
`createWorkspace`, which I've renamed to `postBuildInTX` and moved after
the build insert so it has the build ID.
2026-10-19 14:02:47 +11:00
Ethan 096db5de02 fix(coderd/x/chatd): return MCP OAuth token database errors (#30662)
Relates to CODAGT-1330

Before chatd connects to MCP servers, it refreshes any expired OAuth
tokens. If saving a refreshed token failed, we'd log it and use the new
token for that turn only. A failed write when marking a revoked grant
for reconnect, and a failed re-read after losing a refresh race, were
also just logged, and the turn connected without the token.

To fix, we'll return those database errors so the prepare retry runs. A
transient error from the OAuth provider still keeps the current token
for the turn, like it does today.

This doesn't help if the provider already rotated the refresh token and
the save fails, since the new token is lost either way. On retry, a
provider that rotates tokens rejects the old one and we mark the token
for reconnect, which is where we'd end up today anyway, just a turn
earlier.
2026-10-19 14:02:47 +11:00
Ethan aedd998db6 fix(coderd/x/chatd): return agent and subagent lookup database errors (#30661)
Relates to CODAGT-1330

When chatd prepares a turn for a chat with a workspace, it looks up the
chat's agent so the agent binding is up to date before anything uses it.
That lookup dropped every error, so a failed database read looked the
same as a chat with no agent, and the turn carried on with whatever
binding the chat already had. If reading the chat's bound agent failed,
we'd also log it and resolve a new agent from scratch. Separately, a
failed read of the computer use provider setting hid the `computer_use`
subagent type from `spawn_agent` for that turn.

To fix, we'll just return the database error, so the prepare retry runs.
Not having a usable agent is still a normal result, e.g. the chat has no
workspace, the workspace was deleted, or more than one agent uses the
chat suffix, so a broken template doesn't fail every turn. A computer
use provider we don't recognise still just makes `computer_use`
unavailable.

This follows on from #30492.
2026-10-19 14:02:46 +11:00
Michael Suchacz 121393842c test(coderd/notifications/dispatch/smtptest): renew the expired TLS test certificate (#30922)
Renews the SMTP test server certificate in
`coderd/notifications/dispatch/smtptest/fixtures`. It expired on
2026-10-18 at 13:36:08Z, so the TLS cases of `TestSMTP`
(`TLS:_self-signed`, `TLS:_self-signed_+_SNI`, `PLAIN_auth_and_TLS`)
fail in `test-go-pg-17` and `test-go-race-pg` on every PR.

## What changed

- `server.crt`: the committed `server.csr`, re-signed with the committed
CA (`ca.crt`, `ca.key`) and `v3_ext.conf`. It is valid until 2034-07-12,
a day before the CA expires. The key pair, subject, and extensions (SANs
`myserver.local`, `www.myserver.local`, `127.0.0.1`) are unchanged. Only
the serial, the validity, and the signature differ.
- `ca.srl`: the next serial, which the new certificate uses.
- `generate.sh`: it issued the server certificate for 825 days, and
2024-07-15 plus 825 days is 2026-10-18. It now uses 3649 days, a day
less than the CA's 3650.

The command, run in the fixtures directory:

```sh
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -set_serial 0x0330C6D190E3FE649DAFCDA2F4D765E2D29328DF -out server.crt -days 2824 -extfile v3_ext.conf
```

With OpenSSL 3.0.2, `-CAserial ca.srl` issued a random serial and left
`ca.srl` unchanged, so the command sets the next serial explicitly.

## Review focus

Re-signing keeps the CA and the server key, so no other fixture or test
changes. The one choice is the validity: about 7.7 years, ending a day
before the CA.

## Validation

| Check | `main` | This PR |
|---|---|---|
| `openssl x509 -noout -dates` | `notAfter=Oct 18 13:36:08 2026 GMT` |
`notAfter=Jul 12 14:24:37 2034 GMT` |
| `openssl verify -CAfile ca.crt server.crt` | `certificate has expired`
| `server.crt: OK` |
| `go test ./coderd/notifications/dispatch/... -run TestSMTP -count=1` |
the 3 TLS cases fail with `x509: certificate has expired or is not yet
valid` | pass |

`go test ./coderd/notifications/... -count=1` passes, including
`notifications_test.go`, the other user of `smtptest`. A text diff of
the old and new certificates (`openssl x509 -noout -text`) shows only
the serial, the dates, and the signature.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-18 18:46:46 +02:00
Jaayden Halko e289c6fe01 feat: add project skill API routes (#30827)
Adds experimental routes for managing a chat project's skills under
`/api/experimental/organizations/{organization}/chats/projects/{project}/skills`:
list, create, get, update (PATCH) and delete by skill name.

The handlers reuse the shared skill create and update path from the
personal and organization skill APIs. Reading needs `chat_project:read`
on the project and writing needs `chat_project:update`; callers without
access get 404, matching the project instructions routes. Duplicate
names and the 100-skill-per-project cap return 409. Writes are audited
as `chat_project_skill` with the skill name as the target. The SDK gains
the matching `ExperimentalClient` methods.

Stack (merge top to bottom):
- #30826
- #30827 👈
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882
- #30884
2026-10-18 13:16:23 +07:00
Jaayden Halko a379c849da feat: add project skill queries and authorization (#30826)
Adds the storage and authorization layer for chat project skills. The
`skills` table already allows a `project_id` owner (migration 000621);
this adds the queries for it and authorizes them through the parent chat
project, the same way project instructions work.

- New queries in `skills.sql`: insert, get by name, list metadata,
update (COALESCE on description, content and enabled), delete, and
`GetProjectSkillByIDForUpdate` for the shared update lock.
- dbauthz checks `chat_project:read` on the project for reads and
`chat_project:update` for writes. `authorizeChatProjectInstructions`
became `authorizeChatProjectConfig`, shared by instructions and skills.
`Skill.RBACObject()` still denies project rows so nothing reaches them
without going through the project.
- Audit: new `chat_project_skill` resource type (enum-only migration
000624), `AuditableChatProjectSkill`, and the usual
diff/request/table/FriendlyString/AuditFilter wiring. The API that emits
these entries comes in the next PR.

Stack (merge top to bottom):
- #30826 👈
- #30827
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882
- #30884
2026-10-18 12:58:39 +07:00
Michael Suchacz 54ba766f77 refactor(coderd/x/chatd): move turn preparation helpers into turn_environment.go (#30870)
Moves the helpers that `buildTurnEnvironment` uses from `chatd.go`, and
the `turnEnvironment` type from `generation.go`, into
`turn_environment.go`. The code moves without edits. Only the import
blocks change.

The moved helpers build the turn's workspace context, tool set, system
prompt, and skills. `chatd.go` goes from 4,396 to 3,131 lines, and
`turn_environment.go` from 1,187 to 2,520.

To check that only imports changed, compare the removed lines with the
added lines:

```sh
B=mike/chatd-turn-env-split/receiver-name
H=mike/chatd-turn-env-split/move-turn-helpers
git fetch origin "$B" "$H"
diff <(git diff "origin/$B" "origin/$H" | grep '^-[^-]' | cut -c2- | sort) \
  <(git diff "origin/$B" "origin/$H" | grep '^+[^+]' | cut -c2- | sort)
```

The output lists only import lines. `git diff --color-moved` also marks
the blocks as moved.

After this PR, the stack has the same code as #28757 (head
`6ee4ecb35f8`, on current `main`), except that `turn_environment.go`
names the `*Server` receiver `p` (#30869).

Validation: `go build ./coderd/... ./enterprise/...` and `go vet
./coderd/x/chatd/...` pass, and the pre-commit hook passed. `go test
./coderd/x/chatd/... ./enterprise/coderd/x/chatd/... -count=1` passed in
all packages except one known load flake,
`TestChatTurnStopsAtStepLimit/Default` (timeout while seeding 1,199
steps). A rerun of `./coderd/x/chatd` passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 22:08:44 +00:00
Michael Suchacz 8065f84af2 refactor(coderd/x/chatd): name the Server receiver p in turn_environment.go (#30869)
Renames the `*Server` receiver in `turn_environment.go` from `server` to
`p`. Nothing else changes: each changed line differs only in that name
(`git diff --word-diff` shows it).

#30870 moves helpers from `chatd.go` into this file. Those helpers name
the receiver `p`, as do 22 files in the package, and revive's
`receiver-naming` rule allows one receiver name per type in a file. With
this rename first, the move needs no edits.

Validation: build and vet pass, the `TestBuildTurnEnvironment*` tests
pass, and the pre-commit hook (`lint/go` with revive) passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:58:06 +00:00
Michael Suchacz 752da8d60f test(coderd/x/chatd): remove end-to-end tool policy tests (#30868)
Removes seven end-to-end tool policy tests from `chatd_test.go` (949
lines). The table test from #30867 checks the same policy at
`buildTurnEnvironment`.

- `TestPlanModeSubagentChatExcludesAskUserQuestion`
- `TestPlanModeRootChatAllowsApprovedExternalMCPTools`
- `TestExploreSubagentIsReadOnly`
- `TestExploreChatUsesPersistedMCPSnapshot`
- `TestExploreChatSendMessageCannotMutateMCPSnapshot`
- `TestRootExploreChatStaysBuiltinOnlyAtRuntime`
- `TestRootExploreChatExcludesWebSearchProviderToolAtRuntime`

Each test started chatd with a fake model server, ran a turn, and read
the tool names from the model request. Each had its own fixture.

**Why removal is safe:** a test was removed only if other tests still
catch every mutant it caught. On `main`, 9 mutants were caught only by
these tests, and the table test catches all 9. Review and two audits of
every check in these tests then found nine more regressions that only
these tests caught, and #30867 now covers each one. That includes the
`TestExploreChatSendMessageCannotMutateMCPSnapshot` scenario: the
`ExploreChildAfterMCPReplacement` case calls `SendMessage` on an Explore
child chat, checks the stored MCP servers, and builds the next turn.
`TestEditMessage_MCPServerIDs` still covers the same guard through
`EditMessage`. The first mutation run used an earlier `main` and the
#28757 branch, which removed the same lines.

**Tradeoff:** the table test stops at the result of
`buildTurnEnvironment`. No test now checks plan mode and Explore tool
lists in the model request itself. The audits found one mutant that only
these tests catch: a branch in `generation.go` that clears the active
tools of Explore chats just before the model call. The same change
without the Explore condition fails `TestMCPToolSearchGenerationFlows`,
because the step from `buildTurnEnvironment` to the model request is the
same for every mode. Only an end-to-end test like the ones this PR
removes would catch the Explore-only form, so this PR does not add one.

Validation: build and vet pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:47:32 +00:00
Michael Suchacz c42c9af23a test(coderd): cover the turn tool policy at buildTurnEnvironment (#30867)
Adds `TestBuildTurnEnvironmentToolPolicy`, a table test of the tool
policy at the place chatd applies it: the result of
`buildTurnEnvironment`. #30868 then removes seven end-to-end tests that
checked the same policy through a full turn.

The six cases (`Root`, `PlanRoot`, `PlanChild`, `ExploreRoot`,
`ExploreChild`, `ExploreChildAfterMCPReplacement`) share one fixture:

- three MCP servers that every chat selects: approved for plan mode, not
approved, and approved with a tool allowlist
- two MCP servers that no chat selects: one Force On and one ordinary
- one inline MCP server on each root chat, one without
`allow_in_subagents` on the parent of the child chats, and one workspace
MCP server
- a model with the `web_search` provider tool

Each case builds the tool definitions with
`chatloop.BuildToolDefinitions`, the same function the chat loop uses
for the model request. It then compares the tool names, active tools,
and provider tools with the case. It also searches the full system
prompt for the plan mode and Explore mode overlays and for the root-only
`propose_plan` instruction.

`ExploreChildAfterMCPReplacement` first calls `SendMessage` with a
request to replace the Explore child's MCP servers with the unselected
one. The test checks that the stored selection does not change, then
builds the next turn from the stored chat and messages. `PlanRoot` runs
its `spawn_agent` tool and checks that the general sub-agent keeps the
plan mode.

The PR also adds:

- `TestCreateExploreChatPreservesMCPSelection`: `Server.CreateChat`
stores the MCP servers that a root Explore chat selects
- a plan-mode request in `TestPostChats/Success`: `POST /chats` stores
the requested plan mode
- `TestBuildTurnEnvironmentSplitsPendingUserRowsFromCompactionPrompt`
and a project instructions assertion in `TestBuildTurnEnvironmentMemory`

## Validation

- For each new assertion, Xum removed the code that the assertion checks
and saw the test fail. On this branch, for example, removing the Explore
overlay in `chatd.go` fails `ExploreRoot` and `ExploreChild`.
- In a mutation run, these tests catch 7 mutants (copies of the code
with one policy branch removed) that no test on `main` caught. Two
examples: root Explore chats get MCP tools, and Explore chats get
workspace MCP tools. That run used an earlier `main` and the #28757
branch, which has the same test code.
- Review found regressions that only the end-to-end tests removed in
#30868 caught. Xum applied each one to this branch: the first version of
these tests passes, and the current version fails in the cases below.
- Two independent audits then listed every check in the seven removed
tests, including implicit ones such as a scripted `spawn_agent` call,
and tried a mutant for each check without an obvious replacement. A
mutant counts as a gap only if a removed test fails with it and the rest
of `coderd/x/chatd/...` plus the chat, MCP, Explore, and plan tests in
`coderd` and `enterprise/coderd` pass. The audits found the last two
rows. They also found one gap that this PR leaves open; #30868 explains
why.
- A line coverage comparison found 4 statements in `coderd/x/chatd/...`
that only the seven removed tests run. All 4 are error returns.

| Regression | Failing cases |
|---|---|
| Explore chats get `edit_files` | `ExploreRoot`, `ExploreChild` |
| Explore children keep only the MCP servers approved for plan mode |
`ExploreChild`, `ExploreChildAfterMCPReplacement` |
| `SendMessage` replaces an Explore child's MCP servers |
`ExploreChildAfterMCPReplacement` |
| Chats outside Explore mode get every enabled MCP server in the
organization | `Root` |
| A plan-mode child gets the root-only `propose_plan` instruction |
`PlanChild` |
| A plan-mode root chat does not get `spawn_agent` | `PlanRoot` |
| `Server.CreateChat` drops the MCP servers of a root Explore chat |
`TestCreateExploreChatPreservesMCPSelection` |
| A general sub-agent of a plan-mode chat loses the plan mode |
`PlanRoot` |
| `POST /chats` drops the requested plan mode | `TestPostChats/Success`
|

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:34:52 +00:00
Michael Suchacz a41e5ae6eb refactor: rename prepareGeneration to buildTurnEnvironment (#30866)
Renames the turn preparation step after what it returns: the environment
for one turn. Only names change, plus one small change to how callers
release the environment.

- `generation_preparer.go` becomes `turn_environment.go`, and its test
file becomes `turn_environment_internal_test.go`. GitHub shows both as
renames. A comment in `compactionTriggers.test.ts` that names the test
file follows the rename.
- `prepareGeneration` becomes `buildTurnEnvironment`, and its result
type `generationPrepared` becomes `turnEnvironment`. Four
`TestPrepareGeneration*` tests become `TestBuildTurnEnvironment*`.
- The `Cleanup` field becomes the unexported `cleanup`, and callers use
`Close()`. `Close()` does nothing on a zero value.

The type stays in `generation.go` for now. #30870 moves it next to
`buildTurnEnvironment`.

Validation: build and vet pass, the renamed tests and the `toolinput`
tests pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:20:00 +00:00
Michael Suchacz 2088618930 chore(coderd/x/chatd): log workspace agent lookup errors in turn preparation (#30865)
Logs the error from `getWorkspaceAgent` at debug level in turn
preparation. `prepareGeneration` discarded it.

The turn still goes on without the agent, as before. The agent only adds
its OS and working directory to the instruction header.

Validation: build and vet pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 20:59:22 +00:00
Michael Suchacz 5ccbef037b refactor(coderd/x/chatd): remove the no-op allowedBehaviorToolNames filter (#30864)
Removes `allowedBehaviorToolNames`, `allToolNames`, and
`TestAllowedBehaviorToolNames`, and the active-name check they fed in
`appendDynamicTools`.

The check never skipped a tool. `appendDynamicTools` returns early for
Explore mode and plan mode, so at the check, `allowedBehaviorToolNames`
always returned every tool name. A dynamic tool that shares a built-in
tool's name is still dropped with a warning.

Validation: `go test ./coderd/x/chatd/ -run
'Dynamic|AllowedExplore|StopAfterPlan'` passes, and the pre-commit hook
(build, `lint/go`, `lint/go/new-code`) passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 20:44:13 +00:00
J. Scott Miller 939146b077 fix(coderd/x/chatd): reset stream history only if after_id is deleted (#29808)
Fixes
[CODAGT-1175](https://linear.app/codercom/issue/CODAGT-1175/prevent-chat-stream-resets-from-loading-full-history)

**tl;dr:** The chat stream no longer sends the full history on every
connect when a chat contains old edit tombstones.

On its first sync, the chat stream WebSocket treated any soft-deleted
message (edits create them) as a history reset and sent `history_reset`
plus every message, ignoring `after_id`. The client replaced its
paginated cache with that history, so every connect, reconnect and PWA
resume of a long chat that had ever been edited rendered the whole
transcript. A dogfood chat of about 3.2k messages sent 7.1 MB per
connect.

`historyResetRequired` in `stream_loop.go` now resets on the first sync
with an `after_id` only if message `after_id` is missing or deleted.
Messages are only deleted as a suffix of the chat (an edit deletes the
edited message and every later one), so while that message is live the
client holds none of the deleted rows. Otherwise the stream sends only
live messages newer than `after_id`, and `messageEvents` never sends
tombstones as messages. Deletions after the first sync still reset.
`stream_loop_internal_test.go` covers the initial-sync cases and the
deletion of a streamed message after the first sync,
`TestSubscribeAfterMessageIDWithEdit` runs a real `EditMessage` against
the database, and `ARCHITECTURE.md` gets TODOs for the new rule.

> Generated by Coder Agents on behalf of @jscottmiller.
2026-10-16 15:40:17 -05:00
Bobby Ho 764e67bcff feat: expose skipped and canceled script outcomes in coderd and the Build Timeline (#30875)
feat: expose skipped and canceled script outcomes

Add `skipped` and `canceled` statuses across the Agent API, database,
SDK, and Build Timeline for startup scripts.

- Store and return both outcomes, preserving zero-duration timings,
  and reject unknown statuses. Rollbacks rewrite the new outcomes to
  `exit_failure` with exit code 255.
- Add typed legends, outcome-specific tooltips, and keyboard-accessible
  bars. Fix timeline crashes for `timed_out` and `pipes_left_open`.
- Bump the Agent API to v2.15 while agents continue using v2.14.
  Add API, migration, and Storybook coverage.

First of two PRs for PLAT-550. Agents do not emit the new statuses yet;
a follow-up after #30765 enables reporting. Shutdown scripts remain
outside the timeline, and agent health and badge rules are unchanged.

Refs: https://linear.app/codercom/issue/PLAT-550/phase-3-expose-skipped-and-canceled-script-outcomes
2026-10-16 15:55:28 +00:00
Asher 899d25a5b1 feat: add byte tracking to ssh and pty connections (#30389) 2026-10-16 00:21:40 -08:00
Steven Masley 357e81b470 feat(coderd): list workspace secrets on workspace build audit entries (#30459)
Workspace build audit entries now list the build's secrets: name, env var, file path, and whether the request set the secret or it was carried forward from the previous build. Values are never included. Follows up on [this review thread](https://github.com/coder/coder/pull/30250#discussion_r4199276004).

**Stack** (design decisions in #30248)
1. #30248 Database schema, queries, and RBAC
2. #30249 Encryption at rest
3. #30250 Set secrets on workspace builds
4. #30251 Deliver secrets to the agent
5. #30252 Docs
6. #30388 List a build's secrets
7. **#30459 Audit a build's secrets (this PR)**

- Every workspace build audit entry includes its secrets, including builds that fail and orphaned deletes.
- The entry lists the build's full set of secrets. Removed secrets show up only by being absent.
- The three places that write build audit entries now share one helper instead of building the fields by hand.

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

- `audit.AdditionalFields` gains `workspace_secrets`: `name`, `env_name`, `file_path`, and `source` (`request` or `carry_forward`) for each secret.
- New `audit.WorkspaceBuildFields` is used for job success and failure in `provisionerdserver`, and for the orphan delete completed in `workspacebuilds.go`.
- `source` comes from the `workspace_secrets.source` column (#30248), set by `persistSecrets` (#30250).

</details>

<details>
<summary>Decision log</summary>

(existing decision log, unchanged)

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 18:03:15 -05:00
George K 6d34557d74 feat: add script ordering adoption telemetry (#30860)
Count `coder_script_order` declarations and literal `rule` blocks in
coderd from the existing START plan in
`CompletedJob.TemplateImport.Plan`,
including child modules, without multiplying counts by resource or
module instances. Persist these counts per template version on
successful import after START plan graph validation, without changing
the provisioner API.

Report a deployment-wide `script_order_summary` with the number of
templates using script ordering and total declaration and rule
counts. Include only active, successfully imported versions of
non-deleted templates so repeated imports do not inflate
adoption. Elect one reporting replica per snapshot period and report
explicit zeros when no templates use ordering.

The summary contains only aggregate counts, without template
identifiers or rule contents. Dynamic rule blocks are not counted
because Terraform omits them from configuration JSON.

Configuration-decoding failures are logged and skip updating the
counts without independently failing the import. Script-order summary
collection failures are logged and omit that summary while allowing
the rest of the snapshot to proceed.

Refs: https://linear.app/codercom/issue/PLAT-551
2026-10-15 15:42:33 -07:00