feat(chat): add session-scoped temporary attachments with async parsing

Let users upload documents in chat without ingesting them into a knowledge base: files are parsed in the background, referenced by ID on send, and expire after a configurable TTL.
This commit is contained in:
wizardchen
2026-07-16 14:48:20 +08:00
committed by lyingbug
parent 7b2c9e73bf
commit ceb4d1a310
63 changed files with 3513 additions and 248 deletions
+209 -3
View File
@@ -6,7 +6,10 @@ import (
"encoding/json"
"fmt"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
@@ -44,7 +47,9 @@ type qaRequestContext struct {
images []ImageAttachment // Uploaded images with analysis text
userMessageID string // Created user message ID (populated after createUserMessage)
channel string // Source channel: "web", "api", "im", etc.
attachments types.MessageAttachments // Processed file attachments
attachments types.MessageAttachments // Processed base64 file attachments (legacy inline uploads)
attachmentIDs []string // Pre-uploaded session-scoped document IDs, resolved after SSE starts
attachmentMetas types.MessageAttachments // Metadata-only view of attachmentIDs for the persisted user message
suggestionAttribution *types.SuggestionAttribution
// Snapshot of the request fields needed to persist the input-bar state
@@ -246,6 +251,37 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
logger.Infof(ctx, "[%s] all attachments processed", logPrefix)
}
// Pre-uploaded documents may still be parsing. Only fetch their metadata
// here (fast, available even while processing) to validate agent file-type
// limits and to record the attachments on the persisted user message. The
// heavy content selection happens after the SSE stream is up, so the send
// is not blocked while parsing finishes (see resolveTemporaryAttachments).
var attachmentIDs []string
var attachmentMetas types.MessageAttachments
if len(request.AttachmentIDs) > 0 {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
attachmentMetas = make(types.MessageAttachments, 0, len(request.AttachmentIDs))
for _, id := range request.AttachmentIDs {
doc, getErr := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
if getErr != nil || doc == nil {
return nil, nil, errors.NewBadRequestError(
fmt.Sprintf("attachment %s was not found in this session", secutils.SanitizeForLog(id)))
}
if customAgent != nil && len(customAgent.Config.SupportedFileTypes) > 0 {
ext := strings.TrimPrefix(strings.ToLower(doc.FileType), ".")
if !containsFileType(customAgent.Config.SupportedFileTypes, ext) {
return nil, nil, errors.NewBadRequestError(
fmt.Sprintf("file type %s is not supported by this agent", ext))
}
}
attachmentMetas = append(attachmentMetas, types.MessageAttachment{
ID: doc.ID, URL: doc.ResourceRef, FileName: doc.FileName,
FileType: doc.FileType, FileSize: doc.FileSize,
})
}
attachmentIDs = request.AttachmentIDs
}
// Resolve enable_memory:
// 1. Explicit value in request → honour it. Used by embedded mode
// (force false) and by older clients still sending the literal bool.
@@ -314,6 +350,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
images: request.Images,
channel: request.Channel,
attachments: processedAttachments,
attachmentIDs: attachmentIDs,
attachmentMetas: attachmentMetas,
suggestionAttribution: request.SuggestionAttribution,
reqAgentEnabled: request.AgentEnabled,
reqAgentID: request.AgentID,
@@ -781,8 +819,13 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
}
}
// Create user message
userMsg, err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems, convertImageAttachments(reqCtx.images), reqCtx.attachments, reqCtx.channel, reqCtx.suggestionAttribution)
// Create user message. Include pre-uploaded document metadata so history
// reload shows the attachments even though their content is selected later.
userMessageAttachments := reqCtx.attachments
if len(reqCtx.attachmentMetas) > 0 {
userMessageAttachments = append(append(types.MessageAttachments{}, reqCtx.attachments...), reqCtx.attachmentMetas...)
}
userMsg, err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems, convertImageAttachments(reqCtx.images), userMessageAttachments, reqCtx.channel, reqCtx.suggestionAttribution)
if err != nil {
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
return
@@ -882,6 +925,10 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
}
}()
// Resolve pre-uploaded attachments (may still be parsing): waits with a
// timeline step so the send is not blocked, then injects content/images.
h.resolveTemporaryAttachments(streamCtx, reqCtx)
// Run VLM image analysis if applicable
h.runVLMAnalysisIfNeeded(streamCtx, reqCtx, mode)
@@ -995,6 +1042,165 @@ func (h *Handler) runVLMAnalysisIfNeeded(streamCtx *sseStreamContext, reqCtx *qa
})
}
// defaultAttachmentParseWaitTimeout bounds how long a QA turn waits for
// still-parsing attachments before proceeding with only the finished ones.
// Large or scanned documents can exceed this; raise it via
// WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC when needed.
const defaultAttachmentParseWaitTimeout = 60 * time.Second
// attachmentParseWaitTimeout returns the configured wait timeout, honoring the
// WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC override (in seconds) and falling
// back to the default when unset or invalid.
func attachmentParseWaitTimeout() time.Duration {
if raw := strings.TrimSpace(os.Getenv("WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC")); raw != "" {
if secs, err := strconv.Atoi(raw); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
}
return defaultAttachmentParseWaitTimeout
}
// resolveTemporaryAttachments selects prompt content for pre-uploaded documents
// after the SSE stream is live. When any attachment is still parsing it emits a
// "attachment_parsing" timeline step and waits (bounded); unfinished attachments
// are skipped rather than blocking or failing the whole turn.
func (h *Handler) resolveTemporaryAttachments(streamCtx *sseStreamContext, reqCtx *qaRequestContext) {
if len(reqCtx.attachmentIDs) == 0 {
return
}
ctx := streamCtx.asyncCtx
sessionID := reqCtx.sessionID
tenantID := reqCtx.c.GetUint64(types.TenantIDContextKey.String())
start := time.Now()
var toolCallID string
if h.hasPendingAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs) {
toolCallID = uuid.New().String()
streamCtx.eventBus.Emit(ctx, event.Event{
Type: event.EventAgentToolCall,
SessionID: sessionID,
Data: event.AgentToolCallData{
ToolCallID: toolCallID,
ToolName: "attachment_parsing",
Iteration: 0,
},
})
waitTimeout := attachmentParseWaitTimeout()
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.AttachmentParseWaitTimeoutSec > 0 {
waitTimeout = time.Duration(reqCtx.customAgent.Config.AttachmentParseWaitTimeoutSec) * time.Second
}
h.waitForAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs, waitTimeout)
}
readyIDs, skipped := h.partitionReadyAttachments(ctx, tenantID, sessionID, reqCtx.attachmentIDs)
var temporaryResult *types.TemporaryDocumentPromptResult
var resolveErr error
if len(readyIDs) > 0 {
temporaryResult, resolveErr = h.temporaryDocuments.ResolveForPrompt(ctx, tenantID, sessionID, readyIDs, reqCtx.query)
}
if toolCallID != "" {
output := fmt.Sprintf("已解析 %d 个附件", len(readyIDs))
if skipped > 0 {
output += fmt.Sprintf(",%d 个未完成已跳过", skipped)
}
success := resolveErr == nil
if resolveErr != nil {
output = fmt.Sprintf("附件解析失败: %v", resolveErr)
}
streamCtx.eventBus.Emit(ctx, event.Event{
Type: event.EventAgentToolResult,
SessionID: sessionID,
Data: event.AgentToolResultData{
ToolCallID: toolCallID,
ToolName: "attachment_parsing",
Output: output,
Success: success,
Duration: time.Since(start).Milliseconds(),
Iteration: 0,
Data: map[string]interface{}{
"display_type": "attachment_parsing",
"parsed_count": len(readyIDs),
"skipped_count": skipped,
},
},
})
}
if resolveErr != nil || temporaryResult == nil {
if resolveErr != nil {
logger.Warnf(ctx, "temporary attachment resolution failed for session %s: %v", sessionID, resolveErr)
}
return
}
attachments := temporaryResult.Attachments
if reqCtx.customAgent != nil && len(reqCtx.customAgent.Config.SupportedFileTypes) > 0 {
filtered := attachments[:0]
for _, att := range attachments {
ext := strings.TrimPrefix(strings.ToLower(att.FileType), ".")
if containsFileType(reqCtx.customAgent.Config.SupportedFileTypes, ext) {
filtered = append(filtered, att)
}
}
attachments = filtered
}
reqCtx.attachments = append(reqCtx.attachments, attachments...)
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ImageUploadEnabled {
for _, imageURL := range temporaryResult.ImageURLs {
reqCtx.images = append(reqCtx.images, ImageAttachment{URL: imageURL})
}
}
}
// 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 {
for _, id := range ids {
doc, err := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
if err != nil || doc == nil {
continue
}
if doc.Status == types.TemporaryDocumentStatusUploaded ||
doc.Status == types.TemporaryDocumentStatusProcessing {
return true
}
}
return false
}
// waitForAttachments polls until no attachment is pending or the timeout / ctx
// cancellation fires.
func (h *Handler) waitForAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string, timeout time.Duration) {
deadline := time.Now().Add(timeout)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
if !h.hasPendingAttachments(ctx, tenantID, sessionID, ids) || time.Now().After(deadline) {
return
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
// partitionReadyAttachments splits the ids into ready ones and a count of those
// skipped (missing, failed, or still parsing after the wait).
func (h *Handler) partitionReadyAttachments(ctx context.Context, tenantID uint64, sessionID string, ids []string) (ready []string, skipped int) {
for _, id := range ids {
doc, err := h.temporaryDocuments.Get(ctx, tenantID, sessionID, id)
if err != nil || doc == nil || doc.Status != types.TemporaryDocumentStatusReady {
skipped++
continue
}
ready = append(ready, id)
}
return ready, skipped
}
// persistLastRequestState records the input-bar state the user just sent so
// that reopening this session restores agent/model/KB/web-search/MCP picks.
// Pure UI memo — failures are logged but never bubble up; the caller runs