mirror of
https://github.com/coder/coder.git
synced 2026-11-02 05:23:10 +08:00
## Summary Move chat model management and runtime availability to organization-scoped API routes. The API now identifies the organization in every model-management operation, applies chat model RBAC and ACLs within that organization, and returns only models the caller can use there. Depends on #27958. ## Problem Chat model configurations now belong to organizations, but the existing experimental management and discovery APIs are deployment-shaped. Their routes do not identify an organization, SDK methods do not accept an organization ID, and item operations address a model configuration by ID alone. That contract cannot safely expose organization-owned model configurations. It also does not provide the organization-specific provider information, authorization behavior, ACL management, or recovery guidance needed by the settings and chat clients later in the stack. ## Fix Add organization-scoped chat model endpoints under: ```text /api/experimental/organizations/{organization}/chats/models ``` The new API provides: - Organization-scoped model listing and creation. - Model get, update, and delete operations scoped by both organization and model ID. - Model ACL read and update operations. - Organization-scoped runtime availability and provider status. - Redacted provider descriptors for model-management clients. - Chat model RBAC and row ACL enforcement for writes, runtime discovery, and Chatd model selection. - Recovery guidance when a chat's organization has no usable local model. Historical chats can retain a model reference owned by another organization, but runtime selection uses an authorized local default when one is available. Foreign, inaccessible, disabled, and otherwise unusable models are not exposed as usable selections for the organization. The existing collection and availability routes remain as default-organization compatibility endpoints in this layer: ```text GET /api/experimental/chats/model-configs POST /api/experimental/chats/model-configs GET /api/experimental/chats/models ``` These compatibility routes do not provide access to models in non-default organizations. The previous unscoped item update and delete routes are removed because item operations must include the owning organization. ## Breaking change This changes the experimental HTTP API and Go SDK contracts for chat model management. Clients must migrate model-management and availability requests to the organization-scoped routes and provide an organization identifier. In the Go SDK, the following methods now require an organization ID: - `ChatModelAvailability` - `ChatModels` - `CreateChatModel` - `UpdateChatModel` - `DeleteChatModel` `ChatModels` also changes its return value from `[]ChatModel` to `OrganizationChatModelsResponse`, which includes the organization models and the redacted provider descriptors required by management clients. New item and ACL methods likewise require both the organization ID and model ID. The default-organization compatibility routes reduce the immediate impact for collection and availability callers, but they do not preserve the previous item API or SDK method signatures. Generated clients and direct consumers of the experimental API must be updated before adopting this change. _This pull request description was generated by Coder Agents._
143 lines
4.3 KiB
Go
143 lines
4.3 KiB
Go
//go:build !slim
|
|
|
|
package cli_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"io"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"cdr.dev/slog/v3/sloggers/sloghuman"
|
|
"github.com/coder/coder/v2/cli/clitest"
|
|
"github.com/coder/coder/v2/coderd/aibridgedtest"
|
|
"github.com/coder/coder/v2/coderd/coderdtest"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/scaletest/llmmock"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
const scaletestChatPrompt = "Reply with one short sentence from the scaletest."
|
|
|
|
func TestScaleTestChat(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
values := coderdtest.DeploymentValues(t, func(dv *codersdk.DeploymentValues) {
|
|
require.NoError(t, dv.AI.BridgeConfig.Enabled.Set("true"))
|
|
})
|
|
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
|
|
DeploymentValues: values,
|
|
})
|
|
aibridgedtest.StartTestAIBridgeDaemon(t.Context(), t, api, nil)
|
|
coderdtest.CreateFirstUser(t, client)
|
|
|
|
server := new(llmmock.Server)
|
|
require.NoError(t, server.Start(context.Background(), llmmock.Config{
|
|
Address: "127.0.0.1:0",
|
|
Logger: slog.Make(sloghuman.Sink(io.Discard)).Leveled(slog.LevelDebug),
|
|
}))
|
|
t.Cleanup(func() {
|
|
require.NoError(t, server.Stop())
|
|
})
|
|
mockURL := server.APIAddress() + "/v1"
|
|
|
|
inv, root := clitest.New(t,
|
|
"exp", "scaletest", "chat",
|
|
"--chats-per-workspace", "1",
|
|
"--turns", "1",
|
|
"--prompt", scaletestChatPrompt,
|
|
"--timeout", "30s",
|
|
"--job-timeout", "30s",
|
|
"--cleanup-timeout", "30s",
|
|
"--cleanup-job-timeout", "30s",
|
|
"--scaletest-prometheus-address", "127.0.0.1:0",
|
|
"--scaletest-prometheus-wait", "0s",
|
|
"--provider-propagation-wait", "10ms",
|
|
"--llm-mock-url", mockURL,
|
|
)
|
|
//nolint:gocritic // The scaletest chat command requires an admin client.
|
|
clitest.SetupConfig(t, client, root)
|
|
|
|
var stderr bytes.Buffer
|
|
inv.Stdout = io.Discard
|
|
inv.Stderr = &stderr
|
|
|
|
err := inv.WithContext(ctx).Run()
|
|
require.NoError(t, err, stderr.String())
|
|
require.Contains(t, stderr.String(), "Scale test passed: 1/1 runs succeeded")
|
|
|
|
provider, err := client.AIProvider(ctx, "coder-scaletest-mock")
|
|
require.NoError(t, err)
|
|
require.Equal(t, mockURL, provider.BaseURL)
|
|
|
|
expClient := codersdk.NewExperimentalClient(client)
|
|
defaultOrg, err := client.OrganizationByName(ctx, codersdk.DefaultOrganization)
|
|
require.NoError(t, err)
|
|
configs, err := expClient.ChatModels(ctx, defaultOrg.ID)
|
|
require.NoError(t, err)
|
|
matchingConfigs := scaletestModelConfigsForProvider(configs.Models, provider.ID)
|
|
require.Len(t, matchingConfigs, 1)
|
|
require.True(t, matchingConfigs[0].Enabled)
|
|
|
|
chats, err := expClient.ListChats(ctx, &codersdk.ListChatsOptions{Query: "archived:true"})
|
|
require.NoError(t, err)
|
|
|
|
var scaletestMessages []codersdk.ChatMessage
|
|
for _, chat := range chats {
|
|
resp, err := expClient.GetChatMessages(ctx, chat.ID, nil)
|
|
require.NoError(t, err)
|
|
if userText, ok := chatMessageText(resp.Messages, codersdk.ChatMessageRoleUser); ok &&
|
|
strings.Contains(userText, scaletestChatPrompt) {
|
|
scaletestMessages = resp.Messages
|
|
break
|
|
}
|
|
}
|
|
require.NotEmpty(t, scaletestMessages)
|
|
assistantText, ok := chatMessageText(scaletestMessages, codersdk.ChatMessageRoleAssistant)
|
|
require.True(t, ok, "expected an assistant reply in the scaletest chat")
|
|
require.NotEmpty(t, assistantText)
|
|
}
|
|
|
|
// chatMessageText concatenates the text parts of every message with the given
|
|
// role, reporting whether any such message was found. It aggregates across
|
|
// messages because the API returns them newest-first and a turn can produce
|
|
// more than one message per role.
|
|
func chatMessageText(messages []codersdk.ChatMessage, role codersdk.ChatMessageRole) (string, bool) {
|
|
var (
|
|
b strings.Builder
|
|
found bool
|
|
)
|
|
for _, msg := range messages {
|
|
if msg.Role != role {
|
|
continue
|
|
}
|
|
found = true
|
|
for _, part := range msg.Content {
|
|
if part.Type == codersdk.ChatMessagePartTypeText {
|
|
_, _ = b.WriteString(part.Text)
|
|
}
|
|
}
|
|
}
|
|
return b.String(), found
|
|
}
|
|
|
|
func scaletestModelConfigsForProvider(configs []codersdk.ChatModel, providerID uuid.UUID) []codersdk.ChatModel {
|
|
matches := make([]codersdk.ChatModel, 0, 1)
|
|
for _, config := range configs {
|
|
if config.AIProviderID != providerID {
|
|
continue
|
|
}
|
|
if config.Model != "scaletest-model" {
|
|
continue
|
|
}
|
|
matches = append(matches, config)
|
|
}
|
|
return matches
|
|
}
|