Files
coder/coderd/x/chatd/store_chat_attachment.go
T
Ethan d8e3f4fcf7 feat: evict the oldest attachments at the chat file cap (#29063)
Closes CODAGT-933

Long agent sessions were hitting the 50 attachment cap, after which
every upload, screenshot and `attach_file` call was rejected, so people
were abandoning otherwise healthy chats.

Rather than raise the cap (which just moves the cliff and multiplies the
worst-case per-chat `bytea` storage), a chat now keeps its 50 most
recent attachments. `LinkChatFilesAfterLock` deletes the oldest
`chat_files` rows in the same statement and the cascade drops their
links. Files in the incoming batch are never evicted, so the only
remaining rejection is a single message with more than 50 files.

Nothing in the product ever linked one file to two chats, so rather than
guard the eviction against it, this adds `UNIQUE (file_id)` on
`chat_file_links`, with the migration dropping any existing duplicates
in favour of the oldest chat.

Evicted attachments render as the existing "Attachment expired" tile. A
`pinned` flag is the obvious follow-up if someone needs to keep a
specific file around.
2026-09-10 13:40:16 +10:00

104 lines
2.7 KiB
Go

package chatd
import (
"context"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
"github.com/coder/coder/v2/coderd/x/chatd/chattool"
"github.com/coder/coder/v2/coderd/x/chatfiles"
)
func (p *Server) newStoreChatAttachmentFunc(workspaceCtx *turnWorkspaceContext) chattool.StoreFileFunc {
return func(
ctx context.Context,
name string,
detectName string,
data []byte,
) (chattool.AttachmentMetadata, error) {
workspaceCtx.chatStateMu.Lock()
chatSnapshot := *workspaceCtx.currentChat
workspaceCtx.chatStateMu.Unlock()
return p.storeChatAttachment(ctx, chatSnapshot, name, detectName, data)
}
}
func (p *Server) storeChatAttachment(
ctx context.Context,
chatSnapshot database.Chat,
name string,
detectName string,
data []byte,
) (chattool.AttachmentMetadata, error) {
if !chatSnapshot.WorkspaceID.Valid {
return chattool.AttachmentMetadata{}, xerrors.New("no workspace is associated with this chat. Use the create_workspace tool to create one")
}
storedName, mediaType, err := chatfiles.PrepareStoredFile(name, detectName, data)
if err != nil {
return chattool.AttachmentMetadata{}, err
}
// Insert and link in one transaction so a cap rejection or linking
// failure does not leave behind an unlinked chat file row.
var attachment chattool.AttachmentMetadata
err = p.db.InTx(func(tx database.Store) error {
ws, err := tx.GetWorkspaceByID(ctx, chatSnapshot.WorkspaceID.UUID)
if err != nil {
return xerrors.Errorf("resolve workspace: %w", err)
}
attachment, err = storeLinkedChatFileTx(
ctx,
tx,
chatSnapshot.ID,
chatSnapshot.OwnerID,
ws.OrganizationID,
storedName,
mediaType,
data,
)
return err
}, database.DefaultTXOptions().WithID("store_chat_attachment"))
if err != nil {
return chattool.AttachmentMetadata{}, err
}
return attachment, nil
}
func storeLinkedChatFileTx(
ctx context.Context,
tx database.Store,
chatID uuid.UUID,
ownerID uuid.UUID,
organizationID uuid.UUID,
name string,
mediaType string,
data []byte,
) (chattool.AttachmentMetadata, error) {
row, err := tx.InsertChatFile(ctx, database.InsertChatFileParams{
OwnerID: ownerID,
OrganizationID: organizationID,
Name: name,
Mimetype: mediaType,
Data: data,
})
if err != nil {
return chattool.AttachmentMetadata{}, xerrors.Errorf("insert chat file: %w", err)
}
if err := chatstate.LinkFiles(ctx, tx, chatID, []uuid.UUID{row.ID}); err != nil {
return chattool.AttachmentMetadata{}, err
}
return chattool.AttachmentMetadata{
FileID: row.ID,
MediaType: mediaType,
Name: name,
}, nil
}