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
+3
View File
@@ -31,6 +31,7 @@ type Handler struct {
modelService interfaces.ModelService // Service for model management (VLM access)
userService interfaces.UserService // Service for resolving per-user preferences (e.g. enable_memory default)
attachmentProcessor *AttachmentProcessor // Processor for file attachments
temporaryDocuments interfaces.TemporaryDocumentService
}
// NewHandler creates a new instance of Handler with all necessary dependencies
@@ -51,6 +52,7 @@ func NewHandler(
userService interfaces.UserService,
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
temporaryDocuments interfaces.TemporaryDocumentService,
) *Handler {
return &Handler{
sessionService: sessionService,
@@ -67,6 +69,7 @@ func NewHandler(
storageResolver: storageResolver,
modelService: modelService,
userService: userService,
temporaryDocuments: temporaryDocuments,
attachmentProcessor: NewAttachmentProcessor(
fileService,
documentReader,
+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
@@ -0,0 +1,200 @@
package session
import (
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"strings"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
)
// UploadTemporaryDocument accepts one multipart file and immediately returns
// a session-scoped document ID. Parsing continues in the document worker.
func (h *Handler) UploadTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := c.Param("session_id")
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
maxBytes := secutils.GetMaxFileSizeMB()*1024*1024 + 1024*1024
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
fileHeader, err := c.FormFile("file")
if err != nil {
c.Error(apperrors.NewBadRequestError(fmt.Sprintf("invalid attachment upload: %v", err)))
return
}
file, err := fileHeader.Open()
if err != nil {
c.Error(apperrors.NewBadRequestError("failed to open attachment"))
return
}
defer file.Close()
agent, _ := h.resolveAgent(ctx, c, c.PostForm("agent_id"))
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(fileHeader.Filename)), ".")
options := types.TemporaryDocumentCreateOptions{ParserEngine: strings.TrimSpace(c.PostForm("parser_engine"))}
if agent != nil {
if len(agent.Config.SupportedFileTypes) > 0 && !containsFileType(agent.Config.SupportedFileTypes, ext) {
c.Error(apperrors.NewBadRequestError("file type is not supported by this agent"))
return
}
if isAudioExtension(ext) {
if !agent.Config.AudioUploadEnabled || agent.Config.ASRModelID == "" {
c.Error(apperrors.NewBadRequestError("audio upload is not enabled or no ASR model is configured"))
return
}
options.ASRModelID = agent.Config.ASRModelID
}
// Resolve the parser engine from the agent's chat rules when the caller
// did not pass an explicit engine. Tenant-level rules remain the final
// fallback and are applied in the parse worker.
if options.ParserEngine == "" || options.ParserEngine == "auto" {
if engine := agent.Config.ResolveChatParserEngine(ext); engine != "" {
options.ParserEngine = engine
}
}
// Image understanding (caption/OCR) uses the agent's VLM model. Images
// always benefit; scanned/image-only documents only OCR when the agent
// enabled AttachmentImageUnderstanding (see parse worker threshold gate).
if agent.Config.ImageUploadEnabled && agent.Config.VLMModelID != "" {
options.VLMModelID = agent.Config.VLMModelID
options.ImageUnderstanding = agent.Config.AttachmentImageUnderstanding
options.OCRMaxPages = agent.Config.AttachmentOCRMaxPages
}
}
document, err := h.temporaryDocuments.Create(
ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID,
fileHeader.Filename, fileHeader.Header.Get("Content-Type"), fileHeader.Size, file, options,
)
if err != nil {
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": document})
}
func (h *Handler) ListTemporaryDocuments(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
documents, err := h.temporaryDocuments.List(ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID)
if err != nil {
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": documents})
}
func (h *Handler) GetTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
document, err := h.temporaryDocuments.Get(ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID, c.Param("attachment_id"))
if err != nil {
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
if document == nil {
c.Error(apperrors.NewNotFoundError("Attachment not found"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": document})
}
func (h *Handler) PreviewTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
attachmentID := secutils.SanitizeForLog(c.Param("attachment_id"))
if attachmentID == "" {
c.Error(apperrors.NewBadRequestError("Attachment ID cannot be empty"))
return
}
file, filename, err := h.temporaryDocuments.OpenFile(
ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID, attachmentID,
)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "not found") {
c.Error(apperrors.NewNotFoundError("Attachment not found"))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(apperrors.NewInternalServerError("Failed to retrieve attachment").WithDetails(err.Error()))
return
}
defer file.Close()
contentType, inline := secutils.SafeContentTypeByFilename(filename)
c.Header("Content-Type", contentType)
c.Header("X-Content-Type-Options", "nosniff")
disposition := "inline"
if !inline {
disposition = "attachment"
}
c.Header("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": filename}))
c.Header("Cache-Control", "private, max-age=3600")
c.Stream(func(w io.Writer) bool {
if _, err := io.Copy(w, file); err != nil {
logger.Errorf(ctx, "Failed to stream attachment preview: %v", err)
return false
}
return false
})
}
func (h *Handler) DeleteTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
if err := h.temporaryDocuments.Delete(ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID, c.Param("attachment_id")); err != nil {
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
c.Status(http.StatusNoContent)
}
func sessionIDParam(c *gin.Context) string {
if value := c.Param("session_id"); value != "" {
return value
}
return c.Param("id")
}
func containsFileType(supported []string, ext string) bool {
for _, item := range supported {
if strings.TrimPrefix(strings.ToLower(strings.TrimSpace(item)), ".") == ext {
return true
}
}
return false
}
func isAudioExtension(ext string) bool {
switch ext {
case "mp3", "wav", "m4a", "flac", "ogg", "aac":
return true
default:
return false
}
}
+1
View File
@@ -68,6 +68,7 @@ type CreateKnowledgeQARequest struct {
EnableMemory *bool `json:"enable_memory,omitempty"`
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
AttachmentIDs []string `json:"attachment_ids,omitempty"` // Pre-uploaded session-scoped document IDs
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"`
}