fix(chat): persist attachment content and fix fallback multi-turn context

Persist resolved temporary-attachment content onto the stored user message
so later turns can replay it in history. Close the retrieval progress spinner
on early pipeline exits, and reshape model-fallback messages with a proper
system role plus trailing user question.
This commit is contained in:
wizardchen
2026-07-16 16:38:22 +08:00
committed by lyingbug
parent 92ceb3bd7d
commit 9ae17be43c
7 changed files with 308 additions and 10 deletions
+53
View File
@@ -1146,6 +1146,12 @@ func (h *Handler) resolveTemporaryAttachments(streamCtx *sseStreamContext, reqCt
attachments = filtered
}
reqCtx.attachments = append(reqCtx.attachments, attachments...)
// Persist the freshly selected content back onto the stored user message.
// The message was created with metadata-only attachment entries (content is
// selected here, after the SSE stream is live), so without this write a
// later Agent-mode turn rebuilds history from the Attachments column and
// sees empty attachments (see buildUserHistoryMessage in agent_history.go).
h.persistResolvedAttachmentContent(ctx, reqCtx, attachments)
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ImageUploadEnabled {
for _, imageURL := range temporaryResult.ImageURLs {
reqCtx.images = append(reqCtx.images, ImageAttachment{URL: imageURL})
@@ -1153,6 +1159,53 @@ func (h *Handler) resolveTemporaryAttachments(streamCtx *sseStreamContext, reqCt
}
}
// persistResolvedAttachmentContent writes the parsed content of pre-uploaded
// attachments back onto the stored user message so multi-turn history can
// replay it. Entries are matched by their temporary-document ID; only those
// present on the message are enriched. Failures are logged but never bubble up
// — losing the write only degrades follow-up context, it must not fail the turn.
func (h *Handler) persistResolvedAttachmentContent(
ctx context.Context, reqCtx *qaRequestContext, resolved types.MessageAttachments,
) {
if reqCtx.userMessageID == "" || len(resolved) == 0 {
return
}
// Detach from the request/stream lifetime and pin the session tenant so a
// user-triggered stop (which cancels asyncCtx) does not drop the write.
updateCtx := context.WithValue(
context.WithoutCancel(ctx), types.TenantIDContextKey, reqCtx.session.TenantID,
)
msg, err := h.messageService.GetMessage(updateCtx, reqCtx.sessionID, reqCtx.userMessageID)
if err != nil || msg == nil {
logger.Warnf(updateCtx, "persist attachment content: load user message %s failed: %v",
reqCtx.userMessageID, err)
return
}
byID := make(map[string]types.MessageAttachment, len(resolved))
for _, att := range resolved {
if att.ID != "" {
byID[att.ID] = att
}
}
changed := false
for i := range msg.Attachments {
if msg.Attachments[i].ID == "" {
continue
}
if enriched, ok := byID[msg.Attachments[i].ID]; ok {
msg.Attachments[i] = enriched
changed = true
}
}
if !changed {
return
}
if err := h.messageService.UpdateMessage(updateCtx, msg); err != nil {
logger.Warnf(updateCtx, "persist attachment content: update user message %s failed: %v",
reqCtx.userMessageID, err)
}
}
// hasPendingAttachments reports whether any of the given documents is still
// uploading or being parsed.
func (h *Handler) hasPendingAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string) bool {
@@ -0,0 +1,107 @@
package session
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// attachmentMsgStub implements just the two MessageService methods used by
// persistResolvedAttachmentContent; the rest are inherited from the embedded
// interface and panic if unexpectedly called.
type attachmentMsgStub struct {
interfaces.MessageService
stored *types.Message
updated *types.Message
updateCalls int
}
func (s *attachmentMsgStub) GetMessage(_ context.Context, _ string, _ string) (*types.Message, error) {
return s.stored, nil
}
func (s *attachmentMsgStub) UpdateMessage(_ context.Context, message *types.Message) error {
s.updateCalls++
s.updated = message
return nil
}
func newAttachmentReqCtx() *qaRequestContext {
return &qaRequestContext{
sessionID: "sess-1",
userMessageID: "user-msg-1",
session: &types.Session{TenantID: 42},
}
}
// TestPersistResolvedAttachmentContent_EnrichesMatchingAttachments is the core
// regression guard for PR #2086: the user message is created with
// metadata-only attachment entries, and the parsed content selected after the
// SSE stream starts must be written back so multi-turn (Agent-mode) history can
// replay it via the Attachments column.
func TestPersistResolvedAttachmentContent_EnrichesMatchingAttachments(t *testing.T) {
stub := &attachmentMsgStub{
stored: &types.Message{
ID: "user-msg-1",
SessionID: "sess-1",
Role: "user",
Attachments: types.MessageAttachments{
{ID: "doc-1", FileName: "report.pdf", FileType: ".pdf"},
// Legacy inline upload without an ID must stay untouched.
{FileName: "note.txt", FileType: ".txt", Content: "legacy inline"},
},
},
}
h := &Handler{messageService: stub}
resolved := types.MessageAttachments{
{
ID: "doc-1", FileName: "report.pdf", FileType: ".pdf",
Content: "parsed body text", ContentMode: "selected_chunks",
SelectedChunks: 1, TotalChunks: 3, TokenCount: 12,
},
}
h.persistResolvedAttachmentContent(context.Background(), newAttachmentReqCtx(), resolved)
require.Equal(t, 1, stub.updateCalls, "matching attachment must trigger one persist")
require.NotNil(t, stub.updated)
require.Len(t, stub.updated.Attachments, 2)
assert.Equal(t, "parsed body text", stub.updated.Attachments[0].Content)
assert.Equal(t, "selected_chunks", stub.updated.Attachments[0].ContentMode)
assert.Equal(t, 3, stub.updated.Attachments[0].TotalChunks)
// Legacy inline attachment (no ID) is preserved verbatim.
assert.Equal(t, "legacy inline", stub.updated.Attachments[1].Content)
}
func TestPersistResolvedAttachmentContent_NoMatchSkipsUpdate(t *testing.T) {
stub := &attachmentMsgStub{
stored: &types.Message{
ID: "user-msg-1", SessionID: "sess-1", Role: "user",
Attachments: types.MessageAttachments{{ID: "doc-1", FileName: "a.pdf"}},
},
}
h := &Handler{messageService: stub}
resolved := types.MessageAttachments{{ID: "doc-other", Content: "x"}}
h.persistResolvedAttachmentContent(context.Background(), newAttachmentReqCtx(), resolved)
assert.Equal(t, 0, stub.updateCalls, "no matching ID must not persist")
}
func TestPersistResolvedAttachmentContent_GuardsEmptyInput(t *testing.T) {
stub := &attachmentMsgStub{}
h := &Handler{messageService: stub}
// No resolved attachments.
h.persistResolvedAttachmentContent(context.Background(), newAttachmentReqCtx(), nil)
// No user message ID.
rc := newAttachmentReqCtx()
rc.userMessageID = ""
h.persistResolvedAttachmentContent(context.Background(), rc, types.MessageAttachments{{ID: "doc-1", Content: "x"}})
assert.Equal(t, 0, stub.updateCalls)
}