Files
coder/coderd/x/chatd/memory.go
T
Michael Suchacz 0968f97a43 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.
2026-10-19 12:38:17 +00:00

195 lines
7.4 KiB
Go

package chatd
import (
"context"
"encoding/json"
"net/http"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
"github.com/coder/coder/v2/coderd/x/chatd/chattool"
"github.com/coder/coder/v2/codersdk"
)
// resolveProjectMemory returns the durable-memory store and project name for
// a chat. Only root chats inside a project have memory; chats outside a
// project, subagents, chats whose owner cannot use the project, the disabled
// experiment, and transient lookup failures all report ok=false.
func (p *Server) resolveProjectMemory(ctx context.Context, chat database.Chat) (store chattool.MemoryStore, projectName string, ok bool) {
if !p.experiments.Enabled(codersdk.ExperimentChatProjects) {
return nil, "", false
}
if chat.ParentChatID.Valid || !chat.ProjectID.Valid {
return nil, "", false
}
project, ok := p.usableChatProject(ctx, p.logger.With(slog.F("chat_id", chat.ID), slog.F("owner_id", chat.OwnerID)), chat.ProjectID.UUID, chat)
if !ok {
return nil, "", false
}
return chattool.NewProjectMemoryStore(p.db, chat.ProjectID.UUID, chat.OrganizationID, chat.OwnerID, p.memoryAuditor(chat)), project.Name, true
}
// memoryAuditor records memory changes made by a chat's tools. There is no
// HTTP request, so entries are attributed to the chat owner and name the
// chat that made it.
func (p *Server) memoryAuditor(chat database.Chat) chattool.MemoryAuditFunc {
return func(ctx context.Context, action database.AuditAction, oldMemory, newMemory database.ChatProjectMemory) {
if p.chatWorker == nil || p.chatWorker.opts.Auditor == nil {
return
}
auditor := p.chatWorker.opts.Auditor.Load()
if auditor == nil {
return
}
// Marshaling a map of strings cannot fail.
raw, _ := json.Marshal(map[string]string{"chat_id": chat.ID.String()})
status := http.StatusCreated
if action == database.AuditActionDelete {
status = http.StatusNoContent
}
audit.BackgroundAudit(ctx, &audit.BackgroundAuditParams[database.ChatProjectMemory]{
Audit: *auditor,
Log: p.logger.With(slog.F("chat_id", chat.ID)),
UserID: chat.OwnerID,
OrganizationID: chat.OrganizationID,
Action: action,
Old: oldMemory,
New: newMemory,
Status: status,
AdditionalFields: raw,
})
}
}
// memoryIndexMessage returns the model-only message that brings the chat's
// view of the project memory index up to date, or ok=false when none is
// due. The index lives in conversation history rather than in a tool
// description or the system prompt, because providers cache the request as
// one prefix of tools, system prompt, then messages: a changing index there
// would rewrite the whole cache for every chat in the project on each memory
// write. Appended messages leave the cached prefix intact.
//
// A full snapshot is sent when the prompt has none, which covers a chat's
// first turn and compaction, which drops the earlier snapshot. Changes since
// the model last saw the index go out only at turn start, so other chats'
// 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.
//
// 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
// compaction has replaced.
promptRows, err := p.db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
if err != nil {
return chatstate.Message{}, false, xerrors.Errorf("load prompt messages: %w", err)
}
turnStart := currentTurnStepCount(promptRows) == 0
if !turnStart {
if lastActiveMessageRole(promptRows) == database.ChatMessageRoleAssistant {
return chatstate.Message{}, false, nil
}
// A step can commit some tool results while others, such as
// client-executed dynamic tools, are still pending. Providers reject a
// message between a tool call and its result, so wait until every call
// is resolved.
localCalls, dynamicCalls, _, err := unresolvedToolCallsFromHistory(promptRows, dynamicToolNamesFromChat(chat))
if err != nil {
return chatstate.Message{}, false, xerrors.Errorf("find unresolved tool calls: %w", err)
}
if len(localCalls) > 0 || len(dynamicCalls) > 0 {
return chatstate.Message{}, false, nil
}
}
messages := promptRows
snapshotOnly := !turnStart
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
switch {
case !hasSnapshot && len(current) == 0:
return chatstate.Message{}, false, nil
case !hasSnapshot:
text = chattool.FormatMemoryIndexSnapshot(current)
case snapshotOnly:
return chatstate.Message{}, false, nil
default:
changed, removed := chattool.DiffMemoryIndex(seen, current)
if len(changed) == 0 && len(removed) == 0 {
return chatstate.Message{}, false, nil
}
text = chattool.FormatMemoryIndexUpdate(changed, removed)
}
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{codersdk.ChatMessageText(text)})
if err != nil {
return chatstate.Message{}, false, xerrors.Errorf("marshal memory index: %w", err)
}
return chatstate.Message{
Role: database.ChatMessageRoleUser,
Content: content,
Visibility: database.ChatMessageVisibilityModel,
ModelConfigID: uuid.NullUUID{UUID: chat.LastModelConfigID, Valid: chat.LastModelConfigID != uuid.Nil},
ContentVersion: chatprompt.CurrentContentVersion,
}, true, nil
}
// memoryIndexTexts returns the text of active model-only user rows. Users
// cannot author model-only rows, so index text cannot be forged from chat
// input.
func memoryIndexTexts(messages []database.ChatMessage) []string {
var texts []string
for _, msg := range messages {
if msg.Deleted || msg.Compressed || msg.Role != database.ChatMessageRoleUser || msg.Visibility != database.ChatMessageVisibilityModel {
continue
}
parts, err := chatprompt.ParseContent(msg)
if err != nil {
continue
}
for _, part := range parts {
if part.Type == codersdk.ChatMessagePartTypeText {
texts = append(texts, part.Text)
}
}
}
return texts
}
func lastActiveMessageRole(messages []database.ChatMessage) database.ChatMessageRole {
for i := len(messages) - 1; i >= 0; i-- {
if !messages[i].Deleted && !messages[i].Compressed {
return messages[i].Role
}
}
return ""
}