Files
coder/coderd/x/chatd/store_chat_attachment.go
T
Michael Suchacz 57f38b5c24 fix: keep chat attachments while a linking chat exists
Fixes https://linear.app/codercom/issue/CODAGT-616/keep-chat-attachments-while-chats-remain-unarchived

Chat attachments could disappear even though the chat was still available. This happened when a message was saved without recording which attachments it used, or when cleanup deleted attachments before an archived chat itself was removed.

Creating a chat, sending or queuing a message, and editing a message now record both the message and which attachments it uses as one operation. If the chat is already at the 50-attachment limit, the chat change fails without being partially saved.

Concurrent attachment writes serialize the 50-file cap per chat. Cleanup locks candidates and checks again for new links before deleting. If a file becomes unavailable after input validation, create, send, and edit return a clear client error and roll back the chat change.

An attachment stays available while any chat that uses it still exists. After an archived chat reaches the end of its retention period and is deleted, an old attachment that no remaining chat uses can be cleaned up. The retention guide and unavailable-attachment UI text document this lifecycle. This change cannot restore attachments that were already deleted.

The database migration adds two indexes so attachment cleanup stays fast as attachments accumulate.

> This PR was authored by Mux (AI) on Mike's behalf.
2026-08-11 13:53:15 +02:00

109 lines
2.9 KiB
Go

package chatd
import (
"context"
"errors"
"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"
"github.com/coder/coder/v2/codersdk"
)
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 {
if errors.Is(err, chatstate.ErrChatFileCapExceeded) {
return chattool.AttachmentMetadata{}, xerrors.Errorf("chat already has the maximum of %d linked files", codersdk.MaxChatFileIDs)
}
return chattool.AttachmentMetadata{}, err
}
return chattool.AttachmentMetadata{
FileID: row.ID,
MediaType: mediaType,
Name: name,
}, nil
}