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.
40 lines
1.1 KiB
Go
40 lines
1.1 KiB
Go
package chatstate
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// LinkFiles links files, returning [ErrChatFileCapExceeded] for cap rejections
|
|
// and [ErrChatFileUnavailable] for files that are missing or attached to
|
|
// another chat. Use the caller's transaction so failures roll back related
|
|
// writes; existing links use no additional slots.
|
|
func LinkFiles(ctx context.Context, store database.Store, chatID uuid.UUID, fileIDs []uuid.UUID) error {
|
|
if len(fileIDs) == 0 {
|
|
return nil
|
|
}
|
|
rejected, err := store.LinkChatFiles(ctx, database.LinkChatFilesParams{
|
|
ChatID: chatID,
|
|
MaxFileLinks: int32(codersdk.MaxChatFileIDs),
|
|
FileIds: fileIDs,
|
|
})
|
|
if err != nil {
|
|
wrapped := xerrors.Errorf("link chat files: %w", err)
|
|
if database.IsForeignKeyViolation(err, database.ForeignKeyChatFileLinksFileID) ||
|
|
database.IsUniqueViolation(err, database.UniqueChatFileLinksFileIDKey) {
|
|
return errors.Join(ErrChatFileUnavailable, wrapped)
|
|
}
|
|
return wrapped
|
|
}
|
|
if rejected > 0 {
|
|
return ErrChatFileCapExceeded
|
|
}
|
|
return nil
|
|
}
|