diff --git a/coderd/x/chatd/ARCHITECTURE.md b/coderd/x/chatd/ARCHITECTURE.md index 404646ca3d0..d7f5d3870d1 100644 --- a/coderd/x/chatd/ARCHITECTURE.md +++ b/coderd/x/chatd/ARCHITECTURE.md @@ -862,7 +862,7 @@ A chat worker is identified by a **worker ID**, which is regenerated on worker s A chat may use model configs only from its own organization. Chat creation, message sends, and message edits reject an explicit config that is disabled, unavailable to the caller, or belongs to another organization. -Queued-message promotion revalidates the stored model with daemon authorization. It keeps the model when the model and its provider are enabled and the model belongs to the chat's organization. Worker generation preparation revalidates with the chat owner's authorization context, so it also requires the model to remain readable by the owner. When those checks make the stored model unavailable, the path selects that organization's enabled default. If no local default is available, processing fails with `ErrNoDefaultChatModelConfig`; it never falls back to another organization's model. +Queued-message promotion revalidates the stored model with daemon authorization. It keeps the model when the model and its provider are enabled and the model belongs to the chat's organization. Worker generation preparation revalidates with the chat owner's authorization context, so it also requires the model to remain readable by the owner. When the queued row's model fails promotion's checks, promotion uses the chat's last model if that model passes the same checks, and otherwise the organization's enabled default. When the chat's last model fails generation preparation's checks, generation preparation selects the organization's enabled default. If no local default is available, processing fails with `ErrNoDefaultChatModelConfig`; it never falls back to another organization's model. ## Acquisition loop diff --git a/coderd/x/chatd/chatd_test.go b/coderd/x/chatd/chatd_test.go index f44d5ce4599..fec51a18c57 100644 --- a/coderd/x/chatd/chatd_test.go +++ b/coderd/x/chatd/chatd_test.go @@ -13614,9 +13614,14 @@ func TestQueuedCompletionResolvesOrganizationModel(t *testing.T) { 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, localDefault.ID, "first") + 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) @@ -13667,9 +13672,14 @@ func TestQueuedCompletionResolvesOrganizationModel(t *testing.T) { 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, localDefault.ID, "first") + 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) @@ -13708,7 +13718,7 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) { chat := dbgen.Chat(t, db, database.Chat{ OrganizationID: org.ID, OwnerID: user.ID, - LastModelConfigID: localDefault.ID, + LastModelConfigID: foreignModel.ID, Title: "resolve explicit queued promotion", Status: database.ChatStatusError, }) @@ -13734,7 +13744,7 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) { chat := dbgen.Chat(t, db, database.Chat{ OrganizationID: org.ID, OwnerID: user.ID, - LastModelConfigID: localDefault.ID, + LastModelConfigID: foreignModel.ID, Title: "resolve error send promotion", Status: database.ChatStatusError, }) @@ -13785,6 +13795,22 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) { }) } +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, diff --git a/coderd/x/chatd/chatstate/transitions.go b/coderd/x/chatd/chatstate/transitions.go index 56e088bc2c4..52b49fba97d 100644 --- a/coderd/x/chatd/chatstate/transitions.go +++ b/coderd/x/chatd/chatstate/transitions.go @@ -429,21 +429,33 @@ func (tx *Tx) deletePromotedQueuedMessage(id int64) error { return nil } +// resolveQueuedMessageModelConfigID returns the first of the queued row's +// model and the chat's last model that is enabled, has an enabled +// provider, and belongs to the chat's organization, else the organization +// default. A lookup error other than sql.ErrNoRows is returned without +// trying the next candidate. func (tx *Tx) resolveQueuedMessageModelConfigID( chat database.Chat, queued database.ChatQueuedMessage, ) (uuid.NullUUID, error) { //nolint:gocritic // Queue promotion needs daemon access to deployment model configuration. ctx := dbauthz.AsChatd(tx.ctx) - if queued.ModelConfigID.Valid { - config, err := tx.store.GetEnabledChatModelConfigByID(ctx, queued.ModelConfigID.UUID) + candidates := []uuid.NullUUID{ + queued.ModelConfigID, + {UUID: chat.LastModelConfigID, Valid: true}, + } + for _, candidate := range candidates { + if !candidate.Valid { + continue + } + config, err := tx.store.GetEnabledChatModelConfigByID(ctx, candidate.UUID) if err == nil && config.OrganizationID == chat.OrganizationID { - return queued.ModelConfigID, nil + return candidate, nil } if err != nil && !errors.Is(err, sql.ErrNoRows) { return uuid.NullUUID{}, xerrors.Errorf( "get chat model config %s: %w", - queued.ModelConfigID.UUID, + candidate.UUID, err, ) } diff --git a/coderd/x/chatd/chatstate/transitions_test.go b/coderd/x/chatd/chatstate/transitions_test.go index 1b691d82beb..61800f90508 100644 --- a/coderd/x/chatd/chatstate/transitions_test.go +++ b/coderd/x/chatd/chatstate/transitions_test.go @@ -175,7 +175,7 @@ func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) { localModel := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{ OrganizationID: f.Org.ID, }) - promoted := steerQueuedMessageWithModel(t, f, localModel.ID) + promoted := steerQueuedMessageWithModel(t, f, f.Model.ID, localModel.ID) require.Equal(t, localModel.ID, promoted.ModelConfigID.UUID) }) @@ -187,14 +187,19 @@ func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) { OrganizationID: foreignOrg.ID, IsDefault: true, }) - promoted := steerQueuedMessageWithModel(t, f, foreignModel.ID) + promoted := steerQueuedMessageWithModel(t, f, foreignModel.ID, foreignModel.ID) require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID) }) t.Run("missing model falls back to local default", func(t *testing.T) { t.Parallel() f := newTestFixture(t) - promoted := steerQueuedMessageWithModel(t, f, uuid.New()) + deleted := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{ + OrganizationID: f.Org.ID, + }) + _, err := f.DB.DeleteChatModelConfigByID(context.Background(), deleted.ID) + require.NoError(t, err) + promoted := steerQueuedMessageWithModel(t, f, deleted.ID, uuid.New()) require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID) }) @@ -205,10 +210,24 @@ func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) { OrganizationID: f.Org.ID, }) setChatModelConfigEnabled(t, f.DB, disabled, false) - promoted := steerQueuedMessageWithModel(t, f, disabled.ID) + promoted := steerQueuedMessageWithModel(t, f, disabled.ID, disabled.ID) require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID) }) + t.Run("disabled model falls back to chat model", func(t *testing.T) { + t.Parallel() + f := newTestFixture(t) + chatModel := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{ + OrganizationID: f.Org.ID, + }) + disabled := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{ + OrganizationID: f.Org.ID, + }) + setChatModelConfigEnabled(t, f.DB, disabled, false) + promoted := steerQueuedMessageWithModel(t, f, chatModel.ID, disabled.ID) + require.Equal(t, chatModel.ID, promoted.ModelConfigID.UUID) + }) + t.Run("missing local default rejects promotion", func(t *testing.T) { t.Parallel() f := newTestFixture(t) @@ -390,12 +409,18 @@ func (s *modelConfigErrorStore) GetEnabledChatModelConfigByID( func steerQueuedMessageWithModel( t *testing.T, f *testFixture, - modelConfigID uuid.UUID, + chatModelConfigID uuid.UUID, + queuedModelConfigID uuid.UUID, ) database.ChatMessage { t.Helper() ctx := testutil.Context(t, testutil.WaitShort) created := createTestChat(t, f) - message := userTextMessage("queued model resolution", f.User.ID, modelConfigID) + _, err := f.DB.UpdateChatLastModelConfigByID(ctx, database.UpdateChatLastModelConfigByIDParams{ + ID: created.Chat.ID, + LastModelConfigID: chatModelConfigID, + }) + require.NoError(t, err) + message := userTextMessage("queued model resolution", f.User.ID, queuedModelConfigID) queued, err := f.DB.InsertChatQueuedMessage(ctx, database.InsertChatQueuedMessageParams{ ChatID: created.Chat.ID, Content: message.Content.RawMessage, diff --git a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.test.tsx b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.test.tsx index 1f5e06258a9..6832223c848 100644 --- a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.test.tsx +++ b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.test.tsx @@ -343,50 +343,71 @@ describe("AgentChatPage", () => { // The row was queued with another model than the one the picker shows. it.each([ - ["keeps the row's model when the picker is untouched", undefined], - ["sends the model picked during the edit", "model-c"], - ])("saving a queued edit %s", async (_name, pickedModel) => { - const page = renderQueuedChat({ - queuedMessages: [{ ...row, model_config_id: "model-b" }], - models: [ - { - ...MockChatModel, - id: MockChat.last_model_config_id, - display_name: "Model A", - }, - { ...MockChatModel, id: "model-b", display_name: "Model B" }, - { ...MockChatModel, id: "model-c", display_name: "Model C" }, - ], - }); - await page.rowAction("Edit"); - await waitFor(() => - expect(page.composer().textContent).toBe("queued text"), - ); - if (pickedModel) { - await page.user.click( - screen.getByRole("combobox", { name: "Model A" }), + [ + "keeps the row's model when the picker is untouched", + "model-b", + undefined, + undefined, + ], + [ + "sends the model picked during the edit", + "model-b", + "Model C", + "model-c", + ], + [ + "sends the picker's model when the row's model is no longer available", + "model-deleted", + undefined, + MockChat.last_model_config_id, + ], + ])( + "saving a queued edit %s", + async (_name, rowModel, pickModelName, wantModelConfigID) => { + const page = renderQueuedChat({ + queuedMessages: [{ ...row, model_config_id: rowModel }], + models: [ + { + ...MockChatModel, + id: MockChat.last_model_config_id, + display_name: "Model A", + }, + { ...MockChatModel, id: "model-b", display_name: "Model B" }, + { ...MockChatModel, id: "model-c", display_name: "Model C" }, + ], + }); + await page.rowAction("Edit"); + await waitFor(() => + expect(page.composer().textContent).toBe("queued text"), ); + if (pickModelName) { + await page.user.click( + screen.getByRole("combobox", { name: "Model A" }), + ); + await page.user.click( + within(await screen.findByRole("listbox")).getByRole("option", { + name: new RegExp(pickModelName), + }), + ); + } + await page.type(" edit"); await page.user.click( - within(await screen.findByRole("listbox")).getByRole("option", { - name: /Model C/, - }), + screen.getByRole("button", { name: "Save Edit" }), ); - } - await page.type(" edit"); - await page.user.click(screen.getByRole("button", { name: "Save Edit" })); - await waitFor(() => - expect(page.editChatQueuedMessage).toHaveBeenCalledWith( - MockChat.id, - row.id, - expect.objectContaining({ - content: expect.anything(), - model_config_id: pickedModel, - }), - ), - ); - expect(localStorage.getItem(savedEditKey)).toBeNull(); - }); + await waitFor(() => + expect(page.editChatQueuedMessage).toHaveBeenCalledWith( + MockChat.id, + row.id, + expect.objectContaining({ + content: expect.anything(), + model_config_id: wantModelConfigID, + }), + ), + ); + expect(localStorage.getItem(savedEditKey)).toBeNull(); + }, + ); // react-query delivers the failed request's state to the page on a // scheduler it owns, which may run before the request's own error diff --git a/site/src/pages/AgentsPage/components/ChatConversation/submitChatTurn.ts b/site/src/pages/AgentsPage/components/ChatConversation/submitChatTurn.ts index 814521e06a1..744f58a42b2 100644 --- a/site/src/pages/AgentsPage/components/ChatConversation/submitChatTurn.ts +++ b/site/src/pages/AgentsPage/components/ChatConversation/submitChatTurn.ts @@ -356,14 +356,20 @@ export async function submitChatTurn( if (editingTarget?.kind === "queued") { const queuedMessageID = editingTarget.id; + const queuedRow = store + .getSnapshot() + .queuedMessages.find((row) => row.id === queuedMessageID); // A queued row keeps its model and effort unless the user changes // them during this edit; the picker otherwise shows the chat's model, - // not the row's. + // not the row's. A row whose model is no longer selectable takes the + // picker's model, as a history edit does. const request: TypesGen.EditChatQueuedMessageRequest = { content, - model_config_id: isEditModelDirtyRef.current - ? effectiveSelectedModel || undefined - : undefined, + model_config_id: + isEditModelDirtyRef.current || + isUnavailableHistoricalModelID(queuedRow?.model_config_id, modelOptions) + ? effectiveSelectedModel || undefined + : undefined, reasoning_effort: isEditReasoningEffortDirtyRef.current ? effectiveReasoningEffort : undefined,