Commit Graph
5 Commits
Author SHA1 Message Date
Michael Suchacz 7dee434315 test(coderd/x/chatd): fold taskTestFixture into workerTestFixture (#30924)
`taskTestFixture` in `tasks_test.go` repeated `workerTestFixture` field
for field, with the same seed rows, and carried its own copies of five
chat setup helpers, `publishChatUpdate` and two message builders. This
PR deletes the fixture and the copies and moves the 39 task, hook and
turn-trace tests that built it onto `workerTestFixture` and the shared
helpers. It also drops the fixture's API key row and the `apiKeyID`
parameter of `userTextMessage`, which nothing read.

**Why it is safe**

The copies differed from the shared helpers in two ways, and both are
kept:

- **Clearing the recorder.** The copies cleared the recording pubsub
after setup, and `interruptChat` cleared it before interrupting, so
assertions on published events see only what the code under test
published. `workerTestFixture.pubsub` is now that recorder (from the
layer below), and the shared helpers clear it at the same points. No
worker test reads the fixture recorder's events, so the extra clears do
not change them.
- **The deadline argument.** The task copy of `forceExecutionState` took
an explicit requires-action deadline. `forceExecutionStateWithDeadline`
takes it as a pointer (nil keeps the current one) for
`setRequiresActionDeadline` and the one call that cleared an expired
deadline. The other three callers passed an empty deadline for chats
that never had one, so they call `forceExecutionState`.

The rest of the move keeps the old behavior:

- `startRealTaskWorker` now starts from `testOptions`, which holds the
same values. It unsets the recording task starter so the worker builds
its real one, as before.
- No chatd code reads the fixture's API key. The synthetic gateway key
is looked up by its own token name.

After the change, `rg
'taskTestFixture|taskUserTextMessage|taskAssistantToolCallMessage|f\.apiKey'
coderd/ enterprise/` finds nothing.

**Review focus**

The `clear()` placement in `helpers_test.go`. Setup helpers clear when
they finish, and `interruptChat` clears before it runs.

**Validation**

Same commands as the layer below: the 142 top-level tests in the ten
files listed there, run from `go test -c ./coderd/x/chatd/` binaries
(plain and `-race`) with `-test.count=1 -test.parallel 4`.

| Head | Plain | `-race` |
|---|---|---|
| `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races |
| this PR | 142 passed | 142 passed, no data races |

The pre-commit hook passed.

**Stack**

The stack folds the task test fixture into the shared worker test
fixture.

1. #30923 reuse `recordingPubsub` in the task test fixture
2. #30924 fold `taskTestFixture` into `workerTestFixture` (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 22:48:18 +00:00
Michael Suchacz f0b6bf12ac test(coderd/x/chatd): reuse recordingPubsub in the task test fixture (#30923)
`tasks_test.go` kept its own copy of the recording pubsub,
`taskRecordingPubsub` (59 lines), next to `recordingPubsub` in
`helpers_test.go`. This PR adds the three things the copy had (`clear`,
a `published` snapshot and an `onPublish` hook) to `recordingPubsub`,
points the task fixture at it, and deletes the copy. The task fixture
now reaches the raw pubsub through the embedded field, so its `rawPS`
field goes too.

**Why it is safe**

- The added methods behave like the copy's: `onPublish` runs outside the
lock and before the inner `Publish`, `clear` drops the recorded events,
and `published` returns a copy taken under the lock. It replaces the
copy's `events()`, which would collide with the existing `events` field.
- `recordingPubsub` embeds the full `dbpubsub.Pubsub`, so subscriptions
reach the same inner pubsub the copy forwarded `SubscribeWithErr` to.
Servers built by the task helpers still get the raw pubsub.
- `watchEvents` is the existing `recordingPubsub` method. It filters the
same way the copy did, reading under the lock instead of from a
snapshot.
- After the change, `rg 'taskRecordingPubsub|taskPublishedEvent|rawPS'
coderd/` finds nothing.

**Review focus**

The turn-trace tests set `f.pubsub.onPublish` while holding
`f.pubsub.mu`. Both names are unchanged, and `Publish` still reads the
hook under that lock.

**Validation**

I built the package test binary with `go test -c ./coderd/x/chatd/` (and
with `-race`). Ten files use either fixture: `tasks_test.go`,
`hooks_internal_test.go`, `turn_trace_internal_test.go` and the seven
`workerTestFixture` files. I ran the 142 top-level tests in the ten
files with `-test.count=1 -test.parallel 4`.

| Head | Plain | `-race` |
|---|---|---|
| `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races |
| this PR | 142 passed | 142 passed, no data races |

The pre-commit hook passed.

**Stack**

The stack folds the task test fixture into the shared worker test
fixture.

1. #30923 reuse `recordingPubsub` in the task test fixture (this PR)
2. #30924 fold `taskTestFixture` into `workerTestFixture`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 20:49:14 +00:00
Michael Suchacz 39c4bd6ced refactor(coderd/x/chatd): drop the unused runnerCtx from the runner debug turn (#31010)
Deletes `runnerDebugTurn.runnerCtx` and the context parameter of
`newRunnerDebugTurn`. The field's only reader was the
`LaunchRunHeartbeat` call in `ensureLocked`, which #30988 deleted with
the run heartbeats, so nothing has read it since.

**Why it is safe:** the constructor set the field and no code read it.
The debug turn still uses the context of each call to `Ensure`,
`Context` and `Finalize`, which this PR does not change. `runner.go` and
10 tests stop passing a context, and four of those tests drop the
`context.WithCancel` that they created only for this parameter.

Validation:
- `go build ./coderd/x/chatd/...` and `go vet ./coderd/x/chatd/...`
pass.
- The 25 chatd debug-run tests, `TestRecordGenerationFinishFailure`,
`TestSessionStartDispatchFailureFinishesGeneration` and
`TestStartGeneration_CancelsDeletedToolCallsOnAgent` pass under `-race`.
- `golangci-lint run --fix=false ./coderd/x/chatd/` reports 0 issues,
and the pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. #30988 Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. #30995 Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. #30934 Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. #30981 Share one finalize-once lifecycle between the stream wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. This PR: Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-22 07:55:42 +00:00
Michael Suchacz 4b9880afa6 feat: add --chat-hook-allow-insecure to allow plain HTTP chat hook URLs (#27896)
Adds a hidden `--chat-hook-allow-insecure` /
`CODER_CHAT_HOOK_ALLOW_INSECURE` deployment option (default `false`)
that allows the chat lifecycle hook URL to use plain HTTP for any host.

The HTTPS requirement is enforced at two points, and the flag relaxes
both: `DeploymentValues.Validate()` rejects `http` hook URLs at startup,
and the hook dispatcher's `validateHookURL` allows `http` only for
loopback hosts. With the flag set, any-host `http` is accepted; the
host, fragment/userinfo, secret, and timeout checks are unchanged, and
non-http(s) schemes still fail. This removes the need for an HTTPS
reverse proxy when testing a hook consumer on a trusted network.

Following security review feedback, the flag description and docs state
that plain HTTP lets an on-path attacker forge hook responses (which
control agent execution), and `coder server` logs a startup warning
(with a redacted hook URL) when hooks run over plain HTTP.

Docs, generated API types, and the server config golden are updated
accordingly.

> Mux acted on Mike's behalf to create this PR.
2026-08-05 22:41:17 +02:00
Michael Suchacz c17bed25e0 feat: wire chat lifecycle hooks into chatd (#27429)
Wires chat lifecycle hooks into chatd, gated by the
`agent-lifecycle-hooks` experiment. Part of the lifecycle hooks stack
(#27401, #27428, #27430). See `docs/admin/setup/chat-lifecycle-hooks.md`
for the consumer-facing contract.

## Summary

When a hook URL is configured, chatd dispatches `session_start`,
`user_prompt_submit`, `pre_tool_use`, `post_tool_use`, `pre_compact`,
`post_compact`, and `stop` events to the consumer and applies its
responses.

## Design

- **Stateless**: Coder stores no hook dispatch or decision state.
Delivery is at least once; consumers deduplicate on stable payload
identifiers (chat ID, event type, tool-use ID) and answer duplicates
with the same decision.
- **Admission-time prompt effects**: `user_prompt_submit` dispatches
exactly once per submission (create, send, queue, edit, subagent spawn)
and folds its effects into the stored prompt as typed message parts:
original-or-overridden user parts, then model-only `hook-context`, then
a user-visible `hook-notice`. Hook context is stripped from every
client-facing conversion; hook notices are excluded from model prompts.
The server rejects hook parts in client-submitted content.
- **Tool gating**: `pre_tool_use` allow can override tool input; deny
becomes a synthetic denied tool result, with any returned model context
persisted as a model-only transcript row so it never reaches clients.
The denial text identifies an external policy (the deployment's
lifecycle hook) as the source and marks the decision as persistent, so
the model explains the denial instead of retrying it or misreporting it
as an infrastructure failure.
- **Fail closed**: a dispatch failure rejects the triggering request or
moves the chat to the error state in the same transaction as the
affected step, so a runnable state is never published with unapproved
content.
- **Admission before persistence**: `pre_tool_use` is dispatched for the
calls the model produced, before the assistant message is stored. See
"Staged tool admission" below.
- **Fresh dispatch per tool call**: every non-provider-executed tool
call is decided by its own `pre_tool_use` dispatch; Coder never reuses
an earlier decision on the consumer's behalf. Retries re-dispatch the
same logical event.

## Structure

All hook dispatch flows through one seam: entry points build a
`chathooks.Chat` (chat identity) and a `chathooks.Message` (event
details) and call `Trigger.Trigger`, the only component that talks to
the dispatcher. The integration lives in the `coderd/x/chatd/chathooks`
subpackage, split by responsibility:

- `trigger.go`: the trigger seam; builds the wire envelope per event,
normalizes deny into a typed error, and holds the package's single
enabled-check.
- `effects.go`: pure conversion of hook results into transcript rows and
prompt parts.
- `errors.go`: failure classification (dispatch error messages, denial
mapping, tool-result dispatch-failure scanning).
- `tooluse.go`: the tool-call gate (`pre_tool_use` preflight,
`post_tool_use` payloads, applying admitted input to the step).

Server-bound glue stays in `coderd/x/chatd/hook_server.go`: the
chat-parking dispatch error handlers, the step-commit row insertion
wrappers, and the dynamic post-tool-use state loader, which depends on
chatd validation types.

This PR adopts the `codersdk/x/agenthooks` and
`coderd/x/agenthooks/dispatch` import paths introduced at the tip of
#27401; intermediate commits still reference the pre-move paths and are
not individually buildable.

## Staged tool admission

`pre_tool_use` originally ran at tool execution time, which is after the
assistant message carrying the tool call was already committed. An
`input_override` therefore had to rewrite stored message content in
place. @hugodutka pointed out that chatd treats message content as
immutable, and that the rewrite was a shortcut rather than a
requirement.

It was also a correctness problem in its own right: the rewrite only
updated the database, so the transcript could show one input while a
different one had executed.

The hook now runs before the step is persisted:

```text
provider stream ends (tool calls complete, in memory)
  -> pre_tool_use dispatch per call
  -> ONE transaction: assistant row with admitted inputs, synthetic denials, hook rows
  -> execute
```

The step is inserted once, carrying the input the tool runs with.
`UpdateChatMessageContentByID` and `Tx.UpdateMessageContent` are deleted
from #27428, so message content stays immutable.

Two consequences, both intentional:

- **Clients converge rather than wait.** Tool-call parts still stream
live, so a rewritten call briefly shows the model's proposed input
before the committed message replaces it. The chat store already clears
stream state when an assistant message arrives, so the stored input wins
with no frontend change and no added latency before tool cards appear.
- **A call already in history was already admitted.** Execution consumes
the stored input instead of dispatching a second decision, which keeps
one dispatch and one set of hook effects per call. A consumer policy
change between admission and execution applies to later calls, not to
calls already admitted.

The per-chat debug endpoint still records the provider's original tool
input. Its purpose is to report provider behavior, and it requires an
explicit per-chat debug flag; the invariant here covers the transcript.

## Configuration

Adds `chat-hook-url`, `chat-hook-secret`, `chat-hook-timeout`, and
`chat-hook-enabled` deployment options with startup validation. The
flags are hidden from `coder server --help` while the feature is
experimental; the setup guide documents them.

## Tool input validation

Built-in tool arguments reach a consumer as raw JSON with key spelling
preserved, but the tools decode those bytes with Go, which matches
struct fields case-insensitively and keeps the last match. A policy
reading `path` could therefore authorize one value while the tool
executed another, and a lone case variant such as `{"PATH":"/secret"}`
was invisible to a policy checking for `path`.

Coder now rejects a built-in tool call whose input repeats a key or
spells a schema property with different capitalization, before the
`pre_tool_use` dispatch, so a consumer is never asked to authorize bytes
whose meaning depends on the reader. Rejected calls produce an error
result the model can retry; unambiguous calls in the same batch still
run. A consumer-authored `input_override` is rechecked after the
dispatch and fails the turn closed, because the model cannot correct it.
Dynamic and MCP inputs are excluded because the client and the workspace
agent execute those calls rather than coderd.

Two paths needed more than a schema check. Execution resolves a
deprecated tool name to its canonical tool, so validation resolves
aliases first. The `edit_files` decoder also reads `search` and
`replace`, which its schema does not advertise, so those aliases are now
matched exactly and their case variants ignored.

A hook denial now returns a structured 403 carrying `kind:
"hook_denied"`, mirroring the dispatch-failure response that already
carries its own kind. Without it a client cannot tell a policy decision
apart from a generic failure, and the chat UI titled a denial "Request
failed". Adding a kind needs no migration: `ChatErrorKind` is persisted
only inside the JSONB `chats.last_error` column, whose decoder accepts
unknown kinds.

The hook docs also correct the tool-input convergence window. A batch
dispatches sequentially before the assistant row commits, so the
original input stays visible for a span that scales with the number of
tool calls in the step rather than a single hook timeout.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-29 11:39:12 +00:00