feat: move a chat family between projects in chatd (#30893)
chatd can now move a root chat, together with its subagent chats, into a project, to another project, or out of its project. Nothing calls this yet. #30894 adds the API. **Stack** (moving chats between projects, bottom first): 1. **This PR**: the move in chatd 2. #30894: `PATCH /api/v2/chats/{chat}` takes `project_id` 3. #30895: **Move to project** in the chat menu 4. #30795: drag a chat onto a project folder in the sidebar **Why:** today a chat keeps the project it was created with. A move must follow the family rules of archiving, because a step that runs during a move would still have the memory tools of the old project. - `chatstate.Tx.SetProject` runs only from W, E0 and E1, like `SetArchived`. `SetFamilyProject()` locks the root row before its subagents, in the same order as archiving, so a busy family gets `ErrTransitionNotAllowed` and nothing changes. - A move to the project the chat is already in changes nothing, even while the chat runs. The check reads the locked root row, so it waits for a move that is still in flight. - Only the root row stores `project_id`, and subagents use the project of the root. After the commit, chatd publishes a new `project_change` watch event for each chat of the family. The move keeps `updated_at`, so lists keep their order. - A root chat outside a project now has an empty memory index. When a chat leaves its project, or its project is deleted, its next turn start commits one memory index update that removes the memories the model saw there. **What to scrutinize:** the lock order and the same-project check under the lock in `SetFamilyProject()` (`chatstate/family.go`), the turn-start condition in `memoryIndexMessage()` (`memory.go`), and whether the `ARCHITECTURE.md` text matches them. **Generated** (`make gen`): `queries.sql.go`, `querier.go`, `dbmock` and `dbmetrics` come from `queries/chats.sql`. `coderd/apidoc`, `docs/reference/api/schemas.md` and `typesGenerated.ts` come from the new watch event kind, which is also why two `chats.test.ts` fixtures gain `project_change: false`. **Architecture doc:** `coderd/x/chatd/ARCHITECTURE.md` lists `SetProject` among the transitions and in the execution state diagram (W, E0 and E1 back to themselves). It also says that a root chat's project can change after creation, and that a moved chat's next turn starts with a memory index update from the old project to the new one. ## Testing - `make pre-commit` passes. `go test` passes for `coderd/x/chatd/chatstate`, `coderd/database/dbauthz` (`TestMethodTestSuite`) and the chatd memory tests. - `TestSetFamilyProjectLocksRootFirst` fails with 55P03 when a subagent row is locked first. `TestSetFamilyProjectKeepsTheCurrentProject` covers the same-project move during a run. The transition matrix test gains `SetProject` cases for W, E0 and E1. - `TestMovedChatUsesNewProject` runs two real turns around a move: the second turn uses the instructions and memories of the new project, and `OutOfProject` fails without the memory index removal. > Xum opened this PR on behalf of @ibetitsmike.
This commit is contained in:
1 parent
6ebefb8325
commit
0968f97a43
25 files changed
+575
-31
No files matched your search
Generated
+4
-2
@@ -23670,7 +23670,8 @@ const docTemplate = `{
|
||||
"deleted",
|
||||
"diff_status_change",
|
||||
"action_required",
|
||||
"context_dirty"
|
||||
"context_dirty",
|
||||
"project_change"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"ChatWatchEventKindStatusChange",
|
||||
@@ -23681,7 +23682,8 @@ const docTemplate = `{
|
||||
"ChatWatchEventKindDeleted",
|
||||
"ChatWatchEventKindDiffStatusChange",
|
||||
"ChatWatchEventKindActionRequired",
|
||||
"ChatWatchEventKindContextDirty"
|
||||
"ChatWatchEventKindContextDirty",
|
||||
"ChatWatchEventKindProjectChange"
|
||||
]
|
||||
},
|
||||
"codersdk.ChatWorkspaceTTLResponse": {
|
||||
|
||||
Generated
+4
-2
@@ -21471,7 +21471,8 @@
|
||||
"deleted",
|
||||
"diff_status_change",
|
||||
"action_required",
|
||||
"context_dirty"
|
||||
"context_dirty",
|
||||
"project_change"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"ChatWatchEventKindStatusChange",
|
||||
@@ -21482,7 +21483,8 @@
|
||||
"ChatWatchEventKindDeleted",
|
||||
"ChatWatchEventKindDiffStatusChange",
|
||||
"ChatWatchEventKindActionRequired",
|
||||
"ChatWatchEventKindContextDirty"
|
||||
"ChatWatchEventKindContextDirty",
|
||||
"ChatWatchEventKindProjectChange"
|
||||
]
|
||||
},
|
||||
"codersdk.ChatWorkspaceTTLResponse": {
|
||||
|
||||
@@ -8052,6 +8052,17 @@ func (q *querier) UpdateChatProjectByID(ctx context.Context, arg database.Update
|
||||
}, q.db.UpdateChatProjectByID)(ctx, arg)
|
||||
}
|
||||
|
||||
func (q *querier) UpdateChatProjectIDByID(ctx context.Context, arg database.UpdateChatProjectIDByIDParams) error {
|
||||
chat, err := q.db.GetChatByID(ctx, arg.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.authorizeContext(ctx, policy.ActionUpdate, chat); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.db.UpdateChatProjectIDByID(ctx, arg)
|
||||
}
|
||||
|
||||
func (q *querier) UpdateChatRetryState(ctx context.Context, arg database.UpdateChatRetryStateParams) (database.Chat, error) {
|
||||
// UpdateChatRetryState is used by the chat processor to publish
|
||||
// transient retry state. It should be called with system context.
|
||||
|
||||
@@ -1962,6 +1962,16 @@ func (s *MethodTestSuite) TestChats() {
|
||||
dbm.EXPECT().UpdateChatPinOrder(gomock.Any(), arg).Return(nil).AnyTimes()
|
||||
check.Args(arg).Asserts(chat, policy.ActionUpdate).Returns()
|
||||
}))
|
||||
s.Run("UpdateChatProjectIDByID", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
chat := testutil.Fake(s.T(), faker, database.Chat{})
|
||||
arg := database.UpdateChatProjectIDByIDParams{
|
||||
ID: chat.ID,
|
||||
ProjectID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
|
||||
}
|
||||
dbm.EXPECT().GetChatByID(gomock.Any(), chat.ID).Return(chat, nil).AnyTimes()
|
||||
dbm.EXPECT().UpdateChatProjectIDByID(gomock.Any(), arg).Return(nil).AnyTimes()
|
||||
check.Args(arg).Asserts(chat, policy.ActionUpdate).Returns()
|
||||
}))
|
||||
s.Run("UpdateChatStatus", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
chat := testutil.Fake(s.T(), faker, database.Chat{})
|
||||
arg := database.UpdateChatStatusParams{
|
||||
|
||||
+8
@@ -5745,6 +5745,14 @@ func (m queryMetricsStore) UpdateChatProjectByID(ctx context.Context, arg databa
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) UpdateChatProjectIDByID(ctx context.Context, arg database.UpdateChatProjectIDByIDParams) error {
|
||||
start := time.Now()
|
||||
r0 := m.s.UpdateChatProjectIDByID(ctx, arg)
|
||||
m.queryLatencies.WithLabelValues("UpdateChatProjectIDByID").Observe(time.Since(start).Seconds())
|
||||
m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "UpdateChatProjectIDByID").Inc()
|
||||
return r0
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) UpdateChatRetryState(ctx context.Context, arg database.UpdateChatRetryStateParams) (database.Chat, error) {
|
||||
start := time.Now()
|
||||
r0, r1 := m.s.UpdateChatRetryState(ctx, arg)
|
||||
|
||||
Generated
+14
@@ -10888,6 +10888,20 @@ func (mr *MockStoreMockRecorder) UpdateChatProjectByID(ctx, arg any) *gomock.Cal
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateChatProjectByID", reflect.TypeOf((*MockStore)(nil).UpdateChatProjectByID), ctx, arg)
|
||||
}
|
||||
|
||||
// UpdateChatProjectIDByID mocks base method.
|
||||
func (m *MockStore) UpdateChatProjectIDByID(ctx context.Context, arg database.UpdateChatProjectIDByIDParams) error {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "UpdateChatProjectIDByID", ctx, arg)
|
||||
ret0, _ := ret[0].(error)
|
||||
return ret0
|
||||
}
|
||||
|
||||
// UpdateChatProjectIDByID indicates an expected call of UpdateChatProjectIDByID.
|
||||
func (mr *MockStoreMockRecorder) UpdateChatProjectIDByID(ctx, arg any) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateChatProjectIDByID", reflect.TypeOf((*MockStore)(nil).UpdateChatProjectIDByID), ctx, arg)
|
||||
}
|
||||
|
||||
// UpdateChatRetryState mocks base method.
|
||||
func (m *MockStore) UpdateChatRetryState(ctx context.Context, arg database.UpdateChatRetryStateParams) (database.Chat, error) {
|
||||
m.ctrl.T.Helper()
|
||||
|
||||
Generated
+3
@@ -1651,6 +1651,9 @@ type sqlcQuerier interface {
|
||||
UpdateChatPlanModeByID(ctx context.Context, arg UpdateChatPlanModeByIDParams) (Chat, error)
|
||||
UpdateChatProjectACLByID(ctx context.Context, arg UpdateChatProjectACLByIDParams) error
|
||||
UpdateChatProjectByID(ctx context.Context, arg UpdateChatProjectByIDParams) (ChatProject, error)
|
||||
// Sets the project of one chat. A NULL project_id removes the chat from
|
||||
// its project.
|
||||
UpdateChatProjectIDByID(ctx context.Context, arg UpdateChatProjectIDByIDParams) error
|
||||
// Stores the client-visible retry payload. retry_state_version is
|
||||
// assigned by trigger from the current snapshot_version.
|
||||
UpdateChatRetryState(ctx context.Context, arg UpdateChatRetryStateParams) (Chat, error)
|
||||
|
||||
Generated
+22
@@ -14612,6 +14612,28 @@ func (q *sqlQuerier) UpdateChatPlanModeByID(ctx context.Context, arg UpdateChatP
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updateChatProjectIDByID = `-- name: UpdateChatProjectIDByID :exec
|
||||
UPDATE
|
||||
chats
|
||||
SET
|
||||
-- NOTE: updated_at is intentionally NOT touched here to avoid changing list ordering.
|
||||
project_id = $1::uuid
|
||||
WHERE
|
||||
id = $2::uuid
|
||||
`
|
||||
|
||||
type UpdateChatProjectIDByIDParams struct {
|
||||
ProjectID uuid.NullUUID `db:"project_id" json:"project_id"`
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
}
|
||||
|
||||
// Sets the project of one chat. A NULL project_id removes the chat from
|
||||
// its project.
|
||||
func (q *sqlQuerier) UpdateChatProjectIDByID(ctx context.Context, arg UpdateChatProjectIDByIDParams) error {
|
||||
_, err := q.db.ExecContext(ctx, updateChatProjectIDByID, arg.ProjectID, arg.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
const updateChatRetryState = `-- name: UpdateChatRetryState :one
|
||||
WITH updated_chat AS (
|
||||
UPDATE chats
|
||||
|
||||
@@ -1217,6 +1217,17 @@ chats_expanded AS (
|
||||
SELECT *
|
||||
FROM chats_expanded;
|
||||
|
||||
-- name: UpdateChatProjectIDByID :exec
|
||||
-- Sets the project of one chat. A NULL project_id removes the chat from
|
||||
-- its project.
|
||||
UPDATE
|
||||
chats
|
||||
SET
|
||||
-- NOTE: updated_at is intentionally NOT touched here to avoid changing list ordering.
|
||||
project_id = sqlc.narg('project_id')::uuid
|
||||
WHERE
|
||||
id = @id::uuid;
|
||||
|
||||
-- name: UpdateChatLastModelConfigByID :one
|
||||
WITH updated_chat AS (
|
||||
UPDATE
|
||||
|
||||
@@ -57,7 +57,7 @@ Eviction means that a persisted message may reference a file that no longer exis
|
||||
|
||||
TODO (#27079): messages can now carry a `workspace-file-reference` part (path, name, size, media type, workspace ID) for files uploaded into the chat's workspace. It is metadata only: no file link is written, coderd validates that the path is scoped to the chat's upload directory and that the workspace ID matches the chat's current binding, and prompt conversion renders the reference as text (`[workspace file: <name> (<size>) at <path>]`) so the bytes never reach the model. Describe this here.
|
||||
|
||||
Project instructions are optional context injected into all chats in a project. Stored in `chat_project_instructions`. Subagents have no `project_id`, so they use the root chat's project.
|
||||
Project instructions are optional context injected into all chats in a project. Stored in `chat_project_instructions`. Subagents have no `project_id`, so they use the root chat's project. A root chat can move into a project, between projects, or out of its project after it's created. The move is written inside the `SetProject` transition so that it happens only while no step of the chat runs.
|
||||
|
||||
If the distinction isn't completely clear to you at this point, don't worry. It should become clearer as you learn more about the core state machine.
|
||||
|
||||
@@ -124,6 +124,7 @@ I don't recommend reading the rest of section thoroughly if this is your first t
|
||||
- TODO (#27111): `Create(initialMessages)` now lands in `waiting` instead of `running` when the initial history carries no user message (system messages only); such a chat enters `running` through its first `SendMessage`. The state diagram below needs the matching `N --> W: Create` edge. Describe this here.
|
||||
- When `Create(initialMessages)` creates a child chat, it first locks the family's root chat row with `FOR SHARE` and fails if the root is archived, so a new child never joins an archived family.
|
||||
- `SetArchived(archived)` sets or clears the archived marker for one chat.
|
||||
- `SetProject(project)` sets or clears the project of one chat without changing its execution state. A move of a root chat applies it to the root and each descendant in one transaction, and fails without changing any chat if one of them isn't in `W`, `E0` or `E1`. Only the root's `project_id` changes; subagents go through `SetProject` only so that their execution state is checked too. As in a family archive, the root row is locked first, so a concurrent child creation either joins the move or waits for it. A move to the root's current project applies no transition.
|
||||
- `SendMessage(m, busy_behavior)` inserts a user message directly when the chat is idle, or queues it when the chat is busy. `busy_behavior` must be either `queue` or `interrupt`. With `busy_behavior=interrupt`, it also requests interruption, or cancels a pending dynamic-tool action and inserts the message directly.
|
||||
- `EditMessage(k, replacement)` clears queued messages, cancels or obsoletes active work, marks the truncated active-history suffix as deleted, inserts the replacement turn followed by any caller-provided suffix messages, and lands in `running`.
|
||||
- `DeleteQueuedMessage(qid)` removes one queued message without changing the active history.
|
||||
@@ -169,12 +170,14 @@ stateDiagram-v2
|
||||
W --> W: ClearContext
|
||||
W --> E0: FinishError
|
||||
W --> XW: SetArchived(true)
|
||||
W --> W: SetProject
|
||||
|
||||
E0 --> R0: SendMessage
|
||||
E0 --> R0: EditMessage
|
||||
E0 --> R0: RequestCompaction
|
||||
E0 --> W: ClearContext
|
||||
E0 --> XE0: SetArchived(true)
|
||||
E0 --> E0: SetProject
|
||||
|
||||
E1 --> R1: SendMessage
|
||||
E1 --> R0: EditMessage
|
||||
@@ -184,6 +187,7 @@ stateDiagram-v2
|
||||
E1 --> R0: PromoteQueuedMessage / promoted last queued
|
||||
E1 --> R1: PromoteQueuedMessage / queue still non-empty
|
||||
E1 --> XE1: SetArchived(true)
|
||||
E1 --> E1: SetProject
|
||||
|
||||
R0 --> R0: RecordGenerationAttempt
|
||||
R0 --> R0: RecordRetryState
|
||||
@@ -1012,6 +1016,8 @@ Root chats in a project share durable memory; other chats have none. The agent s
|
||||
|
||||
<!-- TODO(f0ssel): the memory index no longer lives in the `read_memory` tool description. At turn start the generation loop commits a model-only user row: a full `<project-memory-index>` snapshot when the prompt has none (first turn, or after compaction), otherwise a `<project-memory-index-update>` listing changes since the model last saw it. Tool definitions and the system prompt carry no memory state, so memory writes no longer invalidate the provider's cached prefix. Mid-turn only a snapshot dropped by compaction is restored, and never between an assistant step and its tool results. -->
|
||||
|
||||
A moved root chat uses the instructions and memory of its new project from its next turn. The index it saw stays in its history, so that turn starts with an index update from the old index to the new project's. A chat that leaves its project, or whose project is deleted, has an empty index, and the update removes every memory it saw.
|
||||
|
||||
Project instructions are loaded on every turn, so edits show up in existing chats on their next turn. They're loaded alongside the rest of the turn setup, sanitized again, and added to the system prompt by `buildSystemPrompt` as a `<project-instructions>` block, after the memory guidance and before the user prompt. Subagents get them from their root chat.
|
||||
|
||||
###### Project sharing
|
||||
|
||||
@@ -505,6 +505,30 @@ func (p *Server) setChatFamilyArchived(ctx context.Context, chat database.Chat,
|
||||
return nil
|
||||
}
|
||||
|
||||
// MoveChatToProject moves a root chat into a project, or out of its
|
||||
// project when projectID is NULL. Its subagent chats follow because they
|
||||
// use the root's project. While the chat or a subagent chat is not idle,
|
||||
// it returns [chatstate.ErrTransitionNotAllowed], unless the chat is
|
||||
// already in that project, which changes nothing.
|
||||
func (p *Server) MoveChatToProject(ctx context.Context, chat database.Chat, projectID uuid.NullUUID) error {
|
||||
if chat.ID == uuid.Nil {
|
||||
return xerrors.New("chat_id is required")
|
||||
}
|
||||
if chat.ParentChatID.Valid {
|
||||
return chatstate.ErrChatNotRoot
|
||||
}
|
||||
|
||||
familyChats, err := chatstate.SetFamilyProject(ctx, p.db, p.pubsub, chatstate.SetFamilyProjectInput{
|
||||
RootID: chat.ID,
|
||||
ProjectID: projectID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.publishChatPubsubEvents(familyChats, codersdk.ChatWatchEventKindProjectChange)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteQueued removes a queued user message through the chatstate
|
||||
// state machine. Stream side effects are handled by chat:update
|
||||
// consumers.
|
||||
|
||||
@@ -86,6 +86,7 @@ func (b *PublishBuffer) BufferedChannels() []string {
|
||||
var AllExecutionTransitions = []Transition{
|
||||
TransitionCreateChat,
|
||||
TransitionSetArchived,
|
||||
TransitionSetProject,
|
||||
TransitionSendMessage,
|
||||
TransitionEditMessage,
|
||||
TransitionRequestCompaction,
|
||||
|
||||
@@ -151,3 +151,95 @@ func SetFamilyArchived(
|
||||
}
|
||||
return familyChats, nil
|
||||
}
|
||||
|
||||
// SetFamilyProjectInput configures [SetFamilyProject].
|
||||
type SetFamilyProjectInput struct {
|
||||
// RootID identifies the family root. SetFamilyProject rejects
|
||||
// calls for child chats with [ErrChatNotRoot] and unknown chats
|
||||
// with [ErrChatNotFound].
|
||||
RootID uuid.UUID
|
||||
// ProjectID is the root chat's new project. NULL removes the chat
|
||||
// from its project.
|
||||
ProjectID uuid.NullUUID
|
||||
}
|
||||
|
||||
// SetFamilyProject moves a root chat into a project, or out of its
|
||||
// project, inside one transaction. Every family member must be in W,
|
||||
// E0 or E1, or the move rolls back, so no step of the family runs with
|
||||
// the old project's memory tools after the move. Subagent chats have no
|
||||
// project and use the root's, so only the root's project_id changes.
|
||||
//
|
||||
// Like [SetFamilyArchived], it locks the root first and then each
|
||||
// member in GetChatFamilyIDsByRootID order, and it publishes only after
|
||||
// the commit. On success it returns one [database.Chat] per family
|
||||
// member, root first. A root already in the project changes nothing and
|
||||
// returns no chats; the check reads the locked row, so a move back to
|
||||
// the current project waits for a move still in flight.
|
||||
func SetFamilyProject(
|
||||
ctx context.Context,
|
||||
store database.Store,
|
||||
publisher Publisher,
|
||||
input SetFamilyProjectInput,
|
||||
) ([]database.Chat, error) {
|
||||
if store == nil {
|
||||
return nil, xerrors.New("chatstate: SetFamilyProject called with nil store")
|
||||
}
|
||||
if publisher == nil {
|
||||
return nil, xerrors.New("chatstate: SetFamilyProject called with nil publisher")
|
||||
}
|
||||
|
||||
buffer := NewPublishBuffer(publisher)
|
||||
defer buffer.Discard()
|
||||
|
||||
var familyChats []database.Chat
|
||||
err := store.InTx(func(tx database.Store) error {
|
||||
// Child creation takes FOR SHARE on the root row, so holding this
|
||||
// lock keeps new subagent chats out of the family during the move.
|
||||
root, err := tx.GetChatByIDForUpdate(ctx, input.RootID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrChatNotFound
|
||||
}
|
||||
return xerrors.Errorf("lock root chat for move: %w", err)
|
||||
}
|
||||
if root.ParentChatID.Valid {
|
||||
return ErrChatNotRoot
|
||||
}
|
||||
if root.ProjectID == input.ProjectID {
|
||||
return nil
|
||||
}
|
||||
ids, err := tx.GetChatFamilyIDsByRootID(ctx, input.RootID)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("get chat family: %w", err)
|
||||
}
|
||||
familyChats = make([]database.Chat, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
projectID := uuid.NullUUID{}
|
||||
if id == input.RootID {
|
||||
projectID = input.ProjectID
|
||||
}
|
||||
var chat database.Chat
|
||||
machine := NewChatMachine(tx, buffer, id)
|
||||
err := machine.Update(ctx, func(state *Tx, _ database.Store) error {
|
||||
result, err := state.SetProject(SetProjectInput{ProjectID: projectID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
chat = result.Chat
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
familyChats = append(familyChats, chat)
|
||||
}
|
||||
return nil
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := buffer.Flush(); err != nil {
|
||||
return familyChats, err
|
||||
}
|
||||
return familyChats, nil
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package chatstate_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -265,20 +267,7 @@ func TestCreateChildChatWaitsForFamilyArchive(t *testing.T) {
|
||||
createErr <- err
|
||||
}()
|
||||
|
||||
// Wait until the child creation blocks on the root row lock.
|
||||
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
||||
var waiting int
|
||||
err := sqlDB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM pg_stat_activity
|
||||
WHERE datname = current_database()
|
||||
AND pid <> pg_backend_pid()
|
||||
AND wait_event_type = 'Lock'
|
||||
AND query LIKE '%-- name: GetChatByIDForShare%'
|
||||
`).Scan(&waiting)
|
||||
return err == nil && waiting == 1
|
||||
}, testutil.IntervalFast, "wait for child creation to block on the root lock")
|
||||
require.NoError(t, ctx.Err(), "waiting for child creation to block")
|
||||
waitForLockWaiter(ctx, t, sqlDB, "GetChatByIDForShare")
|
||||
select {
|
||||
case err := <-createErr:
|
||||
t.Fatalf("child creation finished while the archive held the root lock: %v", err)
|
||||
@@ -304,6 +293,126 @@ WHERE datname = current_database()
|
||||
require.Equal(t, []uuid.UUID{root.ID}, ids, "no child may join the archived family")
|
||||
}
|
||||
|
||||
// TestSetFamilyProjectLocksRootFirst holds the root row, as a finishing
|
||||
// step does, and checks that the move waits on the root before it locks
|
||||
// a subagent chat. Locking a member first deadlocks against archive and
|
||||
// against steps that lock the root.
|
||||
func TestSetFamilyProjectLocksRootFirst(t *testing.T) {
|
||||
t.Parallel()
|
||||
db, _, sqlDB := dbtestutil.NewDBWithSQLDB(t)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
user, org, model := seedFamilyDeps(t, db)
|
||||
|
||||
root := dbgen.Chat(t, db, database.Chat{
|
||||
OrganizationID: org.ID,
|
||||
OwnerID: user.ID,
|
||||
LastModelConfigID: model.ID,
|
||||
Title: "root",
|
||||
Status: database.ChatStatusRunning,
|
||||
})
|
||||
child := dbgen.Chat(t, db, database.Chat{
|
||||
OrganizationID: org.ID,
|
||||
OwnerID: user.ID,
|
||||
LastModelConfigID: model.ID,
|
||||
Title: "child",
|
||||
Status: database.ChatStatusWaiting,
|
||||
ParentChatID: uuid.NullUUID{UUID: root.ID, Valid: true},
|
||||
RootChatID: uuid.NullUUID{UUID: root.ID, Valid: true},
|
||||
})
|
||||
project := dbgen.ChatProject(t, db, database.ChatProject{
|
||||
OrganizationID: org.ID,
|
||||
OwnerID: user.ID,
|
||||
})
|
||||
|
||||
finish, err := sqlDB.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
if err := finish.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) {
|
||||
t.Errorf("roll back the finishing transaction: %v", err)
|
||||
}
|
||||
})
|
||||
_, err = finish.ExecContext(ctx, `UPDATE chats SET status = 'waiting' WHERE id = $1`, root.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
moveErr := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := chatstate.SetFamilyProject(ctx, db, newRecordingPubsub(), chatstate.SetFamilyProjectInput{
|
||||
RootID: root.ID,
|
||||
ProjectID: uuid.NullUUID{UUID: project.ID, Valid: true},
|
||||
})
|
||||
moveErr <- err
|
||||
}()
|
||||
waitForLockWaiter(ctx, t, sqlDB, "GetChatByIDForUpdate")
|
||||
|
||||
_, err = finish.ExecContext(ctx, `SELECT id FROM chats WHERE id = $1 FOR UPDATE NOWAIT`, child.ID)
|
||||
require.NoError(t, err, "the move must not lock a subagent chat before the root")
|
||||
require.NoError(t, finish.Commit())
|
||||
// The step committed waiting before the move read the root, so the
|
||||
// move sees an idle family.
|
||||
require.NoError(t, testutil.RequireReceive(ctx, t, moveErr))
|
||||
|
||||
moved, err := db.GetChatByID(ctx, root.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uuid.NullUUID{UUID: project.ID, Valid: true}, moved.ProjectID)
|
||||
unchanged, err := db.GetChatByID(ctx, child.ID)
|
||||
require.NoError(t, err)
|
||||
require.False(t, unchanged.ProjectID.Valid, "subagent chats use the root's project")
|
||||
}
|
||||
|
||||
// TestSetFamilyProjectKeepsTheCurrentProject moves a running root chat to
|
||||
// the project it is already in, which changes and publishes nothing.
|
||||
func TestSetFamilyProjectKeepsTheCurrentProject(t *testing.T) {
|
||||
t.Parallel()
|
||||
db, _ := dbtestutil.NewDB(t)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
user, org, model := seedFamilyDeps(t, db)
|
||||
project := dbgen.ChatProject(t, db, database.ChatProject{
|
||||
OrganizationID: org.ID,
|
||||
OwnerID: user.ID,
|
||||
})
|
||||
root := dbgen.Chat(t, db, database.Chat{
|
||||
OrganizationID: org.ID,
|
||||
OwnerID: user.ID,
|
||||
LastModelConfigID: model.ID,
|
||||
Title: "root",
|
||||
Status: database.ChatStatusRunning,
|
||||
ProjectID: uuid.NullUUID{UUID: project.ID, Valid: true},
|
||||
})
|
||||
before, err := db.GetChatByID(ctx, root.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
publisher := newRecordingPubsub()
|
||||
chats, err := chatstate.SetFamilyProject(ctx, db, publisher, chatstate.SetFamilyProjectInput{
|
||||
RootID: root.ID,
|
||||
ProjectID: root.ProjectID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, chats)
|
||||
require.Empty(t, publisher.channels)
|
||||
after, err := db.GetChatByID(ctx, root.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, before, after)
|
||||
}
|
||||
|
||||
// waitForLockWaiter waits until exactly one other session waits on a row
|
||||
// lock while it runs the named sqlc query.
|
||||
func waitForLockWaiter(ctx context.Context, t *testing.T, sqlDB *sql.DB, queryName string) {
|
||||
t.Helper()
|
||||
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
||||
var waiting int
|
||||
err := sqlDB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM pg_stat_activity
|
||||
WHERE datname = current_database()
|
||||
AND pid <> pg_backend_pid()
|
||||
AND wait_event_type = 'Lock'
|
||||
AND query LIKE '%-- name: ' || $1 || '%'
|
||||
`, queryName).Scan(&waiting)
|
||||
return err == nil && waiting == 1
|
||||
}, testutil.IntervalFast, "wait for %s to block on a row lock", queryName)
|
||||
require.NoError(t, ctx.Err(), "waiting for %s to block", queryName)
|
||||
}
|
||||
|
||||
func seedFamilyDeps(t *testing.T, db database.Store) (database.User, database.Organization, database.ChatModelConfig) {
|
||||
t.Helper()
|
||||
user := dbgen.User(t, db, database.User{})
|
||||
|
||||
@@ -10,6 +10,7 @@ type Transition string
|
||||
const (
|
||||
TransitionCreateChat Transition = "CreateChat"
|
||||
TransitionSetArchived Transition = "SetArchived"
|
||||
TransitionSetProject Transition = "SetProject"
|
||||
TransitionSendMessage Transition = "SendMessage"
|
||||
TransitionEditMessage Transition = "EditMessage"
|
||||
TransitionRequestCompaction Transition = "RequestCompaction"
|
||||
@@ -50,6 +51,7 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
},
|
||||
StateW: {
|
||||
TransitionSetArchived: {StateXW},
|
||||
TransitionSetProject: {StateW},
|
||||
TransitionSendMessage: {StateR0},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionRequestCompaction: {StateR0},
|
||||
@@ -58,6 +60,7 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
},
|
||||
StateE0: {
|
||||
TransitionSetArchived: {StateXE0},
|
||||
TransitionSetProject: {StateE0},
|
||||
TransitionSendMessage: {StateR0},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionRequestCompaction: {StateR0},
|
||||
@@ -65,6 +68,7 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
},
|
||||
StateE1: {
|
||||
TransitionSetArchived: {StateXE1},
|
||||
TransitionSetProject: {StateE1},
|
||||
TransitionSendMessage: {StateR1},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateE0, StateE1},
|
||||
|
||||
@@ -418,6 +418,38 @@ func (tx *Tx) SetArchived(input SetArchivedInput) (SetArchivedResult, error) {
|
||||
return SetArchivedResult{}, nil
|
||||
}
|
||||
|
||||
// SetProjectInput configures [Tx.SetProject]. A NULL ProjectID removes
|
||||
// the chat from its project.
|
||||
type SetProjectInput struct {
|
||||
ProjectID uuid.NullUUID
|
||||
}
|
||||
|
||||
// SetProjectResult is returned by [Tx.SetProject].
|
||||
type SetProjectResult struct {
|
||||
// Chat is the row after the move.
|
||||
Chat database.Chat
|
||||
}
|
||||
|
||||
// SetProject sets or clears the chat's project. Like SetArchived, it runs
|
||||
// only from W, E0 and E1, so no step of the chat runs during a move.
|
||||
func (tx *Tx) SetProject(input SetProjectInput) (SetProjectResult, error) {
|
||||
chat, _, err := tx.requireFromAllowed(TransitionSetProject)
|
||||
if err != nil {
|
||||
return SetProjectResult{}, err
|
||||
}
|
||||
if input.ProjectID == chat.ProjectID {
|
||||
return SetProjectResult{Chat: chat}, nil
|
||||
}
|
||||
if err := tx.store.UpdateChatProjectIDByID(tx.ctx, database.UpdateChatProjectIDByIDParams{
|
||||
ID: chat.ID,
|
||||
ProjectID: input.ProjectID,
|
||||
}); err != nil {
|
||||
return SetProjectResult{}, xerrors.Errorf("update project: %w", err)
|
||||
}
|
||||
chat.ProjectID = input.ProjectID
|
||||
return SetProjectResult{Chat: chat}, nil
|
||||
}
|
||||
|
||||
// BusyBehavior controls how SendMessage behaves when the chat is
|
||||
// currently busy (R*/I*/A*) or errored with a non-empty queue (E1).
|
||||
// From W and E0 the two behaviors are equivalent.
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbgen"
|
||||
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
||||
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
@@ -108,6 +109,19 @@ func applySetArchived(t *testing.T, _ *testFixture, tx *chatstate.Tx, _ seededCh
|
||||
return err
|
||||
}
|
||||
|
||||
func applySetProject(t *testing.T, f *testFixture, tx *chatstate.Tx, _ seededChat, _ chatstate.ExecutionState, result *transitionCaseResult) error {
|
||||
t.Helper()
|
||||
project := dbgen.ChatProject(t, f.DB, database.ChatProject{
|
||||
OrganizationID: f.Org.ID,
|
||||
OwnerID: f.User.ID,
|
||||
})
|
||||
var err error
|
||||
result.setProject, err = tx.SetProject(chatstate.SetProjectInput{
|
||||
ProjectID: uuid.NullUUID{UUID: project.ID, Valid: true},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func applySendMessageQueue(t *testing.T, f *testFixture, tx *chatstate.Tx, _ seededChat, _ chatstate.ExecutionState, result *transitionCaseResult) error {
|
||||
t.Helper()
|
||||
var err error
|
||||
@@ -334,6 +348,8 @@ func defaultApplier(tr chatstate.Transition) applierFn {
|
||||
switch tr {
|
||||
case chatstate.TransitionSetArchived:
|
||||
return applySetArchived
|
||||
case chatstate.TransitionSetProject:
|
||||
return applySetProject
|
||||
case chatstate.TransitionSendMessage:
|
||||
return applySendMessageQueue
|
||||
case chatstate.TransitionEditMessage:
|
||||
@@ -391,6 +407,7 @@ func mustMarshalParts(t *testing.T, parts []codersdk.ChatMessagePart) pqtype.Nul
|
||||
// AllowedExecutionTransitionsFrom and AllowedExecutionTransitionOutputs.
|
||||
|
||||
type transitionCaseResult struct {
|
||||
setProject chatstate.SetProjectResult
|
||||
sendMessage chatstate.SendMessageResult
|
||||
editMessage chatstate.EditMessageResult
|
||||
requestCompaction chatstate.RequestCompactionResult
|
||||
@@ -797,6 +814,12 @@ func matrixCases() []transitionCaseSpec {
|
||||
setArchivedCase(chatstate.StateXE0, chatstate.StateE0, database.ChatStatusError),
|
||||
setArchivedCase(chatstate.StateXE1, chatstate.StateE1, database.ChatStatusError),
|
||||
|
||||
// SetProject cases: only idle states move, the state and the
|
||||
// queue stay as they were, and only project_id changes.
|
||||
setProjectCase(chatstate.StateW, database.ChatStatusWaiting),
|
||||
setProjectCase(chatstate.StateE0, database.ChatStatusError),
|
||||
setProjectCase(chatstate.StateE1, database.ChatStatusError),
|
||||
|
||||
// SendMessage(queue) cases: idle states insert directly,
|
||||
// busy states append to the queue tail.
|
||||
sendMessageQueueCase(chatstate.StateW, chatstate.StateR0, true, 0),
|
||||
@@ -971,6 +994,32 @@ func setArchivedCase(from, want chatstate.ExecutionState, wantStatus database.Ch
|
||||
}
|
||||
}
|
||||
|
||||
func setProjectCase(from chatstate.ExecutionState, wantStatus database.ChatStatus) transitionCaseSpec {
|
||||
return transitionCaseSpec{
|
||||
transition: chatstate.TransitionSetProject,
|
||||
from: from,
|
||||
want: from,
|
||||
apply: applySetProject,
|
||||
assert: func(ctx context.Context, t *testing.T, f *testFixture, seeded seededChat, base snapshotBaseline, result transitionCaseResult) {
|
||||
after, err := f.DB.GetChatByID(ctx, seeded.chatID)
|
||||
require.NoError(t, err)
|
||||
require.True(t, after.ProjectID.Valid, "SetProject must set project_id")
|
||||
require.Equal(t, result.setProject.Chat.ProjectID, after.ProjectID,
|
||||
"SetProject returns the stored project_id")
|
||||
require.Equal(t, wantStatus, after.Status,
|
||||
"SetProject preserves chat status")
|
||||
require.Equal(t, base.chat.LastError, after.LastError,
|
||||
"SetProject preserves last_error")
|
||||
require.Equal(t, base.historyVersion, after.HistoryVersion,
|
||||
"SetProject does not insert history")
|
||||
require.Equal(t, base.queueVersion, after.QueueVersion,
|
||||
"SetProject does not mutate queued messages")
|
||||
require.Equal(t, base.queueIDs, queuedIDsByPosition(ctx, t, f, seeded.chatID),
|
||||
"SetProject leaves queued messages unchanged")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func sendMessageQueueCase(from, want chatstate.ExecutionState, directInsert bool, queueDelta int64) transitionCaseSpec {
|
||||
return transitionCaseSpec{
|
||||
transition: chatstate.TransitionSendMessage,
|
||||
|
||||
@@ -415,8 +415,9 @@ func (s *taskStarter) syncMemoryIndex(
|
||||
machine *chatstate.ChatMachine,
|
||||
input chatWorkerTaskStartInput,
|
||||
chat database.Chat,
|
||||
history []database.ChatMessage,
|
||||
) (sessionStartResult, error) {
|
||||
message, ok, err := s.server.memoryIndexMessage(ctx, chat)
|
||||
message, ok, err := s.server.memoryIndexMessage(ctx, chat, history)
|
||||
if err != nil {
|
||||
// Memory is optional context; a lookup failure must not fail the turn.
|
||||
s.server.logger.Warn(ctx, "failed to sync project memory index", slog.F("chat_id", chat.ID), slog.Error(err))
|
||||
@@ -590,7 +591,7 @@ func (s *taskStarter) runGenerationStep(
|
||||
return input, true, nil
|
||||
}
|
||||
}
|
||||
if synced, err := s.syncMemoryIndex(ctx, machine, input, chat); err != nil {
|
||||
if synced, err := s.syncMemoryIndex(ctx, machine, input, chat, messages); err != nil {
|
||||
return input, false, err
|
||||
} else if synced.Chat.ID != uuid.Nil {
|
||||
input.HistoryVersion = synced.Chat.HistoryVersion
|
||||
|
||||
@@ -81,9 +81,24 @@ func (p *Server) memoryAuditor(chat database.Chat) chattool.MemoryAuditFunc {
|
||||
// writes reach the model on its next turn and never mid-turn. Nothing is sent
|
||||
// while the latest assistant step has tool calls without results, which must
|
||||
// follow it directly.
|
||||
func (p *Server) memoryIndexMessage(ctx context.Context, chat database.Chat) (chatstate.Message, bool, error) {
|
||||
store, _, ok := p.resolveProjectMemory(ctx, chat)
|
||||
if !ok {
|
||||
//
|
||||
// A root chat outside a project has an empty index, so a chat that left its
|
||||
// project, or whose project was deleted, has the memories it saw removed at
|
||||
// its next turn start. That removal is all that can be due for such a chat,
|
||||
// so it reads the prompt only at a turn start, which history (the chat's
|
||||
// user-visible messages) shows without a query.
|
||||
func (p *Server) memoryIndexMessage(ctx context.Context, chat database.Chat, history []database.ChatMessage) (chatstate.Message, bool, error) {
|
||||
if !p.experiments.Enabled(codersdk.ExperimentChatProjects) || chat.ParentChatID.Valid {
|
||||
return chatstate.Message{}, false, nil
|
||||
}
|
||||
var store chattool.MemoryStore
|
||||
if chat.ProjectID.Valid {
|
||||
var ok bool
|
||||
store, _, ok = p.resolveProjectMemory(ctx, chat)
|
||||
if !ok {
|
||||
return chatstate.Message{}, false, nil
|
||||
}
|
||||
} else if currentTurnStepCount(history) > 0 {
|
||||
return chatstate.Message{}, false, nil
|
||||
}
|
||||
// Prompt rows include the model-only rows this sends, and exclude rows
|
||||
@@ -111,9 +126,12 @@ func (p *Server) memoryIndexMessage(ctx context.Context, chat database.Chat) (ch
|
||||
}
|
||||
messages := promptRows
|
||||
snapshotOnly := !turnStart
|
||||
current, err := store.List(ctx)
|
||||
if err != nil {
|
||||
return chatstate.Message{}, false, xerrors.Errorf("list project memories: %w", err)
|
||||
var current []chattool.MemoryIndexEntry
|
||||
if store != nil {
|
||||
current, err = store.List(ctx)
|
||||
if err != nil {
|
||||
return chatstate.Message{}, false, xerrors.Errorf("list project memories: %w", err)
|
||||
}
|
||||
}
|
||||
seen, hasSnapshot := chattool.ReplayMemoryIndex(memoryIndexTexts(messages))
|
||||
var text string
|
||||
|
||||
@@ -117,3 +117,120 @@ func TestProjectMemoryIndexKeepsPromptPrefixStable(t *testing.T) {
|
||||
}
|
||||
require.Equal(t, 2, indexRows, "one snapshot and one update")
|
||||
}
|
||||
|
||||
// TestMovedChatUsesNewProject moves a chat between two turns and checks that
|
||||
// the next turn uses the instructions and the memory of the chat's new
|
||||
// project, or of no project once the chat leaves its project.
|
||||
func TestMovedChatUsesNewProject(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
// toBilling moves the chat to Billing instead of out of any project.
|
||||
toBilling bool
|
||||
// want are texts that appear once in the second turn's request.
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "ToProject",
|
||||
toBilling: true,
|
||||
// The model saw the Platform index in turn one, so turn two adds
|
||||
// the Billing memories and removes the Platform ones.
|
||||
want: []string{
|
||||
`in the project "Billing"`,
|
||||
"Write all dates in ISO 8601.",
|
||||
chattool.FormatMemoryIndexUpdate(
|
||||
[]chattool.MemoryIndexEntry{{Name: "invoice-format", Description: "Invoices use ISO dates"}},
|
||||
[]string{"deploy-day"},
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "OutOfProject",
|
||||
want: []string{chattool.FormatMemoryIndexUpdate(nil, []string{"deploy-day"})},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
db, ps := dbtestutil.NewDB(t)
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
requests []*chattest.OpenAIRequest
|
||||
)
|
||||
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
||||
if !req.Stream {
|
||||
return chattest.OpenAINonStreamingResponse("title")
|
||||
}
|
||||
mu.Lock()
|
||||
requests = append(requests, req)
|
||||
mu.Unlock()
|
||||
return chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("ok")...)
|
||||
})
|
||||
user, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
|
||||
platform := dbgen.ChatProject(t, db, database.ChatProject{OrganizationID: org.ID, OwnerID: user.ID, Name: "Platform"})
|
||||
billing := dbgen.ChatProject(t, db, database.ChatProject{OrganizationID: org.ID, OwnerID: user.ID, Name: "Billing"})
|
||||
_, err := db.UpsertChatProjectInstructions(ctx, database.UpsertChatProjectInstructionsParams{
|
||||
ProjectID: billing.ID,
|
||||
Instructions: "Write all dates in ISO 8601.",
|
||||
UpdatedBy: user.ID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
dbgen.ChatProjectMemory(t, db, database.ChatProjectMemory{
|
||||
ProjectID: platform.ID, OrganizationID: org.ID, CreatedBy: user.ID,
|
||||
Name: "deploy-day", Description: "Deploys happen on Tuesdays", Body: "The team deploys every Tuesday.",
|
||||
})
|
||||
dbgen.ChatProjectMemory(t, db, database.ChatProjectMemory{
|
||||
ProjectID: billing.ID, OrganizationID: org.ID, CreatedBy: user.ID,
|
||||
Name: "invoice-format", Description: "Invoices use ISO dates", Body: "Invoices use ISO 8601 dates.",
|
||||
})
|
||||
|
||||
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,
|
||||
ProjectID: uuid.NullUUID{UUID: platform.ID, Valid: true},
|
||||
Title: "moved",
|
||||
ModelConfigID: model.ID,
|
||||
InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hi")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
||||
|
||||
target := uuid.NullUUID{}
|
||||
if tc.toBilling {
|
||||
target = uuid.NullUUID{UUID: billing.ID, Valid: true}
|
||||
}
|
||||
require.NoError(t, server.MoveChatToProject(ctx, chat, target))
|
||||
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
||||
ChatID: chat.ID,
|
||||
CreatedBy: user.ID,
|
||||
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText("what do you know?")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
require.Len(t, requests, 2, "one request per turn")
|
||||
count := func(req *chattest.OpenAIRequest, text string) int {
|
||||
n := 0
|
||||
for _, msg := range req.Messages {
|
||||
if strings.Contains(msg.Content, text) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
last := requests[1]
|
||||
require.Zero(t, count(last, `in the project "Platform"`))
|
||||
for _, text := range tc.want {
|
||||
require.Equal(t, 1, count(last, text), text)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -179,7 +179,7 @@ func TestMemoryIndexMessage(t *testing.T) {
|
||||
db.EXPECT().GetChatMessagesForPromptByChatID(gomock.Any(), chat.ID).Return(append([]database.ChatMessage{prompt}, history...), nil)
|
||||
db.EXPECT().GetChatProjectMemoriesByProjectID(gomock.Any(), projectID).Return(memories, nil).AnyTimes()
|
||||
server := &Server{db: db, logger: slogtest.Make(t, nil), experiments: codersdk.ExperimentsKnown}
|
||||
message, ok, err := server.memoryIndexMessage(t.Context(), chat)
|
||||
message, ok, err := server.memoryIndexMessage(t.Context(), chat, nil)
|
||||
require.NoError(t, err)
|
||||
if !ok {
|
||||
return "", false
|
||||
|
||||
@@ -2230,6 +2230,10 @@ const (
|
||||
// stays usable; a refresh re-pins a drifted chat to the latest
|
||||
// snapshot.
|
||||
ChatWatchEventKindContextDirty ChatWatchEventKind = "context_dirty"
|
||||
// ChatWatchEventKindProjectChange is published for each chat of a
|
||||
// family after its root chat moves into, between or out of projects.
|
||||
// Take project_id only from this kind.
|
||||
ChatWatchEventKindProjectChange ChatWatchEventKind = "project_change"
|
||||
)
|
||||
|
||||
// ChatWatchEvent represents an event from the global chat watch stream.
|
||||
|
||||
Generated
+3
-3
@@ -5993,9 +5993,9 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
|
||||
#### Enumerated Values
|
||||
|
||||
| Value(s) |
|
||||
|----------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `action_required`, `chat_summary_change`, `context_dirty`, `created`, `deleted`, `diff_status_change`, `status_change`, `summary_change`, `title_change` |
|
||||
| Value(s) |
|
||||
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `action_required`, `chat_summary_change`, `context_dirty`, `created`, `deleted`, `diff_status_change`, `project_change`, `status_change`, `summary_change`, `title_change` |
|
||||
|
||||
## codersdk.ChatWorkspaceTTLResponse
|
||||
|
||||
|
||||
@@ -4649,6 +4649,7 @@ describe("semantic cache operations: prefix invalidations", () => {
|
||||
created: false,
|
||||
deleted: false,
|
||||
diff_status_change: false,
|
||||
project_change: false,
|
||||
status_change: true,
|
||||
summary_change: false,
|
||||
title_change: false,
|
||||
@@ -4728,6 +4729,7 @@ describe("semantic cache operations: prefix invalidations", () => {
|
||||
created: false,
|
||||
deleted: false,
|
||||
diff_status_change: true,
|
||||
project_change: false,
|
||||
status_change: true,
|
||||
summary_change: false,
|
||||
title_change: true,
|
||||
|
||||
Generated
+2
@@ -3962,6 +3962,7 @@ export type ChatWatchEventKind =
|
||||
| "created"
|
||||
| "deleted"
|
||||
| "diff_status_change"
|
||||
| "project_change"
|
||||
| "status_change"
|
||||
| "summary_change"
|
||||
| "title_change";
|
||||
@@ -3973,6 +3974,7 @@ export const ChatWatchEventKinds: ChatWatchEventKind[] = [
|
||||
"created",
|
||||
"deleted",
|
||||
"diff_status_change",
|
||||
"project_change",
|
||||
"status_change",
|
||||
"summary_change",
|
||||
"title_change",
|
||||
|
||||
Reference in new issue
Block a user