mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
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.
599 lines
22 KiB
Go
599 lines
22 KiB
Go
package coderd_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/coder/coder/v2/coderd/coderdtest"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chattest"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/codersdk/x/agenthooks"
|
|
"github.com/coder/coder/v2/testutil"
|
|
"github.com/coder/serpent"
|
|
)
|
|
|
|
func TestPostChatsInitialPromptHookErrors(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
statusCode int
|
|
response string
|
|
wantStatus int
|
|
wantMessage string
|
|
wantKind codersdk.ChatErrorKind
|
|
}{
|
|
{
|
|
name: "deny",
|
|
statusCode: http.StatusOK,
|
|
response: `{"permission":{"decision":"deny"},"user_message":"blocked by policy"}`,
|
|
wantStatus: http.StatusForbidden,
|
|
wantMessage: "blocked by policy",
|
|
wantKind: codersdk.ChatErrorKindHookDenied,
|
|
},
|
|
{
|
|
name: "dispatch failure",
|
|
statusCode: http.StatusInternalServerError,
|
|
wantStatus: http.StatusBadGateway,
|
|
wantKind: codersdk.ChatErrorKindHookDispatchFailed,
|
|
},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
requests := make(chan agenthooks.Request, 2)
|
|
consumer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var request agenthooks.Request
|
|
require.NoError(t, json.NewDecoder(r.Body).Decode(&request))
|
|
requests <- request
|
|
w.WriteHeader(test.statusCode)
|
|
if test.response != "" {
|
|
_, err := w.Write([]byte(test.response))
|
|
require.NoError(t, err)
|
|
}
|
|
}))
|
|
t.Cleanup(consumer.Close)
|
|
|
|
client, db := newChatClientWithDatabase(t, func(opts *coderdtest.Options) {
|
|
opts.ChatWorkerDisabled = true
|
|
require.NoError(t, opts.DeploymentValues.AI.Chat.HookURL.Set(consumer.URL))
|
|
opts.DeploymentValues.AI.Chat.HookSecret = serpent.String("test-hook-secret-32-bytes-minimum!!")
|
|
opts.DeploymentValues.AI.Chat.HookTimeout = serpent.Duration(time.Second)
|
|
opts.DeploymentValues.AI.Chat.HookEnabled = serpent.Bool(true)
|
|
})
|
|
user := coderdtest.CreateFirstUser(t, client.Client)
|
|
model := createAdditionalChatModelConfig(t, client, "openai", "gpt-4.1")
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
res, err := client.Request(ctx, http.MethodPost, "/api/experimental/chats", codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
ModelConfigID: &model.ID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "blocked prompt",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
defer res.Body.Close()
|
|
require.Equal(t, test.wantStatus, res.StatusCode)
|
|
// Both outcomes share this wire shape, differing only in kind.
|
|
var response struct {
|
|
codersdk.Response
|
|
Kind codersdk.ChatErrorKind `json:"kind"`
|
|
}
|
|
require.NoError(t, json.NewDecoder(res.Body).Decode(&response))
|
|
require.Equal(t, test.wantKind, response.Kind)
|
|
if test.wantMessage != "" {
|
|
require.Equal(t, test.wantMessage, response.Message)
|
|
}
|
|
request := testutil.RequireReceive(ctx, t, requests)
|
|
require.Equal(t, agenthooks.EventUserPromptSubmit, request.Type)
|
|
require.NotEqual(t, uuid.Nil, request.Meta.ChatID)
|
|
_, err = db.GetChatByID(dbauthz.AsSystemRestricted(ctx), request.Meta.ChatID)
|
|
require.ErrorIs(t, err, sql.ErrNoRows)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestChatLifecycleHooksExperimentDisabled(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var hookRequests atomic.Int32
|
|
consumer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
hookRequests.Add(1)
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
t.Cleanup(consumer.Close)
|
|
|
|
client, _ := newChatClientWithDatabase(t, func(opts *coderdtest.Options) {
|
|
opts.ChatWorkerDisabled = true
|
|
opts.DeploymentValues.Experiments = serpent.StringArray{
|
|
string(codersdk.ExperimentChatAdvisor),
|
|
string(codersdk.ExperimentChatVirtualDesktop),
|
|
}
|
|
require.NoError(t, opts.DeploymentValues.AI.Chat.HookURL.Set(consumer.URL))
|
|
opts.DeploymentValues.AI.Chat.HookSecret = serpent.String("test-hook-secret-32-bytes-minimum!!")
|
|
opts.DeploymentValues.AI.Chat.HookTimeout = serpent.Duration(time.Second)
|
|
opts.DeploymentValues.AI.Chat.HookEnabled = serpent.Bool(true)
|
|
})
|
|
user := coderdtest.CreateFirstUser(t, client.Client)
|
|
model := createAdditionalChatModelConfig(t, client, "openai", "gpt-4.1")
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
_, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
ModelConfigID: &model.ID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "prompt with hooks disabled",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.Zero(t, hookRequests.Load())
|
|
}
|
|
|
|
func TestChatPromptHookContextHiddenFromAPI(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const secret = "test-hook-secret-32-bytes-minimum!!"
|
|
consumer := newHookConsumer(t, secret, agenthooks.Hooks{
|
|
UserPromptSubmit: func(context.Context, agenthooks.Meta, agenthooks.UserPromptSubmitData) (agenthooks.Response, error) {
|
|
return agenthooks.Response{
|
|
ModelContext: "prompt context",
|
|
UserMessage: "prompt notice",
|
|
}, nil
|
|
},
|
|
})
|
|
t.Cleanup(consumer.Close)
|
|
|
|
client, _ := newChatClientWithDatabase(t, func(opts *coderdtest.Options) {
|
|
opts.ChatWorkerDisabled = true
|
|
require.NoError(t, opts.DeploymentValues.AI.Chat.HookURL.Set(consumer.URL))
|
|
opts.DeploymentValues.AI.Chat.HookSecret = serpent.String(secret)
|
|
opts.DeploymentValues.AI.Chat.HookTimeout = serpent.Duration(time.Second)
|
|
opts.DeploymentValues.AI.Chat.HookEnabled = serpent.Bool(true)
|
|
})
|
|
user := coderdtest.CreateFirstUser(t, client.Client)
|
|
model := createAdditionalChatModelConfig(t, client, "openai", "gpt-4.1")
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
ModelConfigID: &model.ID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "initial prompt",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
messages, err := client.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
require.Len(t, messages.Messages, 1)
|
|
require.Equal(t, []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("initial prompt"),
|
|
{Type: codersdk.ChatMessagePartTypeHookNotice, Text: "prompt notice"},
|
|
}, messages.Messages[0].Content)
|
|
}
|
|
|
|
func TestChatLifecycleHooksWorkedExample(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
secret = "test-hook-secret-32-bytes-minimum!!"
|
|
deniedToolCallID = "call_denied"
|
|
allowedToolCallID = "call_allowed"
|
|
)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
var modelCalls atomic.Int32
|
|
secondModelRequest := make(chan []byte, 1)
|
|
thirdModelRequest := make(chan []byte, 1)
|
|
modelURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Lifecycle hooks")
|
|
}
|
|
switch modelCalls.Add(1) {
|
|
case 1:
|
|
chunk := chattest.OpenAIToolCallChunk("read_secret", `{"path":"/tmp/secret"}`)
|
|
chunk.Choices[0].ToolCalls[0].ID = deniedToolCallID
|
|
return chattest.OpenAIStreamingResponse(chunk)
|
|
case 2:
|
|
secondModelRequest <- bytes.Clone(req.RawBody)
|
|
chunk := chattest.OpenAIToolCallChunk("search_docs", `{"query":"customer secret"}`)
|
|
chunk.Choices[0].ToolCalls[0].ID = allowedToolCallID
|
|
return chattest.OpenAIStreamingResponse(chunk)
|
|
case 3:
|
|
thirdModelRequest <- bytes.Clone(req.RawBody)
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
default:
|
|
return chattest.OpenAIErrorResponse(http.StatusInternalServerError, "unexpected_call", "unexpected model call")
|
|
}
|
|
})
|
|
|
|
hookEvents := make(chan agenthooks.EventType, 16)
|
|
recordHook := func(event agenthooks.EventType) {
|
|
hookEvents <- event
|
|
}
|
|
consumer := newHookConsumer(t, secret, agenthooks.Hooks{
|
|
SessionStart: func(context.Context, agenthooks.Meta, agenthooks.SessionStartData) (agenthooks.Response, error) {
|
|
recordHook(agenthooks.EventSessionStart)
|
|
return agenthooks.Response{}, nil
|
|
},
|
|
UserPromptSubmit: func(context.Context, agenthooks.Meta, agenthooks.UserPromptSubmitData) (agenthooks.Response, error) {
|
|
recordHook(agenthooks.EventUserPromptSubmit)
|
|
return agenthooks.Response{}, nil
|
|
},
|
|
PreToolUse: func(_ context.Context, _ agenthooks.Meta, tool agenthooks.PreToolUseData) (agenthooks.Response, error) {
|
|
recordHook(agenthooks.EventPreToolUse)
|
|
switch tool.ToolUseID {
|
|
case deniedToolCallID:
|
|
return agenthooks.Response{Permission: &agenthooks.Permission{
|
|
Decision: agenthooks.PermissionDeny,
|
|
Reason: "secret reads are blocked",
|
|
}}, nil
|
|
case allowedToolCallID:
|
|
return agenthooks.Response{Permission: &agenthooks.Permission{
|
|
Decision: agenthooks.PermissionAllow,
|
|
InputOverride: json.RawMessage(`{"query":"public documentation"}`),
|
|
}}, nil
|
|
default:
|
|
return agenthooks.Response{}, nil
|
|
}
|
|
},
|
|
PostToolUse: func(context.Context, agenthooks.Meta, agenthooks.PostToolUseData) (agenthooks.Response, error) {
|
|
recordHook(agenthooks.EventPostToolUse)
|
|
return agenthooks.Response{
|
|
ModelContext: "The approved search result is safe to use.",
|
|
UserMessage: "Search result approved by policy.",
|
|
}, nil
|
|
},
|
|
Stop: func(context.Context, agenthooks.Meta, agenthooks.StopData) (agenthooks.Response, error) {
|
|
recordHook(agenthooks.EventStop)
|
|
return agenthooks.Response{}, nil
|
|
},
|
|
})
|
|
t.Cleanup(consumer.Close)
|
|
|
|
client, db := newChatClientWithDatabase(t, func(opts *coderdtest.Options) {
|
|
require.NoError(t, opts.DeploymentValues.AI.Chat.HookURL.Set(consumer.URL))
|
|
opts.DeploymentValues.AI.Chat.HookSecret = serpent.String(secret)
|
|
opts.DeploymentValues.AI.Chat.HookTimeout = serpent.Duration(time.Second)
|
|
opts.DeploymentValues.AI.Chat.HookEnabled = serpent.Bool(true)
|
|
})
|
|
user := coderdtest.CreateFirstUser(t, client.Client)
|
|
model := createChatModelConfigWithBaseURL(t, client, modelURL)
|
|
|
|
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
ModelConfigID: &model.ID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "Find the deployment documentation.",
|
|
}},
|
|
UnsafeDynamicTools: []codersdk.DynamicTool{
|
|
{
|
|
Name: "read_secret",
|
|
Description: "Read a secret file.",
|
|
InputSchema: json.RawMessage(`{"type":"object"}`),
|
|
},
|
|
{
|
|
Name: "search_docs",
|
|
Description: "Search public documentation.",
|
|
InputSchema: json.RawMessage(`{"type":"object"}`),
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var stored database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
stored, err = db.GetChatByID(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
|
return err == nil && stored.Status == database.ChatStatusRequiresAction
|
|
}, testutil.IntervalFast)
|
|
require.Equal(t, int32(2), modelCalls.Load())
|
|
require.Contains(t, string(testutil.RequireReceive(ctx, t, secondModelRequest)), "Reason: secret reads are blocked.")
|
|
|
|
messages, err := client.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
var allowedCall *codersdk.ChatMessagePart
|
|
for _, message := range messages.Messages {
|
|
for i := range message.Content {
|
|
part := &message.Content[i]
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolCallID == allowedToolCallID {
|
|
allowedCall = part
|
|
}
|
|
}
|
|
}
|
|
require.NotNil(t, allowedCall)
|
|
require.JSONEq(t, `{"query":"public documentation"}`, string(allowedCall.Args))
|
|
|
|
err = client.SubmitToolResults(ctx, chat.ID, codersdk.SubmitToolResultsRequest{
|
|
Results: []codersdk.ToolResult{{
|
|
ToolCallID: allowedToolCallID,
|
|
Output: json.RawMessage(`{"matches":["agent hooks"]}`),
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
stored, err = db.GetChatByID(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
|
return err == nil && stored.Status == database.ChatStatusWaiting
|
|
}, testutil.IntervalFast)
|
|
require.Contains(t, string(testutil.RequireReceive(ctx, t, thirdModelRequest)), "The approved search result is safe to use.")
|
|
require.Equal(t, int32(3), modelCalls.Load())
|
|
|
|
messages, err = client.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
var foundPostToolNotice bool
|
|
for _, message := range messages.Messages {
|
|
if message.Role != codersdk.ChatMessageRoleSystem {
|
|
continue
|
|
}
|
|
for _, part := range message.Content {
|
|
if part.Type == codersdk.ChatMessagePartTypeText && part.Text == "Search result approved by policy." {
|
|
foundPostToolNotice = true
|
|
}
|
|
}
|
|
}
|
|
require.True(t, foundPostToolNotice)
|
|
|
|
var seenEvents []agenthooks.EventType
|
|
for {
|
|
event := testutil.RequireReceive(ctx, t, hookEvents)
|
|
seenEvents = append(seenEvents, event)
|
|
if event == agenthooks.EventStop {
|
|
break
|
|
}
|
|
}
|
|
require.Contains(t, seenEvents, agenthooks.EventUserPromptSubmit)
|
|
require.Contains(t, seenEvents, agenthooks.EventSessionStart)
|
|
var preToolUseEvents int
|
|
for _, event := range seenEvents {
|
|
if event == agenthooks.EventPreToolUse {
|
|
preToolUseEvents++
|
|
}
|
|
}
|
|
require.GreaterOrEqual(t, preToolUseEvents, 2)
|
|
require.Contains(t, seenEvents, agenthooks.EventPostToolUse)
|
|
}
|
|
|
|
func TestChatHooksFileLinksAfterPromptOverride(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const secret = "test-hook-secret-32-bytes-minimum!!"
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
modelURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
consumer := newHookConsumer(t, secret, agenthooks.Hooks{
|
|
UserPromptSubmit: func(_ context.Context, _ agenthooks.Meta, data agenthooks.UserPromptSubmitData) (agenthooks.Response, error) {
|
|
if strings.Contains(data.Prompt, "REDACTME") {
|
|
return agenthooks.Response{Permission: &agenthooks.Permission{
|
|
Decision: agenthooks.PermissionAllow,
|
|
InputOverride: json.RawMessage(`{"prompt":"redacted"}`),
|
|
}}, nil
|
|
}
|
|
return agenthooks.Response{}, nil
|
|
},
|
|
})
|
|
t.Cleanup(consumer.Close)
|
|
|
|
client, api := newChatClientWithAPI(t, func(opts *coderdtest.Options) {
|
|
require.NoError(t, opts.DeploymentValues.AI.Chat.HookURL.Set(consumer.URL))
|
|
opts.DeploymentValues.AI.Chat.HookSecret = serpent.String(secret)
|
|
opts.DeploymentValues.AI.Chat.HookTimeout = serpent.Duration(time.Second)
|
|
opts.DeploymentValues.AI.Chat.HookEnabled = serpent.Bool(true)
|
|
})
|
|
user := coderdtest.CreateFirstUser(t, client.Client)
|
|
model := createChatModelConfigWithBaseURL(t, client, modelURL)
|
|
|
|
uploadFile := func(name string) uuid.UUID {
|
|
pngData := append([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 16)...)
|
|
resp, err := client.UploadChatFile(ctx, user.OrganizationID, "image/png", name, bytes.NewReader(pngData))
|
|
require.NoError(t, err)
|
|
return resp.ID
|
|
}
|
|
|
|
redactedFile := uploadFile("redacted.png")
|
|
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
ModelConfigID: &model.ID,
|
|
Content: []codersdk.ChatInputPart{
|
|
{Type: codersdk.ChatInputPartTypeText, Text: "REDACTME create"},
|
|
{Type: codersdk.ChatInputPartTypeFile, FileID: redactedFile},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
created, err := client.GetChat(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Empty(t, created.Files, "overridden create must not link dropped attachments")
|
|
|
|
coderdtest.WaitForChatSettled(ctx, t, api, chat.ID)
|
|
|
|
keptFile := uploadFile("kept.png")
|
|
sendResp, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
|
Content: []codersdk.ChatInputPart{
|
|
{Type: codersdk.ChatInputPartTypeText, Text: "keep this"},
|
|
{Type: codersdk.ChatInputPartTypeFile, FileID: keptFile},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
require.False(t, sendResp.Queued)
|
|
afterSend, err := client.GetChat(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, afterSend.Files, 1)
|
|
require.Equal(t, keptFile, afterSend.Files[0].ID)
|
|
|
|
coderdtest.WaitForChatSettled(ctx, t, api, chat.ID)
|
|
|
|
droppedFile := uploadFile("dropped.png")
|
|
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
|
Content: []codersdk.ChatInputPart{
|
|
{Type: codersdk.ChatInputPartTypeText, Text: "REDACTME send"},
|
|
{Type: codersdk.ChatInputPartTypeFile, FileID: droppedFile},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
afterOverride, err := client.GetChat(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, afterOverride.Files, 1, "overridden send must not link dropped attachments")
|
|
require.Equal(t, keptFile, afterOverride.Files[0].ID)
|
|
}
|
|
|
|
func TestChatHookNoticeMessagesInResponses(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const secret = "test-hook-secret-32-bytes-minimum!!"
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
modelURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
|
|
consumer := newHookConsumer(t, secret, agenthooks.Hooks{
|
|
SessionStart: func(context.Context, agenthooks.Meta, agenthooks.SessionStartData) (agenthooks.Response, error) {
|
|
return agenthooks.Response{UserMessage: "session notice"}, nil
|
|
},
|
|
UserPromptSubmit: func(_ context.Context, _ agenthooks.Meta, data agenthooks.UserPromptSubmitData) (agenthooks.Response, error) {
|
|
response := agenthooks.Response{UserMessage: "prompt notice"}
|
|
if data.Prompt == "edited prompt" {
|
|
response.ModelContext = "prompt context"
|
|
}
|
|
return response, nil
|
|
},
|
|
})
|
|
t.Cleanup(consumer.Close)
|
|
|
|
client, db := newChatClientWithDatabase(t, func(opts *coderdtest.Options) {
|
|
require.NoError(t, opts.DeploymentValues.AI.Chat.HookURL.Set(consumer.URL))
|
|
opts.DeploymentValues.AI.Chat.HookSecret = serpent.String(secret)
|
|
opts.DeploymentValues.AI.Chat.HookTimeout = serpent.Duration(time.Second)
|
|
opts.DeploymentValues.AI.Chat.HookEnabled = serpent.Bool(true)
|
|
})
|
|
user := coderdtest.CreateFirstUser(t, client.Client)
|
|
model := createChatModelConfigWithBaseURL(t, client, modelURL)
|
|
|
|
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
ModelConfigID: &model.ID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "initial prompt",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForWaiting := func() {
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
stored, err := db.GetChatByID(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
|
return err == nil && stored.Status == database.ChatStatusWaiting
|
|
}, testutil.IntervalFast)
|
|
}
|
|
waitForWaiting()
|
|
|
|
assertPromptContent := func(message codersdk.ChatMessage, prompt string) {
|
|
t.Helper()
|
|
require.Equal(t, codersdk.ChatMessageRoleUser, message.Role)
|
|
require.Equal(t, []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(prompt),
|
|
{Type: codersdk.ChatMessagePartTypeHookNotice, Text: "prompt notice"},
|
|
}, message.Content)
|
|
}
|
|
|
|
initialMessages, err := client.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
var initialPrompt *codersdk.ChatMessage
|
|
for i := range initialMessages.Messages {
|
|
message := &initialMessages.Messages[i]
|
|
if message.Role == codersdk.ChatMessageRoleUser && len(message.Content) > 0 && message.Content[0].Text == "initial prompt" {
|
|
initialPrompt = message
|
|
break
|
|
}
|
|
}
|
|
require.NotNil(t, initialPrompt)
|
|
assertPromptContent(*initialPrompt, "initial prompt")
|
|
|
|
sent, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "second prompt",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
require.False(t, sent.Queued, "idle chat must insert directly")
|
|
require.NotNil(t, sent.Message)
|
|
require.NotEmpty(t, sent.Messages, "send response must carry the inserted batch")
|
|
last := sent.Messages[len(sent.Messages)-1]
|
|
require.Equal(t, sent.Message.ID, last.ID, "user message must be last in the batch")
|
|
assertPromptContent(last, "second prompt")
|
|
assertPromptContent(*sent.Message, "second prompt")
|
|
|
|
waitForWaiting()
|
|
|
|
edited, err := client.EditChatMessage(ctx, chat.ID, sent.Message.ID, codersdk.EditChatMessageRequest{
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "edited prompt",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
require.NotZero(t, edited.Message.ID, "successful edits must return the replacement message")
|
|
require.NotEmpty(t, edited.Messages, "edit response must carry the inserted batch")
|
|
var editedBatchMessage *codersdk.ChatMessage
|
|
for i := range edited.Messages {
|
|
if edited.Messages[i].ID == edited.Message.ID {
|
|
editedBatchMessage = &edited.Messages[i]
|
|
break
|
|
}
|
|
}
|
|
require.NotNil(t, editedBatchMessage)
|
|
assertPromptContent(*editedBatchMessage, "edited prompt")
|
|
assertPromptContent(edited.Message, "edited prompt")
|
|
|
|
allMessages, err := client.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
var sessionNoticeFound bool
|
|
for _, message := range allMessages.Messages {
|
|
if message.Role != codersdk.ChatMessageRoleSystem {
|
|
continue
|
|
}
|
|
for _, part := range message.Content {
|
|
if part.Type == codersdk.ChatMessagePartTypeText && part.Text == "session notice" {
|
|
sessionNoticeFound = true
|
|
}
|
|
}
|
|
}
|
|
require.True(t, sessionNoticeFound)
|
|
}
|
|
|
|
// newHookConsumer serves hooks with its own URL as the configured audience,
|
|
// which is the value Coder signs when it dispatches there. The listener is
|
|
// allocated first because httptest.NewServer builds its handler before the
|
|
// server has a URL.
|
|
func newHookConsumer(t *testing.T, secret string, hooks agenthooks.Hooks) *httptest.Server {
|
|
t.Helper()
|
|
|
|
server := httptest.NewUnstartedServer(nil)
|
|
server.Config.Handler = agenthooks.NewHTTPHandler([]byte(secret), "http://"+server.Listener.Addr().String(), hooks)
|
|
server.Start()
|
|
return server
|
|
}
|