Closes CODAGT-1607 Follow-up to #32162, which left 5 `export_test.go` shims behind: `coderd`, `aibridged`, `chatd`, `chatstate` and `mcpclient`. This PR removes them. It's stacked on #32433, which deals with the chat workspace functions in `coderd`. Same approach as before. Tests of package internals are now `*_internal_test.go` files, with no changes beyond what the move forces, and tests that only needed a constant just use the value. `chatstate` needed one small accessor, so `AllowedExecutionTransitionOutputs` is just exported for real, and its tests stay where they were. Unfortunately the `mcpclient` connect budget test needs an unexported timeout, so it moved to an internal file and builds its own server there. I've removed `TestConnectAll_LateServerReaped`, `TestAllExecutionStates_Enumeration` and a few assertions instead of moving them, as I couldn't find a breakage that only they would catch. While here, I've dropped the test-only `reaperDone` hook from `mcpclient`. The wait for a connect to finish within its budget is now a small function of its own, with a test that a session which connects too late still gets closed. Nothing checked that before. With no shims left, the `testpackage` path exclusion is gone, so a new `export_test.go` now fails lint.
15410 lines
558 KiB
Go
15410 lines
558 KiB
Go
package chatd_test
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"charm.land/fantasy"
|
|
fantasyanthropic "charm.land/fantasy/providers/anthropic"
|
|
"github.com/google/uuid"
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
io_prometheus_client "github.com/prometheus/client_model/go"
|
|
"github.com/sqlc-dev/pqtype"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"github.com/tidwall/gjson"
|
|
"go.opentelemetry.io/otel/codes"
|
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
|
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
|
"go.uber.org/mock/gomock"
|
|
"golang.org/x/xerrors"
|
|
"google.golang.org/protobuf/encoding/protojson"
|
|
"google.golang.org/protobuf/types/known/structpb"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"cdr.dev/slog/v3/sloggers/slogtest"
|
|
"github.com/coder/coder/v2/agent/agentcontextconfig"
|
|
"github.com/coder/coder/v2/agent/agenttest"
|
|
agentproto "github.com/coder/coder/v2/agent/proto"
|
|
"github.com/coder/coder/v2/coderd/aibridge"
|
|
"github.com/coder/coder/v2/coderd/aibridgedtest"
|
|
"github.com/coder/coder/v2/coderd/coderdtest"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/db2sdk"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/database/dbfake"
|
|
"github.com/coder/coder/v2/coderd/database/dbgen"
|
|
"github.com/coder/coder/v2/coderd/database/dbtestutil"
|
|
"github.com/coder/coder/v2/coderd/database/dbtime"
|
|
dbpubsub "github.com/coder/coder/v2/coderd/database/pubsub"
|
|
coderdpubsub "github.com/coder/coder/v2/coderd/pubsub"
|
|
"github.com/coder/coder/v2/coderd/util/ptr"
|
|
"github.com/coder/coder/v2/coderd/util/slice"
|
|
"github.com/coder/coder/v2/coderd/workspacestats"
|
|
"github.com/coder/coder/v2/coderd/x/chatd"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatadvisor"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatloop"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprovider"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chattest"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chattool"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
|
"github.com/coder/coder/v2/codersdk/workspacesdk/agentconnmock"
|
|
"github.com/coder/coder/v2/codersdk/x/agenthooks"
|
|
"github.com/coder/coder/v2/provisioner/echo"
|
|
proto "github.com/coder/coder/v2/provisionersdk/proto"
|
|
"github.com/coder/coder/v2/testutil"
|
|
"github.com/coder/quartz"
|
|
"github.com/coder/safedial"
|
|
)
|
|
|
|
type recordedOpenAIRequest struct {
|
|
Messages []chattest.OpenAIMessage
|
|
Tools []string
|
|
// Offered is Tools plus the deferred MCP tools listed in the
|
|
// find_tools catalog.
|
|
Offered []string
|
|
Store *bool
|
|
ContentLength int64
|
|
}
|
|
|
|
func testMCPHTTPClient() *http.Client {
|
|
return safedial.NewHTTPClient(nil, safedial.WithAllowedPrefixes(
|
|
netip.MustParsePrefix("127.0.0.0/8"),
|
|
netip.MustParsePrefix("::1/128"),
|
|
))
|
|
}
|
|
|
|
func chatAIGatewayTransportFactoryPointer(factory aibridge.TransportFactory) *atomic.Pointer[aibridge.TransportFactory] {
|
|
var factoryPtr atomic.Pointer[aibridge.TransportFactory]
|
|
factoryPtr.Store(&factory)
|
|
return &factoryPtr
|
|
}
|
|
|
|
func openAIToolName(tool chattest.OpenAITool) string {
|
|
return cmp.Or(tool.Function.Name, tool.Name, tool.Type)
|
|
}
|
|
|
|
// offeredToolNames returns the tools a request advertises plus the
|
|
// deferred MCP tools listed in its find_tools catalog, so tests of which
|
|
// tools a turn offers do not depend on schema deferral. It runs in mock
|
|
// server handler goroutines, so a body that does not parse fails the
|
|
// test through assert, not require.
|
|
func offeredToolNames(t testing.TB, req *chattest.OpenAIRequest) []string {
|
|
t.Helper()
|
|
names := make([]string, 0, len(req.Tools))
|
|
for _, tool := range req.Tools {
|
|
names = append(names, openAIToolName(tool))
|
|
}
|
|
// The typed request omits tool descriptions, which carry the catalog.
|
|
var body struct {
|
|
Tools []struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Function struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
} `json:"function"`
|
|
} `json:"tools"`
|
|
}
|
|
if !assert.NoError(t, json.Unmarshal(req.RawBody, &body), "parse the request body for the find_tools catalog") {
|
|
return names
|
|
}
|
|
for _, tool := range body.Tools {
|
|
if cmp.Or(tool.Function.Name, tool.Name) != chattool.FindToolsName {
|
|
continue
|
|
}
|
|
for _, line := range strings.Split(cmp.Or(tool.Function.Description, tool.Description), "\n") {
|
|
entry, ok := strings.CutPrefix(line, "- ")
|
|
if !ok {
|
|
continue
|
|
}
|
|
if name, _, ok := strings.Cut(entry, " - "); ok {
|
|
names = append(names, name)
|
|
}
|
|
}
|
|
}
|
|
return names
|
|
}
|
|
|
|
func newTestMCPServer(name string) *mcp.Server {
|
|
return mcp.NewServer(&mcp.Implementation{Name: name, Version: "1.0.0"}, nil)
|
|
}
|
|
|
|
func addTestMCPTextTool(server *mcp.Server, name, description, outputPrefix string) {
|
|
server.AddTool(&mcp.Tool{
|
|
Name: name,
|
|
Description: description,
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"input": map[string]any{
|
|
"type": "string",
|
|
"description": "The input string",
|
|
},
|
|
},
|
|
"required": []string{"input"},
|
|
},
|
|
}, func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
var arguments map[string]any
|
|
_ = json.Unmarshal(req.Params.Arguments, &arguments)
|
|
input, _ := arguments["input"].(string)
|
|
return &mcp.CallToolResult{
|
|
Content: []mcp.Content{&mcp.TextContent{Text: outputPrefix + input}},
|
|
}, nil
|
|
})
|
|
}
|
|
|
|
func testMCPHTTPHandler(server *mcp.Server) http.Handler {
|
|
return mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {
|
|
return server
|
|
}, &mcp.StreamableHTTPOptions{Stateless: true})
|
|
}
|
|
|
|
func mustChatLastErrorRawMessage(t testing.TB, payload codersdk.ChatError) pqtype.NullRawMessage {
|
|
t.Helper()
|
|
|
|
encoded, err := json.Marshal(payload)
|
|
require.NoError(t, err)
|
|
return pqtype.NullRawMessage{RawMessage: encoded, Valid: true}
|
|
}
|
|
|
|
func requireChatLastErrorPayload(t testing.TB, raw pqtype.NullRawMessage) codersdk.ChatError {
|
|
t.Helper()
|
|
require.True(t, raw.Valid, "last error should be set")
|
|
|
|
var payload codersdk.ChatError
|
|
require.NoError(t, json.Unmarshal(raw.RawMessage, &payload))
|
|
return payload
|
|
}
|
|
|
|
func chatLastErrorMessage(raw pqtype.NullRawMessage) string {
|
|
if !raw.Valid {
|
|
return ""
|
|
}
|
|
|
|
var payload codersdk.ChatError
|
|
if err := json.Unmarshal(raw.RawMessage, &payload); err == nil && payload.Message != "" {
|
|
return payload.Message
|
|
}
|
|
return string(raw.RawMessage)
|
|
}
|
|
|
|
func recordOpenAIRequest(t testing.TB, req *chattest.OpenAIRequest) recordedOpenAIRequest {
|
|
t.Helper()
|
|
messages := append([]chattest.OpenAIMessage(nil), req.Messages...)
|
|
tools := make([]string, 0, len(req.Tools))
|
|
for _, tool := range req.Tools {
|
|
tools = append(tools, openAIToolName(tool))
|
|
}
|
|
|
|
var store *bool
|
|
if req.Store != nil {
|
|
value := *req.Store
|
|
store = &value
|
|
}
|
|
|
|
var contentLength int64
|
|
if req.Request != nil {
|
|
contentLength = req.ContentLength
|
|
}
|
|
|
|
return recordedOpenAIRequest{
|
|
Messages: messages,
|
|
Tools: tools,
|
|
Offered: offeredToolNames(t, req),
|
|
Store: store,
|
|
ContentLength: contentLength,
|
|
}
|
|
}
|
|
|
|
func requestHasSystemSubstring(req recordedOpenAIRequest, want string) bool {
|
|
for _, msg := range req.Messages {
|
|
if msg.Role == "system" && strings.Contains(msg.Content, want) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func newWorkspaceToolTestServer(
|
|
t *testing.T,
|
|
db database.Store,
|
|
ps dbpubsub.Pubsub,
|
|
agentID uuid.UUID,
|
|
planContent string,
|
|
overrides ...func(cfg *chatd.Config),
|
|
) *chatd.Server {
|
|
t.Helper()
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
mockConn.EXPECT().SetExtraHeaders(gomock.Any()).AnyTimes()
|
|
mockConn.EXPECT().ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).AnyTimes()
|
|
mockConn.EXPECT().LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{AbsolutePathString: "/home/coder"}, nil).AnyTimes()
|
|
mockConn.EXPECT().ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
DoAndReturn(func(_ context.Context, path string, _, _ int64) (io.ReadCloser, string, error) {
|
|
if strings.HasPrefix(path, "/home/coder/.coder/plans/PLAN-") || path == "/home/coder/PLAN.md" {
|
|
return io.NopCloser(strings.NewReader(planContent)), "", nil
|
|
}
|
|
return io.NopCloser(strings.NewReader("")), "", nil
|
|
}).AnyTimes()
|
|
|
|
configOverrides := append([]func(cfg *chatd.Config){
|
|
func(cfg *chatd.Config) {
|
|
cfg.AgentConn = func(_ context.Context, gotAgentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, agentID, gotAgentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
},
|
|
}, overrides...)
|
|
return newActiveTestServer(t, db, ps, configOverrides...)
|
|
}
|
|
|
|
// TestArchiveStateRejectsChildChat verifies that Server.ArchiveChat and
|
|
// Server.UnarchiveChat refuse child chats with ErrArchiveRequiresRootChat
|
|
// whatever the family's archive state, leaving parent and child unchanged.
|
|
func TestArchiveStateRejectsChildChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
for _, tc := range []struct {
|
|
name string
|
|
childArchived bool
|
|
parentArchived bool
|
|
unarchive bool
|
|
}{
|
|
{name: "ArchiveActiveChild"},
|
|
{name: "ArchiveArchivedChild", childArchived: true},
|
|
{name: "UnarchiveActiveChild", unarchive: true},
|
|
{name: "UnarchiveArchivedChild", childArchived: true, unarchive: true},
|
|
{name: "UnarchiveChildOfArchivedParent", childArchived: true, parentArchived: true, unarchive: true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
parent := dbgen.Chat(t, db, database.Chat{OrganizationID: org.ID, OwnerID: user.ID, LastModelConfigID: model.ID})
|
|
child := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID, OwnerID: user.ID, LastModelConfigID: model.ID,
|
|
ParentChatID: uuid.NullUUID{UUID: parent.ID, Valid: true},
|
|
RootChatID: uuid.NullUUID{UUID: parent.ID, Valid: true},
|
|
})
|
|
if tc.childArchived {
|
|
_, err := db.ArchiveChatByID(ctx, child.ID)
|
|
require.NoError(t, err)
|
|
}
|
|
if tc.parentArchived {
|
|
_, err := db.ArchiveChatByID(ctx, parent.ID)
|
|
require.NoError(t, err)
|
|
}
|
|
child, err := db.GetChatByID(ctx, child.ID)
|
|
require.NoError(t, err)
|
|
|
|
if tc.unarchive {
|
|
err = replica.UnarchiveChat(ctx, child)
|
|
} else {
|
|
err = replica.ArchiveChat(ctx, child)
|
|
}
|
|
require.ErrorIs(t, err, chatd.ErrArchiveRequiresRootChat)
|
|
|
|
dbChild, err := db.GetChatByID(ctx, child.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, tc.childArchived, dbChild.Archived, "child archived flag must not change")
|
|
dbParent, err := db.GetChatByID(ctx, parent.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, tc.parentArchived, dbParent.Archived, "parent archived flag must not change")
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestUpdateChatHeartbeatsRequiresOwnership(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "heartbeat-ownership",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
workerID := uuid.New()
|
|
chat, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusRunning,
|
|
WorkerID: uuid.NullUUID{UUID: workerID, Valid: true},
|
|
StartedAt: sql.NullTime{Time: time.Now(), Valid: true},
|
|
HeartbeatAt: sql.NullTime{Time: time.Now(), Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wrong worker_id should return no IDs.
|
|
ids, err := db.UpdateChatHeartbeats(ctx, database.UpdateChatHeartbeatsParams{
|
|
IDs: []uuid.UUID{chat.ID},
|
|
WorkerID: uuid.New(),
|
|
Now: time.Now(),
|
|
})
|
|
require.NoError(t, err)
|
|
require.Empty(t, ids)
|
|
|
|
// Correct worker_id should return the chat's ID.
|
|
ids, err = db.UpdateChatHeartbeats(ctx, database.UpdateChatHeartbeatsParams{
|
|
IDs: []uuid.UUID{chat.ID},
|
|
WorkerID: workerID,
|
|
Now: time.Now(),
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, ids, 1)
|
|
require.Equal(t, chat.ID, ids[0])
|
|
}
|
|
|
|
func TestSendMessageQueueBehaviorQueuesWhenBusy(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "queue-when-busy",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
workerID := uuid.New()
|
|
chat, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusRunning,
|
|
WorkerID: uuid.NullUUID{UUID: workerID, Valid: true},
|
|
StartedAt: sql.NullTime{Time: time.Now(), Valid: true},
|
|
HeartbeatAt: sql.NullTime{Time: time.Now(), Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
result, err := replica.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("queued")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, result.Queued)
|
|
require.NotNil(t, result.QueuedMessage)
|
|
require.Equal(t, database.ChatStatusRunning, result.Chat.Status)
|
|
require.Equal(t, workerID, result.Chat.WorkerID.UUID)
|
|
require.True(t, result.Chat.WorkerID.Valid)
|
|
|
|
queued, err := db.GetChatQueuedMessages(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, queued, 1)
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, messages, 1)
|
|
}
|
|
|
|
func TestMessageFileLinking(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
insertFile := func(name string) uuid.UUID {
|
|
t.Helper()
|
|
row, err := db.InsertChatFile(ctx, database.InsertChatFileParams{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Name: name,
|
|
Mimetype: "image/png",
|
|
Data: []byte("png-bytes"),
|
|
})
|
|
require.NoError(t, err)
|
|
return row.ID
|
|
}
|
|
linkedFileIDs := func(chatID uuid.UUID) []uuid.UUID {
|
|
t.Helper()
|
|
rows, err := db.GetChatFileMetadataByChatID(ctx, chatID)
|
|
require.NoError(t, err)
|
|
ids := make([]uuid.UUID, 0, len(rows))
|
|
for _, row := range rows {
|
|
ids = append(ids, row.ID)
|
|
}
|
|
return ids
|
|
}
|
|
|
|
fileCreate := insertFile("create.png")
|
|
fileSend := insertFile("send.png")
|
|
fileQueued := insertFile("queued.png")
|
|
fileEdit := insertFile("edit.png")
|
|
fileQueuedEdit := insertFile("queued-edit.png")
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "file-linking",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("with attachment"),
|
|
codersdk.ChatMessageFile(fileCreate, "image/png", "create.png"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
require.Contains(t, linkedFileIDs(chat.ID), fileCreate)
|
|
|
|
chat, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusWaiting,
|
|
})
|
|
require.NoError(t, err)
|
|
sendResult, err := replica.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("another attachment"),
|
|
codersdk.ChatMessageFile(fileSend, "image/png", "send.png"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
require.False(t, sendResult.Queued)
|
|
require.Contains(t, linkedFileIDs(chat.ID), fileSend)
|
|
|
|
chat, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusWaiting,
|
|
})
|
|
require.NoError(t, err)
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
var userMessageID int64
|
|
for _, msg := range messages {
|
|
if msg.Role == database.ChatMessageRoleUser {
|
|
userMessageID = msg.ID
|
|
break
|
|
}
|
|
}
|
|
require.NotZero(t, userMessageID)
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
EditedMessageID: userMessageID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("edited attachment"),
|
|
codersdk.ChatMessageFile(fileEdit, "image/png", "edit.png"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
editedLinks := linkedFileIDs(chat.ID)
|
|
require.Contains(t, editedLinks, fileEdit)
|
|
require.Contains(t, editedLinks, fileCreate)
|
|
|
|
// Queued files must be linked before promotion to prevent purge.
|
|
_, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusRunning,
|
|
WorkerID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
|
|
StartedAt: sql.NullTime{Time: time.Now(), Valid: true},
|
|
HeartbeatAt: sql.NullTime{Time: time.Now(), Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
queuedResult, err := replica.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("queued attachment"),
|
|
codersdk.ChatMessageFile(fileQueued, "image/png", "queued.png"),
|
|
},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queuedResult.Queued)
|
|
require.Contains(t, linkedFileIDs(chat.ID), fileQueued)
|
|
|
|
require.NotNil(t, queuedResult.QueuedMessage)
|
|
err = replica.EditQueuedMessage(ctx, chatd.EditQueuedMessageOptions{
|
|
ChatID: chat.ID,
|
|
QueuedMessageID: queuedResult.QueuedMessage.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("queued edit attachment"),
|
|
codersdk.ChatMessageFile(fileQueuedEdit, "image/png", "queued-edit.png"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
require.Contains(t, linkedFileIDs(chat.ID), fileQueuedEdit)
|
|
}
|
|
|
|
func TestMessageFileLinkingCapRollsBack(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
limits chatd.Limits
|
|
attachmentCap int
|
|
}{
|
|
{name: "Default", attachmentCap: codersdk.DefaultChatMaxAttachmentsPerChat},
|
|
{name: "Configured3", limits: chatd.Limits{MaxAttachmentsPerChat: 3}, attachmentCap: 3},
|
|
{name: "Configured60", limits: chatd.Limits{MaxAttachmentsPerChat: 60}, attachmentCap: 60},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New(), func(cfg *chatd.Config) {
|
|
cfg.Limits = tt.limits
|
|
})
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "cap-rollback-" + tt.name,
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
fileParts := make([]codersdk.ChatMessagePart, 0, tt.attachmentCap+1)
|
|
for i := range tt.attachmentCap + 1 {
|
|
row, err := db.InsertChatFile(ctx, database.InsertChatFileParams{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Name: fmt.Sprintf("cap-%d.png", i),
|
|
Mimetype: "image/png",
|
|
Data: []byte("png-bytes"),
|
|
})
|
|
require.NoError(t, err)
|
|
fileParts = append(fileParts, codersdk.ChatMessageFile(row.ID, "image/png", row.Name))
|
|
}
|
|
|
|
chat, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusWaiting,
|
|
})
|
|
require.NoError(t, err)
|
|
messagesBefore, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_, err = replica.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: append([]codersdk.ChatMessagePart{codersdk.ChatMessageText("one too many")}, fileParts...),
|
|
})
|
|
require.ErrorIs(t, err, chatstate.ErrChatFileCapExceeded)
|
|
|
|
messagesAfter, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, messagesAfter, len(messagesBefore), "rejected send must not persist a message")
|
|
files, err := db.GetChatFileMetadataByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Empty(t, files, "rejected send must not link files")
|
|
|
|
sendResult, err := replica.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: append([]codersdk.ChatMessagePart{codersdk.ChatMessageText("exactly at the cap")}, fileParts[:tt.attachmentCap]...),
|
|
})
|
|
require.NoError(t, err)
|
|
require.False(t, sendResult.Queued)
|
|
files, err = db.GetChatFileMetadataByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, files, tt.attachmentCap)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestPlanTurnPromptContract(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
|
|
var (
|
|
requests []recordedOpenAIRequest
|
|
requestsMu sync.Mutex
|
|
)
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
requestsMu.Lock()
|
|
requests = append(requests, recordOpenAIRequest(t, req))
|
|
requestsMu.Unlock()
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("plan acknowledged")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
planModeInstructions := "Ask about deployment sequencing before finalizing the plan."
|
|
err := db.UpsertChatPlanModeInstructions(dbauthz.AsSystemRestricted(ctx), planModeInstructions)
|
|
require.NoError(t, err)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newWorkspaceToolTestServer(t, db, ps, dbAgent.ID, "# Plan\n", func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Title: "plan-turn-prompt-contract",
|
|
ModelConfigID: model.ID,
|
|
PlanMode: database.NullChatPlanMode{ChatPlanMode: database.ChatPlanModePlan, Valid: true},
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Plan the rollout."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
|
|
requestsMu.Lock()
|
|
recorded := append([]recordedOpenAIRequest(nil), requests...)
|
|
requestsMu.Unlock()
|
|
|
|
require.Len(t, recorded, 1, "expected exactly 1 streamed model call")
|
|
require.True(t, requestHasSystemSubstring(recorded[0], "You are in Plan Mode."))
|
|
require.True(t, requestHasSystemSubstring(recorded[0], "The only intentional authored workspace artifact is the plan file"))
|
|
require.True(t, requestHasSystemSubstring(recorded[0], "You may use execute and process_output for exploration"))
|
|
require.True(t, requestHasSystemSubstring(recorded[0], "approved external MCP tools when available"))
|
|
require.True(t, requestHasSystemSubstring(recorded[0], "Workspace MCP tools are not available in root plan mode"))
|
|
require.False(t, requestHasSystemSubstring(recorded[0], "After a successful propose_plan call, stop immediately"))
|
|
require.True(t, requestHasSystemSubstring(recorded[0], planModeInstructions))
|
|
for _, msg := range recorded[0].Messages {
|
|
if msg.Role != "system" {
|
|
continue
|
|
}
|
|
// The overlay prompt includes a placeholder that is replaced at
|
|
// runtime, so strip only the stable body text before checking.
|
|
overlayBody := strings.TrimSuffix(
|
|
chatd.PlanningOverlayPrompt(),
|
|
"{{CODER_CHAT_PLAN_FILE_PATH_BLOCK}}",
|
|
)
|
|
sanitized := strings.ReplaceAll(msg.Content, overlayBody, "")
|
|
require.NotContains(t, sanitized, "propose_plan")
|
|
}
|
|
}
|
|
|
|
func TestSendMessageRejectsInvalidQueuedModelConfigID(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, modelConfig := seedChatDependencies(t, db)
|
|
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
Status: database.ChatStatusRunning,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: modelConfig.ID,
|
|
Title: "reject invalid queued model config",
|
|
})
|
|
|
|
invalidModelConfigID := uuid.New()
|
|
_, err := replica.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("queued")},
|
|
ModelConfigID: invalidModelConfigID,
|
|
})
|
|
require.ErrorIs(t, err, chatd.ErrInvalidModelConfigID)
|
|
|
|
queued, err := db.GetChatQueuedMessages(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Empty(t, queued)
|
|
}
|
|
|
|
func TestCreateChatInsertsWorkspaceAwarenessMessage(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("WithWorkspace", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
tv := dbgen.TemplateVersion(t, db, database.TemplateVersion{
|
|
OrganizationID: org.ID,
|
|
CreatedBy: user.ID,
|
|
})
|
|
tpl := dbgen.Template(t, db, database.Template{
|
|
CreatedBy: user.ID,
|
|
OrganizationID: org.ID,
|
|
ActiveVersionID: tv.ID,
|
|
})
|
|
workspace := dbgen.Workspace(t, db, database.WorkspaceTable{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
TemplateID: tpl.ID,
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: workspace.ID, Valid: true},
|
|
Title: "test-with-workspace",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
messages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
|
|
var workspaceMsg *database.ChatMessage
|
|
for _, msg := range messages {
|
|
if msg.Role == database.ChatMessageRoleSystem {
|
|
content := string(msg.Content.RawMessage)
|
|
if strings.Contains(content, "attached to a workspace") {
|
|
workspaceMsg = &msg
|
|
break
|
|
}
|
|
}
|
|
}
|
|
require.NotNil(t, workspaceMsg, "workspace awareness system message should exist")
|
|
require.Equal(t, database.ChatMessageRoleSystem, workspaceMsg.Role)
|
|
require.Equal(t, database.ChatMessageVisibilityModel, workspaceMsg.Visibility)
|
|
})
|
|
|
|
t.Run("WithoutWorkspace", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "test-without-workspace",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
messages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
|
|
var workspaceMsg *database.ChatMessage
|
|
for _, msg := range messages {
|
|
if msg.Role == database.ChatMessageRoleSystem {
|
|
content := string(msg.Content.RawMessage)
|
|
if strings.Contains(content, "This chat started without an attached workspace") {
|
|
workspaceMsg = &msg
|
|
break
|
|
}
|
|
}
|
|
}
|
|
require.NotNil(t, workspaceMsg, "workspace awareness system message should exist")
|
|
require.Equal(t, database.ChatMessageRoleSystem, workspaceMsg.Role)
|
|
require.Equal(t, database.ChatMessageVisibilityModel, workspaceMsg.Visibility)
|
|
workspaceContent := string(workspaceMsg.Content.RawMessage)
|
|
require.Contains(t, workspaceContent, "missing tools, skills, MCPs, or context prevent progress")
|
|
require.Contains(t, workspaceContent, "create a suitable workspace with create_workspace")
|
|
require.NotContains(t, workspaceContent, "start_workspace")
|
|
require.Contains(t, workspaceContent, "Use the workspace's available context and capabilities to continue the user's request")
|
|
require.NotContains(t, workspaceContent, "Do not create or start a workspace by default")
|
|
})
|
|
}
|
|
|
|
// TestCreateChatWithoutInitialUserContent verifies that chats created
|
|
// without initial user content start idle in `waiting` with system
|
|
// messages only, so no worker picks them up before the first message.
|
|
// APIKeyID is not required because no user message is inserted.
|
|
func TestCreateChatWithoutInitialUserContent(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "empty-create",
|
|
ModelConfigID: model.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusWaiting, chat.Status)
|
|
|
|
messages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.NotEmpty(t, messages, "system messages are still inserted")
|
|
for _, msg := range messages {
|
|
require.Equal(t, database.ChatMessageRoleSystem, msg.Role, "no user message on an empty create")
|
|
}
|
|
}
|
|
|
|
// TestSendMessageFirstUserTurnFallbackTitle verifies that the first
|
|
// message on a chat created without initial content persists the
|
|
// fallback title in the send itself, independent of title generation.
|
|
func TestSendMessageFirstUserTurnFallbackTitle(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const text = "investigate the flaky workspace upload tests today"
|
|
|
|
setup := func(t *testing.T, title string, source database.ChatTitleSource) (context.Context, database.Store, dbpubsub.Pubsub, *chatd.Server, database.Chat) {
|
|
t.Helper()
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: title,
|
|
TitleSource: source,
|
|
ModelConfigID: model.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
return ctx, db, ps, server, chat
|
|
}
|
|
send := func(ctx context.Context, t *testing.T, server *chatd.Server, chatID uuid.UUID) chatd.SendMessageResult {
|
|
t.Helper()
|
|
result, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chatID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText(text)},
|
|
})
|
|
require.NoError(t, err)
|
|
require.False(t, result.Queued)
|
|
return result
|
|
}
|
|
|
|
t.Run("PlaceholderTitle", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, db, ps, server, chat := setup(t, chatprompt.DefaultChatTitle, database.ChatTitleSourceFallback)
|
|
titleEvents := make(chan codersdk.ChatWatchEvent, 1)
|
|
cancel, err := ps.Subscribe(coderdpubsub.ChatWatchEventChannel(chat.OwnerID), func(_ context.Context, payload []byte) {
|
|
var event codersdk.ChatWatchEvent
|
|
if json.Unmarshal(payload, &event) == nil && event.Kind == codersdk.ChatWatchEventKindTitleChange {
|
|
titleEvents <- event
|
|
}
|
|
})
|
|
require.NoError(t, err)
|
|
defer cancel()
|
|
|
|
result := send(ctx, t, server, chat.ID)
|
|
require.True(t, result.FirstUserTurn)
|
|
require.Equal(t, chatprompt.FallbackTitle(text), result.Chat.Title)
|
|
|
|
stored, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, chatprompt.FallbackTitle(text), stored.Title)
|
|
// The sidebar learns the fallback title from a title_change event.
|
|
require.Equal(t, chatprompt.FallbackTitle(text), testutil.RequireReceive(ctx, t, titleEvents).Chat.Title)
|
|
})
|
|
|
|
t.Run("ExistingTitle", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, db, _, server, chat := setup(t, "custom title", database.ChatTitleSourceUser)
|
|
|
|
result := send(ctx, t, server, chat.ID)
|
|
require.False(t, result.FirstUserTurn)
|
|
|
|
stored, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, "custom title", stored.Title)
|
|
require.Equal(t, database.ChatTitleSourceUser, stored.TitleSource)
|
|
})
|
|
|
|
t.Run("PriorVisibleMessage", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, db, _, server, chat := setup(t, chatprompt.DefaultChatTitle, database.ChatTitleSourceFallback)
|
|
|
|
send(ctx, t, server, chat.ID)
|
|
// Reset to an idle chat that still carries the placeholder
|
|
// title but already has a user-visible message.
|
|
_, err := db.UpdateChatTitleByID(ctx, database.UpdateChatTitleByIDParams{
|
|
ID: chat.ID,
|
|
Title: chatprompt.DefaultChatTitle,
|
|
TitleSource: database.ChatTitleSourceFallback,
|
|
})
|
|
require.NoError(t, err)
|
|
_, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusWaiting,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
result := send(ctx, t, server, chat.ID)
|
|
require.False(t, result.FirstUserTurn)
|
|
|
|
stored, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, chatprompt.DefaultChatTitle, stored.Title)
|
|
})
|
|
}
|
|
|
|
// TestArchivedChatRejectsMutations verifies that every mutation verb
|
|
// refuses an archived chat with ErrChatArchived inside its transaction,
|
|
// with hooks disabled so the pre-dispatch admission check cannot mask a
|
|
// missing in-transaction check.
|
|
func TestArchivedChatRejectsMutations(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
chat := dbgen.Chat(t, db, database.Chat{OrganizationID: org.ID, OwnerID: user.ID, LastModelConfigID: model.ID})
|
|
message := dbgen.ChatMessage(t, db, database.ChatMessage{ChatID: chat.ID, CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true}})
|
|
_, err := db.ArchiveChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
chat, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
|
|
content := []codersdk.ChatMessagePart{codersdk.ChatMessageText("after archive")}
|
|
for name, call := range map[string]func(context.Context) error{
|
|
"SendMessage": func(ctx context.Context) error {
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{ChatID: chat.ID, Content: content})
|
|
return err
|
|
},
|
|
"EditMessage": func(ctx context.Context) error {
|
|
_, err := server.EditMessage(ctx, chatd.EditMessageOptions{ChatID: chat.ID, EditedMessageID: message.ID, Content: content})
|
|
return err
|
|
},
|
|
"PromoteQueued": func(ctx context.Context) error {
|
|
return server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{ChatID: chat.ID, QueuedMessageID: 1})
|
|
},
|
|
"SubmitToolResults": func(ctx context.Context) error {
|
|
return server.SubmitToolResults(ctx, chatd.SubmitToolResultsOptions{ChatID: chat.ID, UserID: user.ID})
|
|
},
|
|
"CompactChat": func(ctx context.Context) error {
|
|
_, err := server.CompactChat(ctx, chat)
|
|
return err
|
|
},
|
|
"ClearChat": func(ctx context.Context) error {
|
|
_, err := server.ClearChat(ctx, chat)
|
|
return err
|
|
},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
require.ErrorIs(t, call(ctx), chatd.ErrChatArchived)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestArchiveChatDeletesDebugRuns verifies that archiving schedules the
|
|
// debug-row cleanup for the archived chat.
|
|
func TestArchiveChatDeletesDebugRuns(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newDebugEnabledTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
chat := dbgen.Chat(t, db, database.Chat{OrganizationID: org.ID, OwnerID: user.ID, LastModelConfigID: model.ID})
|
|
// Stamped outside the clock-skew buffer so the cleanup deletes it
|
|
// instead of leaving it for dbpurge.
|
|
staleStart := sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true}
|
|
staleRun, err := db.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{
|
|
ChatID: chat.ID, Kind: "chat_turn", Status: "completed", StartedAt: staleStart, UpdatedAt: staleStart,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.NoError(t, replica.ArchiveChat(ctx, chat))
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, replica))
|
|
|
|
_, err = db.GetChatDebugRunByID(ctx, staleRun.ID)
|
|
require.ErrorIs(t, err, sql.ErrNoRows, "archive must delete the chat's debug runs")
|
|
}
|
|
|
|
func TestAutoPromoteQueuedMessagesPreservesPerTurnModelOrder(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
|
|
firstRunStarted := make(chan struct{})
|
|
secondRunStarted := make(chan struct{}, 1)
|
|
thirdRunStarted := make(chan struct{}, 1)
|
|
allowFirstRunFinish := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
switch requestCount.Add(1) {
|
|
case 1:
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.OpenAITextChunks("first run partial")[0]
|
|
select {
|
|
case <-firstRunStarted:
|
|
default:
|
|
close(firstRunStarted)
|
|
}
|
|
<-allowFirstRunFinish
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
case 2:
|
|
select {
|
|
case secondRunStarted <- struct{}{}:
|
|
default:
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("second run done")...)
|
|
case 3:
|
|
select {
|
|
case thirdRunStarted <- struct{}{}:
|
|
default:
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("third run done")...)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("extra run done")...)
|
|
}
|
|
})
|
|
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
// Disable periodic polling so chained promotions must be driven by
|
|
// signalWake.
|
|
cfg.PendingChatAcquireInterval = time.Hour
|
|
})
|
|
user, org, modelConfigA := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
modelConfigB := insertChatModelConfigWithCallConfig(
|
|
t,
|
|
db,
|
|
user.ID,
|
|
"openai-compat",
|
|
"gpt-4o-mini-queue-b-"+uuid.NewString(),
|
|
codersdk.ChatModelCallConfig{},
|
|
)
|
|
modelConfigC := insertChatModelConfigWithCallConfig(
|
|
t,
|
|
db,
|
|
user.ID,
|
|
"openai-compat",
|
|
"gpt-4o-mini-queue-c-"+uuid.NewString(),
|
|
codersdk.ChatModelCallConfig{},
|
|
)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "auto-promote per-turn model order",
|
|
ModelConfigID: modelConfigA.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.TryReceive(ctx, t, firstRunStarted)
|
|
|
|
queuedB, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("queued b")},
|
|
ModelConfigID: modelConfigB.ID,
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queuedB.Queued)
|
|
|
|
queuedC, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("queued c")},
|
|
ModelConfigID: modelConfigC.ID,
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queuedC.Queued)
|
|
|
|
close(allowFirstRunFinish)
|
|
|
|
testutil.TryReceive(ctx, t, secondRunStarted)
|
|
testutil.TryReceive(ctx, t, thirdRunStarted)
|
|
require.GreaterOrEqual(t, requestCount.Load(), int32(3))
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
queuedMessages, err := db.GetChatQueuedMessages(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Empty(t, queuedMessages)
|
|
|
|
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusWaiting, storedChat.Status)
|
|
require.Equal(t, modelConfigC.ID, storedChat.LastModelConfigID)
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var userTexts []string
|
|
var userModelConfigIDs []uuid.UUID
|
|
for _, message := range messages {
|
|
if message.Role != database.ChatMessageRoleUser {
|
|
continue
|
|
}
|
|
sdkMessage := db2sdk.ChatMessage(message)
|
|
require.Len(t, sdkMessage.Content, 1)
|
|
userTexts = append(userTexts, sdkMessage.Content[0].Text)
|
|
require.True(t, message.ModelConfigID.Valid)
|
|
userModelConfigIDs = append(userModelConfigIDs, message.ModelConfigID.UUID)
|
|
}
|
|
require.Equal(t, []string{"hello", "queued b", "queued c"}, userTexts)
|
|
require.Equal(t, []uuid.UUID{modelConfigA.ID, modelConfigB.ID, modelConfigC.ID}, userModelConfigIDs)
|
|
}
|
|
|
|
type openAIRequestRecorder struct {
|
|
mu sync.Mutex
|
|
requests [][]chattest.OpenAIMessage
|
|
}
|
|
|
|
func (r *openAIRequestRecorder) record(req *chattest.OpenAIRequest) int {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.requests = append(r.requests, append([]chattest.OpenAIMessage(nil), req.Messages...))
|
|
return len(r.requests)
|
|
}
|
|
|
|
func (r *openAIRequestRecorder) messages() [][]chattest.OpenAIMessage {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
return append([][]chattest.OpenAIMessage(nil), r.requests...)
|
|
}
|
|
|
|
func (r *openAIRequestRecorder) userTexts() [][]string {
|
|
var out [][]string
|
|
for _, messages := range r.messages() {
|
|
texts := []string{}
|
|
for _, message := range messages {
|
|
if message.Role == "user" {
|
|
texts = append(texts, message.Content)
|
|
}
|
|
}
|
|
out = append(out, texts)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func chatUserTexts(ctx context.Context, t *testing.T, db database.Store, chatID uuid.UUID) []string {
|
|
t.Helper()
|
|
var texts []string
|
|
for _, message := range chatMessages(ctx, t, db, chatID) {
|
|
if message.Role != database.ChatMessageRoleUser {
|
|
continue
|
|
}
|
|
parts, err := chatprompt.ParseContent(message)
|
|
require.NoError(t, err)
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText {
|
|
texts = append(texts, part.Text)
|
|
}
|
|
}
|
|
}
|
|
return texts
|
|
}
|
|
|
|
func TestSteerDuringMultiStepTurnDeliveredBeforeNextModelCall(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
firstRunStarted := make(chan struct{})
|
|
allowFirstRunFinish := make(chan struct{})
|
|
var recorder openAIRequestRecorder
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if recorder.record(req) > 1 {
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
// list_templates lets this turn take another step without a workspace.
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.OpenAIToolCallChunk("list_templates", `{}`)
|
|
close(firstRunStarted)
|
|
<-allowFirstRunFinish
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "steer-multi-step",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.TryReceive(ctx, t, firstRunStarted)
|
|
for _, s := range []struct {
|
|
text string
|
|
behavior chatd.SendMessageBusyBehavior
|
|
}{
|
|
{text: "queued", behavior: chatd.SendMessageBusyBehaviorQueue},
|
|
{text: "steer"},
|
|
} {
|
|
result, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText(s.text)},
|
|
BusyBehavior: s.behavior,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, result.Queued)
|
|
}
|
|
close(allowFirstRunFinish)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
requests := recorder.messages()
|
|
require.Len(t, requests, 3)
|
|
second := requests[1]
|
|
require.GreaterOrEqual(t, len(second), 2)
|
|
require.Equal(t, "tool", second[len(second)-2].Role)
|
|
require.Equal(t, chattest.OpenAIMessage{Role: "user", Content: "steer"}, second[len(second)-1])
|
|
require.Equal(t, [][]string{
|
|
{"hello"},
|
|
{"hello", "steer"},
|
|
{"hello", "steer", "queued"},
|
|
}, recorder.userTexts())
|
|
require.Equal(t, []string{"hello", "steer", "queued"}, chatUserTexts(ctx, t, db, chat.ID))
|
|
queued, err := db.GetChatQueuedMessages(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Empty(t, queued)
|
|
}
|
|
|
|
func TestEditMessageRejectsMissingMessage(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "missing-edited-message",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: 999999,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
})
|
|
require.Error(t, err)
|
|
require.True(t, errors.Is(err, chatd.ErrEditedMessageNotFound))
|
|
}
|
|
|
|
func TestEditMessageRejectsNonUserMessage(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "non-user-edited-message",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
assistantContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("assistant"),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
assistantMessage := dbgen.ChatMessage(t, db, database.ChatMessage{
|
|
ChatID: chat.ID,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
Role: database.ChatMessageRoleAssistant,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
Content: assistantContent,
|
|
})
|
|
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: assistantMessage.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
})
|
|
require.Error(t, err)
|
|
require.True(t, errors.Is(err, chatd.ErrEditedMessageNotUser))
|
|
}
|
|
|
|
func TestEditMessage_MCPServerIDs(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
optionalConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Optional MCP",
|
|
Slug: "optional-mcp",
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "edit-mcp-server-ids",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{},
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
latestUserMessageID := func(chatID uuid.UUID) int64 {
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chatID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
var id int64
|
|
for _, message := range messages {
|
|
if message.Role == database.ChatMessageRoleUser && !message.Deleted {
|
|
id = message.ID
|
|
}
|
|
}
|
|
require.NotZero(t, id)
|
|
return id
|
|
}
|
|
|
|
// An edit that provides MCP server IDs replaces the selection.
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
EditedMessageID: latestUserMessageID(chat.ID),
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edit with mcp")},
|
|
MCPServerIDs: &[]uuid.UUID{optionalConfig.ID},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
dbChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.ElementsMatch(t, []uuid.UUID{optionalConfig.ID}, dbChat.MCPServerIDs)
|
|
|
|
// A nil selection preserves the persisted one.
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
EditedMessageID: latestUserMessageID(chat.ID),
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edit without mcp")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
dbChat, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.ElementsMatch(t, []uuid.UUID{optionalConfig.ID}, dbChat.MCPServerIDs)
|
|
|
|
// An edit that clears the list cannot remove a force_on server
|
|
// (Cure53 CDM-02-010 parity with the send path).
|
|
forcedConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Forced MCP",
|
|
Slug: "forced-mcp",
|
|
Availability: "force_on",
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
EditedMessageID: latestUserMessageID(chat.ID),
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edit clearing mcp")},
|
|
MCPServerIDs: &[]uuid.UUID{},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
dbChat, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.ElementsMatch(t, []uuid.UUID{forcedConfig.ID}, dbChat.MCPServerIDs,
|
|
"force_on MCP server must survive an emptied mcp_server_ids edit")
|
|
|
|
// Explore child chats keep the spawn-time MCP snapshot immutable.
|
|
exploreContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("explore"),
|
|
})
|
|
require.NoError(t, err)
|
|
createdExplore, err := chatstate.CreateChat(ctx, db, ps, chatstate.CreateChatInput{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
ParentChatID: uuid.NullUUID{UUID: chat.ID, Valid: true},
|
|
RootChatID: uuid.NullUUID{UUID: chat.ID, Valid: true},
|
|
LastModelConfigID: model.ID,
|
|
Title: "explore-mcp-immutable",
|
|
Mode: database.NullChatMode{
|
|
ChatMode: database.ChatModeExplore,
|
|
Valid: true,
|
|
},
|
|
MCPServerIDs: []uuid.UUID{optionalConfig.ID},
|
|
ClientType: database.ChatClientTypeApi,
|
|
InitialMessages: []chatstate.Message{
|
|
{
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: exploreContent,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
exploreChat := createdExplore.Chat
|
|
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: exploreChat.ID,
|
|
CreatedBy: user.ID,
|
|
EditedMessageID: latestUserMessageID(exploreChat.ID),
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edit explore")},
|
|
MCPServerIDs: &[]uuid.UUID{},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
dbChat, err = db.GetChatByID(ctx, exploreChat.ID)
|
|
require.NoError(t, err)
|
|
require.ElementsMatch(t, []uuid.UUID{optionalConfig.ID}, dbChat.MCPServerIDs,
|
|
"explore subagent MCP snapshot must be immutable after spawn")
|
|
}
|
|
|
|
// TestEditMessageDebugCleanupDeletesPreEditRuns verifies that
|
|
// EditMessage schedules the chat debug cleanup goroutine when debug
|
|
// logging is enabled and that it deletes debug runs tied to the
|
|
// pre-edit conversation branch. This exercises the chatd wiring end
|
|
// to end: lazy debugService init, editCutoff sampling from the DB,
|
|
// and the scheduleDebugCleanup retry loop against a real Postgres
|
|
// store.
|
|
func TestEditMessageDebugCleanupDeletesPreEditRuns(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newDebugEnabledTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "debug-edit-cleanup",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("first")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
msgs, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID, AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, msgs, 1)
|
|
editedMsgID := msgs[0].ID
|
|
|
|
// Stale debug run tied to the pre-edit message branch. Stamped
|
|
// well outside the clock-skew buffer so the fast retry path
|
|
// deletes it instead of deferring to dbpurge.
|
|
staleStart := time.Now().Add(-time.Hour).UTC().Truncate(time.Microsecond)
|
|
staleRun, err := db.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{
|
|
ChatID: chat.ID,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
TriggerMessageID: sql.NullInt64{Int64: editedMsgID, Valid: true},
|
|
HistoryTipMessageID: sql.NullInt64{Int64: editedMsgID, Valid: true},
|
|
Kind: "chat_turn",
|
|
Status: "in_progress",
|
|
Provider: sql.NullString{String: "openai", Valid: true},
|
|
Model: sql.NullString{String: model.Model, Valid: true},
|
|
StartedAt: sql.NullTime{Time: staleStart, Valid: true},
|
|
UpdatedAt: sql.NullTime{Time: staleStart, Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Run tied to an earlier message branch that the message-id
|
|
// filter should leave alone even though it predates the edit.
|
|
unrelatedRun, err := db.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{
|
|
ChatID: chat.ID,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
TriggerMessageID: sql.NullInt64{Int64: editedMsgID - 1, Valid: true},
|
|
HistoryTipMessageID: sql.NullInt64{Int64: editedMsgID - 1, Valid: true},
|
|
Kind: "chat_turn",
|
|
Status: "completed",
|
|
Provider: sql.NullString{String: "openai", Valid: true},
|
|
Model: sql.NullString{String: model.Model, Valid: true},
|
|
StartedAt: sql.NullTime{Time: staleStart, Valid: true},
|
|
UpdatedAt: sql.NullTime{Time: staleStart, Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: editedMsgID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, replica))
|
|
|
|
// ErrNoRows on staleRun proves the fast-retry path DELETED the
|
|
// row: in this test it can disappear only via DeleteAfterMessageID,
|
|
// which is reached solely from scheduleDebugCleanup.
|
|
_, err = db.GetChatDebugRunByID(ctx, staleRun.ID)
|
|
require.ErrorIs(t, err, sql.ErrNoRows,
|
|
"pre-edit run matching the message-id filter should be deleted")
|
|
|
|
remaining, err := db.GetChatDebugRunByID(ctx, unrelatedRun.ID)
|
|
require.NoError(t, err,
|
|
"runs outside the edited message branch must survive cleanup")
|
|
require.Equal(t, unrelatedRun.ID, remaining.ID)
|
|
|
|
// Count the seeded rows that survive so the delete count is
|
|
// verified directly (not just by negative lookup). Scoped to
|
|
// seeded IDs because the processor may start a new chat_turn
|
|
// run in parallel when EditMessage transitions the chat back to
|
|
// pending.
|
|
remainingRuns, err := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID, LimitVal: 100,
|
|
})
|
|
require.NoError(t, err)
|
|
seeded := map[uuid.UUID]bool{staleRun.ID: true, unrelatedRun.ID: true}
|
|
survivors := 0
|
|
for _, r := range remainingRuns {
|
|
if seeded[r.ID] {
|
|
survivors++
|
|
}
|
|
}
|
|
require.Equal(t, 1, survivors,
|
|
"exactly one of the two seeded runs should survive (the unrelated run)")
|
|
}
|
|
|
|
// TestEditMessageDebugCleanupPreservesRecentRuns verifies that the
|
|
// clock-skew buffer in the edit-cleanup cutoff prevents the fast
|
|
// retry from deleting debug runs that started within the buffer
|
|
// window. dbpurge deletes those leftovers once they age out.
|
|
func TestEditMessageDebugCleanupPreservesRecentRuns(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newDebugEnabledTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "debug-edit-buffer",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("first")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
msgs, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID, AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, msgs, 1)
|
|
editedMsgID := msgs[0].ID
|
|
|
|
// Within the 30s skew buffer, so the fast retry must leave it
|
|
// alone even though its message ID matches the delete filter.
|
|
recentStart := time.Now().Add(-time.Second).UTC().Truncate(time.Microsecond)
|
|
recentRun, err := db.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{
|
|
ChatID: chat.ID,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
TriggerMessageID: sql.NullInt64{Int64: editedMsgID, Valid: true},
|
|
HistoryTipMessageID: sql.NullInt64{Int64: editedMsgID, Valid: true},
|
|
Kind: "chat_turn",
|
|
Status: "in_progress",
|
|
Provider: sql.NullString{String: "openai", Valid: true},
|
|
Model: sql.NullString{String: model.Model, Valid: true},
|
|
StartedAt: sql.NullTime{Time: recentStart, Valid: true},
|
|
UpdatedAt: sql.NullTime{Time: recentStart, Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: editedMsgID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, replica))
|
|
|
|
remaining, err := db.GetChatDebugRunByID(ctx, recentRun.ID)
|
|
require.NoError(t, err,
|
|
"runs inside the clock-skew buffer must survive the fast retry")
|
|
require.Equal(t, recentRun.ID, remaining.ID)
|
|
|
|
// If the clock-skew buffer were removed the fast retry would
|
|
// have deleted recentRun. Verify the count of seeded survivors
|
|
// directly, ignoring any new chat_turn run the processor may
|
|
// create after the pending status transition.
|
|
remainingRuns, err := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID, LimitVal: 100,
|
|
})
|
|
require.NoError(t, err)
|
|
survivors := 0
|
|
for _, r := range remainingRuns {
|
|
if r.ID == recentRun.ID {
|
|
survivors++
|
|
}
|
|
}
|
|
require.Equal(t, 1, survivors,
|
|
"the buffered run must survive the fast retry")
|
|
}
|
|
|
|
func TestRecoverStaleRequiresActionChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps, rawDB := dbtestutil.NewDBWithSQLDB(t)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
openAIURL := chattest.OpenAI(t)
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
|
|
toolName := "my_dynamic_tool"
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: toolName,
|
|
Description: "A test dynamic tool.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("hello"),
|
|
})
|
|
require.NoError(t, err)
|
|
created, err := chatstate.CreateChat(ctx, db, ps, chatstate.CreateChatInput{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: model.ID,
|
|
Title: "stale-requires-action",
|
|
DynamicTools: nullRawMessage(dynamicToolsJSON),
|
|
ClientType: database.ChatClientTypeApi,
|
|
InitialStatus: database.ChatStatusRunning,
|
|
InitialMessages: []chatstate.Message{
|
|
{
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: content,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
toolCallID := "call_" + uuid.NewString()
|
|
assistantContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
{
|
|
Type: codersdk.ChatMessagePartTypeToolCall,
|
|
ToolCallID: toolCallID,
|
|
ToolName: toolName,
|
|
Args: json.RawMessage(`{}`),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
machine := chatstate.NewChatMachine(db, ps, created.Chat.ID)
|
|
_, err = machine.Update(ctx, func(tx *chatstate.Tx, store database.Store, _ *chatstate.ChatSnapshot) error {
|
|
_, err := tx.CommitStep(chatstate.CommitStepInput{
|
|
Messages: []chatstate.Message{
|
|
{
|
|
Role: database.ChatMessageRoleAssistant,
|
|
Content: assistantContent,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
},
|
|
},
|
|
})
|
|
return err
|
|
})
|
|
require.NoError(t, err)
|
|
_, err = machine.Update(ctx, func(tx *chatstate.Tx, store database.Store, _ *chatstate.ChatSnapshot) error {
|
|
_, err := tx.EnterRequiresAction(chatstate.EnterRequiresActionInput{})
|
|
return err
|
|
})
|
|
require.NoError(t, err)
|
|
_, err = rawDB.ExecContext(ctx,
|
|
"UPDATE chats SET requires_action_deadline_at = $1 WHERE id = $2",
|
|
time.Now().Add(-time.Hour), created.Chat.ID)
|
|
require.NoError(t, err)
|
|
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newTestServer(t, db, ps, uuid.New(), func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
server.Start()
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, created.Chat.ID)
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status)
|
|
require.False(t, chatResult.RequiresActionDeadlineAt.Valid)
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: created.Chat.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, messages, 4)
|
|
parts, err := chatprompt.ParseContent(messages[2])
|
|
require.NoError(t, err)
|
|
require.Len(t, parts, 1)
|
|
require.Equal(t, codersdk.ChatMessagePartTypeToolResult, parts[0].Type)
|
|
require.Equal(t, toolCallID, parts[0].ToolCallID)
|
|
require.Equal(t, toolName, parts[0].ToolName)
|
|
require.True(t, parts[0].IsError)
|
|
require.JSONEq(t, `"Tool execution timed out"`, string(parts[0].Result))
|
|
}
|
|
|
|
func TestNewReplicaRecoversStaleChatFromDeadReplica(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps, rawDB := dbtestutil.NewDBWithSQLDB(t)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
openAIURL := chattest.OpenAI(t)
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("hello"),
|
|
})
|
|
require.NoError(t, err)
|
|
created, err := chatstate.CreateChat(ctx, db, ps, chatstate.CreateChatInput{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: model.ID,
|
|
Title: "orphaned-chat",
|
|
ClientType: database.ChatClientTypeApi,
|
|
InitialStatus: database.ChatStatusRunning,
|
|
InitialMessages: []chatstate.Message{
|
|
{
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: content,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
deadWorkerID := uuid.New()
|
|
deadRunnerID := uuid.New()
|
|
machine := chatstate.NewChatMachine(db, ps, created.Chat.ID)
|
|
_, err = machine.Update(ctx, func(tx *chatstate.Tx, store database.Store, _ *chatstate.ChatSnapshot) error {
|
|
_, err := tx.Acquire(chatstate.AcquireInput{WorkerID: deadWorkerID, RunnerID: deadRunnerID})
|
|
return err
|
|
})
|
|
require.NoError(t, err)
|
|
// Simulate a chat left running by a dead replica with a stale
|
|
// heartbeat (well beyond the stale threshold).
|
|
_, err = rawDB.ExecContext(ctx,
|
|
"UPDATE chat_heartbeats SET heartbeat_at = $1 WHERE chat_id = $2 AND runner_id = $3",
|
|
time.Now().Add(-time.Hour), created.Chat.ID, deadRunnerID)
|
|
require.NoError(t, err)
|
|
|
|
newWorkerID := uuid.New()
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newTestServer(t, db, ps, newWorkerID, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
// Start a new replica. It should recover the stale chat on
|
|
// startup.
|
|
server.Start()
|
|
|
|
var recovered database.Chat
|
|
require.Eventually(t, func() bool {
|
|
recovered, err = db.GetChatByID(ctx, created.Chat.ID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return recovered.Status == database.ChatStatusWaiting &&
|
|
!recovered.WorkerID.Valid &&
|
|
!recovered.RunnerID.Valid
|
|
}, testutil.WaitMedium, testutil.IntervalFast)
|
|
}
|
|
|
|
func TestWaitingChatsAreNotRecoveredAsStale(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
// Create a chat in waiting status. This should NOT be touched
|
|
// by stale recovery.
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "waiting-chat",
|
|
LastModelConfigID: model.ID,
|
|
})
|
|
|
|
// Start a replica with a short stale threshold.
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: testutil.WaitLong,
|
|
InFlightChatStaleAfter: 500 * time.Millisecond,
|
|
})
|
|
server.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
// Wait long enough for multiple periodic recovery cycles to
|
|
// run (staleAfter/5 = 100ms intervals).
|
|
require.Never(t, func() bool {
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return fromDB.Status != database.ChatStatusWaiting
|
|
}, time.Second, testutil.IntervalFast,
|
|
"waiting chat should not be modified by stale recovery")
|
|
}
|
|
|
|
func TestUpdateChatStatusPersistsLastError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
_ = newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "error-persisted",
|
|
LastModelConfigID: model.ID,
|
|
})
|
|
|
|
// Write a minimal structured last_error payload through the
|
|
// query layer, then verify it round-trips through storage.
|
|
errorMessage := "stream response: status 500: internal server error"
|
|
wantPayload := codersdk.ChatError{
|
|
Message: errorMessage,
|
|
Kind: codersdk.ChatErrorKindGeneric,
|
|
}
|
|
chat, err := db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusError,
|
|
WorkerID: uuid.NullUUID{},
|
|
StartedAt: sql.NullTime{},
|
|
HeartbeatAt: sql.NullTime{},
|
|
LastError: mustChatLastErrorRawMessage(t, wantPayload),
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusError, chat.Status)
|
|
require.Equal(t, wantPayload, requireChatLastErrorPayload(t, chat.LastError))
|
|
|
|
// Verify the error is persisted when re-read from the database.
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusError, fromDB.Status)
|
|
require.Equal(t, wantPayload, requireChatLastErrorPayload(t, fromDB.LastError))
|
|
|
|
// Verify the error is cleared when the chat transitions to a
|
|
// non-error status (e.g. running after a retry).
|
|
chat, err = db.UpdateChatStatus(ctx, database.UpdateChatStatusParams{
|
|
ID: chat.ID,
|
|
Status: database.ChatStatusRunning,
|
|
WorkerID: uuid.NullUUID{},
|
|
StartedAt: sql.NullTime{},
|
|
HeartbeatAt: sql.NullTime{},
|
|
LastError: pqtype.NullRawMessage{},
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusRunning, chat.Status)
|
|
require.False(t, chat.LastError.Valid)
|
|
|
|
fromDB, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.False(t, fromDB.LastError.Valid)
|
|
}
|
|
|
|
func TestSubscribeSnapshotIncludesStatusEvent(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "status-snapshot",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
snapshot, _, cancel, ok := replica.Subscribe(ctx, chat.ID, nil, 0, 0)
|
|
require.True(t, ok)
|
|
t.Cleanup(cancel)
|
|
|
|
// Passive server: status is always Pending.
|
|
require.NotEmpty(t, snapshot)
|
|
statusIdx := -1
|
|
for i, event := range snapshot {
|
|
if event.Type == codersdk.ChatStreamEventTypeStatus {
|
|
statusIdx = i
|
|
break
|
|
}
|
|
}
|
|
require.NotEqual(t, -1, statusIdx)
|
|
require.NotNil(t, snapshot[statusIdx].Status)
|
|
}
|
|
|
|
func TestPersistToolResultWithBinaryData(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const binaryOutputBase64 = "SEVBREVSAAAAc29tZSBkYXRhAABtb3JlIGRhdGEARU5E"
|
|
binaryOutput, err := io.ReadAll(base64.NewDecoder(
|
|
base64.StdEncoding,
|
|
strings.NewReader(binaryOutputBase64),
|
|
))
|
|
require.NoError(t, err)
|
|
|
|
var streamedCallCount atomic.Int32
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([][]chattest.OpenAIMessage, 0, 2)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Binary tool result test")
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, append([]chattest.OpenAIMessage(nil), req.Messages...))
|
|
streamedCallsMu.Unlock()
|
|
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"execute",
|
|
`{"command":"cat /home/coder/binary_file.bin"}`,
|
|
),
|
|
)
|
|
}
|
|
// Include literal \u0000 in the response text, which is
|
|
// what a real LLM writes when explaining binary output.
|
|
// json.Marshal encodes the backslash as \\, producing
|
|
// \\u0000 in the JSON bytes. The sanitizer must not
|
|
// corrupt this into invalid JSON.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("The file contains \\u0000 null bytes.")...,
|
|
)
|
|
})
|
|
|
|
// Use "openai-compat" provider so the chatd framework uses the
|
|
// /chat/completions endpoint, where the mock server supports
|
|
// streaming tool calls. The default "openai" provider routes to
|
|
// /responses which only handles text deltas in the mock.
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
mockConn.EXPECT().
|
|
SetExtraHeaders(gomock.Any()).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{}, nil).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(io.NopCloser(strings.NewReader("")), "", nil).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
StartProcess(gomock.Any(), gomock.Any()).
|
|
DoAndReturn(func(_ context.Context, req workspacesdk.StartProcessRequest) (workspacesdk.StartProcessResponse, error) {
|
|
require.Equal(t, "cat /home/coder/binary_file.bin", req.Command)
|
|
return workspacesdk.StartProcessResponse{ID: "proc-binary", Started: true}, nil
|
|
}).
|
|
Times(1)
|
|
mockConn.EXPECT().
|
|
ProcessOutput(gomock.Any(), "proc-binary", gomock.Any()).
|
|
Return(workspacesdk.ProcessOutputResponse{
|
|
Output: string(binaryOutput),
|
|
Running: false,
|
|
ExitCode: ptrRef(0),
|
|
}, nil).
|
|
AnyTimes()
|
|
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "binary-tool-result",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Read /home/coder/binary_file.bin."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
var toolMessage *database.ChatMessage
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for i := range messages {
|
|
if messages[i].Role == database.ChatMessageRoleTool {
|
|
toolMessage = &messages[i]
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.NotNil(t, toolMessage)
|
|
|
|
parts, err := chatprompt.ParseContent(*toolMessage)
|
|
require.NoError(t, err)
|
|
require.Len(t, parts, 1)
|
|
require.Equal(t, codersdk.ChatMessagePartTypeToolResult, parts[0].Type)
|
|
require.Equal(t, "execute", parts[0].ToolName)
|
|
|
|
var result chattool.ExecuteResult
|
|
require.NoError(t, json.Unmarshal(parts[0].Result, &result))
|
|
require.True(t, result.Success)
|
|
require.Equal(t, string(binaryOutput), result.Output)
|
|
require.Equal(t, 0, result.ExitCode)
|
|
|
|
require.GreaterOrEqual(t, streamedCallCount.Load(), int32(2))
|
|
streamedCallsMu.Lock()
|
|
recordedStreamCalls := append([][]chattest.OpenAIMessage(nil), streamedCalls...)
|
|
streamedCallsMu.Unlock()
|
|
require.GreaterOrEqual(t, len(recordedStreamCalls), 2)
|
|
|
|
var foundToolResultInSecondCall bool
|
|
for _, message := range recordedStreamCalls[1] {
|
|
if message.Role != "tool" {
|
|
continue
|
|
}
|
|
if !json.Valid([]byte(message.Content)) {
|
|
continue
|
|
}
|
|
var result chattool.ExecuteResult
|
|
if err := json.Unmarshal([]byte(message.Content), &result); err != nil {
|
|
continue
|
|
}
|
|
if result.Output == string(binaryOutput) {
|
|
foundToolResultInSecondCall = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundToolResultInSecondCall, "expected second streamed model call to include execute tool output")
|
|
}
|
|
|
|
func TestRequiresActionChatPersistsWaitingStatusLabel(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Dynamic tool test")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"my_dynamic_tool",
|
|
`{"input":"hello world"}`,
|
|
),
|
|
)
|
|
})
|
|
|
|
mockPush := &mockWebpushDispatcher{}
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
WebpushDispatcher: mockPush,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(factory),
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: "my_dynamic_tool",
|
|
Description: "A test dynamic tool.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"input": map[string]any{"type": "string"},
|
|
},
|
|
"required": []string{"input"},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "requires-action-status-label",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Please call the dynamic tool."),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
seedLastTurnSummary(ctx, t, db, chat, "previous summary")
|
|
|
|
server.Start()
|
|
|
|
var fromDB database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
got, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
fromDB = got
|
|
if got.Status == database.ChatStatusError {
|
|
return true
|
|
}
|
|
return got.Status == database.ChatStatusRequiresAction &&
|
|
got.LastTurnSummary.Valid &&
|
|
got.LastTurnSummary.String == "Waiting for user input"
|
|
}, testutil.IntervalFast)
|
|
// A requires_action runner stays active until tool results arrive.
|
|
require.NoError(t, server.Close())
|
|
|
|
require.Equal(t, database.ChatStatusRequiresAction, fromDB.Status,
|
|
"expected requires_action, got %s (last_error=%q)",
|
|
fromDB.Status, string(fromDB.LastError.RawMessage))
|
|
require.Equal(t, sql.NullString{String: "Waiting for user input", Valid: true}, fromDB.LastTurnSummary,
|
|
"requires action chats should persist a waiting status label")
|
|
require.Equal(t, int32(0), mockPush.dispatchCount.Load(),
|
|
"expected no web push dispatch for a requires_action chat")
|
|
}
|
|
|
|
func TestChatTurnStopsAtStepLimit(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
limits chatd.Limits
|
|
stepLimit int
|
|
// preseededSteps are committed before the server starts, so the
|
|
// default limit is reached without streaming every step.
|
|
preseededSteps int
|
|
}{
|
|
{name: "Configured1", limits: chatd.Limits{MaxStepsPerTurn: 1}, stepLimit: 1},
|
|
{name: "Configured3", limits: chatd.Limits{MaxStepsPerTurn: 3}, stepLimit: 3},
|
|
{
|
|
name: "Default",
|
|
stepLimit: codersdk.DefaultChatMaxStepsPerTurn,
|
|
preseededSteps: codersdk.DefaultChatMaxStepsPerTurn - 1,
|
|
},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCalls atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
streamedCalls.Add(1)
|
|
// list_templates runs without a workspace, so every step
|
|
// commits a tool result and the history stays incomplete.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("list_templates", `{}`),
|
|
)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
creator := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := creator.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "step-limit-" + tt.name,
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Keep listing templates."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
if tt.preseededSteps > 0 {
|
|
// Insert every preseeded step in one statement. A round
|
|
// trip per message can take most of the context's budget
|
|
// on a loaded CI database.
|
|
preseeded := database.InsertChatMessagesParams{ChatID: chat.ID}
|
|
for i := range tt.preseededSteps {
|
|
callID := fmt.Sprintf("preseeded-%d", i)
|
|
toolCall, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageToolCall(callID, "list_templates", json.RawMessage(`{}`)),
|
|
})
|
|
require.NoError(t, err)
|
|
toolResult, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageToolResult(callID, "list_templates", json.RawMessage(`{"templates":[]}`), false, false),
|
|
})
|
|
require.NoError(t, err)
|
|
appendChatMessageInsertParams(&preseeded, database.ChatMessageRoleAssistant, toolCall, model.ID, uuid.Nil)
|
|
appendChatMessageInsertParams(&preseeded, database.ChatMessageRoleTool, toolResult, model.ID, uuid.Nil)
|
|
}
|
|
inserted, err := db.InsertChatMessages(ctx, preseeded)
|
|
require.NoError(t, err)
|
|
require.Len(t, inserted, 2*tt.preseededSteps)
|
|
}
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.Limits = tt.limits
|
|
})
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, chat.ID)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status,
|
|
"last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
require.EqualValues(t, tt.stepLimit-tt.preseededSteps, streamedCalls.Load())
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{ChatID: chat.ID})
|
|
require.NoError(t, err)
|
|
var steps int
|
|
for _, msg := range messages {
|
|
if msg.Role == database.ChatMessageRoleAssistant {
|
|
steps++
|
|
}
|
|
}
|
|
require.Equal(t, tt.stepLimit, steps)
|
|
|
|
last := messages[len(messages)-1]
|
|
require.Equal(t, database.ChatMessageRoleTool, last.Role)
|
|
parts, err := chatprompt.ParseContent(last)
|
|
require.NoError(t, err)
|
|
require.Len(t, parts, 1)
|
|
require.Equal(t, codersdk.ChatMessagePartTypeToolResult, parts[0].Type)
|
|
require.Equal(t, "list_templates", parts[0].ToolName)
|
|
require.False(t, parts[0].IsError, "result=%s", parts[0].Result)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_InterruptionBehavior(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("partial stream commits synthetic tool result and promotes queued message", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
streamStarted := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
|
|
if requestCount.Add(1) != 1 {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("queued response")...)
|
|
}
|
|
chunks := make(chan chattest.AnthropicChunk, 5)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "message_start",
|
|
Message: chattest.AnthropicChunkMessage{
|
|
ID: "msg-partial-interrupt",
|
|
Type: "message",
|
|
Role: "assistant",
|
|
Model: "claude-3-opus-20240229",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 0,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "text",
|
|
Text: "",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_delta",
|
|
Index: 0,
|
|
Delta: chattest.AnthropicDeltaBlock{Type: "text_delta", Text: "partial assistant output"},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 1,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "tool_use",
|
|
ID: "interrupt-tool-1",
|
|
Name: "read_file",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_delta",
|
|
Index: 1,
|
|
Delta: chattest.AnthropicDeltaBlock{Type: "input_json_delta", PartialJSON: `{"path":"main.go"}`},
|
|
}
|
|
select {
|
|
case <-streamStarted:
|
|
default:
|
|
close(streamStarted)
|
|
}
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.AnthropicResponse{StreamingChunks: chunks}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "interrupt-partial-tool",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("start and call a tool"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.TryReceive(ctx, t, streamStarted)
|
|
for _, send := range []struct {
|
|
text string
|
|
behavior chatd.SendMessageBusyBehavior
|
|
}{
|
|
{text: "queued", behavior: chatd.SendMessageBusyBehaviorQueue},
|
|
{text: "steer", behavior: chatd.SendMessageBusyBehaviorSteer},
|
|
} {
|
|
sent, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText(send.text)},
|
|
BusyBehavior: send.behavior,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
}
|
|
_, _, err = server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.GreaterOrEqual(t, requestCount.Load(), int32(3))
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
var userTexts []string
|
|
var foundPartial bool
|
|
var partialRuntime sql.NullInt64
|
|
for _, msg := range messages {
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
require.NoError(t, parseErr)
|
|
switch msg.Role {
|
|
case database.ChatMessageRoleUser:
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText {
|
|
userTexts = append(userTexts, part.Text)
|
|
}
|
|
}
|
|
case database.ChatMessageRoleAssistant:
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText && strings.Contains(part.Text, "partial assistant output") {
|
|
foundPartial = true
|
|
partialRuntime = msg.RuntimeMs
|
|
}
|
|
}
|
|
}
|
|
}
|
|
require.Equal(t, []string{"start and call a tool", "steer", "queued"}, userTexts)
|
|
require.True(t, foundPartial)
|
|
// The interrupted attempt bills the model invocation window it
|
|
// opened, so the partial assistant row keeps a runtime.
|
|
require.True(t, partialRuntime.Valid)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
call := requireToolCallPart(t, parts, "read_file")
|
|
require.Equal(t, "interrupt-tool-1", call.ToolCallID)
|
|
require.Empty(t, call.Args)
|
|
require.Nil(t, call.CreatedAt, "incomplete streamed call should not have a durable call timestamp")
|
|
result := requireToolResultPart(t, parts, "read_file")
|
|
require.Equal(t, "interrupt-tool-1", result.ToolCallID)
|
|
require.True(t, result.IsError)
|
|
require.JSONEq(t, `{"error":"tool call was interrupted before it produced a result"}`, string(result.Result))
|
|
require.NotNil(t, result.CreatedAt)
|
|
})
|
|
|
|
t.Run("tool execution cancellation commits interrupted result", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var requestCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
if requestCount.Add(1) == 1 {
|
|
chunk := chattest.OpenAIToolCallChunk("read_file", `{"path":"/tmp/slow.txt"}`)
|
|
chunk.Choices[0].ToolCalls[0].ID = "tc-slow"
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("calling tool")[0],
|
|
chunk,
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("after interrupt")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
toolStarted := make(chan struct{})
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/slow.txt", int64(1), int64(0), gomock.Any()).
|
|
DoAndReturn(func(ctx context.Context, _ string, _, _ int64, _ workspacesdk.ReadFileLinesLimits) (workspacesdk.ReadFileLinesResponse, error) {
|
|
close(toolStarted)
|
|
<-ctx.Done()
|
|
return workspacesdk.ReadFileLinesResponse{}, ctx.Err()
|
|
}).Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "interrupt-tool-execution",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("run the slow tool"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.TryReceive(ctx, t, toolStarted)
|
|
queued, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue after interrupt")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorSteer,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queued.Queued)
|
|
_, _, err = server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.GreaterOrEqual(t, requestCount.Load(), int32(2))
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
var foundText bool
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleAssistant {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
require.NoError(t, parseErr)
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText && strings.Contains(part.Text, "calling tool") {
|
|
foundText = true
|
|
}
|
|
}
|
|
}
|
|
require.True(t, foundText)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
call := requireToolCallPart(t, parts, "read_file")
|
|
require.Equal(t, "tc-slow", call.ToolCallID)
|
|
require.NotNil(t, call.CreatedAt)
|
|
result := requireToolResultPart(t, parts, "read_file")
|
|
require.Equal(t, "tc-slow", result.ToolCallID)
|
|
require.True(t, result.IsError)
|
|
require.JSONEq(t, `{"error":"tool call was interrupted before it produced a result"}`, string(result.Result))
|
|
require.NotNil(t, result.CreatedAt)
|
|
require.False(t, result.CreatedAt.Before(*call.CreatedAt))
|
|
})
|
|
|
|
t.Run("anthropic provider-only interruption commits no synthetic result", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
webSearchEnabled := true
|
|
providerToolStarted := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
|
|
if requestCount.Add(1) != 1 {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("after interrupt")...)
|
|
}
|
|
chunks := make(chan chattest.AnthropicChunk, 2)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "message_start",
|
|
Message: chattest.AnthropicChunkMessage{
|
|
ID: "msg-provider-interrupt",
|
|
Type: "message",
|
|
Role: "assistant",
|
|
Model: "claude-3-opus-20240229",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 0,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "server_tool_use",
|
|
ID: "ws-interrupt",
|
|
Name: "web_search",
|
|
Input: json.RawMessage(`{"query":"coder"}`),
|
|
},
|
|
}
|
|
select {
|
|
case <-providerToolStarted:
|
|
default:
|
|
close(providerToolStarted)
|
|
}
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.AnthropicResponse{StreamingChunks: chunks}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{WebSearchEnabled: &webSearchEnabled},
|
|
},
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search for coder")
|
|
testutil.TryReceive(ctx, t, providerToolStarted)
|
|
queued, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue after provider interrupt")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorSteer,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queued.Queued)
|
|
_, _, err = server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
require.False(t, toolResultPartExists(parts, "web_search"),
|
|
"provider-executed web_search should not get a synthetic local result")
|
|
})
|
|
|
|
t.Run("anthropic mixed provider and local interruption keeps local synthetic result", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
webSearchEnabled := true
|
|
streamStarted := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
|
|
if requestCount.Add(1) != 1 {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("after interrupt")...)
|
|
}
|
|
chunks := make(chan chattest.AnthropicChunk, 3)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "message_start",
|
|
Message: chattest.AnthropicChunkMessage{
|
|
ID: "msg-mixed-interrupt",
|
|
Type: "message",
|
|
Role: "assistant",
|
|
Model: "claude-3-opus-20240229",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 0,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "server_tool_use",
|
|
ID: "ws-interrupt",
|
|
Name: "web_search",
|
|
Input: json.RawMessage(`{"query":"coder"}`),
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 1,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "tool_use",
|
|
ID: "tc-local",
|
|
Name: "read_file",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_delta",
|
|
Index: 1,
|
|
Delta: chattest.AnthropicDeltaBlock{Type: "input_json_delta", PartialJSON: `{"path":"main.go"}`},
|
|
}
|
|
select {
|
|
case <-streamStarted:
|
|
default:
|
|
close(streamStarted)
|
|
}
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.AnthropicResponse{StreamingChunks: chunks}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{WebSearchEnabled: &webSearchEnabled},
|
|
},
|
|
})
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "anthropic-mixed-interrupt",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search and read"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
testutil.TryReceive(ctx, t, streamStarted)
|
|
queued, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue after mixed interrupt")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorSteer,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queued.Queued)
|
|
_, _, err = server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
require.False(t, toolResultPartExists(parts, "web_search"))
|
|
call := requireToolCallPart(t, parts, "read_file")
|
|
require.Equal(t, "tc-local", call.ToolCallID)
|
|
require.False(t, call.ProviderExecuted)
|
|
result := requireToolResultPart(t, parts, "read_file")
|
|
require.Equal(t, "tc-local", result.ToolCallID)
|
|
require.False(t, result.ProviderExecuted)
|
|
require.True(t, result.IsError)
|
|
require.JSONEq(t, `{"error":"tool call was interrupted before it produced a result"}`, string(result.Result))
|
|
})
|
|
|
|
t.Run("interrupted reasoning persists timestamps", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
sendReasoning := true
|
|
thinkingBudget := int64(1024)
|
|
reasoningStarted := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
|
|
if requestCount.Add(1) != 1 {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("after interrupt")...)
|
|
}
|
|
chunks := make(chan chattest.AnthropicChunk, 3)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "message_start",
|
|
Message: chattest.AnthropicChunkMessage{
|
|
ID: "msg-reasoning-interrupt",
|
|
Type: "message",
|
|
Role: "assistant",
|
|
Model: "claude-3-opus-20240229",
|
|
},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 0,
|
|
ContentBlock: chattest.AnthropicContentBlock{Type: "thinking"},
|
|
}
|
|
chunks <- chattest.AnthropicChunk{
|
|
Type: "content_block_delta",
|
|
Index: 0,
|
|
Delta: chattest.AnthropicDeltaBlock{Type: "thinking_delta", Thinking: "interrupted thought"},
|
|
}
|
|
select {
|
|
case <-reasoningStarted:
|
|
default:
|
|
close(reasoningStarted)
|
|
}
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.AnthropicResponse{StreamingChunks: chunks}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{
|
|
SendReasoning: &sendReasoning,
|
|
Thinking: &codersdk.ChatModelAnthropicThinkingOptions{BudgetTokens: &thinkingBudget},
|
|
},
|
|
},
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "think")
|
|
testutil.TryReceive(ctx, t, reasoningStarted)
|
|
queued, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue after reasoning")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorSteer,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queued.Queued)
|
|
_, _, err = server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
var reasoningParts []codersdk.ChatMessagePart
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleAssistant {
|
|
continue
|
|
}
|
|
reasoningParts = append(reasoningParts, reasoningPartsFromMessage(t, msg)...)
|
|
}
|
|
require.Len(t, reasoningParts, 1)
|
|
require.Equal(t, "interrupted thought", strings.TrimSpace(reasoningParts[0].Text))
|
|
require.NotNil(t, reasoningParts[0].CreatedAt)
|
|
require.NotNil(t, reasoningParts[0].CompletedAt)
|
|
require.False(t, reasoningParts[0].CreatedAt.IsZero())
|
|
require.False(t, reasoningParts[0].CompletedAt.IsZero())
|
|
require.False(t, reasoningParts[0].CompletedAt.Before(*reasoningParts[0].CreatedAt))
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_DynamicToolsAndStopAfterToolBehavior(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("dynamic tool enters requires action", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
streamedCallCount.Add(1)
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("my_dynamic_tool", `{"query":"test"}`),
|
|
)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
dynamicToolsJSON := dynamicToolJSON(t, "my_dynamic_tool")
|
|
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "dynamic-tool-requires-action",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("call the dynamic tool"),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var chatResult database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusRequiresAction || got.Status == database.ChatStatusError
|
|
}, testutil.IntervalFast)
|
|
require.Equal(t, database.ChatStatusRequiresAction, chatResult.Status,
|
|
"expected requires_action, got %s (last_error=%q)",
|
|
chatResult.Status, chatLastErrorMessage(chatResult.LastError))
|
|
require.True(t, chatResult.RequiresActionDeadlineAt.Valid)
|
|
require.Equal(t, int32(1), streamedCallCount.Load())
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
call := requireToolCallPart(t, parts, "my_dynamic_tool")
|
|
require.JSONEq(t, `{"query":"test"}`, string(call.Args))
|
|
require.False(t, toolResultPartExists(parts, "my_dynamic_tool"),
|
|
"dynamic tool should wait for submitted results")
|
|
})
|
|
|
|
t.Run("successful stop after tool finishes turn", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch streamedCallCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("propose_plan", `{"path":""}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("should not continue")...)
|
|
}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newWorkspaceToolTestServer(t, db, ps, dbAgent.ID, "# Plan\n", func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "stop-after-success",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
PlanMode: database.NullChatPlanMode{ChatPlanMode: database.ChatPlanModePlan, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("propose a plan"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chatResult := waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chatResult.WorkerID.Valid)
|
|
require.False(t, chatResult.RunnerID.Valid)
|
|
require.Equal(t, int32(1), streamedCallCount.Load(),
|
|
"stop after tool should finish without another assistant call")
|
|
|
|
result := requireToolResultPart(t, chatToolParts(ctx, t, db, chat.ID), "propose_plan")
|
|
require.False(t, result.IsError,
|
|
"stop after tool should be based on a successful tool result")
|
|
})
|
|
|
|
t.Run("error stop after tool continues generation", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch streamedCallCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("propose_plan", `{"path":"/tmp/not-plan.txt"}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("tool failed, continue")...)
|
|
}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newWorkspaceToolTestServer(t, db, ps, dbAgent.ID, "# Plan\n", func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "stop-after-error",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
PlanMode: database.NullChatPlanMode{ChatPlanMode: database.ChatPlanModePlan, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("propose a plan with a bad path"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Equal(t, int32(2), streamedCallCount.Load(),
|
|
"error stop after tool result should not finish the turn by itself")
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
result := requireToolResultPart(t, parts, "propose_plan")
|
|
require.True(t, result.IsError)
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "tool failed, continue")
|
|
})
|
|
}
|
|
|
|
func TestCallerSuppliedToolsDisabledSkipsDynamicTools(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var offeredDynamicTool atomic.Bool
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
for _, tool := range req.Tools {
|
|
if tool.Function.Name == "my_dynamic_tool" {
|
|
offeredDynamicTool.Store(true)
|
|
}
|
|
}
|
|
switch streamedCallCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("my_dynamic_tool", `{"query":"test"}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
cfg.DisableCallerSuppliedTools = true
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "dynamic-tools-disabled",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("call the dynamic tool"),
|
|
},
|
|
DynamicTools: dynamicToolJSON(t, "my_dynamic_tool"),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
chatResult := waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chatResult.RequiresActionDeadlineAt.Valid)
|
|
require.Equal(t, int32(2), streamedCallCount.Load(),
|
|
"unresolved call to a disabled dynamic tool should get a local error result and continue")
|
|
require.False(t, offeredDynamicTool.Load())
|
|
|
|
result := requireToolResultPart(t, chatToolParts(ctx, t, db, chat.ID), "my_dynamic_tool")
|
|
require.True(t, result.IsError)
|
|
require.JSONEq(t, `{"error":"Tool not active in this turn: my_dynamic_tool"}`, string(result.Result))
|
|
}
|
|
|
|
func TestDynamicToolCallPausesAndResumes(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Track streaming calls to the mock LLM.
|
|
var streamedCallCount atomic.Int32
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([]chattest.OpenAIRequest, 0, 2)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
// Non-streaming requests are title generation. Return a
|
|
// simple title.
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Dynamic tool test")
|
|
}
|
|
|
|
// Capture the full request for later assertions.
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, chattest.OpenAIRequest{
|
|
Messages: append([]chattest.OpenAIMessage(nil), req.Messages...),
|
|
Tools: append([]chattest.OpenAITool(nil), req.Tools...),
|
|
Stream: req.Stream,
|
|
})
|
|
streamedCallsMu.Unlock()
|
|
|
|
if streamedCallCount.Add(1) == 1 {
|
|
// First call: the LLM invokes our dynamic tool.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"my_dynamic_tool",
|
|
`{"input":"hello world"}`,
|
|
),
|
|
)
|
|
}
|
|
// Second call: the LLM returns a normal text response.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Dynamic tool result received.")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
// Dynamic tools do not need a workspace connection, but the
|
|
// chatd server always builds workspace tools. Use an active
|
|
// server without an agent connection, so the built-in tools
|
|
// are never invoked because the only tool call targets our
|
|
// dynamic tool.
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
// Create a chat with a dynamic tool.
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: "my_dynamic_tool",
|
|
Description: "A test dynamic tool.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"input": map[string]any{"type": "string"},
|
|
},
|
|
"required": []string{"input"},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "dynamic-tool-pause-resume",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Please call the dynamic tool."),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// 1. Wait for the chat to reach requires_action status.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusRequiresAction ||
|
|
got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
require.Equal(t, database.ChatStatusRequiresAction, chatResult.Status,
|
|
"expected requires_action, got %s (last_error=%q)",
|
|
chatResult.Status, chatLastErrorMessage(chatResult.LastError))
|
|
|
|
// 2. Read the assistant message to find the tool-call ID.
|
|
var toolCallID string
|
|
var toolCallFound bool
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleAssistant {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
if parseErr != nil {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolName == "my_dynamic_tool" {
|
|
toolCallID = part.ToolCallID
|
|
toolCallFound = true
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.True(t, toolCallFound, "expected to find tool call for my_dynamic_tool")
|
|
require.NotEmpty(t, toolCallID)
|
|
|
|
// 3. Submit tool results via SubmitToolResults.
|
|
toolResultOutput := json.RawMessage(`{"result":"dynamic tool output"}`)
|
|
err = server.SubmitToolResults(ctx, chatd.SubmitToolResultsOptions{
|
|
ChatID: chat.ID,
|
|
UserID: user.ID,
|
|
ModelConfigID: chatResult.LastModelConfigID,
|
|
Results: []codersdk.ToolResult{{
|
|
ToolCallID: toolCallID,
|
|
Output: toolResultOutput,
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// 4. Wait for the chat to reach a terminal status.
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
// 5. Verify the chat completed successfully.
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
// 6. Verify the mock received exactly 2 streaming calls.
|
|
require.Equal(t, int32(2), streamedCallCount.Load(),
|
|
"expected exactly 2 streaming calls to the LLM")
|
|
|
|
streamedCallsMu.Lock()
|
|
recordedCalls := append([]chattest.OpenAIRequest(nil), streamedCalls...)
|
|
streamedCallsMu.Unlock()
|
|
require.Len(t, recordedCalls, 2)
|
|
|
|
// 7. Verify the dynamic tool appeared in the first call's tool list.
|
|
var foundDynamicTool bool
|
|
for _, tool := range recordedCalls[0].Tools {
|
|
if tool.Function.Name == "my_dynamic_tool" {
|
|
foundDynamicTool = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundDynamicTool,
|
|
"expected 'my_dynamic_tool' in the first LLM call's tool list")
|
|
|
|
// 8. Verify the second call's messages contain the tool result.
|
|
var foundToolResultInSecondCall bool
|
|
for _, message := range recordedCalls[1].Messages {
|
|
if message.Role != "tool" {
|
|
continue
|
|
}
|
|
if strings.Contains(message.Content, "dynamic tool output") {
|
|
foundToolResultInSecondCall = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundToolResultInSecondCall,
|
|
"expected second LLM call to include the submitted dynamic tool result")
|
|
}
|
|
|
|
func TestDynamicToolNamedProposePlanRemainsAvailableOutsidePlanMode(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([]chattest.OpenAIRequest, 0, 1)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Dynamic tool collision test")
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, chattest.OpenAIRequest{
|
|
Messages: append([]chattest.OpenAIMessage(nil), req.Messages...),
|
|
Tools: append([]chattest.OpenAITool(nil), req.Tools...),
|
|
Stream: req.Stream,
|
|
})
|
|
streamedCallsMu.Unlock()
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Dynamic tool list captured.")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: "propose_plan",
|
|
Description: "A dynamic tool whose name collides with the hidden built-in.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"input": map[string]any{"type": "string"},
|
|
},
|
|
"required": []string{"input"},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "dynamic-propose-plan-collision",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("List the available tools."),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
recordedCalls := append([]chattest.OpenAIRequest(nil), streamedCalls...)
|
|
streamedCallsMu.Unlock()
|
|
require.NotEmpty(t, recordedCalls)
|
|
|
|
var foundDynamicTool bool
|
|
for _, tool := range recordedCalls[0].Tools {
|
|
if tool.Function.Name == "propose_plan" {
|
|
foundDynamicTool = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundDynamicTool,
|
|
"expected the dynamic propose_plan tool to remain visible outside plan mode")
|
|
}
|
|
|
|
func TestDynamicToolCallMixedWithBuiltIn(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Track streaming calls to the mock LLM.
|
|
var streamedCallCount atomic.Int32
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([]chattest.OpenAIRequest, 0, 2)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Mixed tool test")
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, chattest.OpenAIRequest{
|
|
Messages: append([]chattest.OpenAIMessage(nil), req.Messages...),
|
|
Tools: append([]chattest.OpenAITool(nil), req.Tools...),
|
|
Stream: req.Stream,
|
|
})
|
|
streamedCallsMu.Unlock()
|
|
|
|
if streamedCallCount.Add(1) == 1 {
|
|
// First call: return TWO tool calls in one
|
|
// response: a built-in tool (read_file) and a
|
|
// dynamic tool (my_dynamic_tool).
|
|
builtinChunk := chattest.OpenAIToolCallChunk(
|
|
"read_file",
|
|
`{"path":"/tmp/test.txt"}`,
|
|
)
|
|
dynamicChunk := chattest.OpenAIToolCallChunk(
|
|
"my_dynamic_tool",
|
|
`{"input":"hello world"}`,
|
|
)
|
|
// Merge both tool calls into one chunk with
|
|
// separate indices so the LLM appears to have
|
|
// requested both tools simultaneously.
|
|
mergedChunk := builtinChunk
|
|
dynCall := dynamicChunk.Choices[0].ToolCalls[0]
|
|
dynCall.Index = 1
|
|
mergedChunk.Choices[0].ToolCalls = append(
|
|
mergedChunk.Choices[0].ToolCalls,
|
|
dynCall,
|
|
)
|
|
return chattest.OpenAIStreamingResponse(mergedChunk)
|
|
}
|
|
// Second call (after tool results): normal text
|
|
// response.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("All done.")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
// Create a chat with a dynamic tool.
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: "my_dynamic_tool",
|
|
Description: "A test dynamic tool.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"input": map[string]any{"type": "string"},
|
|
},
|
|
"required": []string{"input"},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "mixed-builtin-dynamic",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Call both tools."),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// 1. Wait for the chat to reach requires_action status.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusRequiresAction ||
|
|
got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
require.Equal(t, database.ChatStatusRequiresAction, chatResult.Status,
|
|
"expected requires_action, got %s (last_error=%q)",
|
|
chatResult.Status, chatLastErrorMessage(chatResult.LastError))
|
|
|
|
// 2. Verify the built-in tool (read_file) was already
|
|
// executed by checking that a tool result message
|
|
// exists for it in the database.
|
|
var builtinToolResultFound bool
|
|
var toolCallID string
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for _, msg := range messages {
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
if parseErr != nil {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
// Check for the built-in tool result.
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolName == "read_file" {
|
|
builtinToolResultFound = true
|
|
}
|
|
// Find the dynamic tool call ID.
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolName == "my_dynamic_tool" {
|
|
toolCallID = part.ToolCallID
|
|
}
|
|
}
|
|
}
|
|
return builtinToolResultFound && toolCallID != ""
|
|
}, testutil.IntervalFast)
|
|
|
|
require.True(t, builtinToolResultFound,
|
|
"expected read_file tool result in the DB before dynamic tool resolution")
|
|
require.NotEmpty(t, toolCallID)
|
|
|
|
// 3. Submit dynamic tool results.
|
|
err = server.SubmitToolResults(ctx, chatd.SubmitToolResultsOptions{
|
|
ChatID: chat.ID,
|
|
UserID: user.ID,
|
|
ModelConfigID: chatResult.LastModelConfigID,
|
|
Results: []codersdk.ToolResult{{
|
|
ToolCallID: toolCallID,
|
|
Output: json.RawMessage(`{"result":"dynamic output"}`),
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// 4. Wait for the chat to complete.
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
// 5. Verify the LLM received exactly 2 streaming calls.
|
|
require.Equal(t, int32(2), streamedCallCount.Load(),
|
|
"expected exactly 2 streaming calls to the LLM")
|
|
}
|
|
|
|
func TestSubmitToolResultsConcurrency(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// The mock LLM returns a dynamic tool call on the first streaming
|
|
// request, then a plain text reply on the second.
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Concurrency test")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"my_dynamic_tool",
|
|
`{"input":"hello"}`,
|
|
),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Done.")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
// Create a chat with a dynamic tool.
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: "my_dynamic_tool",
|
|
Description: "A test dynamic tool.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"input": map[string]any{"type": "string"},
|
|
},
|
|
"required": []string{"input"},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "concurrency-tool-results",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Please call the dynamic tool."),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the chat to reach requires_action status.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusRequiresAction ||
|
|
got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
require.Equal(t, database.ChatStatusRequiresAction, chatResult.Status,
|
|
"expected requires_action, got %s (last_error=%q)",
|
|
chatResult.Status, chatLastErrorMessage(chatResult.LastError))
|
|
|
|
// Find the tool call ID from the assistant message.
|
|
var toolCallID string
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleAssistant {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
if parseErr != nil {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolName == "my_dynamic_tool" {
|
|
toolCallID = part.ToolCallID
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.NotEmpty(t, toolCallID)
|
|
|
|
// Spawn N goroutines that all try to submit tool results at the
|
|
// same time. Exactly one should succeed; the rest must get a
|
|
// ToolResultStatusConflictError.
|
|
const numGoroutines = 10
|
|
var (
|
|
wg sync.WaitGroup
|
|
ready = make(chan struct{})
|
|
successes atomic.Int32
|
|
conflicts atomic.Int32
|
|
unexpectedErrors = make(chan error, numGoroutines)
|
|
)
|
|
|
|
for range numGoroutines {
|
|
wg.Go(func() {
|
|
// Wait for all goroutines to be ready.
|
|
<-ready
|
|
|
|
submitErr := server.SubmitToolResults(ctx, chatd.SubmitToolResultsOptions{
|
|
ChatID: chat.ID,
|
|
UserID: user.ID,
|
|
ModelConfigID: chatResult.LastModelConfigID,
|
|
Results: []codersdk.ToolResult{{
|
|
ToolCallID: toolCallID,
|
|
Output: json.RawMessage(`{"result":"concurrent output"}`),
|
|
}},
|
|
})
|
|
|
|
if submitErr == nil {
|
|
successes.Add(1)
|
|
return
|
|
}
|
|
var conflict *chatd.ToolResultStatusConflictError
|
|
if errors.As(submitErr, &conflict) && submitErr.Error() == conflict.Error() {
|
|
conflicts.Add(1)
|
|
return
|
|
}
|
|
// Collect unexpected errors for assertion
|
|
// outside the goroutine (require.NoError
|
|
// calls t.FailNow which is illegal here).
|
|
unexpectedErrors <- submitErr
|
|
})
|
|
}
|
|
// Release all goroutines at once.
|
|
close(ready)
|
|
|
|
wg.Wait()
|
|
close(unexpectedErrors)
|
|
|
|
for ue := range unexpectedErrors {
|
|
require.NoError(t, ue, "unexpected error from SubmitToolResults")
|
|
}
|
|
|
|
require.Equal(t, int32(1), successes.Load(),
|
|
"expected exactly 1 goroutine to succeed")
|
|
require.Equal(t, int32(numGoroutines-1), conflicts.Load(),
|
|
"expected %d conflict errors", numGoroutines-1)
|
|
}
|
|
|
|
func ptrRef[T any](v T) *T {
|
|
return &v
|
|
}
|
|
|
|
func TestSubscribeNoDuplicateMessageParts(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "no-dup-parts",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
snapshot, events, cancel, ok := replica.Subscribe(ctx, chat.ID, nil, 0, 0)
|
|
require.True(t, ok)
|
|
t.Cleanup(cancel)
|
|
|
|
// Snapshot should have events (at minimum: status + message).
|
|
require.NotEmpty(t, snapshot)
|
|
|
|
// The events channel should NOT immediately produce any
|
|
// events. The snapshot already contained everything. Before
|
|
// the fix, localSnapshot was replayed into the channel,
|
|
// causing duplicates.
|
|
require.Never(t, func() bool {
|
|
select {
|
|
case <-events:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}, 200*time.Millisecond, testutil.IntervalFast,
|
|
"expected no duplicate events after snapshot")
|
|
}
|
|
|
|
func TestSubscribeAfterMessageID(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: model.ID,
|
|
Title: "after-id-test",
|
|
Status: database.ChatStatusWaiting,
|
|
})
|
|
|
|
// Seed all messages directly so this subscription test is independent
|
|
// of chat processing lifecycle behavior.
|
|
firstContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("first"),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_ = dbgen.ChatMessage(t, db, database.ChatMessage{
|
|
ChatID: chat.ID,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
Role: database.ChatMessageRoleUser,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
Content: firstContent,
|
|
})
|
|
|
|
secondContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("second"),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
msg2 := dbgen.ChatMessage(t, db, database.ChatMessage{
|
|
ChatID: chat.ID,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
Role: database.ChatMessageRoleAssistant,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
Content: secondContent,
|
|
})
|
|
|
|
thirdContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("third"),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_ = dbgen.ChatMessage(t, db, database.ChatMessage{
|
|
ChatID: chat.ID,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
Role: database.ChatMessageRoleUser,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
Content: thirdContent,
|
|
})
|
|
|
|
// Control: Subscribe with afterMessageID=0 returns ALL messages.
|
|
allSnapshot, _, cancelAll, ok := replica.Subscribe(ctx, chat.ID, nil, 0, 0)
|
|
require.True(t, ok)
|
|
cancelAll()
|
|
|
|
allMessages := filterMessageEvents(allSnapshot)
|
|
require.Len(t, allMessages, 3, "afterMessageID=0 should return all three messages")
|
|
|
|
// Subscribe with afterMessageID set to the second message's ID.
|
|
// Only the third message (inserted after msg2) should appear.
|
|
partialSnapshot, _, cancelPartial, ok := replica.Subscribe(ctx, chat.ID, nil, msg2.ID, 0)
|
|
require.True(t, ok)
|
|
cancelPartial()
|
|
|
|
partialMessages := filterMessageEvents(partialSnapshot)
|
|
require.Len(t, partialMessages, 1, "afterMessageID=msg2.ID should return only messages after msg2")
|
|
require.Equal(t, codersdk.ChatMessageRoleUser, partialMessages[0].Message.Role)
|
|
|
|
err = db.SoftDeleteChatMessagesAfterID(ctx, database.SoftDeleteChatMessagesAfterIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: msg2.ID - 1,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
resetSnapshot, _, cancelReset, ok := replica.Subscribe(ctx, chat.ID, nil, msg2.ID, 0)
|
|
require.True(t, ok)
|
|
cancelReset()
|
|
|
|
resets := slice.Filter(resetSnapshot, func(e codersdk.ChatStreamEvent) bool {
|
|
return e.Type == codersdk.ChatStreamEventTypeHistoryReset
|
|
})
|
|
require.Len(t, resets, 1, "deleted cursor should trigger a history reset")
|
|
resetMessages := filterMessageEvents(resetSnapshot)
|
|
require.Len(t, resetMessages, 1, "only the message before the truncation survives")
|
|
require.Equal(t, []codersdk.ChatMessagePart{codersdk.ChatMessageText("first")}, resetMessages[0].Message.Content)
|
|
}
|
|
|
|
func TestSubscribeAfterMessageIDWithEdit(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: model.ID,
|
|
Title: "after-id-edit-test",
|
|
Status: database.ChatStatusWaiting,
|
|
})
|
|
|
|
insertMessage := func(role database.ChatMessageRole, text string) database.ChatMessage {
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(text),
|
|
})
|
|
require.NoError(t, err)
|
|
msg := database.ChatMessage{
|
|
ChatID: chat.ID,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
Role: role,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
Content: content,
|
|
}
|
|
if role == database.ChatMessageRoleUser {
|
|
msg.CreatedBy = uuid.NullUUID{UUID: user.ID, Valid: true}
|
|
}
|
|
return dbgen.ChatMessage(t, db, msg)
|
|
}
|
|
first := insertMessage(database.ChatMessageRoleUser, "first")
|
|
firstReply := insertMessage(database.ChatMessageRoleAssistant, "first reply")
|
|
second := insertMessage(database.ChatMessageRoleUser, "second")
|
|
secondReply := insertMessage(database.ChatMessageRoleAssistant, "second reply")
|
|
|
|
// Editing the second user message deletes it and its reply.
|
|
edit, err := replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
EditedMessageID: second.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("second edited")},
|
|
})
|
|
require.NoError(t, err)
|
|
require.ElementsMatch(t, []int64{second.ID, secondReply.ID}, edit.DeletedMessageIDs)
|
|
require.NotEmpty(t, edit.InsertedMessages)
|
|
newest := edit.InsertedMessages[len(edit.InsertedMessages)-1]
|
|
|
|
isHistoryReset := func(e codersdk.ChatStreamEvent) bool {
|
|
return e.Type == codersdk.ChatStreamEventTypeHistoryReset
|
|
}
|
|
|
|
// A client that loaded after the edit gets neither a reset nor the
|
|
// messages it holds.
|
|
snapshot, _, cancel, ok := replica.Subscribe(ctx, chat.ID, nil, newest.ID, 0)
|
|
require.True(t, ok)
|
|
cancel()
|
|
require.False(t, slices.ContainsFunc(snapshot, isHistoryReset))
|
|
require.Empty(t, filterMessageEvents(snapshot))
|
|
|
|
// A client that loaded before the edit holds deleted messages, so it
|
|
// gets a reset with the live history.
|
|
snapshot, _, cancel, ok = replica.Subscribe(ctx, chat.ID, nil, secondReply.ID, 0)
|
|
require.True(t, ok)
|
|
cancel()
|
|
require.True(t, slices.ContainsFunc(snapshot, isHistoryReset))
|
|
wantIDs := []int64{first.ID, firstReply.ID}
|
|
for _, msg := range edit.InsertedMessages {
|
|
wantIDs = append(wantIDs, msg.ID)
|
|
}
|
|
var gotIDs []int64
|
|
for _, e := range filterMessageEvents(snapshot) {
|
|
gotIDs = append(gotIDs, e.Message.ID)
|
|
}
|
|
require.Equal(t, wantIDs, gotIDs)
|
|
}
|
|
|
|
// filterMessageEvents returns only the Message-type events from a
|
|
// snapshot slice, which is useful for ignoring status / queue events.
|
|
func filterMessageEvents(events []codersdk.ChatStreamEvent) []codersdk.ChatStreamEvent {
|
|
return slice.Filter(events, func(e codersdk.ChatStreamEvent) bool {
|
|
return e.Type == codersdk.ChatStreamEventTypeMessage
|
|
})
|
|
}
|
|
|
|
func TestCreateWorkspaceTool_EndToEnd(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
instruction = "Run the workspace checks before reporting completion."
|
|
skillName = "workspace-checks"
|
|
skillDescription = "Validate the newly created workspace."
|
|
mcpToolName = "workspace__check"
|
|
)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
deploymentValues := coderdtest.DeploymentValues(t)
|
|
// Keep the seeded published snapshot independent of agent discovery.
|
|
deploymentValues.DisableWorkspaceAgentContextSync = true
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
DeploymentValues: deploymentValues,
|
|
IncludeProvisionerDaemon: true,
|
|
})
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
user := coderdtest.CreateFirstUser(t, client)
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
|
|
agentToken := uuid.NewString()
|
|
// Add a startup script so the agent spends time in the
|
|
// "starting" lifecycle state. This lets us verify that
|
|
// create_workspace waits for scripts to finish.
|
|
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionPlan: echo.PlanComplete,
|
|
ProvisionApply: echo.ApplyComplete,
|
|
ProvisionGraph: echo.ProvisionGraphWithAgent(agentToken, func(g *proto.GraphComplete) {
|
|
g.Resources[0].Agents[0].Scripts = []*proto.Script{{
|
|
DisplayName: "setup",
|
|
Script: "sleep 5",
|
|
RunOnStart: true,
|
|
}}
|
|
}),
|
|
})
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
|
|
|
|
workspaceName := "chat-ws-" + strings.ReplaceAll(uuid.NewString(), "-", "")[:8]
|
|
createWorkspaceArgs := fmt.Sprintf(
|
|
`{"template_id":%q,"name":%q}`,
|
|
template.ID.String(),
|
|
workspaceName,
|
|
)
|
|
|
|
var streamedCallCount atomic.Int32
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([]recordedOpenAIRequest, 0, 2)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Create workspace test")
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, recordOpenAIRequest(t, req))
|
|
streamedCallsMu.Unlock()
|
|
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("create_workspace", createWorkspaceArgs),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Workspace created and ready.")...,
|
|
)
|
|
})
|
|
|
|
coderdtest.CreateOpenAICompatChatModel(t, expClient, openAIURL)
|
|
|
|
chat, err := expClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
Content: []codersdk.ChatInputPart{
|
|
{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "Create a workspace from the template and continue.",
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var workspaceAgentID uuid.UUID
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := expClient.GetChat(ctx, chat.ID)
|
|
if getErr != nil || got.WorkspaceID == nil {
|
|
return false
|
|
}
|
|
workspace, getErr := client.Workspace(ctx, *got.WorkspaceID)
|
|
if getErr != nil || workspace.LatestBuild.Status != codersdk.WorkspaceStatusRunning {
|
|
return false
|
|
}
|
|
for _, resource := range workspace.LatestBuild.Resources {
|
|
for _, workspaceAgent := range resource.Agents {
|
|
workspaceAgentID = workspaceAgent.ID
|
|
}
|
|
}
|
|
return workspaceAgentID != uuid.Nil
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
require.EqualValues(t, 1, streamedCallCount.Load())
|
|
|
|
// Publish before the agent connects so the same-turn continuation has
|
|
// a complete snapshot. This does not test startup discovery readiness.
|
|
instructionBody, err := protojson.Marshal(&agentproto.InstructionFileBody{Content: []byte(instruction)})
|
|
require.NoError(t, err)
|
|
skillBody, err := protojson.Marshal(&agentproto.SkillMetaBody{
|
|
Name: skillName,
|
|
Description: skillDescription,
|
|
Meta: []byte("---\nname: " + skillName + "\ndescription: " + skillDescription + "\n---\nRun workspace checks.\n"),
|
|
})
|
|
require.NoError(t, err)
|
|
schema, err := structpb.NewStruct(map[string]any{"type": "object"})
|
|
require.NoError(t, err)
|
|
mcpBody, err := protojson.Marshal(&agentproto.MCPServerBody{
|
|
ServerName: "workspace",
|
|
Tools: []*agentproto.MCPTool{{Name: "check", Description: "Check the workspace.", InputSchema: schema}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
systemCtx := dbauthz.AsSystemRestricted(ctx)
|
|
now := dbtime.Now()
|
|
for _, resource := range []database.UpsertWorkspaceAgentContextResourceParams{
|
|
{Source: "/workspace/AGENTS.md", BodyKind: database.WorkspaceAgentContextBodyKindInstructionFile, Body: instructionBody},
|
|
{Source: "/workspace/skills/" + skillName, BodyKind: database.WorkspaceAgentContextBodyKindSkill, Body: skillBody},
|
|
{Source: "workspace", BodyKind: database.WorkspaceAgentContextBodyKindMcpServer, Body: mcpBody},
|
|
} {
|
|
resource.WorkspaceAgentID = workspaceAgentID
|
|
resource.ContentHash = []byte(resource.Source)
|
|
resource.SizeBytes = int64(len(resource.Body))
|
|
resource.Status = database.WorkspaceAgentContextResourceStatusOk
|
|
resource.Now = now
|
|
_, err = api.Database.UpsertWorkspaceAgentContextResource(systemCtx, resource)
|
|
require.NoError(t, err)
|
|
}
|
|
_, err = api.Database.UpsertWorkspaceAgentContextSnapshot(systemCtx, database.UpsertWorkspaceAgentContextSnapshotParams{
|
|
WorkspaceAgentID: workspaceAgentID,
|
|
Version: 1,
|
|
AggregateHash: []byte("created-workspace-context"),
|
|
ReceivedAt: now,
|
|
})
|
|
require.NoError(t, err)
|
|
_ = agenttest.New(t, client.URL, agentToken)
|
|
|
|
var chatResult codersdk.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := expClient.GetChat(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == codersdk.ChatStatusWaiting || got.Status == codersdk.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == codersdk.ChatStatusError {
|
|
lastError := ""
|
|
if chatResult.LastError != nil {
|
|
lastError = chatResult.LastError.Message
|
|
}
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", lastError)
|
|
}
|
|
|
|
require.NotNil(t, chatResult.WorkspaceID)
|
|
workspaceID := *chatResult.WorkspaceID
|
|
workspace, err := client.Workspace(ctx, workspaceID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, workspaceName, workspace.Name)
|
|
|
|
chatMsgs, err := expClient.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
|
|
var foundCreateWorkspaceResult bool
|
|
for _, message := range chatMsgs.Messages {
|
|
if message.Role != codersdk.ChatMessageRoleTool {
|
|
continue
|
|
}
|
|
for _, part := range message.Content {
|
|
if part.Type != codersdk.ChatMessagePartTypeToolResult || part.ToolName != "create_workspace" {
|
|
continue
|
|
}
|
|
var result map[string]any
|
|
require.NoError(t, json.Unmarshal(part.Result, &result))
|
|
created, ok := result["created"].(bool)
|
|
require.True(t, ok)
|
|
require.True(t, created)
|
|
foundCreateWorkspaceResult = true
|
|
}
|
|
}
|
|
require.True(t, foundCreateWorkspaceResult, "expected create_workspace tool result message")
|
|
require.Len(t, slice.Filter(chatMsgs.Messages, func(message codersdk.ChatMessage) bool {
|
|
return message.Role == codersdk.ChatMessageRoleUser
|
|
}), 1, "workspace context should be available without another user turn")
|
|
|
|
// Verify that the tool waited for startup scripts to
|
|
// complete. The agent should be in "ready" state by the
|
|
// time create_workspace returns its result.
|
|
workspace, err = client.Workspace(ctx, workspaceID)
|
|
require.NoError(t, err)
|
|
var agentLifecycle codersdk.WorkspaceAgentLifecycle
|
|
for _, res := range workspace.LatestBuild.Resources {
|
|
for _, agt := range res.Agents {
|
|
agentLifecycle = agt.LifecycleState
|
|
}
|
|
}
|
|
require.Equal(t, codersdk.WorkspaceAgentLifecycleReady, agentLifecycle,
|
|
"agent should be ready after create_workspace returns; startup scripts were not awaited")
|
|
|
|
streamedCallsMu.Lock()
|
|
recordedStreamCalls := append([]recordedOpenAIRequest(nil), streamedCalls...)
|
|
streamedCallsMu.Unlock()
|
|
require.Len(t, recordedStreamCalls, 2)
|
|
|
|
for i, call := range recordedStreamCalls {
|
|
var systemContent string
|
|
for _, message := range call.Messages {
|
|
if message.Role == "system" {
|
|
systemContent += message.Content + "\n"
|
|
}
|
|
}
|
|
if i == 0 {
|
|
require.NotContains(t, systemContent, instruction)
|
|
require.NotContains(t, systemContent, skillName)
|
|
require.NotContains(t, call.Offered, mcpToolName)
|
|
continue
|
|
}
|
|
require.Contains(t, systemContent, "<workspace-context>")
|
|
require.Contains(t, systemContent, instruction)
|
|
require.Contains(t, systemContent, "<available-skills>")
|
|
require.Contains(t, systemContent, skillName)
|
|
require.Contains(t, systemContent, skillDescription)
|
|
require.Contains(t, call.Offered, mcpToolName)
|
|
}
|
|
|
|
var foundToolResultInSecondCall bool
|
|
for _, message := range recordedStreamCalls[1].Messages {
|
|
if message.Role != "tool" {
|
|
continue
|
|
}
|
|
if !json.Valid([]byte(message.Content)) {
|
|
continue
|
|
}
|
|
var result map[string]any
|
|
if err := json.Unmarshal([]byte(message.Content), &result); err != nil {
|
|
continue
|
|
}
|
|
created, ok := result["created"].(bool)
|
|
if ok && created {
|
|
foundToolResultInSecondCall = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundToolResultInSecondCall, "expected second streamed model call to include create_workspace tool output")
|
|
}
|
|
|
|
type failChatBindStore struct{ database.Store }
|
|
|
|
func (s failChatBindStore) InTx(f func(database.Store) error, opts *database.TxOptions) error {
|
|
return s.Store.InTx(func(tx database.Store) error { return f(failChatBindStore{tx}) }, opts)
|
|
}
|
|
|
|
func (failChatBindStore) UpdateChatWorkspaceBinding(context.Context, database.UpdateChatWorkspaceBindingParams) (database.Chat, error) {
|
|
return database.Chat{}, xerrors.New("bind fails")
|
|
}
|
|
|
|
func TestCreateWorkspaceTool_BindFailureCreatesNoWorkspace(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
Database: failChatBindStore{db},
|
|
Pubsub: ps,
|
|
IncludeProvisionerDaemon: true,
|
|
})
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
user := coderdtest.CreateFirstUser(t, client)
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
|
|
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Bind failure test")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAIToolCallChunk(
|
|
"create_workspace",
|
|
fmt.Sprintf(`{"template_id":%q,"name":"chat-bind-fails"}`, template.ID),
|
|
))
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("Workspace creation failed.")...)
|
|
})
|
|
coderdtest.CreateOpenAICompatChatModel(t, expClient, openAIURL)
|
|
|
|
chat, err := expClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "Create a workspace.",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := expClient.GetChat(ctx, chat.ID)
|
|
return getErr == nil && got.Status == codersdk.ChatStatusWaiting
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
result := requireToolResultPart(t, chatToolParts(ctx, t, db, chat.ID), "create_workspace")
|
|
require.Contains(t, string(result.Result), "bind chat to workspace")
|
|
|
|
workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{Owner: codersdk.Me})
|
|
require.NoError(t, err)
|
|
require.Empty(t, workspaces.Workspaces)
|
|
}
|
|
|
|
func TestStartWorkspaceTool_EndToEnd(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
DeploymentValues: coderdtest.DeploymentValues(t),
|
|
IncludeProvisionerDaemon: true,
|
|
})
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
user := coderdtest.CreateFirstUser(t, client)
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
|
|
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionPlan: echo.PlanComplete,
|
|
ProvisionApply: echo.ApplyComplete,
|
|
})
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
|
|
owner, err := client.User(ctx, codersdk.Me)
|
|
require.NoError(t, err)
|
|
err = api.Database.UpdateTemplateAccessControlByID(dbauthz.As(ctx, coderdtest.AuthzUserSubject(owner)), database.UpdateTemplateAccessControlByIDParams{
|
|
ID: template.ID,
|
|
RequireActiveVersion: true,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Create a workspace, then stop it so start_workspace has
|
|
// something to start. We intentionally skip starting a test
|
|
// agent. The echo provisioner creates new agent rows for each
|
|
// build, so an agent started for build 1 cannot serve build 3.
|
|
// The tool handles the no-agent case gracefully.
|
|
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
|
|
workspace = coderdtest.MustTransitionWorkspace(
|
|
t, client, workspace.ID,
|
|
codersdk.WorkspaceTransitionStart, codersdk.WorkspaceTransitionStop,
|
|
)
|
|
|
|
activeVersion := coderdtest.UpdateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionGraph: []*proto.Response{{
|
|
Type: &proto.Response_Graph{
|
|
Graph: &proto.GraphComplete{
|
|
Parameters: []*proto.RichParameter{{
|
|
Name: "region",
|
|
Type: "string",
|
|
Required: true,
|
|
}},
|
|
},
|
|
},
|
|
}},
|
|
}, template.ID)
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, activeVersion.ID)
|
|
coderdtest.UpdateActiveTemplateVersion(t, client, template.ID, activeVersion.ID)
|
|
|
|
var streamedCallCount atomic.Int32
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([][]chattest.OpenAIMessage, 0, 3)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Start workspace test")
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, append([]chattest.OpenAIMessage(nil), req.Messages...))
|
|
streamedCallsMu.Unlock()
|
|
|
|
switch streamedCallCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("start_workspace", "{}"),
|
|
)
|
|
case 2:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("start_workspace", `{"parameters":{"region":"us"}}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Workspace started and ready.")...,
|
|
)
|
|
}
|
|
})
|
|
|
|
coderdtest.CreateOpenAICompatChatModel(t, expClient, openAIURL)
|
|
|
|
// Create a chat with the stopped workspace pre-associated.
|
|
chat, err := expClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
Content: []codersdk.ChatInputPart{
|
|
{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "Start the workspace.",
|
|
},
|
|
},
|
|
WorkspaceID: &workspace.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var chatResult codersdk.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := expClient.GetChat(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == codersdk.ChatStatusWaiting || got.Status == codersdk.ChatStatusError
|
|
}, testutil.WaitSuperLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == codersdk.ChatStatusError {
|
|
lastError := ""
|
|
if chatResult.LastError != nil {
|
|
lastError = chatResult.LastError.Message
|
|
}
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", lastError)
|
|
}
|
|
|
|
// Verify the workspace was started.
|
|
require.NotNil(t, chatResult.WorkspaceID)
|
|
updatedWorkspace, err := client.Workspace(ctx, workspace.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, codersdk.WorkspaceTransitionStart, updatedWorkspace.LatestBuild.Transition)
|
|
require.Equal(t, activeVersion.ID, updatedWorkspace.LatestBuild.TemplateVersionID, "build must be on the active version")
|
|
|
|
chatMsgs, err := expClient.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
|
|
// The active version needs a parameter the first call did not
|
|
// supply, so the first result tells the model how to retry.
|
|
var startResults []map[string]any
|
|
for _, message := range chatMsgs.Messages {
|
|
if message.Role != codersdk.ChatMessageRoleTool {
|
|
continue
|
|
}
|
|
for _, part := range message.Content {
|
|
if part.Type != codersdk.ChatMessagePartTypeToolResult || part.ToolName != "start_workspace" {
|
|
continue
|
|
}
|
|
var result map[string]any
|
|
require.NoError(t, json.Unmarshal(part.Result, &result))
|
|
startResults = append(startResults, result)
|
|
}
|
|
}
|
|
require.Len(t, startResults, 2)
|
|
// Messages are returned newest first.
|
|
started, rejected := startResults[0], startResults[1]
|
|
require.Contains(t, rejected["error"], "retry start_workspace")
|
|
require.Equal(t, template.ID.String(), rejected["template_id"])
|
|
require.Equal(t, true, started["started"])
|
|
require.Equal(t, true, started["updated_to_active_version"])
|
|
|
|
// Verify the LLM received the tool result in its third call.
|
|
require.GreaterOrEqual(t, streamedCallCount.Load(), int32(3))
|
|
streamedCallsMu.Lock()
|
|
recordedStreamCalls := append([][]chattest.OpenAIMessage(nil), streamedCalls...)
|
|
streamedCallsMu.Unlock()
|
|
require.GreaterOrEqual(t, len(recordedStreamCalls), 3)
|
|
|
|
var foundToolResultInThirdCall bool
|
|
for _, message := range recordedStreamCalls[2] {
|
|
if message.Role != "tool" {
|
|
continue
|
|
}
|
|
if !json.Valid([]byte(message.Content)) {
|
|
continue
|
|
}
|
|
var result map[string]any
|
|
if err := json.Unmarshal([]byte(message.Content), &result); err != nil {
|
|
continue
|
|
}
|
|
started, ok := result["started"].(bool)
|
|
if ok && started {
|
|
foundToolResultInThirdCall = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundToolResultInThirdCall, "expected third streamed model call to include start_workspace tool output")
|
|
}
|
|
|
|
func TestStoppedWorkspaceWithPersistedAgentBindingDoesNotBlockChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var streamedCallCount atomic.Int32
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([][]chattest.OpenAIMessage, 0, 2)
|
|
toolsByCall := make([][]string, 0, 2)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Stopped workspace regression")
|
|
}
|
|
|
|
names := make([]string, 0, len(req.Tools))
|
|
for _, tool := range req.Tools {
|
|
names = append(names, tool.Function.Name)
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, append([]chattest.OpenAIMessage(nil), req.Messages...))
|
|
toolsByCall = append(toolsByCall, names)
|
|
streamedCallsMu.Unlock()
|
|
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("execute", `{"command":"echo hi"}`),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("The workspace is unavailable. Start it before retrying workspace tools.")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
inactive := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := inactive.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "stopped-workspace-regression",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Run echo hi in the workspace."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Close the inactive server. The chat remains in the valid
|
|
// state-machine `running` state created by CreateChat, and the
|
|
// active server created below can acquire it because it is unowned.
|
|
require.NoError(t, inactive.Close())
|
|
|
|
build, err := db.GetLatestWorkspaceBuildByWorkspaceID(ctx, ws.ID)
|
|
require.NoError(t, err)
|
|
chat, err = db.UpdateChatBuildAgentBinding(ctx, database.UpdateChatBuildAgentBindingParams{
|
|
ID: chat.ID,
|
|
BuildID: uuid.NullUUID{UUID: build.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
dbfake.WorkspaceBuild(t, db, ws).Seed(database.WorkspaceBuild{
|
|
Transition: database.WorkspaceTransitionStop,
|
|
BuildNumber: 2,
|
|
}).Do()
|
|
|
|
clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger)
|
|
validationTrap := clock.Trap().NewTimer("chatd", "dial-validation-delay")
|
|
defer validationTrap.Close()
|
|
dialStarted := make(chan struct{})
|
|
var dialCalls atomic.Int32
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
_ = newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.Clock = clock
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
cfg.AgentConn = func(ctx context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
dialCalls.Add(1)
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
close(dialStarted)
|
|
<-ctx.Done()
|
|
return nil, nil, ctx.Err()
|
|
}
|
|
})
|
|
|
|
validationTimer := validationTrap.MustWait(ctx)
|
|
validationTimer.MustRelease(ctx)
|
|
testutil.TryReceive(ctx, t, dialStarted)
|
|
advanceMockClockBy(ctx, t, clock, validationTimer.Duration)
|
|
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
require.EqualValues(t, 1, dialCalls.Load())
|
|
require.GreaterOrEqual(t, streamedCallCount.Load(), int32(2))
|
|
|
|
streamedCallsMu.Lock()
|
|
recordedCalls := append([][]chattest.OpenAIMessage(nil), streamedCalls...)
|
|
recordedTools := append([][]string(nil), toolsByCall...)
|
|
streamedCallsMu.Unlock()
|
|
require.GreaterOrEqual(t, len(recordedCalls), 2)
|
|
require.NotEmpty(t, recordedTools)
|
|
require.Contains(t, recordedTools[0], "execute")
|
|
require.Contains(t, recordedTools[0], "start_workspace")
|
|
|
|
var foundUnavailableToolResult bool
|
|
for _, message := range recordedCalls[1] {
|
|
if message.Role != "tool" {
|
|
continue
|
|
}
|
|
if strings.Contains(message.Content, "workspace has no running agent") {
|
|
foundUnavailableToolResult = true
|
|
break
|
|
}
|
|
if !json.Valid([]byte(message.Content)) {
|
|
continue
|
|
}
|
|
var toolResult map[string]any
|
|
if err := json.Unmarshal([]byte(message.Content), &toolResult); err != nil {
|
|
continue
|
|
}
|
|
errMsg, _ := toolResult["error"].(string)
|
|
outputMsg, _ := toolResult["output"].(string)
|
|
if strings.Contains(errMsg, "workspace has no running agent") ||
|
|
strings.Contains(outputMsg, "workspace has no running agent") {
|
|
foundUnavailableToolResult = true
|
|
break
|
|
}
|
|
}
|
|
require.True(t, foundUnavailableToolResult,
|
|
"expected the second streamed model call to include the unavailable workspace tool result")
|
|
|
|
var toolMessage *database.ChatMessage
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for i := range messages {
|
|
if messages[i].Role == database.ChatMessageRoleTool {
|
|
toolMessage = &messages[i]
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.NotNil(t, toolMessage)
|
|
|
|
parts, err := chatprompt.ParseContent(*toolMessage)
|
|
require.NoError(t, err)
|
|
require.Len(t, parts, 1)
|
|
require.Equal(t, codersdk.ChatMessagePartTypeToolResult, parts[0].Type)
|
|
require.Equal(t, "execute", parts[0].ToolName)
|
|
require.True(t, parts[0].IsError)
|
|
require.Contains(t, string(parts[0].Result), "workspace has no running agent")
|
|
}
|
|
|
|
func TestHeartbeatNoWorkspaceNoBump(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("ok")
|
|
}
|
|
chunks := make(chan chattest.OpenAIChunk)
|
|
go func() {
|
|
defer close(chunks)
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
}))
|
|
|
|
// Set up UsageTracker with manual tick/flush.
|
|
usageTickCh := make(chan time.Time)
|
|
flushCh := make(chan int, 1)
|
|
tracker := workspacestats.NewTracker(db,
|
|
workspacestats.TrackerWithTickFlush(usageTickCh, flushCh),
|
|
workspacestats.TrackerWithLogger(slogtest.Make(t, nil)),
|
|
)
|
|
t.Cleanup(func() { tracker.Close() })
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitLong,
|
|
ChatHeartbeatInterval: 100 * time.Millisecond,
|
|
})
|
|
server.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
// Create a chat WITHOUT linking a workspace.
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "no-workspace-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the chat to be acquired and at least one runner
|
|
// heartbeat to be written.
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
fromDB, listErr := db.GetChatByID(ctx, chat.ID)
|
|
if listErr != nil || fromDB.Status != database.ChatStatusRunning || !fromDB.RunnerID.Valid {
|
|
return false
|
|
}
|
|
heartbeat, heartbeatErr := db.GetChatHeartbeat(ctx, database.GetChatHeartbeatParams{
|
|
ChatID: chat.ID,
|
|
RunnerID: fromDB.RunnerID.UUID,
|
|
})
|
|
if heartbeatErr != nil {
|
|
return false
|
|
}
|
|
return heartbeat.HeartbeatAt.After(fromDB.CreatedAt)
|
|
}, testutil.IntervalFast,
|
|
"chat should be running with at least one heartbeat")
|
|
|
|
// Flush the tracker. Since no workspace was linked, count
|
|
// should be 0.
|
|
testutil.RequireSend(ctx, t, usageTickCh, time.Now())
|
|
count := testutil.RequireReceive(ctx, t, flushCh)
|
|
require.Equal(t, 0, count, "expected no workspaces to be flushed when chat has no workspace")
|
|
}
|
|
|
|
// waitForChatProcessed waits for the chat worker to fully handle a
|
|
// wake for the given chat. It polls until the chat leaves the running
|
|
// state (the worker has finished the turn and updated the DB), then
|
|
// calls WaitUntilIdleForTest so tracked background work settles.
|
|
func waitForChatProcessed(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
server *chatd.Server,
|
|
) {
|
|
t.Helper()
|
|
require.Eventually(t, func() bool {
|
|
c, err := db.GetChatByID(ctx, chatID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
// Wait until the chat reaches a settled state (not being
|
|
// processed). This guarantees the wake was picked up and its
|
|
// background work registered before WaitUntilIdleForTest
|
|
// checks for idleness.
|
|
return c.Status != database.ChatStatusRunning
|
|
}, testutil.WaitShort, testutil.IntervalFast)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
}
|
|
|
|
func newChatdServer(t testing.TB, ps dbpubsub.Pubsub, cfg chatd.Config) *chatd.Server {
|
|
t.Helper()
|
|
server, err := chatd.New(ps, cfg)
|
|
require.NoError(t, err)
|
|
return server
|
|
}
|
|
|
|
// newTestServer creates a passive server whose periodic chat
|
|
// acquisition is effectively disabled, so chats are only processed in
|
|
// response to explicit wakes.
|
|
func newTestServer(
|
|
t *testing.T,
|
|
db database.Store,
|
|
ps dbpubsub.Pubsub,
|
|
replicaID uuid.UUID,
|
|
overrides ...func(*chatd.Config),
|
|
) *chatd.Server {
|
|
t.Helper()
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
cfg := chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: replicaID,
|
|
PendingChatAcquireInterval: testutil.WaitLong,
|
|
Experiments: codersdk.ExperimentsKnown,
|
|
MCPHTTPClient: testMCPHTTPClient(),
|
|
}
|
|
for _, o := range overrides {
|
|
o(&cfg)
|
|
}
|
|
server := newChatdServer(t, ps, cfg)
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
return server
|
|
}
|
|
|
|
func highUsageTextResponse(text string) chattest.AnthropicResponse {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 80,
|
|
OutputTokens: 5,
|
|
}, text)...)
|
|
}
|
|
|
|
func anthropicCompactionResponse(t testing.TB, req *chattest.AnthropicRequest, text string) chattest.AnthropicResponse {
|
|
t.Helper()
|
|
require.True(t, req.Stream)
|
|
// The summary cap is the configured cap bounded by the remaining
|
|
// context window, so it varies per test fixture; exact
|
|
// values are pinned in the chatloop unit tests and the hook test.
|
|
require.Positive(t, req.MaxTokens)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks(text)...)
|
|
}
|
|
|
|
func highUsageReadFileResponse(path string) chattest.AnthropicResponse {
|
|
return readFileResponseWithInputTokens(path, 80)
|
|
}
|
|
|
|
func readFileResponseWithInputTokens(path string, inputTokens int) chattest.AnthropicResponse {
|
|
chunks := chattest.AnthropicToolCallChunks("read_file", fmt.Sprintf(`{"path":%q}`, path))
|
|
for i := range chunks {
|
|
if chunks[i].Type == "message_start" {
|
|
chunks[i].Message.Usage = map[string]int{"input_tokens": inputTokens}
|
|
}
|
|
if chunks[i].Type == "message_delta" {
|
|
chunks[i].UsageMap = map[string]int{"output_tokens": 5}
|
|
}
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chunks...)
|
|
}
|
|
|
|
func TestActiveServer_PersistsAnthropicMessageID(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
chunks := chattest.AnthropicTextChunks("answer")
|
|
chunks[0].Message.ID = "msg_persisted"
|
|
return chattest.AnthropicStreamingResponse(chunks...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{ChatID: chat.ID})
|
|
require.NoError(t, err)
|
|
responseIDs := make(map[database.ChatMessageRole]sql.NullString)
|
|
for _, message := range messages {
|
|
responseIDs[message.Role] = message.ProviderResponseID
|
|
}
|
|
require.Equal(t, sql.NullString{String: "msg_persisted", Valid: true}, responseIDs[database.ChatMessageRoleAssistant])
|
|
require.False(t, responseIDs[database.ChatMessageRoleUser].Valid)
|
|
}
|
|
|
|
func TestActiveServer_RoutingPreservesAPIKeyAfterCompaction(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
compactionSummary = "summary text for AI Gateway compaction"
|
|
contextLimit = int64(100)
|
|
thresholdPercent = int32(70)
|
|
)
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("AI Gateway Compaction")
|
|
}
|
|
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
case 2:
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
default:
|
|
t.Fatalf("unexpected streamed model call %d", streamCount.Load())
|
|
return chattest.AnthropicStreamingResponse()
|
|
}
|
|
})
|
|
factory := chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath())
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, contextLimit, thresholdPercent)
|
|
provider, err := db.GetAIProviderByID(ctx, model.AIProviderID.UUID)
|
|
require.NoError(t, err)
|
|
_, err = db.UpsertUserAIProviderKey(ctx, database.UpsertUserAIProviderKeyParams{
|
|
ID: uuid.New(),
|
|
UserID: user.ID,
|
|
AIProviderID: provider.ID,
|
|
APIKey: "sk-user-aibridge",
|
|
})
|
|
require.NoError(t, err)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
creator := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := creator.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "aigateway-compaction",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("trigger compaction"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
contextContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{{
|
|
Type: codersdk.ChatMessagePartTypeContextFile,
|
|
ContextFileAgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
ContextFilePath: "/home/coder/project/AGENTS.md",
|
|
ContextFileContent: "# Project instructions",
|
|
ContextFileOS: "linux",
|
|
ContextFileDirectory: "/home/coder/project",
|
|
}})
|
|
require.NoError(t, err)
|
|
_, err = db.InsertChatMessages(ctx, singleChatMessageInsertParams(
|
|
chat.ID,
|
|
database.ChatMessageRoleUser,
|
|
contextContent,
|
|
model.ID,
|
|
user.ID,
|
|
))
|
|
require.NoError(t, err)
|
|
|
|
_ = newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
cfg.AllowBYOK = true
|
|
cfg.AllowBYOKSet = true
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, chat.ID)
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status)
|
|
require.False(t, chatResult.LastError.Valid)
|
|
gatewayKey, err := db.GetChatGatewayAPIKey(ctx, database.GetChatGatewayAPIKeyParams{
|
|
UserID: user.ID,
|
|
TokenName: chatd.GatewayTokenName(user.ID),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1)
|
|
|
|
requests := factory.RequestsSnapshot()
|
|
require.NotEmpty(t, requests)
|
|
for _, req := range requests {
|
|
require.Equal(t, provider.Name, req.ProviderName)
|
|
require.Equal(t, aibridge.SourceAgents, req.Source)
|
|
require.Equal(t, gatewayKey.ID, req.APIKeyID)
|
|
require.Equal(t, "sk-user-aibridge", req.Request.Header.Get("X-Api-Key"))
|
|
require.Equal(t, "delegated", req.Request.Header.Get(aibridge.HeaderCoderToken))
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_CompactionRecordsMetric(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
compactionSummary = "summary text for compaction"
|
|
contextLimit = int64(100)
|
|
thresholdPercent = int32(70)
|
|
)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
reg := prometheus.NewRegistry()
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
case 2:
|
|
require.Contains(t, body, compactionSummary)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
default:
|
|
t.Fatalf("unexpected generation request: %s", body)
|
|
return chattest.AnthropicStreamingResponse()
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, contextLimit, thresholdPercent)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
tracerProvider, spans := newRecordingTracerProvider(t)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.PrometheusRegistry = reg
|
|
cfg.TracerProvider = tracerProvider
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-metric",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_compaction_total", 1, map[string]string{
|
|
"provider": "anthropic",
|
|
"model": "claude-sonnet-4-20250514",
|
|
"result": "success",
|
|
})
|
|
requireCompactionSpan(t, spans, "claude-sonnet-4-20250514", chatloop.CompactionSourceAutomatic)
|
|
}
|
|
|
|
func TestActiveServer_Compaction(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
compactionSummary = "summary text for compaction"
|
|
contextLimit = int64(100)
|
|
thresholdPercent = int32(70)
|
|
)
|
|
|
|
newHighUsageReadFileResponse := func(path string) chattest.AnthropicResponse {
|
|
chunks := chattest.AnthropicToolCallChunks("read_file", fmt.Sprintf(`{"path":%q}`, path))
|
|
for i := range chunks {
|
|
if chunks[i].Type == "message_start" {
|
|
chunks[i].Message.Usage = map[string]int{"input_tokens": 80}
|
|
}
|
|
if chunks[i].Type == "message_delta" {
|
|
chunks[i].UsageMap = map[string]int{"output_tokens": 5}
|
|
}
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chunks...)
|
|
}
|
|
|
|
t.Run("commits summary when threshold reached and continues from committed summary", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Contains(t, body, "read_file")
|
|
require.Contains(t, body, "package main")
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return newHighUsageReadFileResponse("/tmp/a.txt")
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
require.Contains(t, body, "The following is a summary of the earlier conversation")
|
|
require.Contains(t, body, `"role":"user"`)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, contextLimit, thresholdPercent)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1 package main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-continues",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.WorkerID.Valid)
|
|
require.False(t, chat.RunnerID.Valid)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.GreaterOrEqual(t, len(generationRequests), 2)
|
|
require.Equal(t, int32(2), streamCount.Load())
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1)
|
|
require.Len(t, compressed.calls, 1)
|
|
require.Len(t, compressed.results, 1)
|
|
|
|
require.Equal(t, database.ChatMessageRoleUser, compressed.summaries[0].Role)
|
|
require.Equal(t, database.ChatMessageVisibilityModel, compressed.summaries[0].Visibility)
|
|
summaryText := messageText(t, compressed.summaries[0])
|
|
require.Contains(t, summaryText, "The following is a summary of the earlier conversation")
|
|
require.Contains(t, summaryText, compactionSummary)
|
|
|
|
callPart := singlePartOfType(t, compressed.calls[0], codersdk.ChatMessagePartTypeToolCall)
|
|
resultPart := singlePartOfType(t, compressed.results[0], codersdk.ChatMessagePartTypeToolResult)
|
|
require.Equal(t, callPart.ToolCallID, resultPart.ToolCallID)
|
|
require.Equal(t, "chat_summarized", resultPart.ToolName)
|
|
require.JSONEq(t, fmt.Sprintf(`{"summary":"summary text for compaction","source":"automatic","threshold_percent":70,"usage_percent":80,"context_tokens":80,"context_limit_tokens":100,"estimated_context_tokens":%d,"trigger_context_limit_tokens":100}`, (len(summaryText)+2)/3), string(resultPart.Result))
|
|
for _, msg := range []database.ChatMessage{compressed.summaries[0], compressed.calls[0], compressed.results[0]} {
|
|
require.False(t, msg.InputTokens.Valid)
|
|
require.False(t, msg.OutputTokens.Valid)
|
|
}
|
|
requireTextPart(t, messages[len(messages)-1], "continued after compaction")
|
|
})
|
|
|
|
t.Run("does not compact when high usage finishes the turn", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
var compactionRequests atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
compactionRequests.Add(1)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
streamCount.Add(1)
|
|
return highUsageTextResponse("done without compaction")
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, contextLimit, thresholdPercent)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "finish with high usage")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
require.Equal(t, int32(1), streamCount.Load())
|
|
require.Equal(t, int32(0), compactionRequests.Load())
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
compressed := compressedChatSummarizedMessages(t, messages)
|
|
require.Empty(t, compressed.summaries)
|
|
require.Empty(t, compressed.calls)
|
|
require.Empty(t, compressed.results)
|
|
for _, msg := range messages {
|
|
require.False(t, msg.Compressed, "message %d should not be compressed", msg.ID)
|
|
}
|
|
requireTextPart(t, messages[len(messages)-1], "done without compaction")
|
|
})
|
|
|
|
t.Run("next message fails when compaction continuation stayed over limit", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
logSink := testutil.NewFakeSink(t)
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return newHighUsageReadFileResponse("/tmp/a.txt")
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
return highUsageTextResponse("still too large")
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, contextLimit, thresholdPercent)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1 package main"}, nil).
|
|
Times(1)
|
|
|
|
reg := prometheus.NewRegistry()
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.Logger = logSink.Logger()
|
|
cfg.PrometheusRegistry = reg
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-next-message-over-limit",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and stay too large"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.Equal(t, int32(2), streamCount.Load())
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "still too large")
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after the large compacted turn"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
require.Equal(t,
|
|
"Conversation compaction could not reduce the history below your compaction threshold. Raise the compaction threshold in settings, or start a new conversation.",
|
|
chatLastErrorMessage(chat.LastError),
|
|
)
|
|
require.Equal(t, int32(2), streamCount.Load(), "over-limit history should fail before another model stream")
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_compaction_total", 1, map[string]string{
|
|
"provider": "anthropic",
|
|
"model": "claude-sonnet-4-20250514",
|
|
"result": "error",
|
|
})
|
|
|
|
isCompactionFailureLog := func(e slog.SinkEntry) bool {
|
|
if e.Level != slog.LevelWarn || e.Message != "chat generation failed" {
|
|
return false
|
|
}
|
|
errValue, ok := sinkFieldValue(e.Fields, "error")
|
|
return ok && strings.Contains(fmt.Sprintf("%v", errValue), "compaction left the chat above the compaction limit")
|
|
}
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
return len(logSink.Entries(isCompactionFailureLog)) > 0
|
|
}, testutil.IntervalFast)
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_ManualCompaction(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const compactionSummary = "manual compaction summary"
|
|
|
|
t.Run("compacts below threshold and returns to waiting without hooks", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
var compactionRequests atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
compactionRequests.Add(1)
|
|
require.Contains(t, body, "hello from the user")
|
|
require.True(t, anthropicMessageHasEphemeralCacheControl(t, req.Messages[len(req.Messages)-1]))
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
streamCount.Add(1)
|
|
// Low usage: far below the 70% threshold so only a
|
|
// manual request can trigger compaction.
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 10,
|
|
OutputTokens: 5,
|
|
}, "assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 100, 70)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Equal(t, int32(1), streamCount.Load())
|
|
require.Equal(t, int32(0), compactionRequests.Load())
|
|
preCompactionMessageCount := len(chatMessages(ctx, t, db, chat.ID))
|
|
|
|
compacted, err := server.CompactChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusRunning, compacted.Status)
|
|
require.True(t, compacted.CompactionRequestedAt.Valid)
|
|
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.False(t, chat.CompactionRequestedAt.Valid,
|
|
"compaction commit must consume the request marker")
|
|
require.Equal(t, int32(1), compactionRequests.Load(), "one forced compaction call")
|
|
require.Equal(t, int32(1), streamCount.Load(),
|
|
"manual compaction alone must not trigger an assistant follow-up")
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.results, 1)
|
|
resultPart := singlePartOfType(t, compressed.results[0], codersdk.ChatMessagePartTypeToolResult)
|
|
require.Equal(t, "chat_summarized", resultPart.ToolName)
|
|
var result map[string]any
|
|
require.NoError(t, json.Unmarshal(resultPart.Result, &result))
|
|
require.Equal(t, "manual", result["source"])
|
|
require.Equal(t, compactionSummary, result["summary"])
|
|
// The commit inserts the summary triplet: a hidden model-only
|
|
// boundary (visible only through the prompt query) plus the
|
|
// user-visible tool call/result pair.
|
|
require.Len(t, compressed.summaries, 1,
|
|
"prompt history contains the compressed summary boundary")
|
|
require.Len(t, compressed.calls, 1)
|
|
require.Len(t, messages, preCompactionMessageCount+2,
|
|
"user-visible history grows by the summary tool call/result pair")
|
|
|
|
// A second /compact with nothing new to summarize is
|
|
// rejected before any LLM call.
|
|
_, err = server.CompactChat(ctx, chat)
|
|
require.ErrorIs(t, err, chatd.ErrNothingToCompact)
|
|
require.Equal(t, int32(1), compactionRequests.Load())
|
|
|
|
// The chat still works: a follow-up message continues from
|
|
// the compacted summary.
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after manual compaction"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.Equal(t, int32(2), streamCount.Load())
|
|
})
|
|
|
|
t.Run("summary keeps the configured output cap", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
// A cap configured at the provider maximum, as the known-model
|
|
// catalog seeds it, must not grow on the summary request: providers
|
|
// reject max_tokens above their output limit.
|
|
const maxOutputTokens = int64(128_000)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
requests.record(req)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
requests.record(req)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 10,
|
|
OutputTokens: 5,
|
|
}, "assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 1_000_000, 80)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
MaxOutputTokens: ptr.Ref(maxOutputTokens),
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
_, err := server.CompactChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.False(t, chat.CompactionRequestedAt.Valid,
|
|
"compaction commit must consume the request marker")
|
|
|
|
recorded := requests.all()
|
|
require.Len(t, recorded, 2, "one chat turn and one summary request")
|
|
require.Equal(t, int(maxOutputTokens), recorded[0].MaxTokens, "chat turn max_tokens")
|
|
require.Equal(t, int(maxOutputTokens), recorded[1].MaxTokens, "summary max_tokens")
|
|
})
|
|
|
|
t.Run("compacts an errored chat and clears last_error", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var compactionRequests atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
compactionRequests.Add(1)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
machine := chatstate.NewChatMachine(db, ps, chat.ID)
|
|
_, err := machine.Update(ctx, func(tx *chatstate.Tx, _ database.Store, _ *chatstate.ChatSnapshot) error {
|
|
_, err := tx.FinishError(chatstate.FinishErrorInput{
|
|
LastError: mustChatLastErrorRawMessage(t, codersdk.ChatError{
|
|
Message: "input length exceeds the maximum allowed input length",
|
|
Kind: codersdk.ChatErrorKindGeneric,
|
|
}),
|
|
})
|
|
return err
|
|
})
|
|
require.NoError(t, err)
|
|
chat, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusError, chat.Status)
|
|
require.True(t, chat.LastError.Valid)
|
|
|
|
compacted, err := server.CompactChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusRunning, compacted.Status)
|
|
require.False(t, compacted.LastError.Valid,
|
|
"requesting compaction from the error state clears last_error")
|
|
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.False(t, chat.CompactionRequestedAt.Valid)
|
|
require.Equal(t, int32(1), compactionRequests.Load(), "one forced compaction call")
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1,
|
|
"prompt history contains the compressed summary boundary")
|
|
})
|
|
|
|
t.Run("retries the summary without tools when the prompt exceeds the context window", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var mu sync.Mutex
|
|
var compactionToolCounts []int
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
mu.Lock()
|
|
compactionToolCounts = append(compactionToolCounts, len(req.Tools))
|
|
mu.Unlock()
|
|
// The tool definitions push the summary request past
|
|
// the window that the tool-less request still fits.
|
|
if len(req.Tools) > 0 {
|
|
return chattest.AnthropicResponse{Error: &chattest.ErrorResponse{
|
|
StatusCode: http.StatusBadRequest,
|
|
Type: "invalid_request_error",
|
|
Message: "prompt is too long: 20000 tokens > 16385 maximum",
|
|
}}
|
|
}
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
compacted, err := server.CompactChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusRunning, compacted.Status)
|
|
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.False(t, chat.CompactionRequestedAt.Valid)
|
|
|
|
mu.Lock()
|
|
toolCounts := slices.Clone(compactionToolCounts)
|
|
mu.Unlock()
|
|
require.Len(t, toolCounts, 2, "one rejected request with tools, one tool-less retry")
|
|
require.Positive(t, toolCounts[0], "the first summary request carries the turn's tool definitions")
|
|
require.Zero(t, toolCounts[1], "the retry drops the tool definitions")
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.results, 1)
|
|
resultPart := singlePartOfType(t, compressed.results[0], codersdk.ChatMessagePartTypeToolResult)
|
|
var result map[string]any
|
|
require.NoError(t, json.Unmarshal(resultPart.Result, &result))
|
|
require.Equal(t, compactionSummary, result["summary"])
|
|
})
|
|
|
|
t.Run("busy chat rejects manual compaction", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
release := make(chan struct{})
|
|
releaseOnce := sync.OnceFunc(func() { close(release) })
|
|
streamStarted := make(chan struct{}, 1)
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
select {
|
|
case streamStarted <- struct{}{}:
|
|
default:
|
|
}
|
|
// Hold the generation open so the chat stays running.
|
|
<-release
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
// Registered after newActiveTestServer so this cleanup runs
|
|
// before server shutdown: a failed assertion must not leave
|
|
// shutdown waiting on the blocked stream.
|
|
t.Cleanup(releaseOnce)
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "stay busy")
|
|
// Wait for the generation to reach the blocked LLM call: the
|
|
// chat is then running with an owning worker.
|
|
testutil.TryReceive(ctx, t, streamStarted)
|
|
|
|
_, err := server.CompactChat(ctx, chat)
|
|
require.ErrorIs(t, err, chatstate.ErrTransitionNotAllowed)
|
|
|
|
releaseOnce()
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_ManualClear(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const clearSentinel = "Previous conversation context was cleared by the user."
|
|
|
|
t.Run("clears synchronously and the next prompt starts fresh", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
var secondStreamBody atomic.Value
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
if streamCount.Add(1) == 2 {
|
|
secondStreamBody.Store(anthropicRequestBody(t, *req))
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Equal(t, int32(1), streamCount.Load())
|
|
preClearMessageCount := len(chatMessages(ctx, t, db, chat.ID))
|
|
|
|
cleared, err := server.ClearChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusWaiting, cleared.Status)
|
|
require.Equal(t, int32(1), streamCount.Load(),
|
|
"clearing must not trigger any model call")
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
require.Len(t, messages, preClearMessageCount+2,
|
|
"user-visible history grows by the clear tool call/result pair")
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatClearedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1,
|
|
"prompt history contains the compressed sentinel boundary")
|
|
require.Equal(t, clearSentinel, messageText(t, compressed.summaries[0]))
|
|
require.Len(t, compressed.calls, 1)
|
|
require.Len(t, compressed.results, 1)
|
|
resultPart := singlePartOfType(t, compressed.results[0], codersdk.ChatMessagePartTypeToolResult)
|
|
require.Equal(t, "chat_cleared", resultPart.ToolName)
|
|
var result map[string]any
|
|
require.NoError(t, json.Unmarshal(resultPart.Result, &result))
|
|
require.Equal(t, "manual", result["source"])
|
|
|
|
_, err = server.ClearChat(ctx, chat)
|
|
require.ErrorIs(t, err, chatd.ErrNothingToClear)
|
|
_, err = server.CompactChat(ctx, chat)
|
|
require.ErrorIs(t, err, chatd.ErrNothingToCompact)
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after clear"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Equal(t, int32(2), streamCount.Load())
|
|
body, _ := secondStreamBody.Load().(string)
|
|
require.Contains(t, body, clearSentinel)
|
|
require.Contains(t, body, "continue after clear")
|
|
require.NotContains(t, body, "hello from the user",
|
|
"pre-clear user content must not reach the model")
|
|
require.NotContains(t, body, "assistant answer",
|
|
"pre-clear assistant content must not reach the model")
|
|
|
|
_, err = server.ClearChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
})
|
|
|
|
t.Run("clears an errored chat and clears last_error", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
machine := chatstate.NewChatMachine(db, ps, chat.ID)
|
|
_, err := machine.Update(ctx, func(tx *chatstate.Tx, _ database.Store, _ *chatstate.ChatSnapshot) error {
|
|
_, err := tx.FinishError(chatstate.FinishErrorInput{
|
|
LastError: mustChatLastErrorRawMessage(t, codersdk.ChatError{
|
|
Message: "input length exceeds the maximum allowed input length",
|
|
Kind: codersdk.ChatErrorKindGeneric,
|
|
}),
|
|
})
|
|
return err
|
|
})
|
|
require.NoError(t, err)
|
|
chat, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusError, chat.Status)
|
|
require.True(t, chat.LastError.Valid)
|
|
|
|
cleared, err := server.ClearChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusWaiting, cleared.Status)
|
|
require.False(t, cleared.LastError.Valid,
|
|
"clearing from the error state clears last_error")
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after clear"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
})
|
|
|
|
t.Run("does not auto-compact from stale pre-clear usage", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
var compactionRequests atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
compactionRequests.Add(1)
|
|
return anthropicCompactionResponse(t, req, "unexpected summary")
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
// The first turn exceeds the threshold, so stale usage would
|
|
// trigger auto-compaction on the next turn without the clear.
|
|
usage := chattest.AnthropicUsage{InputTokens: 90, OutputTokens: 5}
|
|
if streamCount.Add(1) > 1 {
|
|
usage = chattest.AnthropicUsage{InputTokens: 10, OutputTokens: 5}
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(usage, "assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 100, 70)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Equal(t, int32(1), streamCount.Load())
|
|
|
|
_, err := server.ClearChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after clear"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Equal(t, int32(2), streamCount.Load())
|
|
require.Equal(t, int32(0), compactionRequests.Load(),
|
|
"pre-clear usage must not trigger auto-compaction after the boundary")
|
|
})
|
|
|
|
t.Run("respects a compaction boundary", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
return anthropicCompactionResponse(t, req, "compaction summary")
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
_, err := server.CompactChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
// No model-visible message follows the compaction boundary,
|
|
// so the clear must be rejected.
|
|
_, err = server.ClearChat(ctx, chat)
|
|
require.ErrorIs(t, err, chatd.ErrNothingToClear)
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after compaction"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
_, err = server.ClearChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
})
|
|
|
|
t.Run("busy chat rejects manual clear", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
release := make(chan struct{})
|
|
releaseOnce := sync.OnceFunc(func() { close(release) })
|
|
streamStarted := make(chan struct{}, 1)
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
select {
|
|
case streamStarted <- struct{}{}:
|
|
default:
|
|
}
|
|
// Hold the generation open so the chat stays running.
|
|
<-release
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
// Registered after newActiveTestServer so this cleanup runs
|
|
// before server shutdown: a failed assertion must not leave
|
|
// shutdown waiting on the blocked stream.
|
|
t.Cleanup(releaseOnce)
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "stay busy")
|
|
testutil.TryReceive(ctx, t, streamStarted)
|
|
|
|
_, err := server.ClearChat(ctx, chat)
|
|
require.ErrorIs(t, err, chatstate.ErrTransitionNotAllowed)
|
|
|
|
releaseOnce()
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
})
|
|
}
|
|
|
|
type compressedCompactionMessages struct {
|
|
summaries []database.ChatMessage
|
|
calls []database.ChatMessage
|
|
results []database.ChatMessage
|
|
}
|
|
|
|
func compressedChatSummarizedMessages(t *testing.T, messages []database.ChatMessage) compressedCompactionMessages {
|
|
t.Helper()
|
|
seen := map[int64]bool{}
|
|
var out compressedCompactionMessages
|
|
for _, msg := range messages {
|
|
if !msg.Compressed || seen[msg.ID] {
|
|
continue
|
|
}
|
|
seen[msg.ID] = true
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
for _, part := range parts {
|
|
switch part.Type {
|
|
case codersdk.ChatMessagePartTypeText:
|
|
if msg.Role == database.ChatMessageRoleUser {
|
|
out.summaries = append(out.summaries, msg)
|
|
}
|
|
case codersdk.ChatMessagePartTypeToolCall:
|
|
if part.ToolName == "chat_summarized" {
|
|
out.calls = append(out.calls, msg)
|
|
}
|
|
case codersdk.ChatMessagePartTypeToolResult:
|
|
if part.ToolName == "chat_summarized" {
|
|
out.results = append(out.results, msg)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func compressedChatClearedMessages(t *testing.T, messages []database.ChatMessage) compressedCompactionMessages {
|
|
t.Helper()
|
|
seen := map[int64]bool{}
|
|
var out compressedCompactionMessages
|
|
for _, msg := range messages {
|
|
if !msg.Compressed || seen[msg.ID] {
|
|
continue
|
|
}
|
|
seen[msg.ID] = true
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
for _, part := range parts {
|
|
switch part.Type {
|
|
case codersdk.ChatMessagePartTypeText:
|
|
if msg.Role == database.ChatMessageRoleUser {
|
|
out.summaries = append(out.summaries, msg)
|
|
}
|
|
case codersdk.ChatMessagePartTypeToolCall:
|
|
if part.ToolName == "chat_cleared" {
|
|
out.calls = append(out.calls, msg)
|
|
}
|
|
case codersdk.ChatMessagePartTypeToolResult:
|
|
if part.ToolName == "chat_cleared" {
|
|
out.results = append(out.results, msg)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func messageText(t *testing.T, msg database.ChatMessage) string {
|
|
t.Helper()
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
var builder strings.Builder
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText {
|
|
_, _ = builder.WriteString(part.Text)
|
|
}
|
|
}
|
|
return builder.String()
|
|
}
|
|
|
|
func singlePartOfType(t *testing.T, msg database.ChatMessage, typ codersdk.ChatMessagePartType) codersdk.ChatMessagePart {
|
|
t.Helper()
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
var matches []codersdk.ChatMessagePart
|
|
for _, part := range parts {
|
|
if part.Type == typ {
|
|
matches = append(matches, part)
|
|
}
|
|
}
|
|
require.Len(t, matches, 1)
|
|
return matches[0]
|
|
}
|
|
|
|
func TestActiveServer_CompactionModelOverride(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
compactionSummary = "summary text for compaction"
|
|
chatModelName = "claude-sonnet-4-20250514"
|
|
overrideModelName = "claude-3-5-haiku-latest"
|
|
thresholdPercent = int32(70)
|
|
)
|
|
|
|
seedOverrideModel := func(ctx context.Context, t *testing.T, db database.Store, chatModel database.ChatModelConfig, modelName, effort string, contextLimit int64) database.ChatModelConfig {
|
|
t.Helper()
|
|
overrideModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
Model: modelName,
|
|
AIProviderID: chatModel.AIProviderID,
|
|
ContextLimit: contextLimit,
|
|
OrganizationID: chatModel.OrganizationID,
|
|
})
|
|
overrideModel = updateChatModelCallConfig(t, db, overrideModel, codersdk.ChatModelCallConfig{
|
|
ReasoningEffort: &codersdk.ChatModelReasoningEffortConfig{
|
|
Default: &effort,
|
|
Max: &effort,
|
|
},
|
|
})
|
|
require.NoError(t, db.UpsertChatOrganizationModelOverride(ctx, database.UpsertChatOrganizationModelOverrideParams{
|
|
OrganizationID: overrideModel.OrganizationID,
|
|
Context: string(codersdk.ChatModelOverrideContextCompaction),
|
|
ModelConfigID: overrideModel.ID,
|
|
}))
|
|
return overrideModel
|
|
}
|
|
|
|
routingCases := []struct {
|
|
name string
|
|
overrideModel string
|
|
effort string
|
|
keepsTools bool
|
|
assertSummaryRequest func(t *testing.T, req *chattest.AnthropicRequest)
|
|
}{
|
|
{
|
|
// Claude 3.5 predates extended thinking, so effort sends
|
|
// neither thinking nor output_config.
|
|
name: "pre-thinking override model",
|
|
overrideModel: overrideModelName,
|
|
effort: "high",
|
|
assertSummaryRequest: func(t *testing.T, req *chattest.AnthropicRequest) {
|
|
require.Empty(t, string(req.OutputConfig))
|
|
require.Empty(t, string(req.Thinking))
|
|
},
|
|
},
|
|
{
|
|
// High effort maps to 0.8 of the summary call's max_tokens
|
|
// (the remaining-window clamp; its exact value is pinned in
|
|
// the chatloop unit tests).
|
|
name: "legacy budget-thinking override model",
|
|
overrideModel: "claude-haiku-4-5",
|
|
effort: "high",
|
|
assertSummaryRequest: func(t *testing.T, req *chattest.AnthropicRequest) {
|
|
require.Empty(t, string(req.OutputConfig))
|
|
require.Contains(t, string(req.Thinking), `"type":"enabled"`)
|
|
wantBudget := int64(float64(req.MaxTokens) * 0.8)
|
|
require.Contains(t, string(req.Thinking), fmt.Sprintf(`"budget_tokens":%d`, wantBudget))
|
|
},
|
|
},
|
|
{
|
|
name: "adaptive-capable override model",
|
|
overrideModel: "claude-sonnet-4-6",
|
|
effort: "low",
|
|
assertSummaryRequest: func(t *testing.T, req *chattest.AnthropicRequest) {
|
|
require.Contains(t, string(req.OutputConfig), `"effort":"low"`)
|
|
require.Contains(t, string(req.Thinking), `"type":"adaptive"`)
|
|
},
|
|
},
|
|
{
|
|
// Only an override resolving to the chat model itself shares
|
|
// its prompt cache, so only then do the tool definitions stay.
|
|
name: "override resolves to the chat model",
|
|
overrideModel: chatModelName,
|
|
effort: "low",
|
|
keepsTools: true,
|
|
assertSummaryRequest: func(*testing.T, *chattest.AnthropicRequest) {},
|
|
},
|
|
}
|
|
|
|
for _, tc := range routingCases {
|
|
t.Run("summary routes to the override model and continuation stays on the chat model/"+tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
reg := prometheus.NewRegistry()
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Equal(t, tc.overrideModel, req.Model)
|
|
if tc.keepsTools {
|
|
require.NotEmpty(t, req.Tools)
|
|
} else {
|
|
require.Empty(t, req.Tools, "a different model shares no prompt cache, so the summary carries no tool definitions")
|
|
}
|
|
tc.assertSummaryRequest(t, req)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
require.Equal(t, chatModelName, req.Model)
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
// A large window keeps the summary cap clamp
|
|
// (limit minus usage and reserves) above the
|
|
// minimum legacy thinking budget so the effort
|
|
// mapping stays observable on the summary request.
|
|
return readFileResponseWithInputTokens("/tmp/a.txt", 80_000)
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
require.Empty(t, string(req.OutputConfig),
|
|
"the override reasoning effort must not leak into chat model generations")
|
|
require.Empty(t, string(req.Thinking),
|
|
"the override reasoning effort must not leak into chat model generations")
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 100_000, thresholdPercent)
|
|
overrideModel := seedOverrideModel(ctx, t, db, model, tc.overrideModel, tc.effort, 1_000_000)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
tracerProvider, spans := newRecordingTracerProvider(t)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.PrometheusRegistry = reg
|
|
cfg.TracerProvider = tracerProvider
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-override",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1)
|
|
require.Contains(t, messageText(t, compressed.summaries[0]), compactionSummary)
|
|
requireTextPart(t, messages[len(messages)-1], "continued after compaction")
|
|
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_compaction_total", 1, map[string]string{
|
|
"provider": "anthropic",
|
|
"model": tc.overrideModel,
|
|
"result": "success",
|
|
})
|
|
requireCompactionSpan(t, spans, tc.overrideModel, chatloop.CompactionSourceAutomatic)
|
|
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
var compactionRun database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, err := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if err != nil {
|
|
return false
|
|
}
|
|
for _, run := range runs {
|
|
if run.Kind == string(chatdebug.KindCompaction) {
|
|
compactionRun = run
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalMedium)
|
|
require.True(t, compactionRun.Provider.Valid)
|
|
require.Equal(t, "anthropic", compactionRun.Provider.String)
|
|
require.True(t, compactionRun.Model.Valid)
|
|
require.Equal(t, tc.overrideModel, compactionRun.Model.String)
|
|
require.True(t, compactionRun.ModelConfigID.Valid)
|
|
require.Equal(t, overrideModel.ID, compactionRun.ModelConfigID.UUID)
|
|
require.Equal(t, string(chatdebug.StatusCompleted), compactionRun.Status)
|
|
require.True(t, compactionRun.FinishedAt.Valid)
|
|
})
|
|
}
|
|
|
|
t.Run("compaction triggers at 80% of the override window, ignoring its own threshold", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Equal(t, overrideModelName, req.Model)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
// Usage 80 reaches 80% of the override's 100-token window but not the
|
|
// chat trigger at 90% of 1,000. The override's own threshold of 100
|
|
// would disable it if it were read.
|
|
model = updateChatModelCompressionThreshold(t, db, model, 1_000, 90)
|
|
overrideModel := seedOverrideModel(ctx, t, db, model, overrideModelName, "high", 100)
|
|
updateChatModelCompressionThreshold(t, db, overrideModel, 100, 100)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-override-limit",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1)
|
|
// context_limit_tokens stays the chat model's window for chat usage.
|
|
var recorded chatloop.CompactionToolResult
|
|
require.NoError(t, json.Unmarshal(singlePartOfType(t, compressed.results[0], codersdk.ChatMessagePartTypeToolResult).Result, &recorded))
|
|
require.Equal(t, int64(1_000), recorded.ContextLimitTokens)
|
|
require.Equal(t, int64(100), recorded.TriggerContextLimitTokens)
|
|
requireTextPart(t, messages[len(messages)-1], "continued after compaction")
|
|
})
|
|
|
|
t.Run("summary cap fits the override window when the chat trigger binds", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
promptTokens = 170_000
|
|
overrideContextLimit = 200_000
|
|
)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
var summaryMaxTokens atomic.Int64
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Equal(t, overrideModelName, req.Model)
|
|
summaryMaxTokens.Store(int64(req.MaxTokens))
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return readFileResponseWithInputTokens("/tmp/a.txt", promptTokens)
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
// The chat trigger binds (10% of 1,000,000 = 100,000 < 80% of
|
|
// 200,000 = 160,000), but the override model summarizes.
|
|
model = updateChatModelCompressionThreshold(t, db, model, 1_000_000, 10)
|
|
seedOverrideModel(ctx, t, db, model, overrideModelName, "high", overrideContextLimit)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-override-summary-cap",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
maxTokens := summaryMaxTokens.Load()
|
|
require.Positive(t, maxTokens)
|
|
require.LessOrEqual(t, promptTokens+maxTokens, int64(overrideContextLimit))
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "continued after compaction")
|
|
})
|
|
|
|
t.Run("manual summary cap fits the override window when the chat trigger binds", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const (
|
|
promptTokens = 140_000
|
|
overrideContextLimit = 200_000
|
|
)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var summaryMaxTokens atomic.Int64
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Equal(t, overrideModelName, req.Model)
|
|
summaryMaxTokens.Store(int64(req.MaxTokens))
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: promptTokens,
|
|
OutputTokens: 5,
|
|
}, "assistant answer")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
// Usage stays below both triggers (15% of 1,000,000 = 150,000 and
|
|
// 80% of 200,000 = 160,000); the chat trigger binds.
|
|
model = updateChatModelCompressionThreshold(t, db, model, 1_000_000, 15)
|
|
seedOverrideModel(ctx, t, db, model, overrideModelName, "high", overrideContextLimit)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello from the user")
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.Zero(t, summaryMaxTokens.Load())
|
|
|
|
_, err := server.CompactChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
|
|
maxTokens := summaryMaxTokens.Load()
|
|
require.Positive(t, maxTokens)
|
|
require.LessOrEqual(t, promptTokens+maxTokens, int64(overrideContextLimit))
|
|
})
|
|
|
|
const (
|
|
chatOverLimitMessage = "Conversation compaction could not reduce the history below your compaction threshold. Raise the compaction threshold in settings, or start a new conversation."
|
|
overrideOverLimitMessage = "Conversation compaction could not reduce the history below 80% of the organization override's context window. Start a new conversation, or ask an administrator to choose an override model with a larger context window."
|
|
bothOverLimitMessage = "Conversation compaction could not reduce the history below your compaction threshold or 80% of the organization override's context window. Start a new conversation, or raise your compaction threshold in settings and ask an administrator to choose an override model with a larger context window."
|
|
)
|
|
// Usage stays at 80 tokens, the chat threshold is 70%, and the override
|
|
// trigger is 80% of its window.
|
|
for _, tc := range []struct {
|
|
name string
|
|
chatContextLimit int64
|
|
overrideContextLimit int64
|
|
wantMessage string
|
|
}{
|
|
{
|
|
// Override point 72 binds; chat point 700.
|
|
name: "override trigger binds, usage below chat point",
|
|
chatContextLimit: 1_000,
|
|
overrideContextLimit: 90,
|
|
wantMessage: overrideOverLimitMessage,
|
|
},
|
|
{
|
|
// Override point 72 binds; chat point 77.
|
|
name: "override trigger binds, usage reaches chat point",
|
|
chatContextLimit: 110,
|
|
overrideContextLimit: 90,
|
|
wantMessage: bothOverLimitMessage,
|
|
},
|
|
{
|
|
// Chat point 70 binds; override point 800.
|
|
name: "chat trigger binds, usage below override point",
|
|
chatContextLimit: 100,
|
|
overrideContextLimit: 1_000,
|
|
wantMessage: chatOverLimitMessage,
|
|
},
|
|
{
|
|
// Chat point 70 binds; override point 80.
|
|
name: "chat trigger binds, usage reaches override point",
|
|
chatContextLimit: 100,
|
|
overrideContextLimit: 100,
|
|
wantMessage: bothOverLimitMessage,
|
|
},
|
|
} {
|
|
t.Run("next message fails when compaction stays over limit/"+tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Equal(t, overrideModelName, req.Model)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
return highUsageTextResponse("still too large")
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, tc.chatContextLimit, thresholdPercent)
|
|
seedOverrideModel(ctx, t, db, model, overrideModelName, "high", tc.overrideContextLimit)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-override-over-limit",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and stay too large"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.Equal(t, int32(2), streamCount.Load())
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue after the large compacted turn"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
require.Equal(t, tc.wantMessage, chatLastErrorMessage(chat.LastError))
|
|
require.Equal(t, int32(2), streamCount.Load(), "over-limit history should fail before another model stream")
|
|
})
|
|
}
|
|
|
|
t.Run("a new lower override trigger compacts a chat summarized under the old trigger", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount, chatSummaries, overrideSummaries atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
if req.Model == overrideModelName {
|
|
overrideSummaries.Add(1)
|
|
} else {
|
|
chatSummaries.Add(1)
|
|
}
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
case 2:
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 50,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
default:
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "second turn")...)
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 100, thresholdPercent)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-override-added-lower-trigger",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid)
|
|
require.Equal(t, int32(1), chatSummaries.Load())
|
|
|
|
// The post-compaction usage of 50 is under the chat trigger at 70 but
|
|
// reaches the new binding override trigger at 80% of 60 = 48.
|
|
seedOverrideModel(ctx, t, db, model, overrideModelName, "high", 60)
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("continue under the new trigger"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
chat = waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.False(t, chat.LastError.Valid, chatLastErrorMessage(chat.LastError))
|
|
require.Equal(t, int32(1), overrideSummaries.Load())
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "second turn")
|
|
})
|
|
|
|
t.Run("user threshold 100 does not disable the override model trigger", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
body := anthropicRequestBody(t, *req)
|
|
if strings.Contains(body, "You are performing a context compaction") {
|
|
require.Equal(t, overrideModelName, req.Model)
|
|
return anthropicCompactionResponse(t, req, compactionSummary)
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
default:
|
|
require.Contains(t, body, compactionSummary)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 5,
|
|
}, "continued after compaction")...)
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 1_000, thresholdPercent)
|
|
_, err := db.UpdateUserChatCompactionThreshold(ctx, database.UpdateUserChatCompactionThresholdParams{
|
|
UserID: user.ID,
|
|
Key: codersdk.CompactionThresholdKey(model.ID),
|
|
ThresholdPercent: 100,
|
|
})
|
|
require.NoError(t, err)
|
|
seedOverrideModel(ctx, t, db, model, overrideModelName, "high", 100)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "compaction-user-disabled",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
promptMessages, err := db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
compressed := compressedChatSummarizedMessages(t, append(promptMessages, messages...))
|
|
require.Len(t, compressed.summaries, 1)
|
|
requireTextPart(t, messages[len(messages)-1], "continued after compaction")
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_AnthropicModelReasoningEffort(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
model string
|
|
effort string
|
|
checkThinking func(t *testing.T, thinking string)
|
|
}{
|
|
{
|
|
// Pre-4.6 models reject adaptive thinking, so effort becomes an
|
|
// enabled-thinking budget derived from max_tokens.
|
|
name: "LegacyModelEffortHigh",
|
|
model: "claude-haiku-4-5",
|
|
effort: "high",
|
|
checkThinking: func(t *testing.T, thinking string) {
|
|
require.Contains(t, thinking, `"type":"enabled"`)
|
|
require.Contains(t, thinking, `"budget_tokens":3276`)
|
|
},
|
|
},
|
|
{
|
|
// Claude 5+ models run adaptive thinking when the request omits
|
|
// the thinking field, so effort none must send an explicit
|
|
// disable.
|
|
name: "AdaptiveDefaultModelEffortNone",
|
|
model: "claude-sonnet-5",
|
|
effort: "none",
|
|
checkThinking: func(t *testing.T, thinking string) {
|
|
require.Contains(t, thinking, `"type":"disabled"`)
|
|
},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model.Model = tt.model
|
|
model = updateChatModelContextLimit(t, db, model)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
MaxOutputTokens: new(int64(4096)),
|
|
ReasoningEffort: &codersdk.ChatModelReasoningEffortConfig{
|
|
Default: &tt.effort,
|
|
Max: &tt.effort,
|
|
},
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "done")
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 1)
|
|
req := generationRequests[0]
|
|
require.Equal(t, tt.model, req.Model)
|
|
require.Empty(t, string(req.OutputConfig))
|
|
tt.checkThinking(t, string(req.Thinking))
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_BasicAssistantGenerationAndPromptPreparation(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model.ContextLimit = 4096
|
|
model = updateChatModelContextLimit(t, db, model)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
insertSystemTextMessage(ctx, t, db, chat.ID, "sys-2", model.ID)
|
|
insertAssistantTextMessage(ctx, t, db, chat.ID, "working", model.ID)
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 2)
|
|
recovered := generationRequests[1]
|
|
require.Contains(t, string(recovered.System), `"cache_control":{"type":"ephemeral"}`)
|
|
require.Len(t, recovered.Messages, 4)
|
|
require.False(t, anthropicMessageHasEphemeralCacheControl(t, recovered.Messages[0]))
|
|
require.False(t, anthropicMessageHasEphemeralCacheControl(t, recovered.Messages[1]))
|
|
require.True(t, anthropicMessageHasEphemeralCacheControl(t, recovered.Messages[2]))
|
|
require.True(t, anthropicMessageHasEphemeralCacheControl(t, recovered.Messages[3]))
|
|
require.False(t, anthropicRequestContainsPromptSentinel(t, recovered))
|
|
toolNames := anthropicRequestToolNames(recovered)
|
|
require.Contains(t, toolNames, "read_file")
|
|
require.Contains(t, toolNames, "write_file")
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
last := messages[len(messages)-1]
|
|
require.Equal(t, database.ChatMessageRoleAssistant, last.Role)
|
|
require.True(t, last.ContextLimit.Valid)
|
|
require.Equal(t, int64(4096), last.ContextLimit.Int64)
|
|
// runtime_ms is not asserted here: this stream is served in
|
|
// process and routinely finishes in under a millisecond, which
|
|
// InsertChatMessages stores as NULL. Runtime measurement and
|
|
// persistence are pinned deterministically in
|
|
// chatloop.TestGenerateAssistant_RecordsModelInvocationRuntime and
|
|
// TestInterruptTask_PartialAssistantKeepsAttemptRuntime.
|
|
requireTextPart(t, last, "done")
|
|
}
|
|
|
|
// Claude models routed through an OpenRouter provider use the openai-compat
|
|
// fantasy client, which must still emit Anthropic cache_control markers
|
|
// on array-form content blocks. Other model families get none.
|
|
func TestActiveServer_OpenRouterAnthropicPromptCaching(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
modelID string
|
|
wantCaching bool
|
|
}{
|
|
{name: "Claude", modelID: "anthropic/claude-haiku-4.5", wantCaching: true},
|
|
{name: "GPT", modelID: "openai/gpt-5-mini", wantCaching: false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var (
|
|
mu sync.Mutex
|
|
streaming [][]byte
|
|
)
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"caching"}`)
|
|
}
|
|
mu.Lock()
|
|
streaming = append(streaming, req.RawBody)
|
|
mu.Unlock()
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
|
|
user := dbgen.User(t, db, database.User{})
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: user.ID, OrganizationID: org.ID})
|
|
provider := dbgen.AIProvider(t, db, database.AIProvider{Type: database.AIProviderTypeOpenrouter}, func(params *database.InsertAIProviderParams) {
|
|
params.BaseUrl = openAIURL
|
|
})
|
|
dbgen.AIProviderKey(t, db, database.AIProviderKey{ProviderID: provider.ID})
|
|
model := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
Model: tt.modelID,
|
|
IsDefault: true,
|
|
AIProviderID: uuid.NullUUID{UUID: provider.ID, Valid: true},
|
|
OrganizationID: org.ID,
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
require.Len(t, streaming, 2)
|
|
body := streaming[1]
|
|
require.Equal(t, tt.modelID, gjson.GetBytes(body, "model").String())
|
|
messages := gjson.GetBytes(body, "messages").Array()
|
|
require.GreaterOrEqual(t, len(messages), 4)
|
|
require.Equal(t, "system", messages[0].Get("role").String())
|
|
firstUser := slices.IndexFunc(messages, func(msg gjson.Result) bool {
|
|
return msg.Get("role").String() == "user"
|
|
})
|
|
require.Positive(t, firstUser)
|
|
require.Equal(t, "hello", messages[firstUser].Get("content").String(), "earlier user message keeps string content")
|
|
require.NotContains(t, messages[firstUser].Raw, "cache_control")
|
|
last := messages[len(messages)-1]
|
|
require.Equal(t, "user", last.Get("role").String())
|
|
|
|
if !tt.wantCaching {
|
|
require.NotContains(t, string(body), "cache_control")
|
|
require.Equal(t, "continue", last.Get("content").String())
|
|
return
|
|
}
|
|
// Only the last system message carries the breakpoint and
|
|
// switches to array-form content.
|
|
lastSystem := messages[firstUser-1]
|
|
require.Equal(t, "system", lastSystem.Get("role").String())
|
|
for _, msg := range messages[:firstUser-1] {
|
|
require.NotContains(t, msg.Raw, "cache_control")
|
|
}
|
|
systemParts := lastSystem.Get("content").Array()
|
|
require.True(t, lastSystem.Get("content").IsArray(), "system content must be array form to carry cache_control")
|
|
require.Equal(t, "ephemeral", systemParts[len(systemParts)-1].Get("cache_control.type").String())
|
|
require.True(t, last.Get("content").IsArray(), "user content must be array form to carry cache_control")
|
|
userParts := last.Get("content").Array()
|
|
require.Equal(t, "continue", userParts[len(userParts)-1].Get("text").String())
|
|
require.Equal(t, "ephemeral", userParts[len(userParts)-1].Get("cache_control.type").String())
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_ToolExecutionAndPolicy(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("rejects disallowed active tool", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("write_file", `{"path":"/tmp/nope","content":"blocked"}`),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().WriteFile(gomock.Any(), gomock.Any(), gomock.Any()).Times(0)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "active-tool-reject",
|
|
ModelConfigID: model.ID,
|
|
ChatMode: database.NullChatMode{ChatMode: database.ChatModeExplore, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("try to write a file"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
result := requireToolResultPart(t, parts, "write_file")
|
|
require.True(t, result.IsError)
|
|
require.JSONEq(t, `{"error":"Tool not active in this turn: write_file"}`, string(result.Result))
|
|
})
|
|
|
|
t.Run("provider runner executes and preserves metadata", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
const computerResultMetadata = `{"openai":{"type":"openai.responses.computer_call_output_options","data":{"detail":"original"}}}`
|
|
var streamedCallCount atomic.Int32
|
|
var secondRawBody []byte
|
|
var callsMu sync.Mutex
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
callsMu.Lock()
|
|
secondRawBody = append([]byte(nil), req.RawBody...)
|
|
callsMu.Unlock()
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, _, model := seedChatDependenciesWithProviderPolicy(t, db, "openai", openAIURL, "test-key", true, false, true)
|
|
apiKey, _ := dbgen.APIKey(t, db, database.APIKey{UserID: user.ID})
|
|
model.Model = "gpt-5.5"
|
|
model = updateChatModelContextLimit(t, db, model)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AllowBYOKSet = true
|
|
cfg.AllowBYOK = false
|
|
})
|
|
result := codersdk.ChatMessageToolResult(
|
|
"computer-call",
|
|
"computer",
|
|
json.RawMessage(`{"data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4n539HwAHFwLVF8kc1wAAAABJRU5ErkJggg==","mime_type":"image/png"}`),
|
|
false,
|
|
true,
|
|
)
|
|
result.ProviderMetadata = json.RawMessage(computerResultMetadata)
|
|
computerCall := codersdk.ChatMessageToolCall(
|
|
"computer-call",
|
|
"computer",
|
|
json.RawMessage(`{"type":"screenshot"}`),
|
|
)
|
|
computerCall.ProviderExecuted = true
|
|
created, err := chatstate.CreateChat(dbauthz.AsSystemRestricted(ctx), db, ps, chatstate.CreateChatInput{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: model.ID,
|
|
Title: "provider-runner-replay-active",
|
|
MCPServerIDs: []uuid.UUID{},
|
|
ClientType: database.ChatClientTypeApi,
|
|
InitialStatus: database.ChatStatusRunning,
|
|
InitialMessages: []chatstate.Message{
|
|
userMessageForTest(t, "use provider runner", model.ID, user.ID, apiKey.ID),
|
|
assistantMessageForTest(t, []codersdk.ChatMessagePart{computerCall}, model.ID),
|
|
toolMessageForTest(t, []codersdk.ChatMessagePart{result}, model.ID),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
chat := created.Chat
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
waitForTerminalChat(ctx, t, db, chat.ID)
|
|
gotChat, gotErr := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, gotErr)
|
|
require.Equal(t, database.ChatStatusWaiting, gotChat.Status)
|
|
require.Eventually(t, func() bool { return streamedCallCount.Load() >= 1 }, testutil.WaitShort, testutil.IntervalFast)
|
|
|
|
callsMu.Lock()
|
|
body := string(secondRawBody)
|
|
callsMu.Unlock()
|
|
require.Contains(t, body, "computer_call_output")
|
|
require.Contains(t, body, `"detail":"original"`)
|
|
})
|
|
|
|
t.Run("multi step local tool execution", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
var secondCallMessages []chattest.OpenAIMessage
|
|
var callsMu sync.Mutex
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("read_file", `{"path":"/tmp/a.txt"}`),
|
|
)
|
|
}
|
|
callsMu.Lock()
|
|
secondCallMessages = append([]chattest.OpenAIMessage(nil), req.Messages...)
|
|
callsMu.Unlock()
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("all done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{
|
|
Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main",
|
|
}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "multi-step-tool",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
require.GreaterOrEqual(t, streamedCallCount.Load(), int32(2))
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
call := requireToolCallPart(t, parts, "read_file")
|
|
result := requireToolResultPart(t, parts, "read_file")
|
|
require.False(t, result.IsError)
|
|
require.NotNil(t, call.CreatedAt)
|
|
require.NotNil(t, result.CreatedAt)
|
|
require.False(t, result.CreatedAt.Before(*call.CreatedAt))
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "all done")
|
|
|
|
callsMu.Lock()
|
|
secondMessages := append([]chattest.OpenAIMessage(nil), secondCallMessages...)
|
|
callsMu.Unlock()
|
|
require.NotEmpty(t, secondMessages)
|
|
require.True(t, openAIMessagesContain(secondMessages, "1\\tpackage main"))
|
|
})
|
|
|
|
t.Run("parallel local and provider executed timestamps", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
webSearchEnabled := true
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
readA := chattest.OpenAIToolCallChunk("read_file", `{"path":"/tmp/a.txt"}`)
|
|
readB := chattest.OpenAIToolCallChunk("read_file", `{"path":"/tmp/b.txt"}`)
|
|
second := readB.Choices[0].ToolCalls[0]
|
|
second.Index = 1
|
|
readA.Choices[0].ToolCalls = append(readA.Choices[0].ToolCalls, second)
|
|
return chattest.OpenAIResponse{
|
|
StreamingChunks: chattest.OpenAIStreamingResponse(readA).StreamingChunks,
|
|
WebSearch: &chattest.OpenAIWebSearchCall{ID: "ws-timestamps", Query: "coder"},
|
|
}
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
OpenAI: &codersdk.ChatModelOpenAIProviderOptions{WebSearchEnabled: &webSearchEnabled},
|
|
},
|
|
})
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, Content: "a", FileSize: 1, TotalLines: 1, LinesRead: 1}, nil).
|
|
Times(1)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/b.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, Content: "b", FileSize: 1, TotalLines: 1, LinesRead: 1}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "parallel-timestamps",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search and read files"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
for _, toolName := range []string{"read_file", "web_search"} {
|
|
call := requireToolCallPart(t, parts, toolName)
|
|
result := requireToolResultPart(t, parts, toolName)
|
|
require.NotNil(t, call.CreatedAt, toolName)
|
|
require.NotNil(t, result.CreatedAt, toolName)
|
|
require.False(t, result.CreatedAt.Before(*call.CreatedAt), toolName)
|
|
if toolName == "web_search" {
|
|
require.True(t, call.ProviderExecuted)
|
|
require.True(t, result.ProviderExecuted)
|
|
} else {
|
|
require.False(t, call.ProviderExecuted)
|
|
require.False(t, result.ProviderExecuted)
|
|
}
|
|
}
|
|
|
|
// Batch runtime bills a dedicated model-only usage row, so no
|
|
// user-visible tool row ever carries runtime.
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
for _, msg := range messages {
|
|
if msg.Role == database.ChatMessageRoleTool {
|
|
require.False(t, msg.RuntimeMs.Valid)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_RecordsGenerationMetrics(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
reg := prometheus.NewRegistry()
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(openAITextChunksWithStop("hello")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.PrometheusRegistry = reg
|
|
})
|
|
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_steps_total", 1, map[string]string{
|
|
"provider": "openai",
|
|
"model": "gpt-4o-mini",
|
|
})
|
|
requireChatdMetricHistogram(t, reg, "coderd_chatd_message_count", 1, map[string]string{
|
|
"provider": "openai",
|
|
"model": "gpt-4o-mini",
|
|
}, chatdMetricHistogramRequirement{})
|
|
requireChatdMetricHistogram(t, reg, "coderd_chatd_prompt_size_bytes", 1, map[string]string{
|
|
"provider": "openai",
|
|
"model": "gpt-4o-mini",
|
|
}, chatdMetricHistogramRequirement{PositiveSum: true})
|
|
requireChatdMetricHistogram(t, reg, "coderd_chatd_response_size_bytes", 1, map[string]string{
|
|
"provider": "openai",
|
|
"model": "gpt-4o-mini",
|
|
}, chatdMetricHistogramRequirement{PositiveSum: true})
|
|
requireChatdMetricHistogram(t, reg, "coderd_chatd_ttft_seconds", 1, map[string]string{
|
|
"provider": "openai",
|
|
"model": "gpt-4o-mini",
|
|
}, chatdMetricHistogramRequirement{})
|
|
}
|
|
|
|
func TestActiveServer_ToolErrorRecordsMetric(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
toolName string
|
|
toolArgs string
|
|
chatMode database.NullChatMode
|
|
setupAgent func(*agentconnmock.MockAgentConn)
|
|
seedContext func(ctx context.Context, t *testing.T, db database.Store, agentID uuid.UUID)
|
|
}{
|
|
{
|
|
name: "builtin tool IsError",
|
|
toolName: "read_file",
|
|
toolArgs: `{"path":"/tmp/missing.txt"}`,
|
|
setupAgent: func(mockConn *agentconnmock.MockAgentConn) {
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/missing.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: false, Error: "file not found"}, nil).
|
|
Times(1)
|
|
},
|
|
},
|
|
{
|
|
name: "non builtin MCP style tool IsError",
|
|
toolName: "dynamic__error_tool",
|
|
toolArgs: `{"input":"hello"}`,
|
|
setupAgent: func(mockConn *agentconnmock.MockAgentConn) {
|
|
mockConn.EXPECT().CallMCPTool(gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.CallMCPToolResponse{
|
|
IsError: true,
|
|
Content: []workspacesdk.MCPToolContent{{
|
|
Type: "text",
|
|
Text: "dynamic failed",
|
|
}},
|
|
}, nil).
|
|
Times(1)
|
|
},
|
|
seedContext: func(ctx context.Context, t *testing.T, db database.Store, agentID uuid.UUID) {
|
|
seedAgentMCPToolContext(ctx, t, db, agentMCPToolContext{
|
|
AgentID: agentID,
|
|
ServerName: "dynamic",
|
|
ToolName: "error_tool",
|
|
ToolDescription: "dynamic error tool",
|
|
})
|
|
},
|
|
},
|
|
{
|
|
name: "tool Run returns error",
|
|
toolName: "read_file",
|
|
toolArgs: `{"path":"/tmp/error.txt"}`,
|
|
setupAgent: func(mockConn *agentconnmock.MockAgentConn) {
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/error.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{}, xerrors.New("connection refused")).
|
|
Times(1)
|
|
},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
reg := prometheus.NewRegistry()
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(tt.toolName, tt.toolArgs),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
model.Model = "test-model"
|
|
model = updateChatModelContextLimit(t, db, model)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
tt.setupAgent(mockConn)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.PrometheusRegistry = reg
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chatOpts := chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "tool-error-metric",
|
|
ModelConfigID: model.ID,
|
|
ChatMode: tt.chatMode,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("run an erroring tool"),
|
|
},
|
|
}
|
|
if tt.seedContext != nil {
|
|
tt.seedContext(ctx, t, db, dbAgent.ID)
|
|
}
|
|
chat, err := server.CreateChat(ctx, chatOpts)
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
result := requireToolResultPart(t, chatToolParts(ctx, t, db, chat.ID), tt.toolName)
|
|
require.True(t, result.IsError)
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_tool_errors_total", 1, map[string]string{
|
|
"provider": "openai-compat",
|
|
"model": "test-model",
|
|
"tool_name": tt.toolName,
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
func userMessageForTest(
|
|
t *testing.T,
|
|
text string,
|
|
modelID uuid.UUID,
|
|
createdBy uuid.UUID,
|
|
apiKeyID string,
|
|
) chatstate.Message {
|
|
t.Helper()
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{codersdk.ChatMessageText(text)})
|
|
require.NoError(t, err)
|
|
return chatstate.Message{
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: content,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
ModelConfigID: uuid.NullUUID{UUID: modelID, Valid: true},
|
|
CreatedBy: uuid.NullUUID{UUID: createdBy, Valid: true},
|
|
}
|
|
}
|
|
|
|
func assistantMessageForTest(
|
|
t *testing.T,
|
|
parts []codersdk.ChatMessagePart,
|
|
modelID uuid.UUID,
|
|
) chatstate.Message {
|
|
t.Helper()
|
|
content, err := chatprompt.MarshalParts(parts)
|
|
require.NoError(t, err)
|
|
return chatstate.Message{
|
|
Role: database.ChatMessageRoleAssistant,
|
|
Content: content,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
ModelConfigID: uuid.NullUUID{UUID: modelID, Valid: true},
|
|
}
|
|
}
|
|
|
|
func toolMessageForTest(
|
|
t *testing.T,
|
|
parts []codersdk.ChatMessagePart,
|
|
modelID uuid.UUID,
|
|
) chatstate.Message {
|
|
t.Helper()
|
|
content, err := chatprompt.MarshalParts(parts)
|
|
require.NoError(t, err)
|
|
return chatstate.Message{
|
|
Role: database.ChatMessageRoleTool,
|
|
Content: content,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
ModelConfigID: uuid.NullUUID{UUID: modelID, Valid: true},
|
|
}
|
|
}
|
|
|
|
func setupToolExecutionAgentConn(
|
|
t *testing.T,
|
|
mockConn *agentconnmock.MockAgentConn,
|
|
) {
|
|
t.Helper()
|
|
mockConn.EXPECT().SetExtraHeaders(gomock.Any()).AnyTimes()
|
|
mockConn.EXPECT().ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).AnyTimes()
|
|
mockConn.EXPECT().LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{AbsolutePathString: "/home/coder"}, nil).AnyTimes()
|
|
mockConn.EXPECT().ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(io.NopCloser(strings.NewReader("")), "", nil).AnyTimes()
|
|
}
|
|
|
|
func dynamicToolJSON(t *testing.T, name string) []byte {
|
|
t.Helper()
|
|
encoded, err := json.Marshal([]mcp.Tool{{
|
|
Name: name,
|
|
Description: "A test dynamic tool.",
|
|
InputSchema: map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"query": map[string]any{"type": "string"},
|
|
},
|
|
},
|
|
}})
|
|
require.NoError(t, err)
|
|
return encoded
|
|
}
|
|
|
|
func toolResultPartExists(parts []codersdk.ChatMessagePart, toolName string) bool {
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolName == toolName {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func chatToolParts(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
) []codersdk.ChatMessagePart {
|
|
t.Helper()
|
|
var parts []codersdk.ChatMessagePart
|
|
for _, msg := range chatMessages(ctx, t, db, chatID) {
|
|
parsed, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
for _, part := range parsed {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall ||
|
|
part.Type == codersdk.ChatMessagePartTypeToolResult {
|
|
parts = append(parts, part)
|
|
}
|
|
}
|
|
}
|
|
return parts
|
|
}
|
|
|
|
func requireToolCallPart(
|
|
t *testing.T,
|
|
parts []codersdk.ChatMessagePart,
|
|
toolName string,
|
|
) codersdk.ChatMessagePart {
|
|
t.Helper()
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolName == toolName {
|
|
return part
|
|
}
|
|
}
|
|
t.Fatalf("missing tool-call part for %q", toolName)
|
|
return codersdk.ChatMessagePart{}
|
|
}
|
|
|
|
func requireToolResultPart(
|
|
t *testing.T,
|
|
parts []codersdk.ChatMessagePart,
|
|
toolName string,
|
|
) codersdk.ChatMessagePart {
|
|
t.Helper()
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolName == toolName {
|
|
return part
|
|
}
|
|
}
|
|
t.Fatalf("missing tool-result part for %q", toolName)
|
|
return codersdk.ChatMessagePart{}
|
|
}
|
|
|
|
func openAIMessagesContain(messages []chattest.OpenAIMessage, text string) bool {
|
|
for _, msg := range messages {
|
|
if strings.Contains(msg.Content, text) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func requireChatdMetricCounter(
|
|
t *testing.T,
|
|
reg *prometheus.Registry,
|
|
name string,
|
|
wantValue float64,
|
|
wantLabels map[string]string,
|
|
) {
|
|
t.Helper()
|
|
families, err := reg.Gather()
|
|
require.NoError(t, err)
|
|
for _, family := range families {
|
|
if family.GetName() != name {
|
|
continue
|
|
}
|
|
for _, metric := range family.GetMetric() {
|
|
labels := metricLabels(metric)
|
|
if !metricLabelsMatch(labels, wantLabels) {
|
|
continue
|
|
}
|
|
require.Equal(t, wantValue, metric.GetCounter().GetValue())
|
|
return
|
|
}
|
|
t.Fatalf("metric %s with labels %v not found", name, wantLabels)
|
|
}
|
|
t.Fatalf("metric %s not found", name)
|
|
}
|
|
|
|
type chatdMetricHistogramRequirement struct {
|
|
PositiveSum bool
|
|
}
|
|
|
|
func requireChatdMetricHistogram(
|
|
t *testing.T,
|
|
reg *prometheus.Registry,
|
|
name string,
|
|
wantSampleCount uint64,
|
|
wantLabels map[string]string,
|
|
requirement chatdMetricHistogramRequirement,
|
|
) {
|
|
t.Helper()
|
|
families, err := reg.Gather()
|
|
require.NoError(t, err)
|
|
for _, family := range families {
|
|
if family.GetName() != name {
|
|
continue
|
|
}
|
|
for _, metric := range family.GetMetric() {
|
|
labels := metricLabels(metric)
|
|
if !metricLabelsMatch(labels, wantLabels) {
|
|
continue
|
|
}
|
|
histogram := metric.GetHistogram()
|
|
require.Equal(t, wantSampleCount, histogram.GetSampleCount())
|
|
if requirement.PositiveSum {
|
|
require.Positive(t, histogram.GetSampleSum())
|
|
}
|
|
return
|
|
}
|
|
t.Fatalf("metric %s with labels %v not found", name, wantLabels)
|
|
}
|
|
t.Fatalf("metric %s not found", name)
|
|
}
|
|
|
|
func metricLabels(metric interface {
|
|
GetLabel() []*io_prometheus_client.LabelPair
|
|
},
|
|
) map[string]string {
|
|
labels := map[string]string{}
|
|
for _, label := range metric.GetLabel() {
|
|
labels[label.GetName()] = label.GetValue()
|
|
}
|
|
return labels
|
|
}
|
|
|
|
func metricLabelsMatch(labels, wantLabels map[string]string) bool {
|
|
for key, value := range wantLabels {
|
|
if labels[key] != value {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func TestActiveServer_AnthropicUsageMatchesFinalDelta(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
anthropicURL := chattest.NewAnthropic(t, func(_ *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 200,
|
|
OutputTokens: 75,
|
|
CacheCreationInputTokens: 30,
|
|
CacheReadInputTokens: 150,
|
|
}, "cached response")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
last := messages[len(messages)-1]
|
|
require.Equal(t, database.ChatMessageRoleAssistant, last.Role)
|
|
require.Equal(t, sql.NullInt64{Int64: 200, Valid: true}, last.InputTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 75, Valid: true}, last.OutputTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 275, Valid: true}, last.TotalTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 30, Valid: true}, last.CacheCreationTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 150, Valid: true}, last.CacheReadTokens)
|
|
}
|
|
|
|
func TestActiveServer_AnthropicPersistsPerRequestUsage(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
anthropicURL := chattest.NewAnthropic(t, func(_ *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithMessageUsages(
|
|
chattest.AnthropicUsage{
|
|
InputTokens: 2,
|
|
CacheReadInputTokens: 139956,
|
|
CacheCreationInputTokens: 7770,
|
|
},
|
|
chattest.AnthropicUsage{
|
|
InputTokens: 4,
|
|
CacheReadInputTokens: 287682,
|
|
CacheCreationInputTokens: 15556,
|
|
OutputTokens: 4996,
|
|
},
|
|
"cached response",
|
|
)...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
last := messages[len(messages)-1]
|
|
require.Equal(t, database.ChatMessageRoleAssistant, last.Role)
|
|
require.Equal(t, sql.NullInt64{Int64: 139956, Valid: true}, last.CacheReadTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 7770, Valid: true}, last.CacheCreationTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 2, Valid: true}, last.InputTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 4996, Valid: true}, last.OutputTokens)
|
|
require.Equal(t, sql.NullInt64{Int64: 4998, Valid: true}, last.TotalTokens)
|
|
}
|
|
|
|
func TestActiveServer_ChatTurnDebugRunRecordsStreamStep(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse(`{"label":"Debug response"}`)
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 200,
|
|
OutputTokens: 75,
|
|
CacheCreationInputTokens: 30,
|
|
CacheReadInputTokens: 150,
|
|
}, "debug response")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello debug")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var chatTurnRuns []database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, err := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if err != nil {
|
|
return false
|
|
}
|
|
chatTurnRuns = chatTurnRuns[:0]
|
|
for _, run := range runs {
|
|
if run.Kind == string(codersdk.ChatDebugRunKindChatTurn) {
|
|
chatTurnRuns = append(chatTurnRuns, run)
|
|
}
|
|
}
|
|
return len(chatTurnRuns) == 1 && chatTurnRuns[0].FinishedAt.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Len(t, chatTurnRuns, 1)
|
|
run := chatTurnRuns[0]
|
|
require.Equal(t, string(codersdk.ChatDebugStatusCompleted), run.Status)
|
|
|
|
steps, err := db.GetChatDebugStepsByRunID(debugCtx, run.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, steps, 1)
|
|
step := steps[0]
|
|
require.Equal(t, string(codersdk.ChatDebugStepOperationStream), step.Operation)
|
|
require.Equal(t, string(codersdk.ChatDebugStatusCompleted), step.Status)
|
|
require.NotEmpty(t, step.NormalizedRequest)
|
|
require.True(t, step.NormalizedResponse.Valid)
|
|
require.True(t, step.Usage.Valid)
|
|
require.NotEmpty(t, step.Attempts)
|
|
require.True(t, step.FinishedAt.Valid)
|
|
|
|
var normalizedRequest map[string]any
|
|
require.NoError(t, json.Unmarshal(step.NormalizedRequest, &normalizedRequest))
|
|
require.NotEmpty(t, normalizedRequest["messages"])
|
|
|
|
var normalizedResponse map[string]any
|
|
require.NoError(t, json.Unmarshal(step.NormalizedResponse.RawMessage, &normalizedResponse))
|
|
require.NotEmpty(t, normalizedResponse["content"])
|
|
require.NotEmpty(t, normalizedResponse["usage"])
|
|
|
|
var usage map[string]any
|
|
require.NoError(t, json.Unmarshal(step.Usage.RawMessage, &usage))
|
|
require.EqualValues(t, 200, usage["input_tokens"])
|
|
require.EqualValues(t, 75, usage["output_tokens"])
|
|
require.EqualValues(t, 30, usage["cache_creation_tokens"])
|
|
require.EqualValues(t, 150, usage["cache_read_tokens"])
|
|
|
|
var attempts []map[string]any
|
|
require.NoError(t, json.Unmarshal(step.Attempts, &attempts))
|
|
require.Len(t, attempts, 1)
|
|
require.NotEmpty(t, attempts[0]["request_body"])
|
|
require.NotEmpty(t, attempts[0]["response_body"])
|
|
|
|
var summary map[string]any
|
|
require.NoError(t, json.Unmarshal(run.Summary, &summary))
|
|
require.Equal(t, "POST /v1/messages", summary["endpoint_label"])
|
|
require.Equal(t, "hello debug", summary["first_message"])
|
|
require.EqualValues(t, 1, summary["step_count"])
|
|
require.EqualValues(t, 200, summary["total_input_tokens"])
|
|
require.EqualValues(t, 75, summary["total_output_tokens"])
|
|
require.EqualValues(t, 30, summary["total_cache_creation_tokens"])
|
|
require.EqualValues(t, 150, summary["total_cache_read_tokens"])
|
|
}
|
|
|
|
func TestActiveServer_ChatTurnDebugRunRecordsMultipleStreamSteps(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse(`{"label":"Read file"}`)
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return chattest.AnthropicStreamingResponse(
|
|
chattest.AnthropicToolCallChunks("read_file", `{"path":"/tmp/a.txt"}`)...,
|
|
)
|
|
case 2:
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunksWithCacheUsage(chattest.AnthropicUsage{
|
|
InputTokens: 20,
|
|
OutputTokens: 7,
|
|
}, "final debug response")...)
|
|
default:
|
|
t.Fatalf("unexpected stream request %d", streamCount.Load())
|
|
return chattest.AnthropicStreamingResponse()
|
|
}
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "multi-step-debug",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the file and continue"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var chatTurnRuns []database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, err := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if err != nil {
|
|
return false
|
|
}
|
|
chatTurnRuns = chatTurnRuns[:0]
|
|
for _, run := range runs {
|
|
if run.Kind == string(codersdk.ChatDebugRunKindChatTurn) {
|
|
chatTurnRuns = append(chatTurnRuns, run)
|
|
}
|
|
}
|
|
if len(chatTurnRuns) != 1 || !chatTurnRuns[0].FinishedAt.Valid {
|
|
return false
|
|
}
|
|
steps, err := db.GetChatDebugStepsByRunID(ctx, chatTurnRuns[0].ID)
|
|
return err == nil && len(steps) == 2
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Len(t, chatTurnRuns, 1)
|
|
run := chatTurnRuns[0]
|
|
require.Equal(t, string(codersdk.ChatDebugStatusCompleted), run.Status)
|
|
|
|
steps, err := db.GetChatDebugStepsByRunID(debugCtx, run.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, steps, 2)
|
|
for i, step := range steps {
|
|
require.EqualValues(t, i+1, step.StepNumber)
|
|
require.Equal(t, string(codersdk.ChatDebugStepOperationStream), step.Operation)
|
|
require.Equal(t, string(codersdk.ChatDebugStatusCompleted), step.Status)
|
|
require.NotEmpty(t, step.Attempts)
|
|
require.True(t, step.FinishedAt.Valid)
|
|
}
|
|
|
|
var firstResponse map[string]any
|
|
require.NoError(t, json.Unmarshal(steps[0].NormalizedResponse.RawMessage, &firstResponse))
|
|
require.NotEmpty(t, firstResponse["content"])
|
|
|
|
var secondResponse map[string]any
|
|
require.NoError(t, json.Unmarshal(steps[1].NormalizedResponse.RawMessage, &secondResponse))
|
|
require.NotEmpty(t, secondResponse["content"])
|
|
|
|
var summary map[string]any
|
|
require.NoError(t, json.Unmarshal(run.Summary, &summary))
|
|
require.Equal(t, "POST /v1/messages", summary["endpoint_label"])
|
|
require.EqualValues(t, 2, summary["step_count"])
|
|
require.EqualValues(t, 30, summary["total_input_tokens"])
|
|
require.EqualValues(t, 12, summary["total_output_tokens"])
|
|
}
|
|
|
|
func TestActiveServer_AnthropicSanitizesProviderToolBeforeRequest(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search for coder")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
insertOrphanProviderToolCall(ctx, t, db, chat.ID, model.ID)
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 2)
|
|
body := anthropicRequestBody(t, generationRequests[1])
|
|
require.NotContains(t, body, "web_search")
|
|
require.Contains(t, body, "partial")
|
|
require.Contains(t, body, "continue")
|
|
require.Contains(t, body, "redacted-payload")
|
|
}
|
|
|
|
func TestActiveServer_AnthropicContext1MBetaHeader(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
runChat := func(t *testing.T, callConfig *codersdk.ChatModelCallConfig) []chattest.AnthropicRequest {
|
|
t.Helper()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
if callConfig != nil {
|
|
model = updateChatModelCallConfig(t, db, model, *callConfig)
|
|
}
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.NotEmpty(t, generationRequests)
|
|
return generationRequests
|
|
}
|
|
|
|
t.Run("enabled sends beta header", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
generationRequests := runChat(t, &codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{
|
|
Context1MEnabled: new(true),
|
|
},
|
|
},
|
|
})
|
|
for _, req := range generationRequests {
|
|
require.Equal(t, chatprovider.AnthropicBetaContext1M, req.Header.Get(chatprovider.HeaderAnthropicBeta))
|
|
}
|
|
})
|
|
|
|
t.Run("unset omits beta header", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
generationRequests := runChat(t, nil)
|
|
for _, req := range generationRequests {
|
|
require.Empty(t, req.Header.Get(chatprovider.HeaderAnthropicBeta))
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_AnthropicProviderToolPreRequestGuard(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
webSearchEnabled := true
|
|
callConfig := codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{
|
|
WebSearchEnabled: &webSearchEnabled,
|
|
},
|
|
},
|
|
}
|
|
|
|
t.Run("allowed web search survives when provider tool is enabled", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCallConfig(t, db, model, callConfig)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
insertProviderToolPairMessageWithLocalTool(ctx, t, db, chat.ID, model.ID, "ws-allowed")
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 2)
|
|
body := anthropicRequestBody(t, generationRequests[1])
|
|
require.Contains(t, body, "ws-allowed")
|
|
require.Contains(t, body, "web_search")
|
|
})
|
|
|
|
t.Run("web search history survives when provider tool is disabled", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search and read")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
insertProviderToolPairMessageWithLocalTool(ctx, t, db, chat.ID, model.ID, "ws-disabled")
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 2)
|
|
body := anthropicRequestBody(t, generationRequests[1])
|
|
require.Contains(t, body, "ws-disabled")
|
|
require.Contains(t, body, "web_search")
|
|
require.Contains(t, body, "tc-1")
|
|
require.Contains(t, body, "file")
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_AnthropicDropsUnpairedProviderToolBeforePersist(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
toolName string
|
|
toolInput json.RawMessage
|
|
}{
|
|
{
|
|
name: "web_search",
|
|
toolName: "web_search",
|
|
toolInput: json.RawMessage(`{"query":"coder"}`),
|
|
},
|
|
{
|
|
name: "code_execution",
|
|
toolName: "code_execution",
|
|
toolInput: json.RawMessage(`{"code":"print(1)"}`),
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
var requestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
if requestCount.Add(1) == 1 {
|
|
return chattest.AnthropicStreamingResponse(
|
|
anthropicServerToolUseChunks("pt-1", tt.toolName, tt.toolInput, "tool_use")...,
|
|
)
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("after sanitized step")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = enableAnthropicWebSearchForTest(t, db, model)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "run provider tool")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 1)
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
last := messages[len(messages)-1]
|
|
require.Equal(t, database.ChatMessageRoleUser, last.Role)
|
|
requireTextPart(t, last, "run provider tool")
|
|
require.False(t, toolPartExists(chatToolParts(ctx, t, db, chat.ID), tt.toolName),
|
|
"unpaired provider tool content should not be committed")
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_AnthropicKeepsPairedWebSearchBeforePersist(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
for _, tt := range []struct {
|
|
name string
|
|
noResults bool
|
|
}{
|
|
{name: "WithResults"},
|
|
// Clients see a search that found nothing while it streams, so it
|
|
// must persist like any other.
|
|
{name: "NoResults", noResults: true},
|
|
} {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
chunks := anthropicWebSearchPairChunks("ws-1", `{"query":"coder"}`, "search done", "end_turn")
|
|
if tt.noResults {
|
|
for i := range chunks {
|
|
if chunks[i].ContentBlock.Type == "web_search_tool_result" {
|
|
chunks[i].ContentBlock.Content = []map[string]any{}
|
|
}
|
|
}
|
|
}
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
return chattest.AnthropicStreamingResponse(chunks...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = enableAnthropicWebSearchForTest(t, db, model)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search for coder")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 1)
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
toolCall := requireToolCallPart(t, parts, "web_search")
|
|
require.Equal(t, "ws-1", toolCall.ToolCallID)
|
|
require.True(t, toolCall.ProviderExecuted)
|
|
toolResult := requireToolResultPart(t, parts, "web_search")
|
|
require.Equal(t, "ws-1", toolResult.ToolCallID)
|
|
require.True(t, toolResult.ProviderExecuted)
|
|
require.NotEmpty(t, toolResult.ProviderMetadata)
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
requireTextPart(t, messages[len(messages)-1], "search done")
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestActiveServer_AnthropicWebSearchFollowUpHasNoSyntheticCancellation
|
|
// reproduces a bug where sending a follow-up user message after a
|
|
// completed provider-executed web_search turn inserted a synthetic
|
|
// cancellation tool-result ("Tool execution interrupted by new user
|
|
// message") for the server tool call. The provider-executed result
|
|
// lives inside the assistant message, so the cancellation synthesizer
|
|
// saw the call as outstanding and emitted a client-style tool-role
|
|
// result for a srvtoolu_ ID. On the next request that result replays
|
|
// as a plain tool_result block, which Anthropic rejects:
|
|
//
|
|
// unexpected `tool_use_id` found in `tool_result` blocks:
|
|
// srvtoolu_... Each `tool_result` block must have a
|
|
// corresponding `tool_use` block in the previous message.
|
|
func TestActiveServer_AnthropicWebSearchFollowUpHasNoSyntheticCancellation(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
var streamingRequestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
if streamingRequestCount.Add(1) == 1 {
|
|
return chattest.AnthropicStreamingResponse(
|
|
anthropicWebSearchPairChunks("srvtoolu_ws1", `{"query":"coder"}`, "search done", "end_turn")...,
|
|
)
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("follow-up done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = enableAnthropicWebSearchForTest(t, db, model)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search for coder")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
// Simulate a web search turn followed by a user follow-up.
|
|
_, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("thanks, tell me more")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the follow-up turn to run and the chat to settle.
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
return streamingRequestCount.Load() >= 2
|
|
}, testutil.IntervalFast)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
// The provider-executed web_search call is answered by the
|
|
// provider-executed result inside the assistant message. No
|
|
// tool-role message may carry a synthetic result for it.
|
|
for _, msg := range chatMessages(ctx, t, db, chat.ID) {
|
|
if msg.Role != database.ChatMessageRoleTool {
|
|
continue
|
|
}
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
for _, part := range parts {
|
|
if part.Type != codersdk.ChatMessagePartTypeToolResult {
|
|
continue
|
|
}
|
|
require.NotEqual(t, "srvtoolu_ws1", part.ToolCallID,
|
|
"provider-executed web_search call received a synthetic tool-role result: %s", string(part.Result))
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_AnthropicSanitizesWebSearchBeforeContinuation(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
requests := newAnthropicRequestRecorder()
|
|
var requestCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
requests.record(req)
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
if requestCount.Add(1) == 1 {
|
|
chunks := anthropicServerToolUseChunks("ws-1", "web_search", json.RawMessage(`{"query":"coder"}`), "tool_use")
|
|
chunks = append(chunks[:len(chunks)-2], anthropicToolUseChunksWithoutMessageEnvelope(1, "tc-1", "read_file", `{"path":"main.go"}`)...)
|
|
chunks = append(chunks,
|
|
chattest.AnthropicChunk{
|
|
Type: "message_delta",
|
|
StopReason: "tool_use",
|
|
Usage: chattest.AnthropicUsage{InputTokens: 10, OutputTokens: 5},
|
|
},
|
|
chattest.AnthropicChunk{Type: "message_stop"},
|
|
)
|
|
return chattest.AnthropicStreamingResponse(chunks...)
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = enableAnthropicWebSearchForTest(t, db, model)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "main.go", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, Content: "package main", FileSize: 12, TotalLines: 1, LinesRead: 1}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "anthropic-web-search-continuation",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search and read"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
generationRequests := filterAnthropicStreamingRequests(requests.all())
|
|
require.Len(t, generationRequests, 2)
|
|
continuationBody := anthropicRequestBody(t, generationRequests[1])
|
|
require.NotContains(t, continuationBody, "server_tool_use")
|
|
require.NotContains(t, continuationBody, "web_search_tool_result")
|
|
require.NotContains(t, continuationBody, "ws-1")
|
|
require.Contains(t, continuationBody, "tc-1")
|
|
require.Contains(t, continuationBody, "package main")
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
require.False(t, toolPartExists(parts, "web_search"))
|
|
toolCall := requireToolCallPart(t, parts, "read_file")
|
|
require.Equal(t, "tc-1", toolCall.ToolCallID)
|
|
require.False(t, toolCall.ProviderExecuted)
|
|
toolResult := requireToolResultPart(t, parts, "read_file")
|
|
require.Equal(t, "tc-1", toolResult.ToolCallID)
|
|
require.False(t, toolResult.ProviderExecuted)
|
|
}
|
|
|
|
func TestActiveServer_ExclusiveToolPolicy(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("mixed exclusive and local tools commit policy errors", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
advisorChunk := chattest.OpenAIToolCallChunk("advisor", `{"question":"help"}`)
|
|
readChunk := chattest.OpenAIToolCallChunk("read_file", `{"path":"/tmp/a.txt"}`)
|
|
readCall := readChunk.Choices[0].ToolCalls[0]
|
|
readCall.Index = 1
|
|
advisorChunk.Choices[0].ToolCalls = append(advisorChunk.Choices[0].ToolCalls, readCall)
|
|
return chattest.OpenAIStreamingResponse(advisorChunk)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
seedAdvisorConfig(ctx, t, db, codersdk.AdvisorConfig{Enabled: true, MaxUsesPerRun: 3, MaxOutputTokens: 1024})
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "exclusive-local-policy",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("advise and read"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
advisorResult := requireToolResultPart(t, parts, "advisor")
|
|
readResult := requireToolResultPart(t, parts, "read_file")
|
|
require.True(t, advisorResult.IsError)
|
|
require.True(t, readResult.IsError)
|
|
require.Contains(t, string(advisorResult.Result), "advisor must be called alone, without other tools in the same batch")
|
|
require.Contains(t, string(readResult.Result), "this tool was skipped because advisor must run alone in its batch")
|
|
// A third streamed call would be the advisor's nested model call.
|
|
require.Equal(t, int32(2), streamedCallCount.Load())
|
|
})
|
|
|
|
t.Run("mixed exclusive and dynamic tools commit policy errors", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCallCount.Add(1) == 1 {
|
|
advisorChunk := chattest.OpenAIToolCallChunk("advisor", `{"question":"help"}`)
|
|
dynamicChunk := chattest.OpenAIToolCallChunk("mcp_tool", `{"q":"docs"}`)
|
|
dynamicCall := dynamicChunk.Choices[0].ToolCalls[0]
|
|
dynamicCall.Index = 1
|
|
advisorChunk.Choices[0].ToolCalls = append(advisorChunk.Choices[0].ToolCalls, dynamicCall)
|
|
return chattest.OpenAIStreamingResponse(advisorChunk)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
seedAdvisorConfig(ctx, t, db, codersdk.AdvisorConfig{Enabled: true, MaxUsesPerRun: 3, MaxOutputTokens: 1024})
|
|
dynamicToolsJSON, err := json.Marshal([]mcp.Tool{{
|
|
Name: "mcp_tool",
|
|
Description: "dynamic test tool",
|
|
InputSchema: map[string]any{"type": "object", "properties": map[string]any{"q": map[string]any{"type": "string"}}},
|
|
}})
|
|
require.NoError(t, err)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "exclusive-dynamic-policy",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("advise and call dynamic"),
|
|
},
|
|
DynamicTools: dynamicToolsJSON,
|
|
})
|
|
require.NoError(t, err)
|
|
chatResult := waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.NotEqual(t, database.ChatStatusRequiresAction, chatResult.Status)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
advisorResult := requireToolResultPart(t, parts, "advisor")
|
|
dynamicResult := requireToolResultPart(t, parts, "mcp_tool")
|
|
require.True(t, advisorResult.IsError)
|
|
require.True(t, dynamicResult.IsError)
|
|
require.Contains(t, string(advisorResult.Result), "advisor must be called alone, without other tools in the same batch")
|
|
require.Contains(t, string(dynamicResult.Result), "this tool was skipped because advisor must run alone in its batch")
|
|
require.GreaterOrEqual(t, streamedCallCount.Load(), int32(2))
|
|
})
|
|
|
|
t.Run("exclusive tool with provider executed tool executes", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
webSearchEnabled := true
|
|
var streamedCallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch streamedCallCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIResponse{
|
|
StreamingChunks: chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("advisor", `{"question":"search informed advice"}`),
|
|
).StreamingChunks,
|
|
WebSearch: &chattest.OpenAIWebSearchCall{ID: "ws-advisor", Query: "coder"},
|
|
}
|
|
case 2:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("nested advice")...)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
OpenAI: &codersdk.ChatModelOpenAIProviderOptions{WebSearchEnabled: &webSearchEnabled},
|
|
},
|
|
})
|
|
seedAdvisorConfig(ctx, t, db, codersdk.AdvisorConfig{Enabled: true, MaxUsesPerRun: 3, MaxOutputTokens: 1024})
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "search then advise")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
parts := chatToolParts(ctx, t, db, chat.ID)
|
|
advisorResult := requireToolResultPart(t, parts, "advisor")
|
|
webResult := requireToolResultPart(t, parts, "web_search")
|
|
require.False(t, advisorResult.IsError)
|
|
require.True(t, webResult.ProviderExecuted)
|
|
require.GreaterOrEqual(t, streamedCallCount.Load(), int32(3))
|
|
})
|
|
}
|
|
|
|
func TestActiveServer_ReasoningTimestamps(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
sendReasoning := true
|
|
thinkingBudget := int64(1024)
|
|
anthropicURL := chattest.NewAnthropic(t, func(_ *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicReasoningTextChunks(
|
|
[]chattest.AnthropicReasoningBlock{
|
|
{Text: "first thought", Signature: "sig_1"},
|
|
{Text: "second thought", Signature: "sig_2"},
|
|
},
|
|
"answer",
|
|
)...)
|
|
})
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{
|
|
SendReasoning: &sendReasoning,
|
|
Thinking: &codersdk.ChatModelAnthropicThinkingOptions{
|
|
BudgetTokens: &thinkingBudget,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "think")
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
assistant := messages[len(messages)-1]
|
|
reasoningParts := reasoningPartsFromMessage(t, assistant)
|
|
require.Len(t, reasoningParts, 2)
|
|
require.Equal(t, []string{"first thought", "second thought"}, []string{
|
|
strings.TrimSpace(reasoningParts[0].Text),
|
|
strings.TrimSpace(reasoningParts[1].Text),
|
|
})
|
|
for i := range reasoningParts {
|
|
require.NotNil(t, reasoningParts[i].CreatedAt)
|
|
require.NotNil(t, reasoningParts[i].CompletedAt)
|
|
require.False(t, reasoningParts[i].CreatedAt.IsZero())
|
|
require.False(t, reasoningParts[i].CompletedAt.IsZero())
|
|
require.False(t, reasoningParts[i].CompletedAt.Before(*reasoningParts[i].CreatedAt))
|
|
}
|
|
require.False(t, reasoningParts[1].CreatedAt.Before(*reasoningParts[0].CompletedAt))
|
|
}
|
|
|
|
func enableAnthropicWebSearchForTest(
|
|
t *testing.T,
|
|
db database.Store,
|
|
model database.ChatModelConfig,
|
|
) database.ChatModelConfig {
|
|
t.Helper()
|
|
webSearchEnabled := true
|
|
return updateChatModelCallConfig(t, db, model, codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
Anthropic: &codersdk.ChatModelAnthropicProviderOptions{
|
|
WebSearchEnabled: &webSearchEnabled,
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
func anthropicMessageStartChunk(messageID string) chattest.AnthropicChunk {
|
|
return chattest.AnthropicChunk{
|
|
Type: "message_start",
|
|
Message: chattest.AnthropicChunkMessage{
|
|
ID: messageID,
|
|
Type: "message",
|
|
Role: "assistant",
|
|
Model: "claude-3-opus-20240229",
|
|
},
|
|
}
|
|
}
|
|
|
|
func anthropicServerToolUseChunks(
|
|
toolCallID string,
|
|
toolName string,
|
|
input json.RawMessage,
|
|
stopReason string,
|
|
) []chattest.AnthropicChunk {
|
|
chunks := []chattest.AnthropicChunk{
|
|
anthropicMessageStartChunk("msg-" + toolCallID),
|
|
}
|
|
chunks = append(chunks, anthropicServerToolUseChunksWithoutMessageEnvelope(0, toolCallID, toolName, input)...)
|
|
chunks = append(chunks,
|
|
chattest.AnthropicChunk{
|
|
Type: "message_delta",
|
|
StopReason: stopReason,
|
|
Usage: chattest.AnthropicUsage{InputTokens: 10, OutputTokens: 5},
|
|
},
|
|
chattest.AnthropicChunk{Type: "message_stop"},
|
|
)
|
|
return chunks
|
|
}
|
|
|
|
func anthropicServerToolUseChunksWithoutMessageEnvelope(
|
|
index int,
|
|
toolCallID string,
|
|
toolName string,
|
|
input json.RawMessage,
|
|
) []chattest.AnthropicChunk {
|
|
return []chattest.AnthropicChunk{
|
|
{
|
|
Type: "content_block_start",
|
|
Index: index,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "server_tool_use",
|
|
ID: toolCallID,
|
|
Name: toolName,
|
|
Input: input,
|
|
},
|
|
},
|
|
{
|
|
Type: "content_block_stop",
|
|
Index: index,
|
|
},
|
|
}
|
|
}
|
|
|
|
func anthropicToolUseChunksWithoutMessageEnvelope(
|
|
index int,
|
|
toolCallID string,
|
|
toolName string,
|
|
input string,
|
|
) []chattest.AnthropicChunk {
|
|
return []chattest.AnthropicChunk{
|
|
{
|
|
Type: "content_block_start",
|
|
Index: index,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "tool_use",
|
|
ID: toolCallID,
|
|
Name: toolName,
|
|
Input: json.RawMessage(`{}`),
|
|
},
|
|
},
|
|
{
|
|
Type: "content_block_delta",
|
|
Index: index,
|
|
Delta: chattest.AnthropicDeltaBlock{
|
|
Type: "input_json_delta",
|
|
PartialJSON: input,
|
|
},
|
|
},
|
|
{
|
|
Type: "content_block_stop",
|
|
Index: index,
|
|
},
|
|
}
|
|
}
|
|
|
|
func anthropicWebSearchPairChunks(
|
|
toolCallID string,
|
|
queryInput string,
|
|
text string,
|
|
stopReason string,
|
|
) []chattest.AnthropicChunk {
|
|
resultContent := []map[string]any{{
|
|
"type": "web_search_result",
|
|
"url": "https://example.com/coder",
|
|
"title": "Coder",
|
|
"encrypted_content": "encrypted-coder",
|
|
}}
|
|
chunks := []chattest.AnthropicChunk{
|
|
anthropicMessageStartChunk("msg-" + toolCallID),
|
|
}
|
|
chunks = append(chunks, anthropicServerToolUseChunksWithoutMessageEnvelope(0, toolCallID, "web_search", json.RawMessage(queryInput))...)
|
|
chunks = append(chunks,
|
|
chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 1,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "web_search_tool_result",
|
|
ToolUseID: toolCallID,
|
|
Content: resultContent,
|
|
},
|
|
},
|
|
chattest.AnthropicChunk{Type: "content_block_stop", Index: 1},
|
|
chattest.AnthropicChunk{
|
|
Type: "content_block_start",
|
|
Index: 2,
|
|
ContentBlock: chattest.AnthropicContentBlock{
|
|
Type: "text",
|
|
},
|
|
},
|
|
chattest.AnthropicChunk{
|
|
Type: "content_block_delta",
|
|
Index: 2,
|
|
Delta: chattest.AnthropicDeltaBlock{
|
|
Type: "text_delta",
|
|
Text: text,
|
|
},
|
|
},
|
|
chattest.AnthropicChunk{Type: "content_block_stop", Index: 2},
|
|
chattest.AnthropicChunk{
|
|
Type: "message_delta",
|
|
StopReason: stopReason,
|
|
Usage: chattest.AnthropicUsage{InputTokens: 10, OutputTokens: 5},
|
|
},
|
|
chattest.AnthropicChunk{Type: "message_stop"},
|
|
)
|
|
return chunks
|
|
}
|
|
|
|
func toolPartExists(parts []codersdk.ChatMessagePart, toolName string) bool {
|
|
for _, part := range parts {
|
|
if (part.Type == codersdk.ChatMessagePartTypeToolCall || part.Type == codersdk.ChatMessagePartTypeToolResult) &&
|
|
part.ToolName == toolName {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func updateChatModelCompressionThreshold(t *testing.T, db database.Store, model database.ChatModelConfig, contextLimit int64, threshold int32) database.ChatModelConfig {
|
|
t.Helper()
|
|
model.ContextLimit = contextLimit
|
|
model.CompressionThreshold = threshold
|
|
updated, err := db.UpdateChatModelConfig(context.Background(), database.UpdateChatModelConfigParams{
|
|
ID: model.ID,
|
|
DisplayName: model.DisplayName,
|
|
Model: model.Model,
|
|
Enabled: model.Enabled,
|
|
ContextLimit: model.ContextLimit,
|
|
CompressionThreshold: model.CompressionThreshold,
|
|
Options: model.Options,
|
|
AIProviderID: model.AIProviderID,
|
|
})
|
|
require.NoError(t, err)
|
|
return updated
|
|
}
|
|
|
|
func updateChatModelContextLimit(t *testing.T, db database.Store, model database.ChatModelConfig) database.ChatModelConfig {
|
|
t.Helper()
|
|
updated, err := db.UpdateChatModelConfig(context.Background(), database.UpdateChatModelConfigParams{
|
|
ID: model.ID,
|
|
DisplayName: model.DisplayName,
|
|
Model: model.Model,
|
|
Enabled: model.Enabled,
|
|
ContextLimit: model.ContextLimit,
|
|
CompressionThreshold: model.CompressionThreshold,
|
|
Options: model.Options,
|
|
AIProviderID: model.AIProviderID,
|
|
})
|
|
require.NoError(t, err)
|
|
return updated
|
|
}
|
|
|
|
func updateChatModelCallConfig(t *testing.T, db database.Store, model database.ChatModelConfig, callConfig codersdk.ChatModelCallConfig) database.ChatModelConfig {
|
|
t.Helper()
|
|
options, err := json.Marshal(callConfig)
|
|
require.NoError(t, err)
|
|
updated, err := db.UpdateChatModelConfig(context.Background(), database.UpdateChatModelConfigParams{
|
|
ID: model.ID,
|
|
DisplayName: model.DisplayName,
|
|
Model: model.Model,
|
|
Enabled: model.Enabled,
|
|
ContextLimit: model.ContextLimit,
|
|
CompressionThreshold: model.CompressionThreshold,
|
|
Options: options,
|
|
AIProviderID: model.AIProviderID,
|
|
})
|
|
require.NoError(t, err)
|
|
return updated
|
|
}
|
|
|
|
func insertAssistantTextMessage(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
text string,
|
|
modelID uuid.UUID,
|
|
) {
|
|
t.Helper()
|
|
insertChatMessageParts(ctx, t, db, chatID, database.ChatMessageRoleAssistant, modelID, uuid.Nil, []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(text),
|
|
})
|
|
}
|
|
|
|
func insertProviderToolPairMessageWithLocalTool(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
modelID uuid.UUID,
|
|
toolCallID string,
|
|
) {
|
|
t.Helper()
|
|
metadata, err := json.Marshal(fantasy.ProviderMetadata{
|
|
fantasyanthropic.Name: &fantasyanthropic.WebSearchResultMetadata{
|
|
Results: []fantasyanthropic.WebSearchResultItem{{
|
|
URL: "https://example.com",
|
|
Title: "Example",
|
|
EncryptedContent: "encrypted",
|
|
}},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
parts := []codersdk.ChatMessagePart{
|
|
{
|
|
Type: codersdk.ChatMessagePartTypeToolCall,
|
|
ToolCallID: toolCallID,
|
|
ToolName: "web_search",
|
|
Args: json.RawMessage(`{"query":"coder"}`),
|
|
ProviderExecuted: true,
|
|
},
|
|
{
|
|
Type: codersdk.ChatMessagePartTypeToolResult,
|
|
ToolCallID: toolCallID,
|
|
ToolName: "web_search",
|
|
Result: json.RawMessage(`"ok"`),
|
|
ProviderExecuted: true,
|
|
ProviderMetadata: metadata,
|
|
},
|
|
}
|
|
parts = append(parts, codersdk.ChatMessagePart{
|
|
Type: codersdk.ChatMessagePartTypeToolCall,
|
|
ToolCallID: "tc-1",
|
|
ToolName: "read_file",
|
|
Args: json.RawMessage(`{"path":"main.go"}`),
|
|
})
|
|
insertChatMessageParts(ctx, t, db, chatID, database.ChatMessageRoleAssistant, modelID, uuid.Nil, parts)
|
|
insertChatMessageParts(ctx, t, db, chatID, database.ChatMessageRoleTool, modelID, uuid.Nil, []codersdk.ChatMessagePart{
|
|
{
|
|
Type: codersdk.ChatMessagePartTypeToolResult,
|
|
ToolCallID: "tc-1",
|
|
ToolName: "read_file",
|
|
Result: json.RawMessage(`"file"`),
|
|
},
|
|
})
|
|
}
|
|
|
|
func insertChatMessageParts(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
role database.ChatMessageRole,
|
|
modelID uuid.UUID,
|
|
createdBy uuid.UUID,
|
|
parts []codersdk.ChatMessagePart,
|
|
) database.ChatMessage {
|
|
t.Helper()
|
|
content, err := chatprompt.MarshalParts(parts)
|
|
require.NoError(t, err)
|
|
params := singleChatMessageInsertParams(
|
|
chatID,
|
|
role,
|
|
content,
|
|
modelID,
|
|
createdBy,
|
|
)
|
|
messages, err := db.InsertChatMessages(ctx, params)
|
|
require.NoError(t, err)
|
|
require.Len(t, messages, 1)
|
|
return database.ChatMessage(messages[0])
|
|
}
|
|
|
|
func anthropicRequestToolNames(req chattest.AnthropicRequest) []string {
|
|
names := make([]string, 0, len(req.Tools))
|
|
for _, tool := range req.Tools {
|
|
names = append(names, tool.Name)
|
|
}
|
|
return names
|
|
}
|
|
|
|
func anthropicRequestContainsPromptSentinel(t *testing.T, req chattest.AnthropicRequest) bool {
|
|
t.Helper()
|
|
body := anthropicRequestBody(t, req)
|
|
return strings.Contains(body, "__chatd_agent_prompt_sentinel_")
|
|
}
|
|
|
|
func reasoningPartsFromMessage(t *testing.T, msg database.ChatMessage) []codersdk.ChatMessagePart {
|
|
t.Helper()
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
require.NoError(t, err)
|
|
var reasoning []codersdk.ChatMessagePart
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeReasoning {
|
|
reasoning = append(reasoning, part)
|
|
}
|
|
}
|
|
return reasoning
|
|
}
|
|
|
|
func TestPassiveServerDoesNotProcess(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t, dbtestutil.WithDumpOnFailure())
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "should-stay-pending",
|
|
InitialUserContent: []codersdk.ChatMessagePart{{Type: codersdk.ChatMessagePartTypeText, Text: "hello"}},
|
|
ModelConfigID: model.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
// Re-read from DB to catch any unexpected processing.
|
|
stored, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusRunning, stored.Status)
|
|
require.False(t, stored.WorkerID.Valid)
|
|
require.False(t, stored.RunnerID.Valid)
|
|
}
|
|
|
|
// newDebugEnabledTestServer creates a passive test server with
|
|
// AlwaysEnableDebugLogs=true so that IsEnabled(ctx, chatID, ownerID)
|
|
// always returns true regardless of runtime admin config. This lets
|
|
// chatd-level integration tests exercise the debug cleanup wiring
|
|
// without seeding the admin/user opt-in settings tables.
|
|
func newDebugEnabledTestServer(
|
|
t *testing.T,
|
|
db database.Store,
|
|
ps dbpubsub.Pubsub,
|
|
replicaID uuid.UUID,
|
|
) *chatd.Server {
|
|
t.Helper()
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: replicaID,
|
|
PendingChatAcquireInterval: testutil.WaitLong,
|
|
AlwaysEnableDebugLogs: true,
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
return server
|
|
}
|
|
|
|
// newActiveTestServer creates a chatd server that actively polls for
|
|
// and processes pending chats. Use this instead of newTestServer when
|
|
// the test needs the chat loop to actually run. Optional config
|
|
// overrides are applied after the defaults.
|
|
func newActiveTestServer(
|
|
t *testing.T,
|
|
db database.Store,
|
|
ps dbpubsub.Pubsub,
|
|
overrides ...func(*chatd.Config),
|
|
) *chatd.Server {
|
|
t.Helper()
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
cfg := chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
Experiments: codersdk.ExperimentsKnown,
|
|
MCPHTTPClient: testMCPHTTPClient(),
|
|
}
|
|
for _, o := range overrides {
|
|
o(&cfg)
|
|
}
|
|
server := newChatdServer(t, ps, cfg)
|
|
server.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
return server
|
|
}
|
|
|
|
// sinkFieldValue returns the value of the named field from a captured log
|
|
// entry.
|
|
func sinkFieldValue(fields slog.Map, name string) (any, bool) {
|
|
for _, f := range fields {
|
|
if f.Name == name {
|
|
return f.Value, true
|
|
}
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
// TestActiveServer_GenerationErrorLogged drives a full chat worker against a
|
|
// provider that returns a terminal error and asserts that chatd logs the
|
|
// unsanitized failure so an administrator can later diagnose the underlying
|
|
// reason, even though the user-facing message is sanitized.
|
|
func TestActiveServer_GenerationErrorLogged(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
sink := testutil.NewFakeSink(t)
|
|
|
|
const providerErrMessage = "synthetic provider failure for logging test"
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
// A 400 is non-retryable, so the worker fails the turn immediately
|
|
// instead of entering retry backoff.
|
|
return chattest.OpenAIErrorResponse(http.StatusBadRequest, "invalid_request_error", providerErrMessage)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.Logger = sink.Logger()
|
|
})
|
|
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, model.ID, "hello")
|
|
failed := waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
require.True(t, failed.LastError.Valid)
|
|
|
|
isGenerationFailure := func(e slog.SinkEntry) bool {
|
|
return e.Level == slog.LevelWarn && e.Message == "chat generation failed"
|
|
}
|
|
var entry slog.SinkEntry
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
entries := sink.Entries(isGenerationFailure)
|
|
if len(entries) == 0 {
|
|
return false
|
|
}
|
|
entry = entries[0]
|
|
return true
|
|
}, testutil.IntervalFast)
|
|
|
|
chatID, ok := sinkFieldValue(entry.Fields, "chat_id")
|
|
require.True(t, ok, "chat_id field present")
|
|
require.Equal(t, chat.ID, chatID)
|
|
|
|
provider, ok := sinkFieldValue(entry.Fields, "provider")
|
|
require.True(t, ok, "provider field present")
|
|
require.Equal(t, "openai", provider)
|
|
|
|
statusCode, ok := sinkFieldValue(entry.Fields, "status_code")
|
|
require.True(t, ok, "status_code field present")
|
|
require.Equal(t, http.StatusBadRequest, statusCode)
|
|
|
|
// The unsanitized cause must be logged so administrators can see the
|
|
// underlying provider reason, even though the persisted user-facing
|
|
// message omits it.
|
|
errValue, ok := sinkFieldValue(entry.Fields, "error")
|
|
require.True(t, ok, "error field present")
|
|
require.Contains(t, fmt.Sprintf("%v", errValue), providerErrMessage)
|
|
require.NotContains(t, chatLastErrorMessage(failed.LastError), providerErrMessage)
|
|
}
|
|
|
|
func TestProposeChatTitle_DebugRun(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
wantTitle := "Debug proposal title"
|
|
tests := []struct {
|
|
name string
|
|
alwaysEnableDebugLogs bool
|
|
response func() chattest.OpenAIResponse
|
|
wantErr bool
|
|
wantTitle string
|
|
wantTitleGenerationRuns int
|
|
wantDebugStatus codersdk.ChatDebugStatus
|
|
}{
|
|
{
|
|
name: "Enabled",
|
|
alwaysEnableDebugLogs: true,
|
|
response: func() chattest.OpenAIResponse {
|
|
return chattest.OpenAINonStreamingResponse(
|
|
"{\"title\":\"" + wantTitle + "\"}",
|
|
)
|
|
},
|
|
wantTitle: wantTitle,
|
|
wantTitleGenerationRuns: 1,
|
|
wantDebugStatus: codersdk.ChatDebugStatusCompleted,
|
|
},
|
|
{
|
|
name: "Disabled",
|
|
alwaysEnableDebugLogs: false,
|
|
response: func() chattest.OpenAIResponse {
|
|
return chattest.OpenAINonStreamingResponse(
|
|
"{\"title\":\"" + wantTitle + "\"}",
|
|
)
|
|
},
|
|
wantTitle: wantTitle,
|
|
},
|
|
{
|
|
name: "GenerationErrorFinalizesDebugRun",
|
|
alwaysEnableDebugLogs: true,
|
|
response: func() chattest.OpenAIResponse {
|
|
return chattest.OpenAINonStreamingResponse("not json")
|
|
},
|
|
wantErr: true,
|
|
wantTitleGenerationRuns: 1,
|
|
wantDebugStatus: codersdk.ChatDebugStatusError,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps, rawDB := dbtestutil.NewDBWithSQLDB(t)
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
require.False(t, req.Stream)
|
|
return tt.response()
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(
|
|
t,
|
|
db,
|
|
"openai",
|
|
openAIURL,
|
|
)
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}),
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: testutil.WaitLong,
|
|
AlwaysEnableDebugLogs: tt.alwaysEnableDebugLogs,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
Status: database.ChatStatusWaiting,
|
|
ClientType: database.ChatClientTypeUi,
|
|
OwnerID: user.ID,
|
|
Title: "original title",
|
|
LastModelConfigID: model.ID,
|
|
})
|
|
message := insertUserTextMessage(
|
|
t,
|
|
db,
|
|
chat.ID,
|
|
user.ID,
|
|
model.ID,
|
|
"summarize debug title generation",
|
|
model.ContextLimit,
|
|
)
|
|
require.NotEqual(t, uuid.Nil, message.ID)
|
|
|
|
gotTitle, err := server.ProposeChatTitle(ctx, chat)
|
|
if tt.wantErr {
|
|
require.Error(t, err)
|
|
} else {
|
|
require.NoError(t, err)
|
|
require.Equal(t, tt.wantTitle, gotTitle)
|
|
}
|
|
|
|
runs, err := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, runs, tt.wantTitleGenerationRuns)
|
|
if tt.wantTitleGenerationRuns > 0 {
|
|
require.Equal(t, string(codersdk.ChatDebugRunKindTitleGeneration), runs[0].Kind)
|
|
require.Equal(t, string(tt.wantDebugStatus), runs[0].Status)
|
|
require.True(t, runs[0].Provider.Valid)
|
|
require.Equal(t, "openai", runs[0].Provider.String)
|
|
require.True(t, runs[0].FinishedAt.Valid)
|
|
require.True(t, runs[0].HistoryTipMessageID.Valid)
|
|
require.Equal(t, message.ID, runs[0].HistoryTipMessageID.Int64)
|
|
require.False(t, runs[0].TriggerMessageID.Valid)
|
|
require.Equal(t, uuid.NullUUID{UUID: model.ID, Valid: true}, runs[0].ModelConfigID)
|
|
require.Equal(t, sql.NullString{String: model.Model, Valid: true}, runs[0].Model)
|
|
var summary map[string]any
|
|
require.NoError(t, json.Unmarshal(runs[0].Summary, &summary))
|
|
require.Equal(t, "summarize debug title generation", summary["first_message"])
|
|
steps, err := db.GetChatDebugStepsByRunID(ctx, runs[0].ID)
|
|
require.NoError(t, err)
|
|
require.NotEmpty(t, steps)
|
|
}
|
|
if !tt.wantErr {
|
|
// Title generation must not write accounting rows to
|
|
// chat_messages; usage is tracked by AI Gateway.
|
|
var usageMessages int
|
|
err = rawDB.QueryRowContext(
|
|
ctx,
|
|
`SELECT count(*) FROM chat_messages WHERE chat_id = $1 AND visibility = 'model' AND deleted = true`,
|
|
chat.ID,
|
|
).Scan(&usageMessages)
|
|
require.NoError(t, err)
|
|
require.Equal(t, 0, usageMessages)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func seedChatDependencies(
|
|
t *testing.T,
|
|
db database.Store,
|
|
) (database.User, database.Organization, database.ChatModelConfig) {
|
|
t.Helper()
|
|
openAIURL := chattest.OpenAI(t)
|
|
return seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
}
|
|
|
|
// seedChatDependenciesWithProvider creates a user, organization,
|
|
// chat provider, and model config for the given provider type and
|
|
// base URL.
|
|
func seedChatDependenciesWithProvider(
|
|
t *testing.T,
|
|
db database.Store,
|
|
provider string,
|
|
baseURL string,
|
|
) (database.User, database.Organization, database.ChatModelConfig) {
|
|
t.Helper()
|
|
|
|
user := dbgen.User(t, db, database.User{})
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
dbgen.OrganizationMember(t, db, database.OrganizationMember{
|
|
UserID: user.ID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
providerConfig := dbgen.ChatProvider(t, db, database.ChatProvider{
|
|
Provider: provider,
|
|
DisplayName: provider,
|
|
BaseUrl: baseURL,
|
|
})
|
|
model := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
AIProviderID: uuid.NullUUID{UUID: providerConfig.ID, Valid: true},
|
|
IsDefault: true,
|
|
OrganizationID: org.ID,
|
|
})
|
|
return user, org, model
|
|
}
|
|
|
|
func seedChatDependenciesWithProviderPolicy(
|
|
t *testing.T,
|
|
db database.Store,
|
|
provider string,
|
|
baseURL string,
|
|
apiKey string,
|
|
centralAPIKeyEnabled bool,
|
|
allowUserAPIKey bool,
|
|
allowCentralAPIKeyFallback bool,
|
|
) (database.User, database.Organization, database.ChatProvider, database.ChatModelConfig) {
|
|
t.Helper()
|
|
|
|
user := dbgen.User(t, db, database.User{})
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
dbgen.OrganizationMember(t, db, database.OrganizationMember{
|
|
UserID: user.ID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
providerConfig := dbgen.ChatProvider(t, db, database.ChatProvider{
|
|
Provider: provider,
|
|
DisplayName: provider,
|
|
BaseUrl: baseURL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
Enabled: true,
|
|
}, func(p *database.InsertChatProviderParams) {
|
|
p.APIKey = apiKey
|
|
p.CentralApiKeyEnabled = centralAPIKeyEnabled
|
|
p.AllowUserApiKey = allowUserAPIKey
|
|
p.AllowCentralApiKeyFallback = allowCentralAPIKeyFallback
|
|
})
|
|
|
|
model := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
AIProviderID: uuid.NullUUID{UUID: providerConfig.ID, Valid: true},
|
|
IsDefault: true,
|
|
OrganizationID: org.ID,
|
|
})
|
|
|
|
return user, org, providerConfig, model
|
|
}
|
|
|
|
func seedLastTurnSummary(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chat database.Chat,
|
|
summary string,
|
|
) {
|
|
t.Helper()
|
|
|
|
affected, err := db.UpdateChatLastTurnSummary(ctx, database.UpdateChatLastTurnSummaryParams{
|
|
ID: chat.ID,
|
|
ExpectedHistoryVersion: chat.HistoryVersion,
|
|
LastTurnSummary: sql.NullString{String: summary, Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, int64(1), affected)
|
|
}
|
|
|
|
func waitForTerminalChat(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
) database.Chat {
|
|
t.Helper()
|
|
|
|
var chatResult database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
got, err := db.GetChatByID(ctx, chatID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.IntervalFast)
|
|
|
|
return chatResult
|
|
}
|
|
|
|
func insertChatModelConfigWithCallConfig(
|
|
t *testing.T,
|
|
db database.Store,
|
|
userID uuid.UUID,
|
|
provider string,
|
|
model string,
|
|
callConfig codersdk.ChatModelCallConfig,
|
|
) database.ChatModelConfig {
|
|
t.Helper()
|
|
|
|
options, err := json.Marshal(callConfig)
|
|
require.NoError(t, err)
|
|
|
|
// Reuse the newest AI provider of this type (creating a bare one only when
|
|
// none exists) so the config links the seeded provider carrying the mock
|
|
// base URL and API key rather than a fresh credential-less one.
|
|
providers, err := db.GetAIProviders(context.Background(), database.GetAIProvidersParams{IncludeDisabled: true})
|
|
require.NoError(t, err)
|
|
var aiProvider database.AIProvider
|
|
for _, candidate := range providers {
|
|
if candidate.Type != database.AIProviderType(provider) {
|
|
continue
|
|
}
|
|
if aiProvider.ID == uuid.Nil || candidate.CreatedAt.After(aiProvider.CreatedAt) {
|
|
aiProvider = candidate
|
|
}
|
|
}
|
|
if aiProvider.ID == uuid.Nil {
|
|
aiProvider = dbgen.AIProvider(t, db, database.AIProvider{
|
|
Type: database.AIProviderType(provider),
|
|
})
|
|
}
|
|
organizations, err := db.GetOrganizationsByUserID(context.Background(), database.GetOrganizationsByUserIDParams{
|
|
UserID: userID,
|
|
Deleted: sql.NullBool{
|
|
Bool: false,
|
|
Valid: true,
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, organizations, 1)
|
|
return dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
AIProviderID: uuid.NullUUID{UUID: aiProvider.ID, Valid: true},
|
|
Model: model,
|
|
DisplayName: model,
|
|
CreatedBy: uuid.NullUUID{UUID: userID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: userID, Valid: true},
|
|
Options: options,
|
|
OrganizationID: organizations[0].ID,
|
|
})
|
|
}
|
|
|
|
func insertUserTextMessage(
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
userID uuid.UUID,
|
|
modelConfigID uuid.UUID,
|
|
text string,
|
|
contextLimit ...int64,
|
|
) database.ChatMessage {
|
|
t.Helper()
|
|
require.LessOrEqual(t, len(contextLimit), 1)
|
|
|
|
contextLimitValue := int64(0)
|
|
if len(contextLimit) == 1 {
|
|
contextLimitValue = contextLimit[0]
|
|
}
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{codersdk.ChatMessageText(text)})
|
|
require.NoError(t, err)
|
|
|
|
return dbgen.ChatMessage(t, db, database.ChatMessage{
|
|
ChatID: chatID,
|
|
CreatedBy: uuid.NullUUID{UUID: userID, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: modelConfigID, Valid: true},
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: pqtype.NullRawMessage{RawMessage: content.RawMessage, Valid: true},
|
|
ContextLimit: sql.NullInt64{Int64: contextLimitValue, Valid: contextLimitValue != 0},
|
|
})
|
|
}
|
|
|
|
// seedWorkspaceWithAgent creates a full workspace chain with a connected
|
|
// agent. This is the common setup needed by tests that exercise tool
|
|
// execution against a workspace.
|
|
func seedWorkspaceWithAgent(
|
|
t *testing.T,
|
|
db database.Store,
|
|
userID uuid.UUID,
|
|
) (database.WorkspaceTable, database.WorkspaceAgent) {
|
|
t.Helper()
|
|
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
tv := dbgen.TemplateVersion(t, db, database.TemplateVersion{
|
|
OrganizationID: org.ID,
|
|
CreatedBy: userID,
|
|
})
|
|
tpl := dbgen.Template(t, db, database.Template{
|
|
CreatedBy: userID,
|
|
OrganizationID: org.ID,
|
|
ActiveVersionID: tv.ID,
|
|
})
|
|
ws := dbgen.Workspace(t, db, database.WorkspaceTable{
|
|
TemplateID: tpl.ID,
|
|
OwnerID: userID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
pj := dbgen.ProvisionerJob(t, db, nil, database.ProvisionerJob{
|
|
InitiatorID: userID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
_ = dbgen.WorkspaceBuild(t, db, database.WorkspaceBuild{
|
|
TemplateVersionID: tv.ID,
|
|
WorkspaceID: ws.ID,
|
|
JobID: pj.ID,
|
|
})
|
|
res := dbgen.WorkspaceResource(t, db, database.WorkspaceResource{
|
|
Transition: database.WorkspaceTransitionStart,
|
|
JobID: pj.ID,
|
|
})
|
|
dbAgent := dbgen.WorkspaceAgent(t, db, database.WorkspaceAgent{
|
|
ResourceID: res.ID,
|
|
Directory: "/home/coder/project",
|
|
OperatingSystem: "linux",
|
|
})
|
|
require.NoError(t, db.UpdateWorkspaceAgentStartupByID(context.Background(), database.UpdateWorkspaceAgentStartupByIDParams{
|
|
ID: dbAgent.ID,
|
|
Version: "v1.0.0",
|
|
ExpandedDirectory: "/home/coder/project",
|
|
}))
|
|
dbAgent, err := db.GetWorkspaceAgentByID(context.Background(), dbAgent.ID)
|
|
require.NoError(t, err)
|
|
return ws, dbAgent
|
|
}
|
|
|
|
func setOpenAIProviderBaseURL(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
baseURL string,
|
|
) {
|
|
t.Helper()
|
|
|
|
providers, err := db.GetAIProviders(ctx, database.GetAIProvidersParams{IncludeDisabled: true})
|
|
require.NoError(t, err)
|
|
for _, provider := range providers {
|
|
if provider.Type != database.AIProviderTypeOpenai {
|
|
continue
|
|
}
|
|
_, err = db.UpdateAIProvider(ctx, database.UpdateAIProviderParams{
|
|
ID: provider.ID,
|
|
Type: provider.Type,
|
|
DisplayName: provider.DisplayName,
|
|
Icon: provider.Icon,
|
|
Enabled: provider.Enabled,
|
|
BaseUrl: baseURL,
|
|
Settings: provider.Settings,
|
|
SettingsKeyID: provider.SettingsKeyID,
|
|
})
|
|
require.NoError(t, err)
|
|
return
|
|
}
|
|
require.Fail(t, "openai provider not found")
|
|
}
|
|
|
|
func TestInterruptUnownedChatClearsLastTurnSummary(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
for _, tc := range []struct {
|
|
name string
|
|
interrupting bool
|
|
}{
|
|
{name: "InterruptRunning"},
|
|
{name: "InterruptInterrupting", interrupting: true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
// The server is never started, so no worker acquires the chat.
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}),
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
user, org, model := seedChatDependencies(t, db)
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "interrupt-unowned",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
if tc.interrupting {
|
|
// A worker acquires the chat, sees it interrupted, and
|
|
// abandons it before its runner starts.
|
|
machine := chatstate.NewChatMachine(db, ps, chat.ID)
|
|
_, err := machine.Update(ctx, func(tx *chatstate.Tx, _ database.Store, _ *chatstate.ChatSnapshot) error {
|
|
if _, err := tx.Acquire(chatstate.AcquireInput{WorkerID: uuid.New(), RunnerID: uuid.New()}); err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.Interrupt(chatstate.InterruptInput{}); err != nil {
|
|
return err
|
|
}
|
|
_, err := tx.Abandon(chatstate.AbandonInput{})
|
|
return err
|
|
})
|
|
require.NoError(t, err)
|
|
}
|
|
chat, err = db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.False(t, chat.WorkerID.Valid)
|
|
seedLastTurnSummary(ctx, t, db, chat, "previous summary")
|
|
|
|
updated, interrupted, err := server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
require.True(t, interrupted, "the call reports the interruption although the chat is already waiting")
|
|
require.Equal(t, database.ChatStatusWaiting, updated.Status)
|
|
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
return err == nil && !fromDB.LastTurnSummary.Valid
|
|
}, testutil.IntervalFast, "the inline interruption must clear the cached turn summary")
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInterruptChatDoesNotSendWebPushNotification(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Set up a mock OpenAI that blocks until the request context is
|
|
// canceled (i.e. until the chat is interrupted).
|
|
streamStarted := make(chan struct{})
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.OpenAITextChunks("partial")[0]
|
|
select {
|
|
case <-streamStarted:
|
|
default:
|
|
close(streamStarted)
|
|
}
|
|
// Block until the chat context is canceled by the interrupt.
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
})
|
|
|
|
// Mock webpush dispatcher that records calls.
|
|
mockPush := &mockWebpushDispatcher{}
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
WebpushDispatcher: mockPush,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "interrupt-no-push",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
seedLastTurnSummary(ctx, t, db, chat, "previous summary")
|
|
|
|
server.Start()
|
|
|
|
// Wait for the chat to be picked up and start streaming.
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
fromDB, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
return fromDB.Status == database.ChatStatusRunning && fromDB.WorkerID.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
select {
|
|
case <-streamStarted:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}, testutil.IntervalFast)
|
|
|
|
// Interrupt the chat. The worker finalizes the interruption asynchronously.
|
|
updated, _, _ := server.InterruptChat(ctx, chat)
|
|
require.Equal(t, database.ChatStatusInterrupting, updated.Status)
|
|
|
|
// Wait for the chat to finish processing and return to waiting.
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
fromDB, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
return fromDB.Status == database.ChatStatusWaiting && !fromDB.WorkerID.Valid
|
|
}, testutil.IntervalFast)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.False(t, fromDB.LastTurnSummary.Valid,
|
|
"interrupted chats should clear cached turn summaries")
|
|
|
|
// Verify no web push notification was dispatched.
|
|
require.Equal(t, int32(0), mockPush.dispatchCount.Load(),
|
|
"expected no web push dispatch for an interrupted chat")
|
|
}
|
|
|
|
// mockWebpushDispatcher implements webpush.Dispatcher and records Dispatch calls.
|
|
type mockWebpushDispatcher struct {
|
|
dispatchCount atomic.Int32
|
|
mu sync.Mutex
|
|
lastMessage codersdk.WebpushMessage
|
|
lastUserID uuid.UUID
|
|
}
|
|
|
|
func (m *mockWebpushDispatcher) Dispatch(_ context.Context, userID uuid.UUID, msg codersdk.WebpushMessage) error {
|
|
m.dispatchCount.Add(1)
|
|
m.mu.Lock()
|
|
m.lastMessage = msg
|
|
m.lastUserID = userID
|
|
m.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
func (m *mockWebpushDispatcher) getLastMessage() codersdk.WebpushMessage {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return m.lastMessage
|
|
}
|
|
|
|
func (*mockWebpushDispatcher) Test(_ context.Context, _ codersdk.WebpushSubscription) error {
|
|
return nil
|
|
}
|
|
|
|
func (*mockWebpushDispatcher) PublicKey() string {
|
|
return "test-vapid-public-key"
|
|
}
|
|
|
|
func TestSuccessfulChatSendsWebPushWithNavigationData(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Set up a mock OpenAI that returns a simple successful response.
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("done")...,
|
|
)
|
|
})
|
|
|
|
// Mock webpush dispatcher that captures the dispatched message.
|
|
mockPush := &mockWebpushDispatcher{}
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
WebpushDispatcher: mockPush,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
server.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "push-nav-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the chat to complete and return to waiting status.
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
fromDB, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
return fromDB.Status == database.ChatStatusWaiting && !fromDB.WorkerID.Valid && mockPush.dispatchCount.Load() == 1
|
|
}, testutil.IntervalFast)
|
|
|
|
// Verify a web push notification was dispatched exactly once.
|
|
require.Equal(t, int32(1), mockPush.dispatchCount.Load(),
|
|
"expected exactly one web push dispatch for a completed chat")
|
|
|
|
// Verify the notification was sent to the correct user.
|
|
mockPush.mu.Lock()
|
|
capturedMsg := mockPush.lastMessage
|
|
capturedUserID := mockPush.lastUserID
|
|
mockPush.mu.Unlock()
|
|
|
|
require.Equal(t, user.ID, capturedUserID,
|
|
"web push should be dispatched to the chat owner")
|
|
|
|
// Verify the Data field contains the correct navigation URL.
|
|
expectedURL := fmt.Sprintf("/agents/%s", chat.ID)
|
|
require.Equal(t, expectedURL, capturedMsg.Data["url"],
|
|
"web push Data should contain the chat navigation URL")
|
|
}
|
|
|
|
func TestCloseDuringShutdownContextCanceledShouldRetryOnNewReplica(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var requestCount atomic.Int32
|
|
streamStarted := make(chan struct{})
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
// Ignore non-streaming requests (e.g. title generation) so
|
|
// they don't interfere with the request counter used to
|
|
// coordinate the streaming chat flow.
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("shutdown-retry")
|
|
}
|
|
if requestCount.Add(1) == 1 {
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.OpenAITextChunks("partial")[0]
|
|
select {
|
|
case <-streamStarted:
|
|
default:
|
|
close(streamStarted)
|
|
}
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("retry", " complete")...)
|
|
})
|
|
|
|
loggerA := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
serverA := newChatdServer(t, ps, chatd.Config{
|
|
Logger: loggerA,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitLong,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(factory),
|
|
})
|
|
serverA.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, serverA.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := serverA.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "shutdown-retry",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.Eventually(t, func() bool {
|
|
fromDB, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
return fromDB.Status == database.ChatStatusRunning && fromDB.WorkerID.Valid
|
|
}, testutil.WaitMedium, testutil.IntervalFast)
|
|
|
|
require.Eventually(t, func() bool {
|
|
select {
|
|
case <-streamStarted:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}, testutil.WaitMedium, testutil.IntervalFast)
|
|
|
|
require.NoError(t, serverA.Close())
|
|
|
|
loggerB := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
serverB := newChatdServer(t, ps, chatd.Config{
|
|
Logger: loggerB,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitLong,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(factory),
|
|
})
|
|
serverB.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, serverB.Close())
|
|
})
|
|
|
|
require.Eventually(t, func() bool {
|
|
return requestCount.Load() >= 2
|
|
}, testutil.WaitMedium, testutil.IntervalFast)
|
|
|
|
require.Eventually(t, func() bool {
|
|
fromDB, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
return fromDB.Status == database.ChatStatusWaiting &&
|
|
!fromDB.WorkerID.Valid &&
|
|
!fromDB.LastError.Valid
|
|
}, testutil.WaitMedium, testutil.IntervalFast)
|
|
}
|
|
|
|
func TestSuccessfulChatSendsWebPushWithSummary(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const assistantText = "I have completed the task successfully and all tests are passing now."
|
|
const summaryText = "Finished unit tests"
|
|
|
|
var nonStreamingRequests atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
if strings.Contains(string(req.RawBody), "propose_turn_status_label") {
|
|
nonStreamingRequests.Add(1)
|
|
return chattest.OpenAINonStreamingResponse(fmt.Sprintf(`{"label":%q}`, summaryText))
|
|
}
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"Summary push test"}`)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks(assistantText)...,
|
|
)
|
|
})
|
|
|
|
mockPush := &mockWebpushDispatcher{}
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
WebpushDispatcher: mockPush,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
server.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "summary-push-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("do the thing")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// The push notification is dispatched asynchronously after the
|
|
// chat finishes, so we poll for it rather than checking
|
|
// immediately after the status transitions to waiting.
|
|
var fromDB database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
var dbErr error
|
|
fromDB, dbErr = db.GetChatByID(ctx, chat.ID)
|
|
return dbErr == nil && mockPush.dispatchCount.Load() >= 1 && fromDB.LastTurnSummary.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
msg := mockPush.getLastMessage()
|
|
require.Equal(t, summaryText, fromDB.LastTurnSummary.String,
|
|
"last turn summary should be the LLM-generated status label")
|
|
require.Equal(t, fromDB.LastTurnSummary.String, msg.Body,
|
|
"push body should reuse the persisted generated status label")
|
|
require.Equal(t, int32(1), nonStreamingRequests.Load(),
|
|
"expected exactly one non-streaming request for status label generation")
|
|
}
|
|
|
|
func TestSuccessfulChatPersistsTurnSummaryWithoutWebPush(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const assistantText = "I fixed the bug and added regression coverage."
|
|
const summaryText = "Fixed regression bug"
|
|
|
|
var nonStreamingRequests atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
if strings.Contains(string(req.RawBody), "propose_turn_status_label") {
|
|
nonStreamingRequests.Add(1)
|
|
return chattest.OpenAINonStreamingResponse(fmt.Sprintf(`{"label":%q}`, summaryText))
|
|
}
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"Summary push test"}`)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks(assistantText)...,
|
|
)
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "summary-no-webpush-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("do the thing")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var fromDB database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
var dbErr error
|
|
fromDB, dbErr = db.GetChatByID(ctx, chat.ID)
|
|
return dbErr == nil && fromDB.LastTurnSummary.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Equal(t, summaryText, fromDB.LastTurnSummary.String,
|
|
"status label should persist even when web push is unavailable")
|
|
require.Equal(t, int32(1), nonStreamingRequests.Load(),
|
|
"expected exactly one non-streaming request for status label generation")
|
|
}
|
|
|
|
func TestSuccessfulChatSendsWebPushFallbackWithoutSummaryForEmptyAssistantText(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var nonStreamingRequests atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
if strings.Contains(string(req.RawBody), "propose_turn_status_label") {
|
|
nonStreamingRequests.Add(1)
|
|
return chattest.OpenAINonStreamingResponse(`{"label":"Unexpected label"}`)
|
|
}
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"Empty summary push test"}`)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks(" ")...,
|
|
)
|
|
})
|
|
|
|
mockPush := &mockWebpushDispatcher{}
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
WebpushDispatcher: mockPush,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "empty-summary-push-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("do the thing")},
|
|
})
|
|
require.NoError(t, err)
|
|
seedLastTurnSummary(ctx, t, db, chat, "previous summary")
|
|
|
|
server.Start()
|
|
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
return mockPush.dispatchCount.Load() >= 1
|
|
}, testutil.IntervalFast)
|
|
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, sql.NullString{String: "Finished latest turn", Valid: true}, fromDB.LastTurnSummary,
|
|
"fallback status label should be persisted")
|
|
|
|
msg := mockPush.getLastMessage()
|
|
require.Equal(t, "Finished latest turn", msg.Body,
|
|
"push body should fall back when the final assistant text is empty")
|
|
require.Equal(t, int32(0), nonStreamingRequests.Load(),
|
|
"status label model should not run when final assistant text has no usable text")
|
|
}
|
|
|
|
func TestErroredChatClearsLastTurnSummaryAndSendsWebPush(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIErrorResponse(http.StatusBadRequest, "invalid_request_error", "Bad request")
|
|
})
|
|
|
|
mockPush := &mockWebpushDispatcher{}
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
WebpushDispatcher: mockPush,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "error-summary-clear-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("do the thing")},
|
|
})
|
|
require.NoError(t, err)
|
|
seedLastTurnSummary(ctx, t, db, chat, "previous summary")
|
|
|
|
server.Start()
|
|
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
fromDB, dbErr := db.GetChatByID(ctx, chat.ID)
|
|
return dbErr == nil &&
|
|
fromDB.Status == database.ChatStatusError &&
|
|
mockPush.dispatchCount.Load() >= 1
|
|
}, testutil.IntervalFast)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.False(t, fromDB.LastTurnSummary.Valid,
|
|
"errored chats should clear cached turn summaries")
|
|
|
|
msg := mockPush.getLastMessage()
|
|
require.NotEqual(t, "Hit an error", msg.Body)
|
|
require.Contains(t, msg.Body, "OpenAI returned an unexpected error")
|
|
}
|
|
|
|
func TestComputerUseSubagentToolsAndModel(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// The organization's computer use override selects this Anthropic model;
|
|
// the root chat runs on an openai-compat model. Claude 5.5 accepts
|
|
// computer use only through the computer_toolset_20260801 toolset.
|
|
const computerUseModelName = "claude-opus-5-5"
|
|
|
|
// Track tools and model from the Anthropic LLM calls (the
|
|
// computer use child chat). We use a raw HTTP handler because
|
|
// the chattest AnthropicRequest struct does not capture tools.
|
|
type anthropicTool struct {
|
|
Type string `json:"type"`
|
|
Name string `json:"name"`
|
|
}
|
|
type anthropicCall struct {
|
|
Model string
|
|
Tools []string
|
|
RawTools []anthropicTool
|
|
Beta string
|
|
Stream bool
|
|
System []string
|
|
Messages []json.RawMessage
|
|
}
|
|
var anthropicMu sync.Mutex
|
|
var anthropicCalls []anthropicCall
|
|
var sentComputerBatch bool
|
|
|
|
writeSSE := func(w http.ResponseWriter, chunks []map[string]any) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
flusher, _ := w.(http.Flusher)
|
|
for _, chunk := range chunks {
|
|
chunkBytes, _ := json.Marshal(chunk)
|
|
eventType, _ := chunk["type"].(string)
|
|
_, _ = fmt.Fprintf(w, "event: %s\ndata: %s\n\n",
|
|
eventType, chunkBytes)
|
|
flusher.Flush()
|
|
}
|
|
}
|
|
messageStart := map[string]any{
|
|
"type": "message_start",
|
|
"message": map[string]any{
|
|
"id": "msg-test",
|
|
"type": "message",
|
|
"role": "assistant",
|
|
"model": computerUseModelName,
|
|
},
|
|
}
|
|
// computerMemberChunks streams one computer toolset member call.
|
|
computerMemberChunks := func(index int, id, member, input string) []map[string]any {
|
|
return []map[string]any{
|
|
{
|
|
"type": "content_block_start",
|
|
"index": index,
|
|
"content_block": map[string]any{
|
|
"type": "tool_use",
|
|
"id": id,
|
|
"name": member,
|
|
"toolset_name": "computer",
|
|
"input": map[string]any{},
|
|
},
|
|
},
|
|
{
|
|
"type": "content_block_delta",
|
|
"index": index,
|
|
"delta": map[string]any{
|
|
"type": "input_json_delta",
|
|
"partial_json": input,
|
|
},
|
|
},
|
|
{"type": "content_block_stop", "index": index},
|
|
}
|
|
}
|
|
|
|
anthropicSrv := httptest.NewServer(http.HandlerFunc(
|
|
func(w http.ResponseWriter, r *http.Request) {
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Model string `json:"model"`
|
|
Stream bool `json:"stream"`
|
|
Tools []anthropicTool `json:"tools"`
|
|
Messages []json.RawMessage `json:"messages"`
|
|
System []struct {
|
|
Text string `json:"text"`
|
|
} `json:"system"`
|
|
}
|
|
if err := json.Unmarshal(body, &req); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
names := make([]string, len(req.Tools))
|
|
declaresToolset := false
|
|
for i, tool := range req.Tools {
|
|
names[i] = tool.Name
|
|
if tool.Type == "computer_toolset_20260801" {
|
|
declaresToolset = true
|
|
}
|
|
}
|
|
system := make([]string, len(req.System))
|
|
for i, block := range req.System {
|
|
system[i] = block.Text
|
|
}
|
|
anthropicMu.Lock()
|
|
anthropicCalls = append(anthropicCalls, anthropicCall{
|
|
Model: req.Model,
|
|
Tools: names,
|
|
RawTools: req.Tools,
|
|
Beta: r.Header.Get("anthropic-beta"),
|
|
Stream: req.Stream,
|
|
System: system,
|
|
Messages: req.Messages,
|
|
})
|
|
// The child's first turn request gets a two-action computer
|
|
// batch; every later request gets a text reply.
|
|
sendComputerBatch := req.Stream && declaresToolset && !sentComputerBatch
|
|
if sendComputerBatch {
|
|
sentComputerBatch = true
|
|
}
|
|
anthropicMu.Unlock()
|
|
|
|
if !req.Stream {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"id": "msg-test",
|
|
"type": "message",
|
|
"role": "assistant",
|
|
"model": computerUseModelName,
|
|
"content": []map[string]any{{"type": "text", "text": "Done."}},
|
|
"stop_reason": "end_turn",
|
|
"usage": map[string]any{"input_tokens": 10, "output_tokens": 5},
|
|
})
|
|
return
|
|
}
|
|
|
|
if sendComputerBatch {
|
|
chunks := []map[string]any{messageStart}
|
|
chunks = append(chunks, computerMemberChunks(0, "toolu_click", "left_click", `{"coordinate":[100,200]}`)...)
|
|
chunks = append(chunks, computerMemberChunks(1, "toolu_type", "type", `{"text":"hello"}`)...)
|
|
chunks = append(chunks,
|
|
map[string]any{
|
|
"type": "message_delta",
|
|
"delta": map[string]any{"stop_reason": "tool_use"},
|
|
"usage": map[string]any{"output_tokens": 5},
|
|
},
|
|
map[string]any{"type": "message_stop"},
|
|
)
|
|
writeSSE(w, chunks)
|
|
return
|
|
}
|
|
|
|
// Stream a minimal Anthropic SSE response.
|
|
writeSSE(w, []map[string]any{
|
|
messageStart,
|
|
{
|
|
"type": "content_block_start",
|
|
"index": 0,
|
|
"content_block": map[string]any{
|
|
"type": "text",
|
|
"text": "",
|
|
},
|
|
},
|
|
{
|
|
"type": "content_block_delta",
|
|
"index": 0,
|
|
"delta": map[string]any{
|
|
"type": "text_delta",
|
|
"text": "Done.",
|
|
},
|
|
},
|
|
{"type": "content_block_stop", "index": 0},
|
|
{
|
|
"type": "message_delta",
|
|
"delta": map[string]any{"stop_reason": "end_turn"},
|
|
"usage": map[string]any{"output_tokens": 5},
|
|
},
|
|
{"type": "message_stop"},
|
|
})
|
|
},
|
|
))
|
|
t.Cleanup(anthropicSrv.Close)
|
|
|
|
// OpenAI mock for the root chat. The first streaming call
|
|
// triggers spawn_agent; subsequent calls reply
|
|
// with text.
|
|
var openAICallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if openAICallCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"spawn_agent",
|
|
`{"type":"computer_use","prompt":"do the desktop thing","title":"cu-sub"}`,
|
|
),
|
|
)
|
|
}
|
|
// Include literal \u0000 in the response text, which is
|
|
// what a real LLM writes when explaining binary output.
|
|
// json.Marshal encodes the backslash as \\, producing
|
|
// \\u0000 in the JSON bytes. The sanitizer must not
|
|
// corrupt this into invalid JSON.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("The file contains \\u0000 null bytes.")...,
|
|
)
|
|
})
|
|
|
|
// Seed the DB: user, openai-compat provider, model config.
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
// Add an Anthropic provider pointing to our mock server.
|
|
anthropicProvider := dbgen.ChatProvider(t, db, database.ChatProvider{
|
|
Provider: "anthropic",
|
|
DisplayName: "Anthropic",
|
|
APIKey: "test-anthropic-key",
|
|
BaseUrl: anthropicSrv.URL,
|
|
})
|
|
computerUseModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
AIProviderID: uuid.NullUUID{UUID: anthropicProvider.ID, Valid: true},
|
|
Model: computerUseModelName,
|
|
OrganizationID: org.ID,
|
|
})
|
|
require.NoError(t, db.UpsertChatOrganizationModelOverride(ctx, database.UpsertChatOrganizationModelOverrideParams{
|
|
OrganizationID: org.ID,
|
|
Context: string(codersdk.ChatModelOverrideContextComputerUse),
|
|
ModelConfigID: computerUseModel.ID,
|
|
}))
|
|
|
|
// Build workspace + agent records so getWorkspaceConn can
|
|
// resolve the agent for the computer use child.
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
// Mock agent connection that returns valid display dimensions
|
|
// for the initial screenshot check in the computer use path and
|
|
// records the desktop actions the computer tool runs.
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
var desktopMu sync.Mutex
|
|
var desktopActions []string
|
|
mockConn.EXPECT().
|
|
ExecuteDesktopAction(gomock.Any(), gomock.Any()).
|
|
DoAndReturn(func(_ context.Context, action workspacesdk.DesktopAction) (workspacesdk.DesktopActionResponse, error) {
|
|
desktopMu.Lock()
|
|
desktopActions = append(desktopActions, action.Action)
|
|
desktopMu.Unlock()
|
|
return workspacesdk.DesktopActionResponse{
|
|
Output: action.Action + " action performed",
|
|
ScreenshotWidth: 1920,
|
|
ScreenshotHeight: 1080,
|
|
ScreenshotData: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4n539HwAHFwLVF8kc1wAAAABJRU5ErkJggg==",
|
|
}, nil
|
|
}).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
SetExtraHeaders(gomock.Any()).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).
|
|
AnyTimes()
|
|
mockConn.EXPECT().
|
|
LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{}, xerrors.New("not found")).
|
|
AnyTimes()
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
providers, providersErr := db.GetAIProviders(ctx, database.GetAIProvidersParams{})
|
|
require.NoError(t, providersErr)
|
|
routes := make(map[string]aibridge.TransportFactory, len(providers))
|
|
for _, provider := range providers {
|
|
switch provider.Type {
|
|
case database.AIProviderTypeOpenaiCompat:
|
|
routes[provider.Name] = chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
case database.AIProviderTypeAnthropic:
|
|
routes[provider.Name] = chattest.NewMockAIBridgeTransport(t, anthropicSrv.URL)
|
|
}
|
|
}
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(providerRoutedTransportFactory{routes: routes})
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
// Create a root chat with a workspace so the child inherits it.
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "computer-use-detection",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Use the desktop to check the UI"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the root chat AND the computer use child to finish.
|
|
// The root chat spawns the child, then the chatd server picks
|
|
// up and runs the child (which hits the Anthropic mock).
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
if got.Status != database.ChatStatusWaiting &&
|
|
got.Status != database.ChatStatusError {
|
|
return false
|
|
}
|
|
// Ensure the Anthropic mock received the child's computer batch
|
|
// request and the follow-up that carries the batch results.
|
|
anthropicMu.Lock()
|
|
defer anthropicMu.Unlock()
|
|
toolsetCalls := 0
|
|
for _, call := range anthropicCalls {
|
|
for _, tool := range call.RawTools {
|
|
if call.Stream && tool.Type == "computer_toolset_20260801" {
|
|
toolsetCalls++
|
|
}
|
|
}
|
|
}
|
|
return toolsetCalls >= 2
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
anthropicMu.Lock()
|
|
calls := append([]anthropicCall(nil), anthropicCalls...)
|
|
anthropicMu.Unlock()
|
|
|
|
require.NotEmpty(t, calls,
|
|
"expected at least one Anthropic LLM call")
|
|
|
|
var childCall anthropicCall
|
|
for _, call := range calls {
|
|
if call.Stream {
|
|
childCall = call
|
|
break
|
|
}
|
|
}
|
|
require.True(t, childCall.Stream,
|
|
"expected at least one streaming Anthropic child LLM call")
|
|
|
|
childModel := childCall.Model
|
|
childTools := childCall.Tools
|
|
|
|
// 1. Verify the model is the computer use model.
|
|
require.Equal(t, computerUseModelName, childModel,
|
|
"computer use subagent should use %s",
|
|
computerUseModelName)
|
|
|
|
// 2. Verify the computer tool is the GA toolset, which takes no
|
|
// beta header.
|
|
require.Contains(t, childCall.RawTools, anthropicTool{Type: "computer_toolset_20260801"},
|
|
"computer use subagent should have the computer toolset")
|
|
require.NotContains(t, childCall.Beta, "computer-use",
|
|
"the computer toolset needs no computer use beta header")
|
|
|
|
// 3. Verify standard workspace tools are present (the same
|
|
// set a regular subagent gets).
|
|
standardTools := []string{
|
|
"read_file", "write_file", "edit_files", "execute",
|
|
"process_output", "process_list", "process_signal",
|
|
}
|
|
for _, tool := range standardTools {
|
|
require.Contains(t, childTools, tool,
|
|
"computer use subagent should have standard tool %q",
|
|
tool)
|
|
}
|
|
|
|
// 4. Verify workspace provisioning tools are NOT present.
|
|
workspaceProvisioningTools := []string{
|
|
"list_templates", "read_template",
|
|
"create_workspace", "start_workspace", "stop_workspace",
|
|
}
|
|
for _, tool := range workspaceProvisioningTools {
|
|
require.NotContains(t, childTools, tool,
|
|
"computer use subagent should NOT have workspace "+
|
|
"provisioning tool %q", tool)
|
|
}
|
|
|
|
// 5. Verify subagent tools are NOT present.
|
|
subagentTools := []string{
|
|
"spawn_agent",
|
|
"wait_agent", "message_agent", "interrupt_agent", "list_agents",
|
|
}
|
|
for _, tool := range subagentTools {
|
|
require.NotContains(t, childTools, tool,
|
|
"computer use subagent should NOT have subagent "+
|
|
"tool %q", tool)
|
|
}
|
|
|
|
// 6. Verify the root-only advisor tool and guidance are NOT
|
|
// present.
|
|
require.NotContains(t, childTools, chatadvisor.ToolName,
|
|
"computer use subagent should NOT have the advisor tool")
|
|
require.NotEmpty(t, childCall.System,
|
|
"expected the child request to carry a system prompt")
|
|
for _, text := range childCall.System {
|
|
require.NotContains(t, text, chatadvisor.ParentGuidanceBlock,
|
|
"computer use subagent should NOT get the advisor guidance")
|
|
}
|
|
|
|
// 7. Verify both batch actions ran in order and no screenshot
|
|
// followed them.
|
|
desktopMu.Lock()
|
|
actions := append([]string(nil), desktopActions...)
|
|
desktopMu.Unlock()
|
|
clickIndex := slices.Index(actions, "left_click")
|
|
require.GreaterOrEqual(t, clickIndex, 0, "desktop actions: %v", actions)
|
|
require.Equal(t, []string{"left_click", "type"}, actions[clickIndex:])
|
|
|
|
// 8. Verify the follow-up request replays both member calls and
|
|
// their results as toolset members.
|
|
type replayedBlock struct {
|
|
Type string `json:"type"`
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
ToolsetName string `json:"toolset_name"`
|
|
ToolUseID string `json:"tool_use_id"`
|
|
Content json.RawMessage `json:"content"`
|
|
}
|
|
var followUp *anthropicCall
|
|
for i := range calls {
|
|
if calls[i].Stream && slices.Contains(calls[i].RawTools, anthropicTool{Type: "computer_toolset_20260801"}) {
|
|
followUp = &calls[i]
|
|
}
|
|
}
|
|
require.NotNil(t, followUp)
|
|
var memberCalls []string
|
|
results := map[string]replayedBlock{}
|
|
for _, raw := range followUp.Messages {
|
|
var message struct {
|
|
Content json.RawMessage `json:"content"`
|
|
}
|
|
require.NoError(t, json.Unmarshal(raw, &message))
|
|
var blocks []replayedBlock
|
|
if json.Unmarshal(message.Content, &blocks) != nil {
|
|
// String content holds no tool blocks.
|
|
continue
|
|
}
|
|
for _, block := range blocks {
|
|
switch block.Type {
|
|
case "tool_use":
|
|
if block.ToolsetName == "computer" {
|
|
memberCalls = append(memberCalls, block.ID+":"+block.Name)
|
|
}
|
|
case "tool_result":
|
|
results[block.ToolUseID] = block
|
|
}
|
|
}
|
|
}
|
|
require.Equal(t, []string{"toolu_click:left_click", "toolu_type:type"}, memberCalls)
|
|
for _, id := range []string{"toolu_click", "toolu_type"} {
|
|
require.Contains(t, results, id)
|
|
require.Equal(t, "computer", results[id].ToolsetName, "tool_result %s", id)
|
|
}
|
|
for id, action := range map[string]string{"toolu_click": "left_click", "toolu_type": "type"} {
|
|
require.Contains(t, string(results[id].Content), action+" action performed")
|
|
require.NotContains(t, string(results[id].Content), `"image"`)
|
|
}
|
|
|
|
// 9. Verify the child chat has Mode = computer_use in
|
|
// the DB.
|
|
childRows, err := db.GetChildChatsByParentIDs(ctx, database.GetChildChatsByParentIDsParams{
|
|
ParentIds: []uuid.UUID{chat.ID},
|
|
})
|
|
require.NoError(t, err)
|
|
children := make([]database.Chat, 0, len(childRows))
|
|
for _, row := range childRows {
|
|
children = append(children, row.Chat)
|
|
}
|
|
require.Len(t, children, 1)
|
|
require.True(t, children[0].Mode.Valid)
|
|
require.Equal(t, database.ChatModeComputerUse,
|
|
children[0].Mode.ChatMode)
|
|
}
|
|
|
|
func TestInterruptChatPersistsPartialResponse(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Set up a mock OpenAI that streams a partial response and then
|
|
// blocks until the request context is canceled (simulating an
|
|
// interrupt mid-stream).
|
|
chunksDelivered := make(chan struct{})
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
// Send two partial text chunks so there is meaningful
|
|
// content to persist.
|
|
for _, c := range chattest.OpenAITextChunks("hello world") {
|
|
chunks <- c
|
|
}
|
|
// Signal that chunks have been written to the HTTP response.
|
|
select {
|
|
case <-chunksDelivered:
|
|
default:
|
|
close(chunksDelivered)
|
|
}
|
|
// Block until interrupt cancels the context.
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
})
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
server := newChatdServer(t, ps, chatd.Config{
|
|
Logger: logger,
|
|
Database: db,
|
|
ReplicaID: uuid.New(),
|
|
PendingChatAcquireInterval: 10 * time.Millisecond,
|
|
InFlightChatStaleAfter: testutil.WaitSuperLong,
|
|
Experiments: codersdk.ExperimentsKnown,
|
|
AIBridgeTransportFactory: chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)),
|
|
})
|
|
server.Start()
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Close())
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "interrupt-persist-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the mock to finish sending chunks.
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
select {
|
|
case <-chunksDelivered:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}, testutil.IntervalFast)
|
|
|
|
// Now interrupt the chat. The provider has sent partial content.
|
|
updated, _, _ := server.InterruptChat(ctx, chat)
|
|
require.Equal(t, database.ChatStatusInterrupting, updated.Status)
|
|
|
|
// Wait for the partial assistant message to be persisted.
|
|
// After the interrupt, the chatloop runs persistInterruptedStep
|
|
// which inserts the message and publishes a "message" event.
|
|
// We poll the DB directly for the assistant message rather than
|
|
// relying on the chat status (which transitions to "waiting"
|
|
// before the persist completes).
|
|
var assistantMsg *database.ChatMessage
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
msgs, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for i := range msgs {
|
|
if msgs[i].Role == database.ChatMessageRoleAssistant {
|
|
assistantMsg = &msgs[i]
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.NotNilf(t, assistantMsg, "expected a persisted assistant message after interrupt")
|
|
|
|
// Parse the content and verify it contains the partial text.
|
|
parts, err := chatprompt.ParseContent(*assistantMsg)
|
|
require.NoError(t, err)
|
|
|
|
var foundText string
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText {
|
|
foundText += part.Text
|
|
}
|
|
}
|
|
require.Contains(t, foundText, "hello world",
|
|
"partial assistant response should contain the streamed text")
|
|
}
|
|
|
|
func TestProcessChat_UserProviderKey_Success(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const userAPIKey = "user-test-key"
|
|
|
|
var authHeadersMu sync.Mutex
|
|
authHeaders := make([]string, 0, 1)
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
authHeadersMu.Lock()
|
|
authHeaders = append(authHeaders, req.Header.Get("Authorization"))
|
|
authHeadersMu.Unlock()
|
|
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("user provider key success")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("hello from the saved user key")...,
|
|
)
|
|
})
|
|
|
|
user, org, provider, model := seedChatDependenciesWithProviderPolicy(
|
|
t,
|
|
db,
|
|
"openai-compat",
|
|
openAIURL,
|
|
"",
|
|
false,
|
|
true,
|
|
false,
|
|
)
|
|
_, err := db.UpsertUserAIProviderKey(ctx, database.UpsertUserAIProviderKeyParams{
|
|
ID: uuid.New(),
|
|
UserID: user.ID,
|
|
AIProviderID: provider.ID,
|
|
APIKey: userAPIKey,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
creator := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := creator.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "user-provider-key-success",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("say hello"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_ = newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, chat.ID)
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status)
|
|
require.False(t, chatResult.LastError.Valid)
|
|
|
|
authHeadersMu.Lock()
|
|
recordedAuthHeaders := append([]string(nil), authHeaders...)
|
|
authHeadersMu.Unlock()
|
|
require.Contains(t, recordedAuthHeaders, "Bearer "+userAPIKey)
|
|
}
|
|
|
|
func seedAIGatewayOpenAITestDependencies(
|
|
t *testing.T,
|
|
db database.Store,
|
|
openAIURL string,
|
|
) (database.User, database.Organization, database.AIProvider, database.ChatModelConfig) {
|
|
t.Helper()
|
|
|
|
user := dbgen.User(t, db, database.User{})
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
dbgen.OrganizationMember(t, db, database.OrganizationMember{
|
|
UserID: user.ID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
provider := dbgen.AIProvider(t, db, database.AIProvider{
|
|
Type: database.AIProviderTypeOpenai,
|
|
Name: "primary-openai-" + uuid.NewString(),
|
|
BaseUrl: openAIURL,
|
|
})
|
|
model := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
Model: "gpt-4o-mini",
|
|
IsDefault: true,
|
|
AIProviderID: uuid.NullUUID{UUID: provider.ID, Valid: true},
|
|
OrganizationID: org.ID,
|
|
})
|
|
_, err := db.UpsertUserAIProviderKey(context.Background(), database.UpsertUserAIProviderKeyParams{
|
|
ID: uuid.New(),
|
|
UserID: user.ID,
|
|
AIProviderID: provider.ID,
|
|
APIKey: "sk-user-aibridge",
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
return user, org, provider, model
|
|
}
|
|
|
|
func TestProcessChat_RoutingUsesDelegatedAPIKey(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if req.Stream {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("hello through AI Gateway")...,
|
|
)
|
|
}
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"AI Gateway Chat"}`)
|
|
})
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
|
|
user, org, provider, model := seedAIGatewayOpenAITestDependencies(t, db, openAIURL)
|
|
|
|
creator := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := creator.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "aigateway-routing",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("say hello"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_, events, cancel, ok := creator.Subscribe(ctx, chat.ID, nil, 0, 0)
|
|
require.True(t, ok)
|
|
t.Cleanup(cancel)
|
|
|
|
_ = newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
cfg.AllowBYOK = true
|
|
cfg.AllowBYOKSet = true
|
|
})
|
|
|
|
_ = events
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, chat.ID)
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status)
|
|
require.False(t, chatResult.LastError.Valid)
|
|
gatewayKey, err := db.GetChatGatewayAPIKey(ctx, database.GetChatGatewayAPIKeyParams{
|
|
UserID: user.ID,
|
|
TokenName: chatd.GatewayTokenName(user.ID),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
requests := factory.RequestsSnapshot()
|
|
require.NotEmpty(t, requests)
|
|
require.True(t, slices.ContainsFunc(requests, func(req chattest.RecordedRequest) bool {
|
|
return req.Request.URL.Path == "/v1/responses"
|
|
}), "no request to /v1/responses found")
|
|
for _, req := range requests {
|
|
require.Equal(t, provider.Name, req.ProviderName)
|
|
require.Equal(t, aibridge.SourceAgents, req.Source)
|
|
require.Equal(t, gatewayKey.ID, req.APIKeyID)
|
|
require.Equal(t, "Bearer sk-user-aibridge", req.Request.Header.Get("Authorization"))
|
|
require.Empty(t, req.Request.Header.Get("X-Api-Key"))
|
|
require.Equal(t, "delegated", req.Request.Header.Get(aibridge.HeaderCoderToken))
|
|
require.True(t, strings.HasPrefix(req.Request.URL.Path, "/v1/"), "unexpected aibridge path %q", req.Request.URL.Path)
|
|
}
|
|
}
|
|
|
|
func TestProcessChat_RoutingPreservesAPIKeyAfterWorkspaceContext(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if req.Stream {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("hello after workspace context")...,
|
|
)
|
|
}
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"AI Gateway Workspace"}`)
|
|
})
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
user, org, provider, model := seedAIGatewayOpenAITestDependencies(t, db, openAIURL)
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
creator := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := creator.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "aigateway-workspace-context",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("use the workspace context"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
const contextText = "# Project instructions\nAlways keep routing metadata."
|
|
// Workspace context is sourced from the agent's pinned snapshot. Seed it so
|
|
// the chat hydrates it on the lazy first-turn bind and the workspace-context
|
|
// path runs before AI gateway routing resolves the key.
|
|
seedAgentInstructionContext(ctx, t, db, dbAgent.ID,
|
|
"/home/coder/project/AGENTS.md", contextText)
|
|
_ = newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
cfg.AllowBYOK = true
|
|
cfg.AllowBYOKSet = true
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupWorkspaceContextAgentConn(t, mockConn, dbAgent, contextText, nil)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, chat.ID)
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status)
|
|
require.False(t, chatResult.LastError.Valid)
|
|
|
|
// Workspace context is pinned to the chat, not injected as a user message.
|
|
// Confirm the agent's pushed instruction hydrated onto the chat so the
|
|
// workspace-context path ran before AI gateway routing resolved the key.
|
|
pinned, err := db.ListChatContextResourcesByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.NotEmpty(t, pinned, "workspace context should be pinned to the chat")
|
|
gatewayKey, err := db.GetChatGatewayAPIKey(ctx, database.GetChatGatewayAPIKeyParams{
|
|
UserID: user.ID,
|
|
TokenName: chatd.GatewayTokenName(user.ID),
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
requests := factory.RequestsSnapshot()
|
|
require.NotEmpty(t, requests)
|
|
for _, req := range requests {
|
|
require.Equal(t, provider.Name, req.ProviderName)
|
|
require.Equal(t, aibridge.SourceAgents, req.Source)
|
|
require.Equal(t, gatewayKey.ID, req.APIKeyID)
|
|
require.Equal(t, "Bearer sk-user-aibridge", req.Request.Header.Get("Authorization"))
|
|
require.Equal(t, "delegated", req.Request.Header.Get(aibridge.HeaderCoderToken))
|
|
}
|
|
}
|
|
|
|
func TestProcessChat_UserProviderKey_MissingKeyError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var llmCalls atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
llmCalls.Add(1)
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("unexpected non-streaming request")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("unexpected streaming request")...,
|
|
)
|
|
})
|
|
|
|
user, org, _, model := seedChatDependenciesWithProviderPolicy(
|
|
t,
|
|
db,
|
|
"openai-compat",
|
|
openAIURL,
|
|
"",
|
|
false,
|
|
true,
|
|
false,
|
|
)
|
|
|
|
creator := newTestServer(t, db, ps, uuid.New())
|
|
chat, err := creator.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "user-provider-key-missing",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("say hello"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
_ = newActiveTestServer(t, db, ps)
|
|
|
|
chatResult := waitForTerminalChat(ctx, t, db, chat.ID)
|
|
require.Equal(t, database.ChatStatusError, chatResult.Status)
|
|
persistedError := requireChatLastErrorPayload(t, chatResult.LastError)
|
|
require.NotEmpty(t, persistedError.Message)
|
|
require.NotContains(t, persistedError.Message, "panicked")
|
|
require.Equal(t, codersdk.ChatErrorKindGeneric, persistedError.Kind)
|
|
require.NotEqual(t, database.ChatStatusRunning, chatResult.Status)
|
|
require.Zero(t, llmCalls.Load(), "missing user key should fail before any LLM request")
|
|
}
|
|
|
|
func TestProcessChatPanicRecovery(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
|
|
// Wrap the database so we can trigger a panic on the main
|
|
// goroutine of processChat. The chatloop's toolBatch has
|
|
// its own recover, so panicking inside a tool goroutine won't
|
|
// reach the processChat-level recovery. Instead, we panic
|
|
// during PersistStep's InTx call, which runs synchronously on
|
|
// the processChat goroutine.
|
|
panicWrapper := &panicOnInTxDB{Store: db}
|
|
|
|
firstOpenAICallStarted := make(chan struct{})
|
|
continueFirstOpenAICall := make(chan struct{})
|
|
var openAICallCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("Panic recovery test")
|
|
}
|
|
|
|
if openAICallCount.Add(1) == 1 {
|
|
close(firstOpenAICallStarted)
|
|
<-continueFirstOpenAICall
|
|
}
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("hello")...,
|
|
)
|
|
})
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
// Pass the panic wrapper to the server, but use the real
|
|
// database for seeding so those operations don't panic.
|
|
server := newActiveTestServer(t, panicWrapper, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "panic-recovery",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("hello"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.TryReceive(ctx, t, firstOpenAICallStarted)
|
|
|
|
// Enable the panic while the first provider call is blocked. The next InTx
|
|
// call is PersistStep inside the chatloop, running synchronously on the
|
|
// processChat goroutine after the provider returns.
|
|
panicWrapper.enablePanic()
|
|
close(continueFirstOpenAICall)
|
|
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
require.Equal(t, int32(2), openAICallCount.Load())
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var assistantText string
|
|
for _, message := range messages {
|
|
if message.Role != database.ChatMessageRoleAssistant {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(message)
|
|
require.NoError(t, parseErr)
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeText {
|
|
assistantText += part.Text
|
|
}
|
|
}
|
|
}
|
|
require.Equal(t, "hello", assistantText)
|
|
require.False(t, chatResult.LastError.Valid)
|
|
}
|
|
|
|
// panicOnInTxDB wraps a database.Store and panics on the first InTx
|
|
// call after enablePanic is called. Subsequent calls pass through
|
|
// so the processChat cleanup defer can update the chat status.
|
|
type panicOnInTxDB struct {
|
|
database.Store
|
|
active atomic.Bool
|
|
panicked atomic.Bool
|
|
}
|
|
|
|
func (d *panicOnInTxDB) enablePanic() { d.active.Store(true) }
|
|
|
|
func (d *panicOnInTxDB) InTx(f func(database.Store) error, opts *database.TxOptions) error {
|
|
if d.active.Load() && !d.panicked.Load() {
|
|
d.panicked.Store(true)
|
|
panic("intentional test panic")
|
|
}
|
|
return d.Store.InTx(f, opts)
|
|
}
|
|
|
|
func TestMCPToolSearchGenerationFlows(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("search activates tools within and across turns", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
mcpSrv := newTestMCPServer("search-mcp")
|
|
addTestMCPTextTool(mcpSrv, "alpha", "Alpha deferred action", "alpha: ")
|
|
addTestMCPTextTool(mcpSrv, "beta", "Beta deferred action", "beta: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
var (
|
|
streamCount atomic.Int32
|
|
requestsMu sync.Mutex
|
|
requests []recordedOpenAIRequest
|
|
)
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
requestsMu.Lock()
|
|
requests = append(requests, recordOpenAIRequest(t, req))
|
|
requestsMu.Unlock()
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(chattool.FindToolsName, `{"names":["search-mcp__alpha","search-mcp__beta"]}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Search MCP",
|
|
Slug: "search-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "deferred search",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("find deferred actions"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
requestsMu.Lock()
|
|
recorded := append([]recordedOpenAIRequest(nil), requests...)
|
|
requestsMu.Unlock()
|
|
require.Len(t, recorded, 3)
|
|
require.Contains(t, recorded[0].Tools, "read_file")
|
|
require.Contains(t, recorded[0].Tools, chattool.FindToolsName)
|
|
require.NotContains(t, recorded[0].Tools, "search-mcp__alpha")
|
|
require.NotContains(t, recorded[0].Tools, "search-mcp__beta")
|
|
for _, request := range recorded[1:] {
|
|
require.Contains(t, request.Tools, chattool.FindToolsName)
|
|
require.Contains(t, request.Tools, "search-mcp__alpha")
|
|
require.Contains(t, request.Tools, "search-mcp__beta")
|
|
require.Less(t,
|
|
slices.Index(request.Tools, "search-mcp__alpha"),
|
|
slices.Index(request.Tools, "search-mcp__beta"),
|
|
)
|
|
}
|
|
})
|
|
|
|
t.Run("direct call activates schema on next step", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
mcpSrv := newTestMCPServer("direct-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echo deferred input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
var (
|
|
streamCount atomic.Int32
|
|
requestsMu sync.Mutex
|
|
requests []recordedOpenAIRequest
|
|
)
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
requestsMu.Lock()
|
|
requests = append(requests, recordOpenAIRequest(t, req))
|
|
requestsMu.Unlock()
|
|
if streamCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("direct-mcp__echo", `{"input":"hello"}`),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Direct MCP",
|
|
Slug: "direct-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "direct deferred call",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("call the deferred tool directly"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
requestsMu.Lock()
|
|
recorded := append([]recordedOpenAIRequest(nil), requests...)
|
|
requestsMu.Unlock()
|
|
require.Len(t, recorded, 2)
|
|
require.NotContains(t, recorded[0].Tools, "direct-mcp__echo")
|
|
require.Contains(t, recorded[1].Tools, "direct-mcp__echo")
|
|
require.True(t, openAIMessagesContain(recorded[1].Messages, "echo: hello"))
|
|
})
|
|
|
|
t.Run("partition-denied find_tools calls count toward call totals", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
mcpSrv := newTestMCPServer("count-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echo input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
var streamCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
// Malformed JSON input: partitioned into a synthetic
|
|
// denial before ExecuteLocalTools, so the tool's own
|
|
// handler and decode never see this call.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(chattool.FindToolsName, `{"queries":["echo"`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Count MCP",
|
|
Slug: "count-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
reg := prometheus.NewRegistry()
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.PrometheusRegistry = reg
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "count denied find_tools",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_find_tools_calls_total", 1, nil)
|
|
})
|
|
|
|
t.Run("hook-denied find_tools calls count toward call totals", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
mcpSrv := newTestMCPServer("hooked-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echo input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
var streamCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch streamCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(chattool.FindToolsName, `{"queries":["echo"]}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
})
|
|
consumer := preToolUseConsumer(t, func(data agenthooks.PreToolUseData) string {
|
|
require.Equal(t, chattool.FindToolsName, data.ToolName)
|
|
return `{"permission":{"decision":"deny","reason":"blocked by policy"}}`
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Hooked MCP",
|
|
Slug: "hooked-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
reg := prometheus.NewRegistry()
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.HookDispatcher = newHookDispatcher(t, db, consumer)
|
|
cfg.PrometheusRegistry = reg
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "count hook-denied find_tools",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_find_tools_calls_total", 1, nil)
|
|
})
|
|
|
|
t.Run("admission-failed find_tools calls count toward call totals", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
mcpSrv := newTestMCPServer("failing-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echo input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(chattool.FindToolsName, `{"queries":["echo"]}`),
|
|
)
|
|
})
|
|
// A pre_tool_use dispatch failure errors admission before the
|
|
// step commits, so the call never reaches executeLocalTools.
|
|
consumer := newHookConsumer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
var request agenthooks.Request
|
|
require.NoError(t, json.NewDecoder(r.Body).Decode(&request))
|
|
if request.Type != agenthooks.EventPreToolUse {
|
|
_, err := w.Write([]byte(`{}`))
|
|
require.NoError(t, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
})
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Failing MCP",
|
|
Slug: "failing-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
reg := prometheus.NewRegistry()
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.HookDispatcher = newHookDispatcher(t, db, consumer)
|
|
cfg.PrometheusRegistry = reg
|
|
})
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "count admission-failed find_tools",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
|
|
requireChatdMetricCounter(t, reg, "coderd_chatd_find_tools_calls_total", 1, nil)
|
|
})
|
|
}
|
|
|
|
// TestMCPServerToolInvocation verifies that when a chat has
|
|
// mcp_server_ids set, the chat loop connects to those MCP servers,
|
|
// discovers their tools, and the LLM can invoke them.
|
|
//
|
|
// NOTE: This test uses a raw database.Store (no dbauthz wrapper).
|
|
// The chatd RBAC authorization of GetMCPServerConfigsByIDs (which
|
|
// requires ActionRead on ResourceDeploymentConfig) is covered by
|
|
// the chatd role definition tests, not here.
|
|
func TestMCPServerToolInvocation(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Start a real MCP server that exposes an "echo" tool.
|
|
mcpSrv := newTestMCPServer("test-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpHTTP := testMCPHTTPHandler(mcpSrv)
|
|
mcpTS := httptest.NewServer(mcpHTTP)
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
// Track which tool names are sent to the LLM and capture
|
|
// whether the MCP tool result appears in the second call.
|
|
var (
|
|
callCount atomic.Int32
|
|
llmToolNames []string
|
|
llmToolsMu sync.Mutex
|
|
foundMCPResult atomic.Bool
|
|
)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
// Record tool names from the first streamed call.
|
|
if callCount.Add(1) == 1 {
|
|
names := offeredToolNames(t, req)
|
|
llmToolsMu.Lock()
|
|
llmToolNames = names
|
|
llmToolsMu.Unlock()
|
|
|
|
// Ask the LLM to call the MCP echo tool.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"test-mcp__echo",
|
|
`{"input":"hello from LLM"}`,
|
|
),
|
|
)
|
|
}
|
|
|
|
// Second call: verify the tool result was fed back.
|
|
for _, msg := range req.Messages {
|
|
if msg.Role == "tool" && strings.Contains(msg.Content, "echo: hello from LLM") {
|
|
foundMCPResult.Store(true)
|
|
}
|
|
}
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Got it!")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
// Seed the MCP server config in the database. This must
|
|
// happen after seedChatDependencies so user.ID exists for
|
|
// the foreign key.
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Test MCP",
|
|
Slug: "test-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
mockConn.EXPECT().SetExtraHeaders(gomock.Any()).AnyTimes()
|
|
mockConn.EXPECT().ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).AnyTimes()
|
|
mockConn.EXPECT().LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{}, nil).AnyTimes()
|
|
mockConn.EXPECT().ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(io.NopCloser(strings.NewReader("")), "", nil).AnyTimes()
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "mcp-tool-test",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Echo something via MCP."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Verify MCPServerIDs were persisted on the chat record.
|
|
dbChat, getErr := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, getErr)
|
|
require.Equal(t, []uuid.UUID{mcpConfig.ID}, dbChat.MCPServerIDs)
|
|
|
|
// Wait for the chat to finish processing.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
llmToolsMu.Lock()
|
|
recordedNames := append([]string(nil), llmToolNames...)
|
|
llmToolsMu.Unlock()
|
|
require.Contains(t, recordedNames, "test-mcp__echo",
|
|
"MCP tool should be offered to the LLM")
|
|
|
|
// The tool result from the MCP server ("echo: hello from
|
|
// LLM") should have been fed back to the LLM as a tool
|
|
// message in the second call.
|
|
require.True(t, foundMCPResult.Load(),
|
|
"MCP tool result should appear in the second LLM call")
|
|
|
|
// Verify the tool result was persisted in the database.
|
|
var foundToolMessage bool
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleTool {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
if parseErr != nil || len(parts) == 0 {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult &&
|
|
part.ToolName == "test-mcp__echo" &&
|
|
strings.Contains(string(part.Result), "echo: hello from LLM") {
|
|
foundToolMessage = true
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.True(t, foundToolMessage,
|
|
"MCP tool result should be persisted as a tool message in the database")
|
|
}
|
|
|
|
func TestActiveServer_ChatTurnDebugRunRecordsMCPConnectPerPreparation(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
mcpSrv := newTestMCPServer("test-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
var callCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if callCount.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"test-mcp__echo",
|
|
`{"input":"hello from LLM"}`,
|
|
),
|
|
)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Got it!")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Test MCP",
|
|
Slug: "test-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "mcp-connect-debug-test",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Echo something via MCP."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var chatTurnRuns []database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, runsErr := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if runsErr != nil {
|
|
return false
|
|
}
|
|
chatTurnRuns = chatTurnRuns[:0]
|
|
for _, run := range runs {
|
|
if run.Kind == string(codersdk.ChatDebugRunKindChatTurn) {
|
|
chatTurnRuns = append(chatTurnRuns, run)
|
|
}
|
|
}
|
|
return len(chatTurnRuns) == 1 && chatTurnRuns[0].FinishedAt.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Len(t, chatTurnRuns, 1)
|
|
var summary struct {
|
|
MCPConnect []struct {
|
|
Slug string `json:"slug"`
|
|
Outcome string `json:"outcome"`
|
|
} `json:"mcp_connect"`
|
|
}
|
|
require.NoError(t, json.Unmarshal(chatTurnRuns[0].Summary, &summary))
|
|
// A tool-call turn runs at least three preparations: the
|
|
// assistant step that requests the tool, the local tool
|
|
// execution step, and the assistant step that consumes the
|
|
// result. Each preparation reconnects to the MCP server and
|
|
// must contribute its connect outcome to the finalized run.
|
|
require.GreaterOrEqual(t, len(summary.MCPConnect), 3)
|
|
for _, entry := range summary.MCPConnect {
|
|
require.Equal(t, "test-mcp", entry.Slug)
|
|
require.Equal(t, "connected", entry.Outcome)
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_ChatTurnDebugRunRecordsMCPConnectOnDecisionError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
mcpSrv := newTestMCPServer("test-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
// Every streamed assistant response is a high-usage tool call,
|
|
// so the turn compacts once and the post-compaction assistant
|
|
// is still over the context limit: the next decision fails
|
|
// terminally with the still-over-limit error.
|
|
var streamCount atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if strings.Contains(anthropicRequestBody(t, *req), "You are performing a context compaction") {
|
|
return anthropicCompactionResponse(t, req, "summary text for compaction")
|
|
}
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
if streamCount.Add(1) == 1 {
|
|
return highUsageReadFileResponse("/tmp/a.txt")
|
|
}
|
|
return highUsageReadFileResponse("/tmp/b.txt")
|
|
})
|
|
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 100, 70)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Test MCP",
|
|
Slug: "test-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
setupToolExecutionAgentConn(t, mockConn)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/a.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
mockConn.EXPECT().ReadFileLines(gomock.Any(), "/tmp/b.txt", int64(1), int64(0), gomock.Any()).
|
|
Return(workspacesdk.ReadFileLinesResponse{Success: true, FileSize: 12, TotalLines: 1, LinesRead: 1, Content: "1\tpackage main"}, nil).
|
|
Times(1)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()))
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
AgentID: uuid.NullUUID{UUID: dbAgent.ID, Valid: true},
|
|
Title: "mcp-connect-decision-error-test",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("read the files"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var chatTurnRuns []database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, runsErr := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if runsErr != nil {
|
|
return false
|
|
}
|
|
chatTurnRuns = chatTurnRuns[:0]
|
|
for _, run := range runs {
|
|
if run.Kind == string(codersdk.ChatDebugRunKindChatTurn) {
|
|
chatTurnRuns = append(chatTurnRuns, run)
|
|
}
|
|
}
|
|
return len(chatTurnRuns) == 1 && chatTurnRuns[0].FinishedAt.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Len(t, chatTurnRuns, 1)
|
|
var summary struct {
|
|
MCPConnect []struct {
|
|
Slug string `json:"slug"`
|
|
Outcome string `json:"outcome"`
|
|
} `json:"mcp_connect"`
|
|
}
|
|
require.NoError(t, json.Unmarshal(chatTurnRuns[0].Summary, &summary))
|
|
// The turn performs six preparations: the first assistant step,
|
|
// its tool execution, the compaction, the post-compaction
|
|
// assistant step, its tool execution, and the preparation whose
|
|
// decision fails with still-over-limit. Each one must
|
|
// contribute its connect outcome, including the final
|
|
// preparation that exits through the decision error.
|
|
require.GreaterOrEqual(t, len(summary.MCPConnect), 6)
|
|
for _, entry := range summary.MCPConnect {
|
|
require.Equal(t, "test-mcp", entry.Slug)
|
|
require.Equal(t, "connected", entry.Outcome)
|
|
}
|
|
}
|
|
|
|
// overrideReadFailStore wraps a database.Store so
|
|
// GetChatOrganizationModelOverride fails once the test arms it,
|
|
// making a later generation preparation fail after its MCP connect
|
|
// phase has already completed.
|
|
type overrideReadFailStore struct {
|
|
database.Store
|
|
fail *atomic.Bool
|
|
}
|
|
|
|
func (s *overrideReadFailStore) GetChatOrganizationModelOverride(ctx context.Context, arg database.GetChatOrganizationModelOverrideParams) (database.ChatOrganizationModelOverride, error) {
|
|
if s.fail.Load() && arg.Context == "compaction" {
|
|
return database.ChatOrganizationModelOverride{}, xerrors.New("injected compaction override read failure")
|
|
}
|
|
return s.Store.GetChatOrganizationModelOverride(ctx, arg)
|
|
}
|
|
|
|
func TestActiveServer_ChatTurnDebugRunRecordsMCPConnectOnPrepareError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
mcpSrv := newTestMCPServer("test-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
// Serving the first assistant stream arms the failure, so the
|
|
// next preparation completes its MCP connect phase and then
|
|
// fails reading the compaction override before returning a
|
|
// prepared generation.
|
|
var failOverrideReads atomic.Bool
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
failOverrideReads.Store(true)
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Done!")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Test MCP",
|
|
Slug: "test-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
server := newActiveTestServer(t, &overrideReadFailStore{Store: db, fail: &failOverrideReads}, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "mcp-connect-prepare-error-test",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Say done."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var chatTurnRuns []database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, runsErr := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if runsErr != nil {
|
|
return false
|
|
}
|
|
chatTurnRuns = chatTurnRuns[:0]
|
|
for _, run := range runs {
|
|
if run.Kind == string(codersdk.ChatDebugRunKindChatTurn) {
|
|
chatTurnRuns = append(chatTurnRuns, run)
|
|
}
|
|
}
|
|
return len(chatTurnRuns) == 1 && chatTurnRuns[0].FinishedAt.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Len(t, chatTurnRuns, 1)
|
|
var summary struct {
|
|
MCPConnect []struct {
|
|
Slug string `json:"slug"`
|
|
Outcome string `json:"outcome"`
|
|
} `json:"mcp_connect"`
|
|
}
|
|
require.NoError(t, json.Unmarshal(chatTurnRuns[0].Summary, &summary))
|
|
// The preparation feeding the assistant step records one
|
|
// outcome. The following preparation connects to the MCP server
|
|
// and then fails reading the compaction override; its attempts
|
|
// must still contribute their connect outcomes even though
|
|
// preparation never returns a prepared generation.
|
|
require.GreaterOrEqual(t, len(summary.MCPConnect), 2)
|
|
for _, entry := range summary.MCPConnect {
|
|
require.Equal(t, "test-mcp", entry.Slug)
|
|
require.Equal(t, "connected", entry.Outcome)
|
|
}
|
|
}
|
|
|
|
func TestActiveServer_ChatTurnDebugRunRecordsMCPConnectOnFirstPrepareError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
mcpSrv := newTestMCPServer("test-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Done!")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Test MCP",
|
|
Slug: "test-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
// Armed from the start: the very first preparation connects to
|
|
// the MCP server and then fails reading the compaction override,
|
|
// so no model or compaction action ever creates the debug run
|
|
// through Ensure.
|
|
var failOverrideReads atomic.Bool
|
|
failOverrideReads.Store(true)
|
|
server := newActiveTestServer(t, &overrideReadFailStore{Store: db, fail: &failOverrideReads}, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AlwaysEnableDebugLogs = true
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "mcp-connect-first-prepare-error-test",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Say done."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusError)
|
|
require.NoError(t, server.Close())
|
|
debugCtx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
var chatTurnRuns []database.ChatDebugRun
|
|
testutil.Eventually(debugCtx, t, func(ctx context.Context) bool {
|
|
runs, runsErr := db.GetChatDebugRunsByChatID(ctx, database.GetChatDebugRunsByChatIDParams{
|
|
ChatID: chat.ID,
|
|
LimitVal: 100,
|
|
})
|
|
if runsErr != nil {
|
|
return false
|
|
}
|
|
chatTurnRuns = chatTurnRuns[:0]
|
|
for _, run := range runs {
|
|
if run.Kind == string(codersdk.ChatDebugRunKindChatTurn) {
|
|
chatTurnRuns = append(chatTurnRuns, run)
|
|
}
|
|
}
|
|
return len(chatTurnRuns) == 1 && chatTurnRuns[0].FinishedAt.Valid
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Len(t, chatTurnRuns, 1)
|
|
var summary struct {
|
|
MCPConnect []struct {
|
|
Slug string `json:"slug"`
|
|
Outcome string `json:"outcome"`
|
|
} `json:"mcp_connect"`
|
|
}
|
|
require.NoError(t, json.Unmarshal(chatTurnRuns[0].Summary, &summary))
|
|
// Every preparation fails after its connect phase, so the run
|
|
// exists only because recording the outcomes created it; it must
|
|
// carry at least the first attempt's connect outcome.
|
|
require.GreaterOrEqual(t, len(summary.MCPConnect), 1)
|
|
for _, entry := range summary.MCPConnect {
|
|
require.Equal(t, "test-mcp", entry.Slug)
|
|
require.Equal(t, "connected", entry.Outcome)
|
|
}
|
|
}
|
|
|
|
func TestPlanModeRootChatApprovedExternalMCPWorkflowCanReachProposePlan(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
mcpSrv := newTestMCPServer("plan-workflow-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpTS := httptest.NewServer(testMCPHTTPHandler(mcpSrv))
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
var (
|
|
callCount atomic.Int32
|
|
llmToolNames []string
|
|
llmToolsMu sync.Mutex
|
|
sawMCPResult atomic.Bool
|
|
proposePlanReached atomic.Bool
|
|
)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
switch callCount.Add(1) {
|
|
case 1:
|
|
names := offeredToolNames(t, req)
|
|
llmToolsMu.Lock()
|
|
llmToolNames = names
|
|
llmToolsMu.Unlock()
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"plan-workflow-mcp__echo",
|
|
`{"input":"prepare the plan"}`,
|
|
),
|
|
)
|
|
case 2:
|
|
for _, msg := range req.Messages {
|
|
if msg.Role == "tool" && strings.Contains(msg.Content, "echo: prepare the plan") {
|
|
sawMCPResult.Store(true)
|
|
}
|
|
}
|
|
proposePlanReached.Store(true)
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("propose_plan", `{"path":""}`),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("should not continue")...,
|
|
)
|
|
}
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Plan Workflow MCP",
|
|
Slug: "plan-workflow-mcp",
|
|
Url: mcpTS.URL,
|
|
AllowInPlanMode: true,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
mockConn.EXPECT().SetExtraHeaders(gomock.Any()).AnyTimes()
|
|
mockConn.EXPECT().ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).AnyTimes()
|
|
mockConn.EXPECT().LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{AbsolutePathString: "/home/coder"}, nil).AnyTimes()
|
|
mockConn.EXPECT().ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
DoAndReturn(func(_ context.Context, path string, _, _ int64) (io.ReadCloser, string, error) {
|
|
if strings.HasSuffix(path, ".md") {
|
|
return io.NopCloser(strings.NewReader("# Plan\n- Use the approved MCP tool findings.\n")), "", nil
|
|
}
|
|
return io.NopCloser(strings.NewReader("")), "", nil
|
|
}).AnyTimes()
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "plan-mode-mcp-propose-plan",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
PlanMode: database.NullChatPlanMode{ChatPlanMode: database.ChatPlanModePlan, Valid: true},
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Use the approved MCP tool, then propose the plan."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
|
|
chatResult, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusWaiting, chatResult.Status)
|
|
|
|
llmToolsMu.Lock()
|
|
recordedNames := append([]string(nil), llmToolNames...)
|
|
llmToolsMu.Unlock()
|
|
require.Contains(t, recordedNames, "plan-workflow-mcp__echo",
|
|
"approved external MCP tools should be available in the root plan-mode workflow")
|
|
require.True(t, sawMCPResult.Load(),
|
|
"the root plan-mode workflow should feed the approved MCP result into the propose_plan turn")
|
|
require.True(t, proposePlanReached.Load(),
|
|
"the root plan-mode workflow should reach propose_plan after using the approved MCP tool")
|
|
require.Equal(t, int32(2), callCount.Load(),
|
|
"the workflow should stop immediately after propose_plan succeeds")
|
|
|
|
var foundProposePlanResult bool
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleTool {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
if parseErr != nil {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolName == "propose_plan" {
|
|
foundProposePlanResult = true
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.True(t, foundProposePlanResult,
|
|
"the root plan-mode workflow should persist a propose_plan tool result")
|
|
}
|
|
|
|
// TestMCPServerOAuth2TokenRefresh verifies that when a chat uses an
|
|
// MCP server with OAuth2 auth and the stored access token is expired,
|
|
// chatd refreshes the token using the stored refresh_token before
|
|
// connecting. The refreshed token is persisted to the database and
|
|
// the MCP tool call succeeds.
|
|
func TestMCPServerOAuth2TokenRefresh(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// The "fresh" token that the mock OAuth2 server returns after
|
|
// a successful refresh_token grant.
|
|
freshAccessToken := "fresh-access-token-" + uuid.New().String()
|
|
|
|
// Mock OAuth2 token endpoint that exchanges a refresh token
|
|
// for a new access token.
|
|
var refreshCalled atomic.Int32
|
|
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
refreshCalled.Add(1)
|
|
|
|
if r.Method != http.MethodPost {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
grantType := r.FormValue("grant_type")
|
|
if grantType != "refresh_token" {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
_, _ = w.Write([]byte(`{"error":"unsupported_grant_type"}`))
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = fmt.Fprintf(w, `{"access_token":%q,"token_type":"Bearer","expires_in":3600,"refresh_token":"rotated-refresh-token"}`, freshAccessToken)
|
|
}))
|
|
t.Cleanup(tokenSrv.Close)
|
|
|
|
// Start a real MCP server with an auth middleware that only
|
|
// accepts the fresh access token. An expired token (or any
|
|
// other value) gets a 401.
|
|
mcpSrv := newTestMCPServer("authed-mcp")
|
|
addTestMCPTextTool(mcpSrv, "echo", "Echoes the input", "echo: ")
|
|
mcpHTTP := testMCPHTTPHandler(mcpSrv)
|
|
// Wrap with auth check.
|
|
authMux := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
auth := r.Header.Get("Authorization")
|
|
if auth != "Bearer "+freshAccessToken {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_, _ = w.Write([]byte(`{"error":"invalid_token","error_description":"The access token is invalid or expired"}`))
|
|
return
|
|
}
|
|
mcpHTTP.ServeHTTP(w, r)
|
|
})
|
|
mcpTS := httptest.NewServer(authMux)
|
|
t.Cleanup(mcpTS.Close)
|
|
|
|
// Track LLM interactions.
|
|
var (
|
|
callCount atomic.Int32
|
|
llmToolNames []string
|
|
llmToolsMu sync.Mutex
|
|
foundMCPResult atomic.Bool
|
|
)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
if callCount.Add(1) == 1 {
|
|
names := offeredToolNames(t, req)
|
|
llmToolsMu.Lock()
|
|
llmToolNames = names
|
|
llmToolsMu.Unlock()
|
|
|
|
// Ask the LLM to call the MCP echo tool.
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk(
|
|
"authed-mcp__echo",
|
|
`{"input":"hello via refreshed token"}`,
|
|
),
|
|
)
|
|
}
|
|
|
|
// Second call: verify the tool result was fed back.
|
|
for _, msg := range req.Messages {
|
|
if msg.Role == "tool" && strings.Contains(msg.Content, "echo: hello via refreshed token") {
|
|
foundMCPResult.Store(true)
|
|
}
|
|
}
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Done!")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
// Seed the MCP server config with OAuth2 auth pointing to our
|
|
// mock token endpoint.
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Authed MCP",
|
|
Slug: "authed-mcp",
|
|
Url: mcpTS.URL,
|
|
AuthType: "oauth2",
|
|
OAuth2ClientID: "test-client-id",
|
|
OAuth2TokenURL: tokenSrv.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
|
|
// Seed an expired OAuth2 token with a valid refresh_token.
|
|
_, err := db.UpsertMCPServerUserToken(ctx, database.UpsertMCPServerUserTokenParams{
|
|
MCPServerConfigID: mcpConfig.ID,
|
|
UserID: user.ID,
|
|
AccessToken: "old-expired-access-token",
|
|
RefreshToken: "old-refresh-token",
|
|
TokenType: "Bearer",
|
|
Expiry: sql.NullTime{Time: time.Now().Add(-1 * time.Hour), Valid: true},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
ws, dbAgent := seedWorkspaceWithAgent(t, db, user.ID)
|
|
|
|
ctrl := gomock.NewController(t)
|
|
mockConn := agentconnmock.NewMockAgentConn(ctrl)
|
|
mockConn.EXPECT().SetExtraHeaders(gomock.Any()).AnyTimes()
|
|
mockConn.EXPECT().ContextConfig(gomock.Any()).
|
|
Return(workspacesdk.ContextConfigResponse{}, xerrors.New("not supported")).AnyTimes()
|
|
mockConn.EXPECT().LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{}, nil).AnyTimes()
|
|
mockConn.EXPECT().ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(io.NopCloser(strings.NewReader("")), "", nil).AnyTimes()
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.AgentConn = func(_ context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
|
|
require.Equal(t, dbAgent.ID, agentID)
|
|
return mockConn, func() {}, nil
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "oauth2-refresh-test",
|
|
ModelConfigID: model.ID,
|
|
WorkspaceID: uuid.NullUUID{UUID: ws.ID, Valid: true},
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Echo something via the authed MCP."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the chat to finish processing.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
// The token should have been refreshed.
|
|
require.Greater(t, refreshCalled.Load(), int32(0),
|
|
"OAuth2 token endpoint should have been called to refresh the expired token")
|
|
|
|
llmToolsMu.Lock()
|
|
recordedNames := append([]string(nil), llmToolNames...)
|
|
llmToolsMu.Unlock()
|
|
require.Contains(t, recordedNames, "authed-mcp__echo",
|
|
"MCP tool should be offered to the LLM")
|
|
|
|
// The tool result should have been fed back to the LLM.
|
|
require.True(t, foundMCPResult.Load(),
|
|
"MCP tool result should appear in the second LLM call")
|
|
|
|
// Verify the refreshed token was persisted to the database.
|
|
dbToken, err := db.GetMCPServerUserToken(ctx, database.GetMCPServerUserTokenParams{
|
|
MCPServerConfigID: mcpConfig.ID,
|
|
UserID: user.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, freshAccessToken, dbToken.AccessToken,
|
|
"refreshed access token should be persisted in the database")
|
|
require.Equal(t, "rotated-refresh-token", dbToken.RefreshToken,
|
|
"rotated refresh token should be persisted in the database")
|
|
}
|
|
|
|
// TestMCPServerOAuth2TokenRefreshFailureGraceful verifies that when
|
|
// the OAuth2 token endpoint is down, the chat still proceeds without
|
|
// the MCP server's tools. The expired token is preserved unchanged.
|
|
func TestMCPServerOAuth2TokenRefreshFailureGraceful(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
// Token endpoint that always returns an error.
|
|
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadGateway)
|
|
_, _ = w.Write([]byte(`{"error":"server_error","error_description":"token endpoint unavailable"}`))
|
|
}))
|
|
t.Cleanup(tokenSrv.Close)
|
|
|
|
// The LLM just replies with text, no tool calls.
|
|
var callCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
callCount.Add(1)
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("I responded without MCP tools.")...,
|
|
)
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
mcpConfig := dbgen.MCPServerConfig(t, db, database.MCPServerConfig{
|
|
OrganizationID: org.ID,
|
|
DisplayName: "Broken MCP",
|
|
Slug: "broken-mcp",
|
|
Url: "http://127.0.0.1:0/does-not-exist",
|
|
AuthType: "oauth2",
|
|
OAuth2ClientID: "test-client-id",
|
|
OAuth2TokenURL: tokenSrv.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true},
|
|
})
|
|
_, err := db.UpsertMCPServerUserToken(ctx, database.UpsertMCPServerUserTokenParams{
|
|
MCPServerConfigID: mcpConfig.ID,
|
|
UserID: user.ID,
|
|
AccessToken: "old-expired-token",
|
|
RefreshToken: "old-refresh-token",
|
|
TokenType: "Bearer",
|
|
Expiry: sql.NullTime{Time: time.Now().Add(-1 * time.Hour), Valid: true},
|
|
})
|
|
|
|
require.NoError(t, err)
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "graceful-degradation-test",
|
|
ModelConfigID: model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Hello, just reply."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Chat should finish successfully despite the failed refresh.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat should not fail", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
// The LLM should have been called at least once.
|
|
require.Greater(t, callCount.Load(), int32(0),
|
|
"LLM should be called even when MCP token refresh fails")
|
|
|
|
// The original token should be unchanged in the database.
|
|
dbToken, err := db.GetMCPServerUserToken(ctx, database.GetMCPServerUserTokenParams{
|
|
MCPServerConfigID: mcpConfig.ID,
|
|
UserID: user.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, "old-expired-token", dbToken.AccessToken,
|
|
"original token should be preserved when refresh fails")
|
|
}
|
|
|
|
func TestChatTemplateAgentsAllowedEnforcement(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
|
|
// Declare templates before the handler so the closure can
|
|
// reference their IDs when building tool-call arguments.
|
|
var tplAllowed, tplBlocked database.Template
|
|
|
|
// Set up a mock OpenAI server that chains tool calls:
|
|
// 1. list_templates
|
|
// 2. read_template (blocked template, should fail)
|
|
// 3. read_template (allowed template, should succeed)
|
|
// 4. create_workspace (blocked template, should fail)
|
|
// 5. text response
|
|
var callCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch callCount.Add(1) {
|
|
case 1:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("list_templates", `{}`),
|
|
)
|
|
case 2:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("read_template",
|
|
fmt.Sprintf(`{"template_id":%q}`, tplBlocked.ID.String())),
|
|
)
|
|
case 3:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("read_template",
|
|
fmt.Sprintf(`{"template_id":%q}`, tplAllowed.ID.String())),
|
|
)
|
|
case 4:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("create_workspace",
|
|
fmt.Sprintf(`{"template_id":%q}`, tplBlocked.ID.String())),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Done testing.")...,
|
|
)
|
|
}
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
|
|
// Create two templates the user can see.
|
|
tplAllowed = dbgen.Template(t, db, database.Template{
|
|
OrganizationID: org.ID,
|
|
CreatedBy: user.ID,
|
|
Name: "allowed-template",
|
|
AgentsAllowed: true,
|
|
})
|
|
tplBlocked = dbgen.Template(t, db, database.Template{
|
|
OrganizationID: org.ID,
|
|
CreatedBy: user.ID,
|
|
Name: "blocked-template",
|
|
AgentsAllowed: false,
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
// Provide a CreateWorkspace function so the tool reaches the template
|
|
// access check instead of returning "not configured". The blocked
|
|
// template must be rejected before this function is called.
|
|
cfg.CreateWorkspace = func(
|
|
_ context.Context,
|
|
_, _ uuid.UUID,
|
|
_ codersdk.CreateWorkspaceRequest,
|
|
) (codersdk.Workspace, database.Chat, error) {
|
|
t.Error("CreateWorkspace should not be called for a blocked template")
|
|
return codersdk.Workspace{}, database.Chat{}, xerrors.New("unexpected call")
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "template-access-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Test template access enforcement"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the chat to finish processing.
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
// Collect all tool results keyed by tool name. Each tool may
|
|
// have been called more than once, so we store a slice.
|
|
var toolResults map[string][]string
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
toolResults = map[string][]string{}
|
|
messages, dbErr := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
if dbErr != nil {
|
|
return false
|
|
}
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleTool {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
if parseErr != nil {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult {
|
|
toolResults[part.ToolName] = append(
|
|
toolResults[part.ToolName], string(part.Result))
|
|
}
|
|
}
|
|
}
|
|
// We expect results from all four tool calls.
|
|
return len(toolResults["list_templates"]) >= 1 &&
|
|
len(toolResults["read_template"]) >= 2 &&
|
|
len(toolResults["create_workspace"]) >= 1
|
|
}, testutil.IntervalFast)
|
|
|
|
require.Contains(t, toolResults["list_templates"][0], tplAllowed.ID.String(),
|
|
"allowed template should appear in list_templates result")
|
|
require.NotContains(t, toolResults["list_templates"][0], tplBlocked.ID.String(),
|
|
"blocked template should not appear in list_templates result")
|
|
|
|
require.Contains(t, toolResults["read_template"][0], "not available",
|
|
"read_template for blocked template should return an actionable error")
|
|
require.Contains(t, toolResults["read_template"][1], tplAllowed.ID.String(),
|
|
"read_template for allowed template should return template details")
|
|
|
|
require.Contains(t, toolResults["create_workspace"][0], "not available",
|
|
"create_workspace for blocked template should be rejected")
|
|
}
|
|
|
|
func TestChatAsksUserWhenListTemplatesRequiresSelection(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db, ps := dbtestutil.NewDB(t)
|
|
|
|
var tplCode, tplDocker database.Template
|
|
var callCount atomic.Int32
|
|
var sawSelectionRule atomic.Bool
|
|
var sawSelectionRequiredResult atomic.Bool
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
switch callCount.Add(1) {
|
|
case 1:
|
|
promptAndTools := string(req.RawBody)
|
|
for _, message := range req.Messages {
|
|
promptAndTools += "\n" + message.Content
|
|
}
|
|
if strings.Contains(promptAndTools, "follow its next_step") {
|
|
sawSelectionRule.Store(true)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("list_templates", `{}`),
|
|
)
|
|
case 2:
|
|
if listTemplatesResultRequiresUserSelection(req.Messages) {
|
|
sawSelectionRequiredResult.Store(true)
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks(
|
|
"I found two templates, typescript-alpha and Docker Containers. Which template should I use?",
|
|
)...,
|
|
)
|
|
}
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAIToolCallChunk("create_workspace",
|
|
fmt.Sprintf(`{"template_id":%q}`, tplCode.ID.String())),
|
|
)
|
|
default:
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Done.")...,
|
|
)
|
|
}
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
tplCode = dbgen.Template(t, db, database.Template{
|
|
OrganizationID: org.ID,
|
|
CreatedBy: user.ID,
|
|
Name: "code-2",
|
|
DisplayName: "typescript-alpha",
|
|
Description: "this is a long description",
|
|
AgentsAllowed: true,
|
|
})
|
|
tplDocker = dbgen.Template(t, db, database.Template{
|
|
OrganizationID: org.ID,
|
|
CreatedBy: user.ID,
|
|
Name: "docker",
|
|
DisplayName: "Docker Containers",
|
|
Description: "Provision Docker containers as Coder workspaces",
|
|
AgentsAllowed: true,
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.CreateWorkspace = func(
|
|
context.Context,
|
|
uuid.UUID,
|
|
uuid.UUID,
|
|
codersdk.CreateWorkspaceRequest,
|
|
) (codersdk.Workspace, database.Chat, error) {
|
|
t.Error("create_workspace should not be called when list_templates requires user selection")
|
|
return codersdk.Workspace{}, database.Chat{}, xerrors.New("unexpected create_workspace call")
|
|
}
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "ask-template-selection-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("Create a workspace."),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var chatResult database.Chat
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
chatResult = got
|
|
return got.Status == database.ChatStatusWaiting || got.Status == database.ChatStatusError
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
if chatResult.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat run failed", "last_error=%q", chatLastErrorMessage(chatResult.LastError))
|
|
}
|
|
|
|
require.True(t, sawSelectionRule.Load(), "model request should include the next_step selection rule")
|
|
require.True(t, sawSelectionRequiredResult.Load(), "model should receive a list_templates result requiring user selection")
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var listTemplatesResult map[string]any
|
|
var assistantText string
|
|
var sawCreateWorkspaceResult bool
|
|
for _, message := range messages {
|
|
parts, parseErr := chatprompt.ParseContent(message)
|
|
require.NoError(t, parseErr)
|
|
for _, part := range parts {
|
|
switch {
|
|
case part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolName == "list_templates":
|
|
require.NoError(t, json.Unmarshal(part.Result, &listTemplatesResult))
|
|
case part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolName == "create_workspace":
|
|
sawCreateWorkspaceResult = true
|
|
case message.Role == database.ChatMessageRoleAssistant && part.Type == codersdk.ChatMessagePartTypeText:
|
|
assistantText += part.Text
|
|
}
|
|
}
|
|
}
|
|
|
|
require.NotNil(t, listTemplatesResult, "expected list_templates tool result")
|
|
require.Equal(t, chattool.NextStepAskUser, listTemplatesResult["next_step"])
|
|
require.NotContains(t, listTemplatesResult, "recommended_template_id")
|
|
require.Contains(t, listTemplatesResult["templates"], any(map[string]any{
|
|
"id": tplCode.ID.String(),
|
|
"name": "code-2",
|
|
"display_name": "typescript-alpha",
|
|
"description": "this is a long description",
|
|
}))
|
|
require.Contains(t, listTemplatesResult["templates"], any(map[string]any{
|
|
"id": tplDocker.ID.String(),
|
|
"name": "docker",
|
|
"display_name": "Docker Containers",
|
|
"description": "Provision Docker containers as Coder workspaces",
|
|
}))
|
|
require.False(t, sawCreateWorkspaceResult, "agent should ask instead of calling create_workspace")
|
|
require.Contains(t, assistantText, "Which template should I use?")
|
|
}
|
|
|
|
func listTemplatesResultRequiresUserSelection(messages []chattest.OpenAIMessage) bool {
|
|
for _, message := range messages {
|
|
if message.Role != "tool" || !json.Valid([]byte(message.Content)) {
|
|
continue
|
|
}
|
|
|
|
var result map[string]any
|
|
if err := json.Unmarshal([]byte(message.Content), &result); err != nil {
|
|
continue
|
|
}
|
|
if result["next_step"] == chattool.NextStepAskUser {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// TestCreateChatImmediatelyProcessesNewChat verifies that CreateChat
|
|
// starts processing a new chat without waiting for the acquire ticker
|
|
// to fire. The ticker interval is set to an hour so it never fires
|
|
// during the test.
|
|
func TestCreateChatImmediatelyProcessesNewChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
processed := make(chan struct{})
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
// Signal that the LLM was reached. This proves the chat
|
|
// was acquired and processing started.
|
|
select {
|
|
case <-processed:
|
|
default:
|
|
close(processed)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("hello from the model")...,
|
|
)
|
|
})
|
|
|
|
// Use a 1-hour acquire interval so the ticker never fires.
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.PendingChatAcquireInterval = time.Hour
|
|
cfg.InFlightChatStaleAfter = testutil.WaitSuperLong
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
// CreateChat should start the first turn without waiting for the
|
|
// acquire ticker.
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "wake-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// The chat should be processed immediately. The LLM handler
|
|
// closes the `processed` channel when it receives a streaming
|
|
// request. If CreateChat only relied on the 1-hour ticker,
|
|
// this receive would time out.
|
|
testutil.TryReceive(ctx, t, processed)
|
|
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
// Verify the chat was fully processed.
|
|
fromDB, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusWaiting, fromDB.Status,
|
|
"chat should be in waiting status after processing completes")
|
|
}
|
|
|
|
// TestSendMessageImmediatelyProcessesWaitingChat verifies that sending
|
|
// a follow-up message to a waiting chat starts the next turn without
|
|
// waiting for the acquire ticker.
|
|
func TestSendMessageImmediatelyProcessesWaitingChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
|
|
firstProcessed := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
secondProcessed := make(chan struct{})
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
switch requestCount.Add(1) {
|
|
case 1:
|
|
select {
|
|
case <-firstProcessed:
|
|
default:
|
|
close(firstProcessed)
|
|
}
|
|
case 2:
|
|
close(secondProcessed)
|
|
}
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("response")...,
|
|
)
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.PendingChatAcquireInterval = time.Hour
|
|
cfg.InFlightChatStaleAfter = testutil.WaitSuperLong
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
|
|
user, org, model := seedChatDependencies(t, db)
|
|
setOpenAIProviderBaseURL(ctx, t, db, openAIURL)
|
|
|
|
// CreateChat processes the first turn immediately.
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "wake-send-test",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("first")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the first turn to actually reach the LLM, then
|
|
// wait for the processing goroutine to finish so the chat
|
|
// transitions to "waiting" status.
|
|
testutil.TryReceive(ctx, t, firstProcessed)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
// Now send a follow-up message, which should also be
|
|
// processed immediately without waiting for the acquire ticker.
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("second")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.TryReceive(ctx, t, secondProcessed)
|
|
require.NoError(t, chatd.WaitUntilIdleForTest(ctx, server))
|
|
|
|
// Both turns processed. Verify the second request reached the LLM.
|
|
require.GreaterOrEqual(t, requestCount.Load(), int32(2),
|
|
"LLM should have received at least 2 streaming requests")
|
|
}
|
|
|
|
// TestAgentContextFilesAndSkillsLoadedIntoChat verifies the full
|
|
// end-to-end path: the workspace agent reads instruction files and
|
|
// discovers skills from the filesystem, chatd fetches them via a
|
|
// real tailnet agent connection, and both the <workspace-context>
|
|
// block and <available-skills> index appear in the LLM prompt.
|
|
//
|
|
// This test is NOT parallel because it sets process-wide environment
|
|
// variables via t.Setenv to configure the agent's context config.
|
|
func TestAgentContextFilesAndSkillsLoadedIntoChat(t *testing.T) {
|
|
fakeHome := t.TempDir()
|
|
t.Setenv("HOME", fakeHome)
|
|
t.Setenv("USERPROFILE", fakeHome)
|
|
|
|
instructionsDir := filepath.Join(fakeHome, ".coder")
|
|
skillsDir := filepath.Join(fakeHome, ".coder", "skills")
|
|
require.NoError(t, os.MkdirAll(instructionsDir, 0o755))
|
|
require.NoError(t, os.MkdirAll(skillsDir, 0o755))
|
|
|
|
t.Setenv(agentcontextconfig.EnvInstructionsDirs, instructionsDir)
|
|
t.Setenv(agentcontextconfig.EnvInstructionsFile, "AGENTS.md")
|
|
t.Setenv(agentcontextconfig.EnvSkillsDirs, skillsDir)
|
|
t.Setenv(agentcontextconfig.EnvSkillMetaFile, "SKILL.md")
|
|
t.Setenv(agentcontextconfig.EnvMCPConfigFiles, filepath.Join(fakeHome, "nonexistent-mcp.json"))
|
|
|
|
require.NoError(t, os.WriteFile(
|
|
filepath.Join(instructionsDir, "AGENTS.md"),
|
|
[]byte("# Project Rules\nAlways write tests."),
|
|
0o600,
|
|
))
|
|
|
|
skillDir := filepath.Join(skillsDir, "my-cool-skill")
|
|
require.NoError(t, os.MkdirAll(skillDir, 0o755))
|
|
require.NoError(t, os.WriteFile(
|
|
filepath.Join(skillDir, "SKILL.md"),
|
|
[]byte("---\nname: my-cool-skill\ndescription: A test skill\n---\nDo the cool thing.\n"),
|
|
0o600,
|
|
))
|
|
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
DeploymentValues: coderdtest.DeploymentValues(t),
|
|
IncludeProvisionerDaemon: true,
|
|
})
|
|
db := api.Database
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
user := coderdtest.CreateFirstUser(t, client)
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
|
|
agentToken := uuid.NewString()
|
|
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionPlan: echo.PlanComplete,
|
|
ProvisionApply: echo.ApplyComplete,
|
|
ProvisionGraph: echo.ProvisionGraphWithAgent(agentToken),
|
|
})
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
|
|
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
|
|
|
|
_ = agenttest.New(t, client.URL, agentToken, agenttest.WithContextConfigFromEnv())
|
|
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
|
|
|
|
// Pinned context is the sole source of workspace context. The chat binds
|
|
// its agent lazily on the first turn and re-pins from that agent's pushed
|
|
// snapshot, so the snapshot must exist before the turn runs. Wait for the
|
|
// agent to push its instruction file and skill before creating the chat;
|
|
// otherwise the re-pin copies nothing and the prompt omits them.
|
|
builtWorkspace, err := client.Workspace(ctx, workspace.ID)
|
|
require.NoError(t, err)
|
|
var agentID uuid.UUID
|
|
for _, res := range builtWorkspace.LatestBuild.Resources {
|
|
for _, agent := range res.Agents {
|
|
agentID = agent.ID
|
|
}
|
|
}
|
|
require.NotEqual(t, uuid.Nil, agentID, "workspace should expose an agent")
|
|
require.Eventually(t, func() bool {
|
|
pushed, lerr := db.ListWorkspaceAgentContextResources(
|
|
dbauthz.AsSystemRestricted(ctx), agentID)
|
|
return lerr == nil && len(pushed) >= 2
|
|
}, testutil.WaitSuperLong, testutil.IntervalFast)
|
|
|
|
// Capture LLM requests so we can inspect the system prompt.
|
|
var streamedCallsMu sync.Mutex
|
|
streamedCalls := make([][]chattest.OpenAIMessage, 0, 2)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("context test")
|
|
}
|
|
|
|
streamedCallsMu.Lock()
|
|
streamedCalls = append(streamedCalls, append([]chattest.OpenAIMessage(nil), req.Messages...))
|
|
streamedCallsMu.Unlock()
|
|
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("Got it.")...,
|
|
)
|
|
})
|
|
|
|
coderdtest.CreateOpenAICompatChatModel(t, expClient, openAIURL)
|
|
|
|
workspaceID := workspace.ID
|
|
chat, err := expClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
WorkspaceID: &workspaceID,
|
|
Content: []codersdk.ChatInputPart{
|
|
{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "Hello, what are the project rules?",
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := expClient.GetChat(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
return got.Status == codersdk.ChatStatusWaiting || got.Status == codersdk.ChatStatusError
|
|
}, testutil.WaitSuperLong, testutil.IntervalFast)
|
|
|
|
streamedCallsMu.Lock()
|
|
recordedCalls := append([][]chattest.OpenAIMessage(nil), streamedCalls...)
|
|
streamedCallsMu.Unlock()
|
|
require.NotEmpty(t, recordedCalls, "LLM should have received at least one streaming request")
|
|
|
|
var allSystemContent string
|
|
for _, msg := range recordedCalls[0] {
|
|
if msg.Role == "system" {
|
|
allSystemContent += msg.Content + "\n"
|
|
}
|
|
}
|
|
|
|
require.Contains(t, allSystemContent, "<workspace-context>",
|
|
"system prompt should contain workspace-context block")
|
|
require.Contains(t, allSystemContent, "Always write tests.",
|
|
"system prompt should contain AGENTS.md content")
|
|
require.Contains(t, allSystemContent, "AGENTS.md",
|
|
"system prompt should reference the source file")
|
|
|
|
planBlockCount := 0
|
|
standalonePlanBlockCount := 0
|
|
for _, msg := range recordedCalls[0] {
|
|
if msg.Role != "system" {
|
|
continue
|
|
}
|
|
planBlockCount += strings.Count(
|
|
msg.Content,
|
|
"<plan-file-path>\nYour plan file path for this chat is:",
|
|
)
|
|
trimmed := strings.TrimSpace(msg.Content)
|
|
if strings.HasPrefix(trimmed, "<plan-file-path>") &&
|
|
strings.HasSuffix(trimmed, "</plan-file-path>") {
|
|
standalonePlanBlockCount++
|
|
}
|
|
}
|
|
|
|
require.Contains(t, allSystemContent, "<available-skills>",
|
|
"system prompt should contain available-skills block")
|
|
require.Contains(t, allSystemContent, "my-cool-skill",
|
|
"system prompt should list the discovered skill")
|
|
require.Contains(t, allSystemContent, "A test skill",
|
|
"system prompt should include the skill description")
|
|
require.Contains(t, allSystemContent, "<plan-file-path>",
|
|
"system prompt should contain the plan-file-path block")
|
|
require.Contains(t, allSystemContent, "PLAN-"+chat.ID.String()+".md",
|
|
"system prompt should use the chat-specific plan path")
|
|
require.Contains(t, allSystemContent,
|
|
"Do not use "+strings.TrimRight(fakeHome, "/")+"/PLAN.md.",
|
|
"system prompt should warn against the home-root plan path")
|
|
require.Equal(t, 1, planBlockCount,
|
|
"system prompt should contain a single plan-file-path block")
|
|
require.Zero(t, standalonePlanBlockCount,
|
|
"plan-file-path block should be part of the main system prompt, not a standalone message")
|
|
}
|
|
|
|
// TestInterruptChatCancelsToolCallsOnAgent checks that tool calls reach a
|
|
// real agent with the tool call IDs the interrupt cancels.
|
|
func TestInterruptChatCancelsToolCallsOnAgent(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
DeploymentValues: coderdtest.DeploymentValues(t),
|
|
IncludeProvisionerDaemon: true,
|
|
})
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
user := coderdtest.CreateFirstUser(t, client)
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
|
|
agentToken := uuid.NewString()
|
|
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionPlan: echo.PlanComplete,
|
|
ProvisionApply: echo.ApplyComplete,
|
|
ProvisionGraph: echo.ProvisionGraphWithAgent(agentToken),
|
|
})
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
|
|
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
|
|
_ = agenttest.New(t, client.URL, agentToken)
|
|
resources := coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
|
|
|
|
writtenPath := filepath.Join(t.TempDir(), "written.txt")
|
|
writeArgs, err := json.Marshal(map[string]string{"path": writtenPath, "content": "hello"})
|
|
require.NoError(t, err)
|
|
// The default timeout would end execute's wait before the interrupt.
|
|
executeArgs, err := json.Marshal(map[string]string{
|
|
"command": "sleep 300",
|
|
"timeout": "10m",
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
var streamedCalls atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if streamedCalls.Add(1) > 1 {
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
}
|
|
chunk := chattest.OpenAIToolCallChunk("write_file", string(writeArgs))
|
|
executeCall := chattest.OpenAIToolCallChunk("execute", string(executeArgs)).Choices[0].ToolCalls[0]
|
|
executeCall.Index = 1
|
|
chunk.Choices[0].ToolCalls = append(chunk.Choices[0].ToolCalls, executeCall)
|
|
return chattest.OpenAIStreamingResponse(chunk)
|
|
})
|
|
coderdtest.CreateOpenAICompatChatModel(t, expClient, openAIURL)
|
|
|
|
workspaceID := workspace.ID
|
|
chat, err := expClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
WorkspaceID: &workspaceID,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: "Write the file and run the command.",
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
_, err := os.Stat(writtenPath)
|
|
return err == nil
|
|
}, testutil.IntervalFast, "write_file should act on the agent")
|
|
conn := dialAgentForChat(ctx, t, client, resources[0].Agents[0].ID, chat.ID)
|
|
_ = awaitRunningChatProcess(ctx, t, conn)
|
|
|
|
_, err = expClient.InterruptChat(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
got, err := expClient.GetChat(ctx, chat.ID)
|
|
return err == nil && got.Status == codersdk.ChatStatusWaiting
|
|
}, testutil.IntervalFast, "chat should wait after the interrupt")
|
|
|
|
messages, err := expClient.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
results := make(map[string]codersdk.ChatMessagePart)
|
|
for _, message := range messages.Messages {
|
|
for _, part := range message.Content {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult {
|
|
results[part.ToolName] = part
|
|
}
|
|
}
|
|
}
|
|
require.Len(t, results, 2, "want one result per tool call")
|
|
|
|
writeResult := results["write_file"]
|
|
require.False(t, writeResult.IsError, "write_file result: %s", writeResult.Result)
|
|
require.JSONEq(t, `{"ok":true}`, string(writeResult.Result))
|
|
executeResult := results["execute"]
|
|
require.False(t, executeResult.IsError, "execute result: %s", executeResult.Result)
|
|
require.JSONEq(t, `{"canceled":true,"error":"tool call was canceled while running","exit_code":-1,"success":false}`, string(executeResult.Result))
|
|
}
|
|
|
|
// TestEditMessageCancelsToolCallsOnAgent checks that editing a user message
|
|
// cancels the running execute call the edit deletes on the agent, before the
|
|
// replacement turn calls the model.
|
|
func TestEditMessageCancelsToolCallsOnAgent(t *testing.T) {
|
|
t.Skip("flaky until PLAT-717: the agent netstack drops a SYN that reuses a source port it holds in TIME_WAIT")
|
|
t.Parallel()
|
|
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
DeploymentValues: coderdtest.DeploymentValues(t),
|
|
IncludeProvisionerDaemon: true,
|
|
})
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
user := coderdtest.CreateFirstUser(t, client)
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
|
|
agentToken := uuid.NewString()
|
|
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionPlan: echo.PlanComplete,
|
|
ProvisionApply: echo.ApplyComplete,
|
|
ProvisionGraph: echo.ProvisionGraphWithAgent(agentToken),
|
|
})
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
|
|
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
|
|
_ = agenttest.New(t, client.URL, agentToken)
|
|
resources := coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
|
|
agentID := resources[0].Agents[0].ID
|
|
|
|
type agentProcess struct {
|
|
conn workspacesdk.AgentConn
|
|
id string
|
|
}
|
|
type modelRequest struct {
|
|
body string
|
|
process workspacesdk.ProcessOutputResponse
|
|
processErr error
|
|
}
|
|
// The fake model routes each request to the case whose prompt it
|
|
// contains, so the cases share one coderd, workspace, and agent.
|
|
type editCase struct {
|
|
name string
|
|
// dynamicTools are declared on the chat. The model step drops a
|
|
// dynamic tool named like an active built-in, so the built-in runs.
|
|
dynamicTools []string
|
|
prompt string
|
|
editedPrompt string
|
|
executeChunk chattest.OpenAIChunk
|
|
editedTurnRequest chan modelRequest
|
|
// deletedProcess is the agent process of the execute call the edit
|
|
// deletes. The subtest stores it before the edit.
|
|
deletedProcess atomic.Pointer[agentProcess]
|
|
}
|
|
cases := []*editCase{
|
|
{name: "Baseline"},
|
|
{name: "DynamicToolNamedExecute", dynamicTools: []string{"execute"}},
|
|
}
|
|
for _, tc := range cases {
|
|
tc.prompt = "Run the command for " + tc.name + "."
|
|
tc.editedPrompt = "Say done for " + tc.name + "."
|
|
// The default timeout would end execute's wait before the edit.
|
|
executeArgs, err := json.Marshal(map[string]string{
|
|
"command": "sleep 300",
|
|
"timeout": "10m",
|
|
})
|
|
require.NoError(t, err)
|
|
tc.executeChunk = chattest.OpenAIToolCallChunk("execute", string(executeArgs))
|
|
tc.editedTurnRequest = make(chan modelRequest, 1)
|
|
}
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
body := string(req.RawBody)
|
|
for _, tc := range cases {
|
|
switch {
|
|
case strings.Contains(body, tc.editedPrompt):
|
|
// The edited turn cancels deleted tool calls before it calls
|
|
// the model, and the cancel waits for the process to exit.
|
|
got := modelRequest{body: body}
|
|
proc := tc.deletedProcess.Load()
|
|
got.process, got.processErr = proc.conn.ProcessOutput(req.Context(), proc.id, nil)
|
|
select {
|
|
case tc.editedTurnRequest <- got:
|
|
default:
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("done")...)
|
|
case strings.Contains(body, tc.prompt):
|
|
return chattest.OpenAIStreamingResponse(tc.executeChunk)
|
|
}
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("unexpected request")...)
|
|
})
|
|
coderdtest.CreateOpenAICompatChatModel(t, expClient, openAIURL)
|
|
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
var dynamicTools []codersdk.DynamicTool
|
|
for _, name := range tc.dynamicTools {
|
|
dynamicTools = append(dynamicTools, codersdk.DynamicTool{
|
|
Name: name,
|
|
Description: "client-executed " + name,
|
|
InputSchema: json.RawMessage(`{"type":"object","properties":{}}`),
|
|
})
|
|
}
|
|
workspaceID := workspace.ID
|
|
chat, err := expClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
|
OrganizationID: user.OrganizationID,
|
|
WorkspaceID: &workspaceID,
|
|
UnsafeDynamicTools: dynamicTools,
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: tc.prompt,
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
conn := dialAgentForChat(ctx, t, client, agentID, chat.ID)
|
|
proc := awaitRunningChatProcess(ctx, t, conn)
|
|
|
|
providerToolCallID := tc.executeChunk.Choices[0].ToolCalls[0].ID
|
|
messages, err := expClient.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
var userMessageID, assistantMessageID int64
|
|
for _, message := range messages.Messages {
|
|
if message.Role == codersdk.ChatMessageRoleUser && userMessageID == 0 {
|
|
userMessageID = message.ID
|
|
}
|
|
for _, part := range message.Content {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolCallID == providerToolCallID {
|
|
assistantMessageID = message.ID
|
|
}
|
|
}
|
|
}
|
|
require.NotZero(t, userMessageID)
|
|
require.NotZero(t, assistantMessageID)
|
|
require.Equal(t, chattool.ToolCallID(chat.ID, assistantMessageID, providerToolCallID).String(), proc.ID,
|
|
"the agent should run the execute call under its tool call ID")
|
|
tc.deletedProcess.Store(&agentProcess{conn: conn, id: proc.ID})
|
|
|
|
_, err = expClient.EditChatMessage(ctx, chat.ID, userMessageID, codersdk.EditChatMessageRequest{
|
|
Content: []codersdk.ChatInputPart{{
|
|
Type: codersdk.ChatInputPartTypeText,
|
|
Text: tc.editedPrompt,
|
|
}},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
edited := testutil.RequireReceive(ctx, t, tc.editedTurnRequest)
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
got, err := expClient.GetChat(ctx, chat.ID)
|
|
return err == nil && got.Status == codersdk.ChatStatusWaiting
|
|
}, testutil.IntervalFast, "chat should wait after the edited turn")
|
|
|
|
require.NoError(t, edited.processErr)
|
|
require.False(t, edited.process.Running,
|
|
"the deleted execute call's process should have exited when the edited turn calls the model")
|
|
require.True(t, edited.process.Canceled,
|
|
"the agent should have received a cancel for the deleted execute call's tool call ID")
|
|
require.NotContains(t, edited.body, tc.prompt)
|
|
require.NotContains(t, edited.body, providerToolCallID,
|
|
"the edited turn's history should not contain the deleted execute call")
|
|
})
|
|
}
|
|
}
|
|
|
|
// dialAgentForChat dials the workspace agent and sends the chat ID header
|
|
// that chatd sends, so the agent scopes process requests to chatID.
|
|
func dialAgentForChat(ctx context.Context, t *testing.T, client *codersdk.Client, agentID, chatID uuid.UUID) workspacesdk.AgentConn {
|
|
t.Helper()
|
|
conn, err := workspacesdk.New(client).DialAgent(ctx, agentID, nil)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() { _ = conn.Close() })
|
|
conn.SetExtraHeaders(http.Header{workspacesdk.CoderChatIDHeader: {chatID.String()}})
|
|
return conn
|
|
}
|
|
|
|
// awaitRunningChatProcess waits until the agent lists exactly one process
|
|
// for conn's chat and that process is running, and returns it.
|
|
func awaitRunningChatProcess(ctx context.Context, t *testing.T, conn workspacesdk.AgentConn) workspacesdk.ProcessInfo {
|
|
t.Helper()
|
|
var proc workspacesdk.ProcessInfo
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
list, err := conn.ListProcesses(ctx)
|
|
if err != nil || len(list.Processes) != 1 || !list.Processes[0].Running {
|
|
return false
|
|
}
|
|
proc = list.Processes[0]
|
|
return true
|
|
}, testutil.IntervalFast, "execute should start a process on the agent")
|
|
return proc
|
|
}
|
|
|
|
// TestEditMessageWithModelConfigOverride verifies that callers can
|
|
// change the model when editing a previous user message. The
|
|
// replacement message must persist with the new model and the chat's
|
|
// LastModelConfigID must be advanced so the assistant turn that follows
|
|
// runs against the new selection.
|
|
func TestEditMessageWithModelConfigOverride(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, modelA := seedChatDependencies(t, db)
|
|
modelB := insertChatModelConfigWithCallConfig(
|
|
t,
|
|
db,
|
|
user.ID,
|
|
"openai",
|
|
"gpt-4o-mini-edit-"+uuid.NewString(),
|
|
codersdk.ChatModelCallConfig{},
|
|
)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Title: "edit-with-model-override",
|
|
ModelConfigID: modelA.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("original")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
initial, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, initial, 1)
|
|
require.Equal(t, modelA.ID, initial[0].ModelConfigID.UUID)
|
|
|
|
result, err := replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: initial[0].ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
ModelConfigID: modelB.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, result.Message.ModelConfigID.Valid)
|
|
require.Equal(t, modelB.ID, result.Message.ModelConfigID.UUID)
|
|
|
|
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, modelB.ID, storedChat.LastModelConfigID,
|
|
"edit must update last_model_config_id so the assistant turn picks up the new model")
|
|
}
|
|
|
|
// TestEditMessagePreservesModelConfigByDefault verifies that omitting
|
|
// ModelConfigID on edit keeps the original message's model. This is the
|
|
// existing default for callers that only edit the text.
|
|
func TestEditMessagePreservesModelConfigByDefault(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, modelA := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Title: "edit-preserves-model",
|
|
ModelConfigID: modelA.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("original")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
initial, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, initial, 1)
|
|
|
|
result, err := replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: initial[0].ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, result.Message.ModelConfigID.Valid)
|
|
require.Equal(t, modelA.ID, result.Message.ModelConfigID.UUID)
|
|
|
|
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, modelA.ID, storedChat.LastModelConfigID,
|
|
"edit without model override must not change last_model_config_id")
|
|
}
|
|
|
|
func TestEditMessageReasoningEffort(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
for _, tc := range []struct {
|
|
name string
|
|
requested *string
|
|
want string
|
|
}{
|
|
{name: "PreservesByDefault", want: "low"},
|
|
{name: "Overrides", requested: new("high"), want: "high"},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Title: "edit-reasoning-effort",
|
|
ModelConfigID: model.ID,
|
|
ReasoningEffort: new("low"),
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("original")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
initial, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, initial, 1)
|
|
require.True(t, initial[0].ReasoningEffort.Valid)
|
|
require.Equal(t, database.ChatReasoningEffortLow, initial[0].ReasoningEffort.ChatReasoningEffort)
|
|
|
|
result, err := replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: initial[0].ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
ReasoningEffort: tc.requested,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, result.Message.ReasoningEffort.Valid)
|
|
require.Equal(t, database.ChatReasoningEffort(tc.want), result.Message.ReasoningEffort.ChatReasoningEffort)
|
|
|
|
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.True(t, storedChat.LastReasoningEffort.Valid)
|
|
require.Equal(t, database.ChatReasoningEffort(tc.want), storedChat.LastReasoningEffort.ChatReasoningEffort)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestEditMessageRejectsUnknownModelConfig verifies the edit handler
|
|
// returns ErrInvalidModelConfigID when the requested model does not
|
|
// exist, mirroring SendMessage's validation.
|
|
func TestEditMessageRejectsUnknownModelConfig(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, modelA := seedChatDependencies(t, db)
|
|
|
|
chat, err := replica.CreateChat(ctx, chatd.CreateOptions{
|
|
OwnerID: user.ID,
|
|
OrganizationID: org.ID,
|
|
Title: "edit-unknown-model",
|
|
ModelConfigID: modelA.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("original")},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
initial, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, initial, 1)
|
|
|
|
_, err = replica.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
EditedMessageID: initial[0].ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
ModelConfigID: uuid.New(),
|
|
})
|
|
require.ErrorIs(t, err, chatd.ErrInvalidModelConfigID)
|
|
|
|
// The edit must roll back: the original message should still be
|
|
// present and the chat's LastModelConfigID unchanged.
|
|
stillThere, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
require.Len(t, stillThere, 1)
|
|
require.Equal(t, initial[0].ID, stillThere[0].ID)
|
|
|
|
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, modelA.ID, storedChat.LastModelConfigID)
|
|
}
|
|
|
|
func TestQueuedCompletionResolvesOrganizationModel(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("TurnCompletion", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
firstRunStarted := make(chan struct{})
|
|
allowFirstRunFinish := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if requestCount.Add(1) == 1 {
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
select {
|
|
case <-firstRunStarted:
|
|
default:
|
|
close(firstRunStarted)
|
|
}
|
|
<-allowFirstRunFinish
|
|
chunks <- chattest.OpenAITextChunks("first done")[0]
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("second done")...)
|
|
})
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
user, org, localDefault := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
chatModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
AIProviderID: localDefault.AIProviderID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, chatModel.ID, "first")
|
|
testutil.TryReceive(ctx, t, firstRunStarted)
|
|
disableChatModelConfig(t, db, chatModel)
|
|
insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
|
close(allowFirstRunFinish)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
var queuedMessage database.ChatMessage
|
|
for _, message := range messages {
|
|
if message.Role != database.ChatMessageRoleUser {
|
|
continue
|
|
}
|
|
parts, err := chatprompt.ParseContent(message)
|
|
require.NoError(t, err)
|
|
if len(parts) == 1 && parts[0].Text == "queued" {
|
|
queuedMessage = message
|
|
}
|
|
}
|
|
require.NotZero(t, queuedMessage.ID)
|
|
require.Equal(t, localDefault.ID, queuedMessage.ModelConfigID.UUID)
|
|
})
|
|
|
|
t.Run("InterruptionCompletion", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitSuperLong)
|
|
streamStarted := make(chan struct{})
|
|
var requestCount atomic.Int32
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if requestCount.Add(1) == 1 {
|
|
chunks := make(chan chattest.OpenAIChunk, 1)
|
|
go func() {
|
|
defer close(chunks)
|
|
select {
|
|
case <-streamStarted:
|
|
default:
|
|
close(streamStarted)
|
|
}
|
|
<-req.Context().Done()
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
}
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("second done")...)
|
|
})
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
})
|
|
user, org, localDefault := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
chatModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
AIProviderID: localDefault.AIProviderID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
|
|
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, chatModel.ID, "first")
|
|
testutil.TryReceive(ctx, t, streamStarted)
|
|
disableChatModelConfig(t, db, chatModel)
|
|
insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
|
current, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
_, _, err = server.InterruptChat(ctx, current)
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
var queuedMessage database.ChatMessage
|
|
for _, message := range messages {
|
|
if message.Role != database.ChatMessageRoleUser {
|
|
continue
|
|
}
|
|
parts, err := chatprompt.ParseContent(message)
|
|
require.NoError(t, err)
|
|
if len(parts) == 1 && parts[0].Text == "queued" {
|
|
queuedMessage = message
|
|
}
|
|
}
|
|
require.NotZero(t, queuedMessage.ID)
|
|
require.Equal(t, localDefault.ID, queuedMessage.ModelConfigID.UUID)
|
|
})
|
|
}
|
|
|
|
func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("ExplicitPromotion", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, localDefault := seedChatDependencies(t, db)
|
|
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: foreignModel.ID,
|
|
Title: "resolve explicit queued promotion",
|
|
Status: database.ChatStatusError,
|
|
})
|
|
queued := insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
|
|
|
err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
|
ChatID: chat.ID,
|
|
QueuedMessageID: queued.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
delivered := requireDeliveredQueuedMessage(ctx, t, db, chat.ID, queued.ID)
|
|
require.Equal(t, localDefault.ID, delivered.ModelConfigID.UUID)
|
|
})
|
|
|
|
t.Run("ErrorStateSendPromotion", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, localDefault := seedChatDependencies(t, db)
|
|
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: foreignModel.ID,
|
|
Title: "resolve error send promotion",
|
|
Status: database.ChatStatusError,
|
|
})
|
|
insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
|
|
|
result, err := server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("new")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.NotEmpty(t, result.InsertedMessages)
|
|
promoted := result.InsertedMessages[len(result.InsertedMessages)-1]
|
|
require.Equal(t, localDefault.ID, promoted.ModelConfigID.UUID)
|
|
})
|
|
|
|
t.Run("NoLocalDefaultKeepsQueuedRow", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
server := newTestServer(t, db, ps, uuid.New())
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user := dbgen.User(t, db, database.User{})
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: foreignModel.ID,
|
|
Title: "keep unresolved queued row",
|
|
Status: database.ChatStatusError,
|
|
})
|
|
queued := insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
|
|
|
err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
|
ChatID: chat.ID,
|
|
QueuedMessageID: queued.ID,
|
|
})
|
|
require.ErrorIs(t, err, chatd.ErrNoDefaultChatModelConfig)
|
|
rows, err := db.GetChatQueuedMessages(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Len(t, rows, 1)
|
|
require.Equal(t, queued.ID, rows[0].ID)
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{ChatID: chat.ID})
|
|
require.NoError(t, err)
|
|
require.Empty(t, messages)
|
|
})
|
|
}
|
|
|
|
func disableChatModelConfig(t *testing.T, db database.Store, model database.ChatModelConfig) {
|
|
t.Helper()
|
|
_, err := db.UpdateChatModelConfig(context.Background(), database.UpdateChatModelConfigParams{
|
|
ID: model.ID,
|
|
DisplayName: model.DisplayName,
|
|
Model: model.Model,
|
|
Enabled: false,
|
|
IsDefault: model.IsDefault,
|
|
ContextLimit: model.ContextLimit,
|
|
CompressionThreshold: model.CompressionThreshold,
|
|
Options: model.Options,
|
|
AIProviderID: model.AIProviderID,
|
|
})
|
|
require.NoError(t, err)
|
|
}
|
|
|
|
func insertQueuedMessage(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
createdBy uuid.UUID,
|
|
modelConfigID uuid.UUID,
|
|
text string,
|
|
) database.ChatQueuedMessage {
|
|
t.Helper()
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{codersdk.ChatMessageText(text)})
|
|
require.NoError(t, err)
|
|
queued, err := db.InsertChatQueuedMessageWithCreator(ctx, database.InsertChatQueuedMessageWithCreatorParams{
|
|
ChatID: chatID,
|
|
Content: content.RawMessage,
|
|
ModelConfigID: uuid.NullUUID{UUID: modelConfigID, Valid: true},
|
|
CreatedBy: createdBy,
|
|
BusyBehavior: database.ChatBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
return queued
|
|
}
|
|
|
|
func requireDeliveredQueuedMessage(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
queuedID int64,
|
|
) database.ChatMessage {
|
|
t.Helper()
|
|
for _, message := range chatMessages(ctx, t, db, chatID) {
|
|
if message.QueuedMessageID.Valid && message.QueuedMessageID.Int64 == queuedID {
|
|
return message
|
|
}
|
|
}
|
|
require.FailNow(t, "queued message not delivered", "queued message %d", queuedID)
|
|
return database.ChatMessage{}
|
|
}
|
|
|
|
func TestPromoteQueuedPreservesReasoningEffort(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
replica := newTestServer(t, db, ps, uuid.New())
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
user, org, model := seedChatDependencies(t, db)
|
|
|
|
chat := dbgen.Chat(t, db, database.Chat{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
LastModelConfigID: model.ID,
|
|
Title: "promote-reasoning-effort",
|
|
Status: database.ChatStatusError,
|
|
})
|
|
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{codersdk.ChatMessageText("queued")})
|
|
require.NoError(t, err)
|
|
queued, err := db.InsertChatQueuedMessageWithCreator(ctx, database.InsertChatQueuedMessageWithCreatorParams{
|
|
ChatID: chat.ID,
|
|
Content: content.RawMessage,
|
|
ModelConfigID: uuid.NullUUID{UUID: model.ID, Valid: true},
|
|
ReasoningEffort: database.NullChatReasoningEffort{ChatReasoningEffort: database.ChatReasoningEffortHigh, Valid: true},
|
|
CreatedBy: user.ID,
|
|
BusyBehavior: database.ChatBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, queued.ReasoningEffort.Valid)
|
|
require.Equal(t, database.ChatReasoningEffortHigh, queued.ReasoningEffort.ChatReasoningEffort)
|
|
|
|
err = replica.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
|
ChatID: chat.ID,
|
|
QueuedMessageID: queued.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
delivered := requireDeliveredQueuedMessage(ctx, t, db, chat.ID, queued.ID)
|
|
require.True(t, delivered.ReasoningEffort.Valid)
|
|
require.Equal(t, database.ChatReasoningEffortHigh, delivered.ReasoningEffort.ChatReasoningEffort)
|
|
|
|
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.True(t, storedChat.LastReasoningEffort.Valid)
|
|
require.Equal(t, database.ChatReasoningEffortHigh, storedChat.LastReasoningEffort.ChatReasoningEffort)
|
|
}
|
|
|
|
// TestAdvisorHappyPath_RootChat walks the advisor tool end-to-end:
|
|
// parent calls advisor alone, the nested advisor call produces text, and
|
|
// the structured result flows back into the parent conversation.
|
|
// TestActiveServer_ExclusiveToolPolicy covers mixed-batch rejection; this
|
|
// test covers the glue from chatd wiring -> chatadvisor.Tool -> Runtime.Run ->
|
|
// nested model call -> structured result back to the outer model.
|
|
func TestAdvisorHappyPath_RootChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const advisorReply = "break the problem into smaller pieces first"
|
|
const advisorReasoning = "advisor-only reasoning: compare the refactoring risks"
|
|
advisorDeltas := []string{"break the problem ", "into smaller pieces first"}
|
|
|
|
var (
|
|
streamedCallCount atomic.Int32
|
|
streamedCallsMu sync.Mutex
|
|
advisorCallSeen atomic.Bool
|
|
firstCallMessages []chattest.OpenAIMessage
|
|
advisorMessages []chattest.OpenAIMessage
|
|
finalCallMessages []chattest.OpenAIMessage
|
|
)
|
|
|
|
// Declared before the OpenAI handler so the nested advisor stream can
|
|
// gate its completion on the live collector below having observed the
|
|
// streamed deltas.
|
|
var (
|
|
livePartsMu sync.Mutex
|
|
liveAdvisorDeltas []string
|
|
liveAdvisorReasoning []string
|
|
liveAssistantReasoning []string
|
|
)
|
|
liveDeltasCaptured := func() bool {
|
|
livePartsMu.Lock()
|
|
defer livePartsMu.Unlock()
|
|
return slices.Equal(advisorDeltas, liveAdvisorDeltas) &&
|
|
slices.Equal([]string{advisorReasoning}, liveAdvisorReasoning)
|
|
}
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
switch streamedCallCount.Add(1) {
|
|
case 1:
|
|
// Parent turn 1: call advisor solo.
|
|
require.True(t, slices.ContainsFunc(req.Tools, func(tool chattest.OpenAITool) bool {
|
|
return tool.Function.Name == chatadvisor.ToolName
|
|
}), "parent request must offer advisor")
|
|
streamedCallsMu.Lock()
|
|
firstCallMessages = append([]chattest.OpenAIMessage(nil), req.Messages...)
|
|
streamedCallsMu.Unlock()
|
|
chunk := chattest.OpenAIToolCallChunk(
|
|
"advisor",
|
|
`{"question":"how should I approach this refactor?"}`,
|
|
)
|
|
chunk.Choices[0].ToolCalls[0].ID = "advisor-happy-path-call"
|
|
return chattest.OpenAIStreamingResponse(chunk)
|
|
case 2:
|
|
// Nested advisor turn. The nested call has no tools because
|
|
// chatadvisor.RunAdvisor runs with MaxSteps=1 and no tool
|
|
// set.
|
|
require.Empty(t, req.Tools,
|
|
"advisor's nested call must run without tools")
|
|
streamedCallsMu.Lock()
|
|
advisorMessages = append([]chattest.OpenAIMessage(nil), req.Messages...)
|
|
streamedCallsMu.Unlock()
|
|
advisorCallSeen.Store(true)
|
|
// Stream the deltas, then hold the nested response open until
|
|
// the live subscriber has captured them. Advisor deltas are
|
|
// stream-only: they live in the generation attempt's message
|
|
// part episode, and once the tool result is committed the
|
|
// subscriber's stream loop targets the next episode and never
|
|
// replays this one. Without the hold, a slow pubsub sync makes
|
|
// the subscriber skip the episode entirely and the deltas are
|
|
// lost, flaking the streaming assertions below.
|
|
chunks := make(chan chattest.OpenAIChunk)
|
|
go func() {
|
|
defer close(chunks)
|
|
chunks <- chattest.OpenAIChunk{Choices: []chattest.OpenAIChunkChoice{{ReasoningDelta: advisorReasoning}}}
|
|
for _, chunk := range chattest.OpenAITextChunks(advisorDeltas...) {
|
|
chunks <- chunk
|
|
}
|
|
deadline := time.NewTimer(testutil.WaitLong)
|
|
defer deadline.Stop()
|
|
for !liveDeltasCaptured() {
|
|
select {
|
|
case <-deadline.C:
|
|
// Give up and let the assertions below report the
|
|
// failure instead of hanging the stream forever.
|
|
return
|
|
case <-time.After(testutil.IntervalFast):
|
|
}
|
|
}
|
|
}()
|
|
return chattest.OpenAIResponse{StreamingChunks: chunks}
|
|
default:
|
|
// Parent turn 2: observe the advisor tool result and close
|
|
// out with a final text reply.
|
|
streamedCallsMu.Lock()
|
|
finalCallMessages = append([]chattest.OpenAIMessage(nil), req.Messages...)
|
|
streamedCallsMu.Unlock()
|
|
return chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("acknowledged")...,
|
|
)
|
|
}
|
|
})
|
|
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
|
seedAdvisorConfig(ctx, t, db, codersdk.AdvisorConfig{
|
|
Enabled: true,
|
|
MaxUsesPerRun: 3,
|
|
MaxOutputTokens: 16384,
|
|
})
|
|
server := newTestServer(t, db, ps, uuid.New(), func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(
|
|
chattest.NewMockAIBridgeTransport(t, openAIURL),
|
|
)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "advisor-happy-path",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("help me refactor this module"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Advisor deltas are transient; a late subscriber misses them.
|
|
_, liveEvents, cancelLive, ok := server.Subscribe(ctx, chat.ID, nil, 0, 0)
|
|
require.True(t, ok)
|
|
liveCollectorDone := make(chan struct{})
|
|
go func() {
|
|
defer close(liveCollectorDone)
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case event, eventsOK := <-liveEvents:
|
|
if !eventsOK {
|
|
return
|
|
}
|
|
if event.Type != codersdk.ChatStreamEventTypeMessagePart ||
|
|
event.MessagePart == nil {
|
|
continue
|
|
}
|
|
part := event.MessagePart.Part
|
|
livePartsMu.Lock()
|
|
if event.MessagePart.Role == codersdk.ChatMessageRoleAssistant && part.Type == codersdk.ChatMessagePartTypeReasoning {
|
|
liveAssistantReasoning = append(liveAssistantReasoning, part.Text)
|
|
}
|
|
livePartsMu.Unlock()
|
|
if event.MessagePart.Role != codersdk.ChatMessageRoleTool ||
|
|
part.Type != codersdk.ChatMessagePartTypeToolResult ||
|
|
part.ToolName != chatadvisor.ToolName ||
|
|
part.ToolCallID != "advisor-happy-path-call" {
|
|
continue
|
|
}
|
|
livePartsMu.Lock()
|
|
if part.ResultDelta != "" {
|
|
liveAdvisorDeltas = append(liveAdvisorDeltas, part.ResultDelta)
|
|
}
|
|
if part.ReasoningDelta != "" {
|
|
liveAdvisorReasoning = append(liveAdvisorReasoning, part.ReasoningDelta)
|
|
}
|
|
livePartsMu.Unlock()
|
|
}
|
|
}
|
|
}()
|
|
|
|
server.Start()
|
|
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
if getErr != nil {
|
|
return false
|
|
}
|
|
if got.Status != database.ChatStatusWaiting &&
|
|
got.Status != database.ChatStatusError {
|
|
return false
|
|
}
|
|
return streamedCallCount.Load() >= 3
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
|
|
streamedCallsMu.Lock()
|
|
gotFirstMessages := append([]chattest.OpenAIMessage(nil), firstCallMessages...)
|
|
gotAdvisorMessages := append([]chattest.OpenAIMessage(nil), advisorMessages...)
|
|
gotFinalMessages := append([]chattest.OpenAIMessage(nil), finalCallMessages...)
|
|
streamedCallsMu.Unlock()
|
|
|
|
require.True(t, advisorCallSeen.Load(),
|
|
"the nested advisor call must execute; missing it means the tool never ran")
|
|
require.NotEmpty(t, gotAdvisorMessages,
|
|
"advisor call must receive the nested prompt messages")
|
|
require.NotEmpty(t, gotFinalMessages,
|
|
"parent must make a follow-up call after the advisor result")
|
|
require.True(t, slices.ContainsFunc(gotFirstMessages, func(msg chattest.OpenAIMessage) bool {
|
|
return strings.Contains(msg.Content, chatadvisor.ParentGuidanceBlock)
|
|
}), "the parent's first request must carry the advisor guidance")
|
|
|
|
var advisorSawQuestion bool
|
|
var advisorSawUserTurn bool
|
|
for _, msg := range gotAdvisorMessages {
|
|
if strings.Contains(msg.Content, "how should I approach this refactor?") {
|
|
advisorSawQuestion = true
|
|
}
|
|
if msg.Role == "user" && strings.Contains(msg.Content, "help me refactor this module") {
|
|
advisorSawUserTurn = true
|
|
}
|
|
}
|
|
require.True(t, advisorSawQuestion,
|
|
"advisor must receive the parent's question verbatim")
|
|
require.True(t, advisorSawUserTurn,
|
|
"advisor must receive the parent's conversation snapshot as nested context")
|
|
|
|
for _, msg := range gotAdvisorMessages {
|
|
require.NotContains(t, msg.Content, chatadvisor.ParentGuidanceBlock,
|
|
"ParentGuidanceBlock must be stripped before reaching the advisor")
|
|
require.NotContains(t, msg.Content, "did not receive a result",
|
|
"the advisor must not see its own pending call as interrupted")
|
|
}
|
|
require.True(t, slices.ContainsFunc(gotAdvisorMessages, func(msg chattest.OpenAIMessage) bool {
|
|
return strings.Contains(msg.Content, "ran the advisor tool") &&
|
|
strings.Contains(msg.Content, "Result: pending")
|
|
}), "the advisor must see its own call marked as pending")
|
|
|
|
var parentSawAdvisorResult bool
|
|
for _, msg := range gotFinalMessages {
|
|
require.NotContains(t, msg.Content, advisorReasoning)
|
|
if msg.Role == "tool" && strings.Contains(msg.Content, advisorReply) {
|
|
parentSawAdvisorResult = true
|
|
}
|
|
}
|
|
require.True(t, parentSawAdvisorResult,
|
|
"parent must see the advisor reply in its continuation call")
|
|
|
|
// Stop the live collector and assert it captured the streaming
|
|
// advisor deltas during processing. Late subscribers no longer
|
|
// see committed parts because publishMessage claims them out of
|
|
// new snapshots, so the assertion must use the live collector.
|
|
require.Eventually(t, liveDeltasCaptured, testutil.WaitLong, testutil.IntervalFast,
|
|
"advisor nested text deltas must stream into the parent tool card")
|
|
cancelLive()
|
|
<-liveCollectorDone
|
|
livePartsMu.Lock()
|
|
collectedAdvisorDeltas := append([]string(nil), liveAdvisorDeltas...)
|
|
collectedAdvisorReasoning := append([]string(nil), liveAdvisorReasoning...)
|
|
collectedAssistantReasoning := append([]string(nil), liveAssistantReasoning...)
|
|
livePartsMu.Unlock()
|
|
require.Equal(t, advisorDeltas, collectedAdvisorDeltas,
|
|
"advisor nested text deltas must stream into the parent tool card")
|
|
|
|
require.Equal(t, []string{advisorReasoning}, collectedAdvisorReasoning)
|
|
require.Empty(t, collectedAssistantReasoning, "advisor reasoning must not become parent assistant reasoning")
|
|
persisted, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
AfterID: 0,
|
|
})
|
|
require.NoError(t, err)
|
|
for _, msg := range persisted {
|
|
require.NotContains(t, string(msg.Content.RawMessage), "reasoning_delta")
|
|
require.NotContains(t, string(msg.Content.RawMessage), advisorReasoning)
|
|
require.NotContains(t, string(msg.Content.RawMessage), "result_delta",
|
|
"advisor deltas are stream-only and must not be persisted")
|
|
}
|
|
result := requireToolResultPart(t, chatToolParts(ctx, t, db, chat.ID), chatadvisor.ToolName)
|
|
require.False(t, result.IsError)
|
|
require.Contains(t, string(result.Result), advisorReply)
|
|
}
|
|
|
|
// TestAdvisorMaxUsesPerTurn verifies that max_uses_per_run holds across
|
|
// the model steps of one user turn, including a compaction between
|
|
// them, that a refunded provider failure does not consume a use, and
|
|
// that the next user prompt starts a fresh budget.
|
|
func TestAdvisorMaxUsesPerTurn(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
advisorCall := func(inputTokens int) chattest.AnthropicResponse {
|
|
chunks := chattest.AnthropicToolCallChunks(chatadvisor.ToolName, `{"question":"what next?"}`)
|
|
for i := range chunks {
|
|
if chunks[i].Type == "message_start" {
|
|
chunks[i].Message.Usage = map[string]int{"input_tokens": inputTokens}
|
|
}
|
|
}
|
|
return chattest.AnthropicStreamingResponse(chunks...)
|
|
}
|
|
|
|
var parentCalls, adviceCalls, compactions atomic.Int32
|
|
anthropicURL := chattest.NewAnthropic(t, func(req *chattest.AnthropicRequest) chattest.AnthropicResponse {
|
|
if !req.Stream {
|
|
return chattest.AnthropicNonStreamingResponse("title")
|
|
}
|
|
if strings.Contains(anthropicRequestBody(t, *req), "You are performing a context compaction") {
|
|
compactions.Add(1)
|
|
return anthropicCompactionResponse(t, req, "advisor quota summary")
|
|
}
|
|
// The nested advisor call is the only streamed generation
|
|
// without tools.
|
|
if len(req.Tools) == 0 {
|
|
if parentCalls.Load() == 1 {
|
|
return chattest.AnthropicResponse{Error: &chattest.ErrorResponse{
|
|
StatusCode: http.StatusBadRequest,
|
|
Type: "invalid_request_error",
|
|
Message: "advisor request rejected",
|
|
}}
|
|
}
|
|
adviceCalls.Add(1)
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("advice")...)
|
|
}
|
|
switch parentCalls.Add(1) {
|
|
case 1, 3, 5:
|
|
return advisorCall(10)
|
|
case 2:
|
|
// Usage over the compaction threshold compacts the chat
|
|
// after this step's advisor call completes.
|
|
return advisorCall(80)
|
|
default:
|
|
return chattest.AnthropicStreamingResponse(chattest.AnthropicTextChunks("done")...)
|
|
}
|
|
})
|
|
|
|
user, org, model := seedAnthropicChatDependencies(t, db, anthropicURL)
|
|
model = updateChatModelCompressionThreshold(t, db, model, 100, 70)
|
|
seedAdvisorConfig(ctx, t, db, codersdk.AdvisorConfig{
|
|
MaxUsesPerRun: 1,
|
|
MaxOutputTokens: 1024,
|
|
})
|
|
server := newTestServer(t, db, ps, uuid.New(), func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(
|
|
chattest.NewMockAIBridgeTransport(t, anthropicURL, chattest.WithPreservePath()),
|
|
)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "advisor-max-uses",
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("plan this change"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
server.Start()
|
|
|
|
waitForTurn := func(minParentCalls int32) {
|
|
t.Helper()
|
|
require.Eventually(t, func() bool {
|
|
got, getErr := db.GetChatByID(ctx, chat.ID)
|
|
return getErr == nil &&
|
|
got.Status == database.ChatStatusWaiting &&
|
|
parentCalls.Load() >= minParentCalls
|
|
}, testutil.WaitLong, testutil.IntervalFast)
|
|
}
|
|
waitForTurn(4)
|
|
require.EqualValues(t, 1, compactions.Load(), "the turn must compact between advisor calls")
|
|
require.EqualValues(t, 1, adviceCalls.Load(),
|
|
"the advisor call after the use limit must not reach the provider")
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue")},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForTurn(6)
|
|
require.EqualValues(t, 2, adviceCalls.Load(), "a new user prompt must get a fresh advisor budget")
|
|
|
|
messages := chatMessages(ctx, t, db, chat.ID)
|
|
compressed := compressedChatSummarizedMessages(t, messages)
|
|
require.Len(t, compressed.results, 1)
|
|
summaryID := compressed.results[0].ID
|
|
type advisorOutcome struct {
|
|
resultType chatadvisor.ResultType
|
|
afterSummary bool
|
|
}
|
|
var outcomes []advisorOutcome
|
|
for _, msg := range messages {
|
|
if msg.Role != database.ChatMessageRoleTool || msg.Compressed {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
require.NoError(t, parseErr)
|
|
for _, part := range parts {
|
|
if part.Type != codersdk.ChatMessagePartTypeToolResult || part.ToolName != chatadvisor.ToolName {
|
|
continue
|
|
}
|
|
var result chatadvisor.AdvisorResult
|
|
require.NoError(t, json.Unmarshal(part.Result, &result))
|
|
outcomes = append(outcomes, advisorOutcome{resultType: result.Type, afterSummary: msg.ID > summaryID})
|
|
}
|
|
}
|
|
require.Equal(t, []advisorOutcome{
|
|
{resultType: chatadvisor.ResultTypeError},
|
|
{resultType: chatadvisor.ResultTypeAdvice},
|
|
{resultType: chatadvisor.ResultTypeLimitReached, afterSummary: true},
|
|
{resultType: chatadvisor.ResultTypeAdvice, afterSummary: true},
|
|
}, outcomes)
|
|
}
|
|
|
|
// TestProviderSwitchSanitizesAndRestoresPEToolHistory verifies the A→B→A
|
|
// provider-switch contract:
|
|
//
|
|
// 1. A turn using model MA (backed by provider A) produces a
|
|
// provider-executed (PE) tool call in the DB.
|
|
// 2. A subsequent turn using model MB (backed by provider B) does NOT
|
|
// send that PE tool call to provider B.
|
|
// 3. A further turn back to MA sends the PE tool call to provider A again.
|
|
// 4. The DB row is never mutated; the filter is read-time only.
|
|
func TestProviderSwitchSanitizesAndRestoresPEToolHistory(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
user := dbgen.User(t, db, database.User{})
|
|
org := dbgen.Organization(t, db, database.Organization{})
|
|
dbgen.OrganizationMember(t, db, database.OrganizationMember{
|
|
UserID: user.ID,
|
|
OrganizationID: org.ID,
|
|
})
|
|
|
|
// Given: two AI providers A and B
|
|
const peToolCallID = "pe_switch_test_id"
|
|
|
|
chanA := make(chan string, 4)
|
|
chanB := make(chan string, 4)
|
|
|
|
serverAURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"switch-test"}`)
|
|
}
|
|
chanA <- string(req.RawBody)
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("answer from A")...)
|
|
})
|
|
serverBURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse(`{"title":"switch-test"}`)
|
|
}
|
|
chanB <- string(req.RawBody)
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("answer from B")...)
|
|
})
|
|
cpA := dbgen.ChatProvider(t, db, database.ChatProvider{
|
|
Provider: "openai-compat",
|
|
BaseUrl: serverAURL,
|
|
})
|
|
cpB := dbgen.ChatProvider(t, db, database.ChatProvider{
|
|
Provider: "openai-compat",
|
|
BaseUrl: serverBURL,
|
|
})
|
|
|
|
mA := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
Model: "gpt-4o-mini",
|
|
DisplayName: "Model A",
|
|
Enabled: true,
|
|
AIProviderID: uuid.NullUUID{UUID: cpA.ID, Valid: true},
|
|
OrganizationID: org.ID,
|
|
})
|
|
mB := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
|
|
Model: "gpt-4o-mini",
|
|
DisplayName: "Model B",
|
|
Enabled: true,
|
|
AIProviderID: uuid.NullUUID{UUID: cpB.ID, Valid: true},
|
|
OrganizationID: org.ID,
|
|
})
|
|
|
|
server := newActiveTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
provA, err := db.GetAIProviderByID(ctx, cpA.ID)
|
|
require.NoError(t, err)
|
|
provB, err := db.GetAIProviderByID(ctx, cpB.ID)
|
|
require.NoError(t, err)
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(providerRoutedTransportFactory{
|
|
routes: map[string]aibridge.TransportFactory{
|
|
provA.Name: chattest.NewMockAIBridgeTransport(t, serverAURL),
|
|
provB.Name: chattest.NewMockAIBridgeTransport(t, serverBURL),
|
|
},
|
|
})
|
|
})
|
|
|
|
// Given: an initial conversation turn with model A that produces provider-executed
|
|
// tool call results
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: "provider-switch-test",
|
|
ModelConfigID: mA.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
insertChatMessageParts(ctx, t, db, chat.ID, database.ChatMessageRoleAssistant, mA.ID, uuid.Nil,
|
|
[]codersdk.ChatMessagePart{
|
|
{
|
|
Type: codersdk.ChatMessagePartTypeToolCall,
|
|
ToolCallID: peToolCallID,
|
|
ToolName: "web_search",
|
|
Args: json.RawMessage(`{"query":"coder"}`),
|
|
ProviderExecuted: true,
|
|
},
|
|
{
|
|
Type: codersdk.ChatMessagePartTypeToolResult,
|
|
ToolCallID: peToolCallID,
|
|
ToolName: "web_search",
|
|
Result: json.RawMessage(`"search results"`),
|
|
ProviderExecuted: true,
|
|
},
|
|
codersdk.ChatMessageText("here is the answer"),
|
|
},
|
|
)
|
|
|
|
// When: a conversation turn is executed with model B
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: mB.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("continue with B")},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
// When: a further conversation turn is executed with model A again
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: mA.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("back to A")},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
// Then: the provider-executed tool call results should still be in the database
|
|
allMessages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chat.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
var peRowFound bool
|
|
for _, msg := range allMessages {
|
|
if msg.Role != database.ChatMessageRoleAssistant || msg.ModelConfigID.UUID != mA.ID {
|
|
continue
|
|
}
|
|
parts, parseErr := chatprompt.ParseContent(msg)
|
|
require.NoError(t, parseErr)
|
|
for _, p := range parts {
|
|
if p.ProviderExecuted && p.ToolCallID == peToolCallID {
|
|
peRowFound = true
|
|
}
|
|
}
|
|
}
|
|
require.True(t, peRowFound, "PE tool call must still be in the DB after provider switches")
|
|
|
|
// Skip initial generation request
|
|
_ = testutil.TryReceive(ctx, t, chanA)
|
|
|
|
// Then: PE tool call ID from A must not appear in the request to provider B
|
|
turn2Body := testutil.TryReceive(ctx, t, chanB)
|
|
require.NotContains(t, turn2Body, peToolCallID,
|
|
"provider B must not receive the PE tool call from provider A")
|
|
|
|
// Then: PE tool call ID must appear in the second request to provider A
|
|
turn3Body := testutil.TryReceive(ctx, t, chanA)
|
|
require.Contains(t, turn3Body, peToolCallID,
|
|
"provider A must receive its own PE tool call when switching back")
|
|
}
|
|
|
|
// providerRoutedTransportFactory implements aibridge.TransportFactory by
|
|
// dispatching to a different mock transport per AI provider name. It
|
|
// exists for tests that exercise two providers in the same chat (e.g.
|
|
// switching models mid-conversation), where a single
|
|
// chattest.MockAIBridgeTransport's fixed target can't represent both.
|
|
type providerRoutedTransportFactory struct {
|
|
routes map[string]aibridge.TransportFactory
|
|
}
|
|
|
|
func (f providerRoutedTransportFactory) TransportFor(providerName string, source aibridge.Source) (http.RoundTripper, error) {
|
|
route, ok := f.routes[providerName]
|
|
if !ok {
|
|
return nil, xerrors.Errorf("no mock transport configured for provider %q", providerName)
|
|
}
|
|
return route.TransportFor(providerName, source)
|
|
}
|
|
|
|
func seedAdvisorConfig(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
cfg codersdk.AdvisorConfig,
|
|
) {
|
|
t.Helper()
|
|
|
|
data, err := json.Marshal(cfg)
|
|
require.NoError(t, err)
|
|
err = db.UpsertChatAdvisorConfig(
|
|
dbauthz.AsSystemRestricted(ctx),
|
|
string(data),
|
|
)
|
|
require.NoError(t, err)
|
|
}
|
|
|
|
// nullRawMessage wraps raw JSON in a NullRawMessage. An empty input
|
|
// becomes the zero value (Valid=false).
|
|
func nullRawMessage(raw []byte) pqtype.NullRawMessage {
|
|
if len(raw) == 0 {
|
|
return pqtype.NullRawMessage{}
|
|
}
|
|
return pqtype.NullRawMessage{RawMessage: raw, Valid: true}
|
|
}
|
|
|
|
func setupWorkspaceContextAgentConn(
|
|
t *testing.T,
|
|
mockConn *agentconnmock.MockAgentConn,
|
|
agent database.WorkspaceAgent,
|
|
contextText string,
|
|
contextConfigCalls *atomic.Int32,
|
|
) {
|
|
t.Helper()
|
|
directory := agent.ExpandedDirectory
|
|
if directory == "" {
|
|
directory = agent.Directory
|
|
}
|
|
if directory == "" {
|
|
directory = "/home/coder/project"
|
|
}
|
|
operatingSystem := agent.OperatingSystem
|
|
if operatingSystem == "" {
|
|
operatingSystem = "linux"
|
|
}
|
|
mockConn.EXPECT().SetExtraHeaders(gomock.Any()).AnyTimes()
|
|
mockConn.EXPECT().ContextConfig(gomock.Any()).DoAndReturn(
|
|
func(context.Context) (workspacesdk.ContextConfigResponse, error) {
|
|
if contextConfigCalls != nil {
|
|
contextConfigCalls.Add(1)
|
|
}
|
|
return workspacesdk.ContextConfigResponse{
|
|
Parts: []codersdk.ChatMessagePart{{
|
|
Type: codersdk.ChatMessagePartTypeContextFile,
|
|
ContextFilePath: directory + "/AGENTS.md",
|
|
ContextFileContent: contextText,
|
|
ContextFileOS: operatingSystem,
|
|
ContextFileDirectory: directory,
|
|
}},
|
|
}, nil
|
|
},
|
|
).AnyTimes()
|
|
mockConn.EXPECT().LS(gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(workspacesdk.LSResponse{AbsolutePathString: "/home/coder"}, nil).AnyTimes()
|
|
mockConn.EXPECT().ReadFile(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
|
|
Return(io.NopCloser(strings.NewReader("")), "", nil).AnyTimes()
|
|
}
|
|
|
|
func newRecordingTracerProvider(t *testing.T) (*sdktrace.TracerProvider, *tracetest.SpanRecorder) {
|
|
t.Helper()
|
|
recorder := tracetest.NewSpanRecorder()
|
|
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder))
|
|
// t.Context is canceled before Cleanup runs.
|
|
t.Cleanup(func() { require.NoError(t, provider.Shutdown(context.Background())) })
|
|
return provider, recorder
|
|
}
|
|
|
|
func spanAttr(t *testing.T, span sdktrace.ReadOnlySpan, key string) string {
|
|
t.Helper()
|
|
for _, attr := range span.Attributes() {
|
|
if string(attr.Key) == key {
|
|
return attr.Value.Emit()
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func requireCompactionSpan(t *testing.T, recorder *tracetest.SpanRecorder, model string, source chatloop.CompactionSource) {
|
|
t.Helper()
|
|
var compactions []sdktrace.ReadOnlySpan
|
|
for _, span := range recorder.Ended() {
|
|
if span.Name() == string(chatloop.StageCompaction) {
|
|
compactions = append(compactions, span)
|
|
}
|
|
}
|
|
require.Len(t, compactions, 1)
|
|
require.Equal(t, model, spanAttr(t, compactions[0], chatloop.AttrModel))
|
|
require.Equal(t, string(source), spanAttr(t, compactions[0], chatloop.AttrCompactionSource))
|
|
}
|
|
|
|
func TestActiveServer_TracesChatTurn(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
type spanIndex map[string][]sdktrace.ReadOnlySpan
|
|
|
|
type harness struct {
|
|
db database.Store
|
|
server *chatd.Server
|
|
recorder *tracetest.SpanRecorder
|
|
user database.User
|
|
org database.Organization
|
|
model database.ChatModelConfig
|
|
}
|
|
newHarness := func(t *testing.T, respond func(*chattest.OpenAIRequest) chattest.OpenAIResponse, overrides ...func(*chatd.Config)) harness {
|
|
t.Helper()
|
|
db, ps := dbtestutil.NewDB(t)
|
|
provider, recorder := newRecordingTracerProvider(t)
|
|
openAIURL := chattest.NewOpenAI(t, respond)
|
|
user, org, model := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
server := newActiveTestServer(t, db, ps, append([]func(*chatd.Config){func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
|
|
cfg.TracerProvider = provider
|
|
}}, overrides...)...)
|
|
return harness{db: db, server: server, recorder: recorder, user: user, org: org, model: model}
|
|
}
|
|
// A turn span can end after the chat status is visible.
|
|
waitForTurns := func(ctx context.Context, t *testing.T, recorder *tracetest.SpanRecorder, n int) spanIndex {
|
|
t.Helper()
|
|
var index spanIndex
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
index = spanIndex{}
|
|
for _, span := range recorder.Ended() {
|
|
stage := spanAttr(t, span, chatloop.AttrStage)
|
|
index[stage] = append(index[stage], span)
|
|
}
|
|
return len(index[string(chatloop.StageChatTurn)]) >= n
|
|
}, testutil.IntervalFast)
|
|
require.Len(t, index[string(chatloop.StageChatTurn)], n)
|
|
slices.SortFunc(index[string(chatloop.StageChatTurn)], func(a, b sdktrace.ReadOnlySpan) int {
|
|
return a.StartTime().Compare(b.StartTime())
|
|
})
|
|
return index
|
|
}
|
|
run := func(t *testing.T, respond func(*chattest.OpenAIRequest) chattest.OpenAIResponse, wantStatus database.ChatStatus) (harness, uuid.UUID, spanIndex) {
|
|
t.Helper()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
h := newHarness(t, respond)
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, wantStatus)
|
|
return h, chat.ID, waitForTurns(ctx, t, h.recorder, 1)
|
|
}
|
|
blockFirstStream := func(started chan<- struct{}, release <-chan struct{}, first chattest.OpenAIResponse) func(*chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
var calls atomic.Int32
|
|
return func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
close(started)
|
|
select {
|
|
case <-release:
|
|
case <-req.Context().Done():
|
|
}
|
|
return first
|
|
}
|
|
return chattest.OpenAIStreamingResponse(openAITextChunksWithStop("done")...)
|
|
}
|
|
}
|
|
// A streaming response can be consumed only once.
|
|
textResponse := func() chattest.OpenAIResponse {
|
|
return chattest.OpenAIStreamingResponse(openAITextChunksWithStop("hello")...)
|
|
}
|
|
|
|
single := func(t *testing.T, index spanIndex, stage chatloop.Stage) sdktrace.ReadOnlySpan {
|
|
t.Helper()
|
|
require.Len(t, index[string(stage)], 1, "expected exactly one %s span", stage)
|
|
return index[string(stage)][0]
|
|
}
|
|
childrenOf := func(index spanIndex, stage chatloop.Stage, parent sdktrace.ReadOnlySpan) []sdktrace.ReadOnlySpan {
|
|
var found []sdktrace.ReadOnlySpan
|
|
for _, span := range index[string(stage)] {
|
|
if span.Parent().SpanID() == parent.SpanContext().SpanID() {
|
|
found = append(found, span)
|
|
}
|
|
}
|
|
return found
|
|
}
|
|
childOf := func(t *testing.T, index spanIndex, stage chatloop.Stage, parent sdktrace.ReadOnlySpan) sdktrace.ReadOnlySpan {
|
|
t.Helper()
|
|
found := childrenOf(index, stage, parent)
|
|
require.Len(t, found, 1, "expected exactly one %s span under %s", stage, parent.Name())
|
|
return found[0]
|
|
}
|
|
stepByAction := func(t *testing.T, steps []sdktrace.ReadOnlySpan, action string) sdktrace.ReadOnlySpan {
|
|
t.Helper()
|
|
for _, step := range steps {
|
|
if spanAttr(t, step, chatloop.AttrGenerationAction) == action {
|
|
return step
|
|
}
|
|
}
|
|
t.Fatalf("no generation_step span with action %q", action)
|
|
return nil
|
|
}
|
|
requireChild := func(t *testing.T, child, parent sdktrace.ReadOnlySpan) {
|
|
t.Helper()
|
|
require.Equal(t, parent.SpanContext().TraceID(), child.SpanContext().TraceID(), "%s is not in %s's trace", child.Name(), parent.Name())
|
|
require.Equal(t, parent.SpanContext().SpanID(), child.Parent().SpanID(), "%s is not a child of %s", child.Name(), parent.Name())
|
|
require.False(t, child.StartTime().Before(parent.StartTime()), "%s starts before %s", child.Name(), parent.Name())
|
|
require.False(t, child.EndTime().After(parent.EndTime()), "%s ends after %s", child.Name(), parent.Name())
|
|
}
|
|
lastUserMessage := func(ctx context.Context, t *testing.T, db database.Store, chatID uuid.UUID) database.ChatMessage {
|
|
t.Helper()
|
|
messages := chatMessages(ctx, t, db, chatID)
|
|
for i := len(messages) - 1; i >= 0; i-- {
|
|
if messages[i].Role == database.ChatMessageRoleUser {
|
|
return messages[i]
|
|
}
|
|
}
|
|
t.Fatal("chat has no user message")
|
|
return database.ChatMessage{}
|
|
}
|
|
requireStandaloneQueueWait := func(t *testing.T, index spanIndex, queuedAt time.Time) {
|
|
t.Helper()
|
|
queueWait := single(t, index, chatloop.StageQueueWait)
|
|
require.False(t, queueWait.Parent().IsValid(), "queue_wait is a trace root")
|
|
require.Equal(t, queuedAt.UTC(), queueWait.StartTime().UTC())
|
|
require.Equal(t, string(chatloop.ScopeTurn), spanAttr(t, queueWait, chatloop.AttrScope))
|
|
require.Equal(t, string(chatloop.ChatKindRoot), spanAttr(t, queueWait, chatloop.AttrChatKind))
|
|
}
|
|
requireInterrupted := func(t *testing.T, turn sdktrace.ReadOnlySpan) {
|
|
t.Helper()
|
|
require.Equal(t, string(chatloop.TurnOutcomeInterrupted), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
require.Equal(t, codes.Unset, turn.Status().Code)
|
|
}
|
|
|
|
t.Run("Completed", func(t *testing.T) {
|
|
t.Parallel()
|
|
h, chatID, index := run(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return textResponse()
|
|
}, database.ChatStatusWaiting)
|
|
|
|
turn := single(t, index, chatloop.StageChatTurn)
|
|
require.Equal(t, codes.Unset, turn.Status().Code)
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
require.Equal(t, string(chatloop.ChatKindRoot), spanAttr(t, turn, chatloop.AttrChatKind))
|
|
require.Equal(t, chatID.String(), spanAttr(t, turn, chatloop.AttrChatID))
|
|
require.False(t, turn.Parent().IsValid(), "chat_turn is a trace root")
|
|
require.Equal(t, "invoke_agent coder", turn.Name())
|
|
require.Equal(t, "invoke_agent", spanAttr(t, turn, "gen_ai.operation.name"))
|
|
require.Equal(t, chatID.String(), spanAttr(t, turn, "gen_ai.conversation.id"))
|
|
require.Equal(t, h.user.ID.String(), spanAttr(t, turn, "user.id"))
|
|
require.Equal(t, h.org.ID.String(), spanAttr(t, turn, chatloop.AttrOrganizationID))
|
|
|
|
requireChild(t, single(t, index, chatloop.StageAcquisition), turn)
|
|
steps := index[string(chatloop.StageGenerationStep)]
|
|
for _, step := range steps {
|
|
requireChild(t, step, turn)
|
|
}
|
|
generate := stepByAction(t, steps, "generate_assistant")
|
|
finish := stepByAction(t, steps, "finish_turn")
|
|
for _, step := range []sdktrace.ReadOnlySpan{generate, finish} {
|
|
requireChild(t, childOf(t, index, chatloop.StagePrepare, step), step)
|
|
}
|
|
stream := single(t, index, chatloop.StageStream)
|
|
requireChild(t, stream, generate)
|
|
requireChild(t, single(t, index, chatloop.StageTimeToFirstToken), stream)
|
|
requireChild(t, single(t, index, chatloop.StageCommit), generate)
|
|
require.NotEmpty(t, spanAttr(t, generate, chatloop.AttrProvider))
|
|
require.Equal(t, spanAttr(t, stream, chatloop.AttrProvider), spanAttr(t, generate, chatloop.AttrProvider))
|
|
require.Equal(t, "chat "+h.model.Model, stream.Name())
|
|
require.Equal(t, spanAttr(t, stream, "gen_ai.provider.name"), spanAttr(t, turn, "gen_ai.provider.name"))
|
|
// Title generation is a non-streaming model call that runs outside
|
|
// the turn, so it must still be attributed to the chat owner.
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
var modelCall sdktrace.ReadOnlySpan
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
for _, span := range h.recorder.Ended() {
|
|
if spanAttr(t, span, chatloop.AttrStage) == string(chatloop.StageModelCall) {
|
|
modelCall = span
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}, testutil.IntervalFast)
|
|
require.Equal(t, "chat "+h.model.Model, modelCall.Name())
|
|
require.Equal(t, h.user.ID.String(), spanAttr(t, modelCall, "user.id"))
|
|
require.Equal(t, chatID.String(), spanAttr(t, modelCall, "gen_ai.conversation.id"))
|
|
require.Equal(t, chatID.String(), spanAttr(t, stream, "gen_ai.conversation.id"))
|
|
require.Equal(t, h.user.ID.String(), spanAttr(t, stream, "user.id"))
|
|
require.Equal(t, h.model.Model, spanAttr(t, stream, "gen_ai.request.model"))
|
|
require.Empty(t, index[string(chatloop.StageQueueWait)])
|
|
require.Empty(t, index[string(chatloop.StageRetryBackoff)])
|
|
})
|
|
|
|
t.Run("ProviderError", func(t *testing.T) {
|
|
t.Parallel()
|
|
_, _, index := run(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
// A 400 is non-retryable.
|
|
return chattest.OpenAIErrorResponse(http.StatusBadRequest, "invalid_request_error", "synthetic failure")
|
|
}, database.ChatStatusError)
|
|
|
|
turn := single(t, index, chatloop.StageChatTurn)
|
|
require.Equal(t, codes.Error, turn.Status().Code)
|
|
require.Equal(t, string(chatloop.TurnOutcomeError), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
step := single(t, index, chatloop.StageGenerationStep)
|
|
requireChild(t, step, turn)
|
|
require.Equal(t, "generate_assistant", spanAttr(t, step, chatloop.AttrGenerationAction))
|
|
stream := single(t, index, chatloop.StageStream)
|
|
requireChild(t, stream, step)
|
|
require.Equal(t, codes.Error, stream.Status().Code)
|
|
require.Empty(t, index[string(chatloop.StageRetryBackoff)])
|
|
})
|
|
|
|
t.Run("ToolCall", func(t *testing.T) {
|
|
t.Parallel()
|
|
var calls atomic.Int32
|
|
_, _, index := run(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAIToolCallChunk("list_templates", `{}`))
|
|
}
|
|
return textResponse()
|
|
}, database.ChatStatusWaiting)
|
|
|
|
turn := single(t, index, chatloop.StageChatTurn)
|
|
execute := stepByAction(t, index[string(chatloop.StageGenerationStep)], "execute_local_tools")
|
|
requireChild(t, execute, turn)
|
|
toolCall := single(t, index, chatloop.StageToolCall)
|
|
requireChild(t, toolCall, execute)
|
|
require.Equal(t, "list_templates", spanAttr(t, toolCall, chatloop.AttrToolName))
|
|
require.NotEmpty(t, spanAttr(t, toolCall, chatloop.AttrProvider))
|
|
require.Equal(t, spanAttr(t, execute, chatloop.AttrProvider), spanAttr(t, toolCall, chatloop.AttrProvider))
|
|
require.Equal(t, spanAttr(t, execute, chatloop.AttrModel), spanAttr(t, toolCall, chatloop.AttrModel))
|
|
})
|
|
|
|
t.Run("ProviderRetryKeepsTurnOpen", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger)
|
|
retryTrap := clock.Trap().NewTimer("chatworker", "generation-retry")
|
|
defer retryTrap.Close()
|
|
var calls atomic.Int32
|
|
h := newHarness(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
return chattest.OpenAIRateLimitResponse()
|
|
}
|
|
return textResponse()
|
|
}, func(cfg *chatd.Config) { cfg.Clock = clock })
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
retryTimer := retryTrap.MustWait(ctx)
|
|
retryTimer.MustRelease(ctx)
|
|
advanceMockClockBy(ctx, t, clock, retryTimer.Duration)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 1)
|
|
|
|
turn := single(t, index, chatloop.StageChatTurn)
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
steps := index[string(chatloop.StageGenerationStep)]
|
|
for _, step := range steps {
|
|
requireChild(t, step, turn)
|
|
}
|
|
backoff := single(t, index, chatloop.StageRetryBackoff)
|
|
require.True(t, slices.ContainsFunc(steps, func(step sdktrace.ReadOnlySpan) bool {
|
|
return step.SpanContext().SpanID() == backoff.Parent().SpanID()
|
|
}), "retry_backoff runs inside a generation step of the turn")
|
|
require.Len(t, index[string(chatloop.StageStream)], 2)
|
|
})
|
|
|
|
// The task timeout fires during the provider retry backoff.
|
|
t.Run("TaskTimeoutRetryKeepsTurnOpen", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger)
|
|
retryTrap := clock.Trap().NewTimer("chatworker", "generation-retry")
|
|
defer retryTrap.Close()
|
|
taskRetryTrap := clock.Trap().NewTimer("chatworker", "task-retry-generation")
|
|
defer taskRetryTrap.Close()
|
|
var calls atomic.Int32
|
|
h := newHarness(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
return chattest.OpenAIRateLimitResponse()
|
|
}
|
|
return textResponse()
|
|
}, func(cfg *chatd.Config) { cfg.Clock = clock })
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
// Holding the backoff timer lets the task timeout fire first.
|
|
retryTimer := retryTrap.MustWait(ctx)
|
|
advanceMockClockBy(ctx, t, clock, 15*time.Minute)
|
|
retryTimer.MustRelease(ctx)
|
|
taskRetry := taskRetryTrap.MustWait(ctx)
|
|
taskRetry.MustRelease(ctx)
|
|
advanceMockClockBy(ctx, t, clock, taskRetry.Duration)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
|
|
var turns []sdktrace.ReadOnlySpan
|
|
testutil.Eventually(ctx, t, func(context.Context) bool {
|
|
turns = nil
|
|
for _, span := range h.recorder.Ended() {
|
|
if spanAttr(t, span, chatloop.AttrStage) == string(chatloop.StageChatTurn) {
|
|
turns = append(turns, span)
|
|
}
|
|
}
|
|
return slices.ContainsFunc(turns, func(turn sdktrace.ReadOnlySpan) bool {
|
|
return spanAttr(t, turn, chatloop.AttrTurnOutcome) == string(chatloop.TurnOutcomeCompleted)
|
|
})
|
|
}, testutil.IntervalFast)
|
|
require.Len(t, turns, 1)
|
|
steps := 0
|
|
for _, span := range h.recorder.Ended() {
|
|
if span.Name() == string(chatloop.StageGenerationStep) {
|
|
steps++
|
|
require.Equal(t, turns[0].SpanContext().SpanID(), span.Parent().SpanID())
|
|
}
|
|
}
|
|
require.GreaterOrEqual(t, steps, 2)
|
|
})
|
|
|
|
t.Run("PostToolUseHookFailureFailsTurn", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
consumer := newHookConsumer(t, func(w http.ResponseWriter, r *http.Request) {
|
|
var request agenthooks.Request
|
|
if err := json.NewDecoder(r.Body).Decode(&request); err == nil && request.Type == agenthooks.EventPostToolUse {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte(`{}`))
|
|
})
|
|
var calls atomic.Int32
|
|
h := newHarness(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAIToolCallChunk("list_templates", `{}`))
|
|
}
|
|
return textResponse()
|
|
}, func(cfg *chatd.Config) { cfg.HookDispatcher = newHookDispatcher(t, nil, consumer) })
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusError)
|
|
index := waitForTurns(ctx, t, h.recorder, 1)
|
|
|
|
// The tool result commit also fails the turn.
|
|
turn := single(t, index, chatloop.StageChatTurn)
|
|
require.Equal(t, string(chatloop.TurnOutcomeError), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
require.Equal(t, codes.Error, turn.Status().Code)
|
|
require.Contains(t, turn.Status().Description, "HTTP status 500")
|
|
requireChild(t, stepByAction(t, index[string(chatloop.StageGenerationStep)], "execute_local_tools"), turn)
|
|
})
|
|
|
|
t.Run("MCPConnectFailure", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
mcpTS := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
}))
|
|
t.Cleanup(mcpTS.Close)
|
|
h := newHarness(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
return textResponse()
|
|
})
|
|
mcpConfig := dbgen.MCPServerConfig(t, h.db, database.MCPServerConfig{
|
|
OrganizationID: h.org.ID,
|
|
DisplayName: "Broken MCP",
|
|
Slug: "broken-mcp",
|
|
Url: mcpTS.URL,
|
|
CreatedBy: uuid.NullUUID{UUID: h.user.ID, Valid: true},
|
|
UpdatedBy: uuid.NullUUID{UUID: h.user.ID, Valid: true},
|
|
})
|
|
chat, err := h.server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: h.org.ID,
|
|
OwnerID: h.user.ID,
|
|
Title: "mcp-connect-failure",
|
|
ModelConfigID: h.model.ID,
|
|
MCPServerIDs: []uuid.UUID{mcpConfig.ID},
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 1)
|
|
|
|
// Generation continues without the failed server.
|
|
connects := index[string(chatloop.StageMCPConnect)]
|
|
require.NotEmpty(t, connects)
|
|
prepares := index[string(chatloop.StagePrepare)]
|
|
for _, connect := range connects {
|
|
require.Equal(t, codes.Error, connect.Status().Code)
|
|
require.Contains(t, connect.Status().Description, "broken-mcp")
|
|
require.Equal(t, "0", spanAttr(t, connect, chatloop.AttrMCPServersConnected))
|
|
require.Equal(t, "1", spanAttr(t, connect, chatloop.AttrMCPServersFailed))
|
|
require.True(t, slices.ContainsFunc(prepares, func(prepare sdktrace.ReadOnlySpan) bool {
|
|
return prepare.SpanContext().SpanID() == connect.Parent().SpanID()
|
|
}), "mcp_connect runs inside prepare")
|
|
}
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, single(t, index, chatloop.StageChatTurn), chatloop.AttrTurnOutcome))
|
|
})
|
|
|
|
t.Run("QueuedMessagePromotedByFinishTurn", func(t *testing.T) {
|
|
t.Parallel()
|
|
// The stop hook routes the finish through the hook-aware path.
|
|
for _, stopHook := range []bool{false, true} {
|
|
t.Run(fmt.Sprintf("StopHook=%t", stopHook), func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
var stopCalls atomic.Int32
|
|
var overrides []func(*chatd.Config)
|
|
if stopHook {
|
|
consumer := stopConsumer(t, func() (int, string) {
|
|
stopCalls.Add(1)
|
|
return http.StatusOK, `{}`
|
|
})
|
|
overrides = append(overrides, func(cfg *chatd.Config) {
|
|
cfg.HookDispatcher = newHookDispatcher(t, nil, consumer)
|
|
})
|
|
}
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
h := newHarness(t, blockFirstStream(started, release, textResponse()), overrides...)
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
sent, err := h.server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("next")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
close(release)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
if stopHook {
|
|
require.GreaterOrEqual(t, stopCalls.Load(), int32(2))
|
|
}
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
requireStandaloneQueueWait(t, index, sent.QueuedMessage.CreatedAt)
|
|
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[1].StartTime().UTC())
|
|
require.NotEqual(t, turns[0].SpanContext().TraceID(), turns[1].SpanContext().TraceID())
|
|
for _, turn := range turns {
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
requireChild(t, childOf(t, index, chatloop.StageAcquisition, turn), turn)
|
|
}
|
|
})
|
|
}
|
|
})
|
|
|
|
t.Run("QueuedMessagePromotedByInterrupt", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
h := newHarness(t, blockFirstStream(started, release, textResponse()))
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
sent, err := h.server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("stop and do this")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorSteer,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
_, _, err = h.server.InterruptChat(ctx, chat)
|
|
require.NoError(t, err)
|
|
close(release)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
requireStandaloneQueueWait(t, index, sent.QueuedMessage.CreatedAt)
|
|
requireInterrupted(t, turns[0])
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turns[1], chatloop.AttrTurnOutcome))
|
|
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[1].StartTime().UTC())
|
|
})
|
|
|
|
t.Run("SteerMessageDeliveredBeforeModelCall", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
toolCall := chattest.OpenAIStreamingResponse(chattest.OpenAIToolCallChunk("list_templates", `{}`))
|
|
h := newHarness(t, blockFirstStream(started, release, toolCall))
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
sent, err := h.server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("next")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorSteer,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
close(release)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
requireStandaloneQueueWait(t, index, sent.QueuedMessage.CreatedAt)
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turns[1], chatloop.AttrTurnOutcome))
|
|
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[1].StartTime().UTC())
|
|
})
|
|
|
|
// Send now moves the message to the steer lane without interrupting,
|
|
// so the running turn completes and then delivers it.
|
|
t.Run("PromoteQueuedWhileRunning", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
h := newHarness(t, blockFirstStream(started, release, textResponse()))
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
sent, err := h.server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("next")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
err = h.server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
|
ChatID: chat.ID,
|
|
QueuedMessageID: sent.QueuedMessage.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
close(release)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
requireStandaloneQueueWait(t, index, sent.QueuedMessage.CreatedAt)
|
|
for _, turn := range turns {
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
}
|
|
})
|
|
|
|
t.Run("EditAbandonsTurn", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
defer close(release)
|
|
h := newHarness(t, blockFirstStream(started, release, textResponse()))
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
_, err := h.server.EditMessage(ctx, chatd.EditMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
EditedMessageID: lastUserMessage(ctx, t, h.db, chat.ID).ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("edited")},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
require.Equal(t, string(chatloop.TurnOutcomeAbandoned), spanAttr(t, turns[0], chatloop.AttrTurnOutcome))
|
|
require.Equal(t, codes.Unset, turns[0].Status().Code)
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turns[1], chatloop.AttrTurnOutcome))
|
|
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[1].StartTime().UTC())
|
|
})
|
|
|
|
t.Run("ShutdownAbandonsTurn", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
defer close(release)
|
|
h := newHarness(t, blockFirstStream(started, release, textResponse()))
|
|
createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
require.NoError(t, h.server.Close())
|
|
index := waitForTurns(ctx, t, h.recorder, 1)
|
|
|
|
turn := single(t, index, chatloop.StageChatTurn)
|
|
require.Equal(t, string(chatloop.TurnOutcomeAbandoned), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
require.Equal(t, codes.Unset, turn.Status().Code)
|
|
})
|
|
|
|
failWithQueuedMessage := func(ctx context.Context, t *testing.T) (harness, database.Chat, database.ChatQueuedMessage) {
|
|
t.Helper()
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
h := newHarness(t, blockFirstStream(started, release,
|
|
chattest.OpenAIErrorResponse(http.StatusBadRequest, "invalid_request_error", "synthetic failure")))
|
|
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
|
testutil.TryReceive(ctx, t, started)
|
|
sent, err := h.server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("queued")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
close(release)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusError)
|
|
waitForTurns(ctx, t, h.recorder, 1)
|
|
return h, chat, *sent.QueuedMessage
|
|
}
|
|
|
|
t.Run("PromoteQueuedFromError", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
h, chat, queued := failWithQueuedMessage(ctx, t)
|
|
|
|
err := h.server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
|
ChatID: chat.ID,
|
|
QueuedMessageID: queued.ID,
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
requireStandaloneQueueWait(t, index, queued.CreatedAt)
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[1].StartTime().UTC())
|
|
})
|
|
|
|
t.Run("SendFromErrorPromotesQueueHead", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
h, chat, queued := failWithQueuedMessage(ctx, t)
|
|
|
|
// The send promotes the head and queues its own message, which the
|
|
// finishing turn then promotes.
|
|
sent, err := h.server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: h.user.ID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("retry")},
|
|
BusyBehavior: chatd.SendMessageBusyBehaviorQueue,
|
|
})
|
|
require.NoError(t, err)
|
|
require.True(t, sent.Queued)
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 3)
|
|
|
|
queueWaits := index[string(chatloop.StageQueueWait)]
|
|
require.Len(t, queueWaits, 2)
|
|
starts := []time.Time{queueWaits[0].StartTime().UTC(), queueWaits[1].StartTime().UTC()}
|
|
require.Contains(t, starts, queued.CreatedAt.UTC())
|
|
require.Contains(t, starts, sent.QueuedMessage.CreatedAt.UTC())
|
|
for _, queueWait := range queueWaits {
|
|
require.False(t, queueWait.Parent().IsValid(), "queue_wait is a trace root")
|
|
}
|
|
})
|
|
|
|
t.Run("RequiresActionEndsTurn", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
var calls atomic.Int32
|
|
h := newHarness(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
return chattest.OpenAIStreamingResponse(chattest.OpenAIToolCallChunk("my_dynamic_tool", `{"query":"test"}`))
|
|
}
|
|
return textResponse()
|
|
})
|
|
chat, err := h.server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: h.org.ID,
|
|
OwnerID: h.user.ID,
|
|
Title: "requires-action-trace",
|
|
ModelConfigID: h.model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("call the dynamic tool")},
|
|
DynamicTools: dynamicToolJSON(t, "my_dynamic_tool"),
|
|
})
|
|
require.NoError(t, err)
|
|
var waiting database.Chat
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
got, err := h.db.GetChatByID(ctx, chat.ID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
waiting = got
|
|
return got.Status == database.ChatStatusRequiresAction
|
|
}, testutil.IntervalFast)
|
|
waitForTurns(ctx, t, h.recorder, 1)
|
|
|
|
call := requireToolCallPart(t, chatToolParts(ctx, t, h.db, chat.ID), "my_dynamic_tool")
|
|
require.NoError(t, h.server.SubmitToolResults(ctx, chatd.SubmitToolResultsOptions{
|
|
ChatID: chat.ID,
|
|
UserID: h.user.ID,
|
|
ModelConfigID: waiting.LastModelConfigID,
|
|
Results: []codersdk.ToolResult{{ToolCallID: call.ToolCallID, Output: json.RawMessage(`{"ok":true}`)}},
|
|
}))
|
|
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
|
index := waitForTurns(ctx, t, h.recorder, 2)
|
|
|
|
var submittedAt time.Time
|
|
for _, msg := range chatMessages(ctx, t, h.db, chat.ID) {
|
|
if msg.Role == database.ChatMessageRoleTool {
|
|
submittedAt = msg.CreatedAt
|
|
}
|
|
}
|
|
require.False(t, submittedAt.IsZero())
|
|
turns := index[string(chatloop.StageChatTurn)]
|
|
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[0].StartTime().UTC())
|
|
require.Equal(t, submittedAt.UTC(), turns[1].StartTime().UTC())
|
|
stepByAction(t, childrenOf(index, chatloop.StageGenerationStep, turns[0]), "enter_requires_action")
|
|
for _, turn := range turns {
|
|
require.Equal(t, string(chatloop.TurnOutcomeCompleted), spanAttr(t, turn, chatloop.AttrTurnOutcome))
|
|
acquisition := childOf(t, index, chatloop.StageAcquisition, turn)
|
|
require.Equal(t, turn.StartTime(), acquisition.StartTime())
|
|
}
|
|
})
|
|
}
|