feat(session): persist last request state for UI restoration

Sessions now record the input-bar state used for the most recent QA
request (agent, model, KB scope, web search). The chat UI hydrates
those settings on session reopen so users see the same configuration
they used last time, instead of the global default.

The state is stored in the existing sessions.agent_config JSONB column
to avoid a new migration. Frontend snapshots the user's global defaults
on session enter and restores them on session leave, so opening an old
session does not pollute new-chat defaults.
This commit is contained in:
wizardchen
2026-05-18 22:24:39 +08:00
committed by lyingbug
parent 8dd9b67df9
commit 7bb38f81b6
8 changed files with 282 additions and 20 deletions
@@ -239,6 +239,33 @@ func (r *sessionRepository) Update(ctx context.Context, session *types.Session,
return res.RowsAffected, res.Error
}
// UpdateLastRequestState writes only the agent_config column (used here to
// store SessionLastRequestState) and bumps updated_at. We deliberately bypass
// the regular Update path so the call doesn't perturb title/description and
// stays cheap (single-row UPDATE by PK).
func (r *sessionRepository) UpdateLastRequestState(
ctx context.Context, tenantID uint64, userID string, sessionID string,
state *types.SessionLastRequestState,
) (int64, error) {
now := time.Now()
var stateValue interface{}
if state != nil {
v, err := state.Value()
if err != nil {
return 0, err
}
stateValue = v
}
res := applySessionUserScope(r.db.WithContext(ctx).
Model(&types.Session{}).
Where("tenant_id = ? AND id = ?", tenantID, sessionID), userID).
Updates(map[string]interface{}{
"agent_config": stateValue,
"updated_at": now,
})
return res.RowsAffected, res.Error
}
// Delete deletes a session
func (r *sessionRepository) Delete(ctx context.Context, tenantID uint64, userID string, id string) (int64, error) {
res := applySessionUserScope(
+27
View File
@@ -247,6 +247,33 @@ func (s *sessionService) UpdateSession(ctx context.Context, session *types.Sessi
return nil
}
// UpdateSessionLastRequestState persists the input-bar state used by the most
// recent QA request on this session. Called from the QA handler after a
// request is accepted so the UI can rehydrate the same settings on reopen.
// Best-effort: scope mismatches are logged and swallowed — failing to record
// the UI memo should never fail the user's chat request.
func (s *sessionService) UpdateSessionLastRequestState(
ctx context.Context, sessionID string, state *types.SessionLastRequestState,
) error {
if sessionID == "" {
return stderrors.New("session id is required")
}
tenantID := types.MustTenantIDFromContext(ctx)
userID := sessionUserIDFromContext(ctx)
affected, err := s.sessionRepo.UpdateLastRequestState(ctx, tenantID, userID, sessionID, state)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"tenant_id": tenantID,
})
return err
}
if affected == 0 {
logger.Warnf(ctx, "UpdateSessionLastRequestState: no rows affected for session %s", sessionID)
}
return nil
}
// DeleteSession removes a session by its ID
func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
// Validate session ID
+51 -4
View File
@@ -35,11 +35,17 @@ type qaRequestContext struct {
webSearchEnabled bool
enableMemory bool // Whether memory feature is enabled
mentionedItems types.MentionedItems
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
images []ImageAttachment // Uploaded images with analysis text
userMessageID string // Created user message ID (populated after createUserMessage)
channel string // Source channel: "web", "api", "im", etc.
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
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
// Snapshot of the request fields needed to persist the input-bar state
// for session restoration. Kept verbatim from the request so we record
// what the user had selected on the UI (not server-side resolutions).
reqAgentEnabled bool
reqAgentID string
}
// buildQARequest converts the qaRequestContext into a types.QARequest for service invocation.
@@ -241,6 +247,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
images: request.Images,
channel: request.Channel,
attachments: processedAttachments,
reqAgentEnabled: request.AgentEnabled,
reqAgentID: request.AgentID,
}
return reqCtx, &request, nil
@@ -608,6 +616,13 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
ctx := reqCtx.ctx
sessionID := reqCtx.sessionID
// Persist the input-bar state used for this request so reopening the
// session can rehydrate agent / model / KB / web-search / MCP selections.
// This is a pure UI memo (no behavioural effect) and runs in a goroutine
// to avoid adding a DB round-trip to TTFB. Use WithoutCancel so a fast
// client disconnect doesn't drop the write.
go h.persistLastRequestState(ctx, reqCtx, mode)
// Agent mode: emit agent query event before message creation
if mode == qaModeAgent {
if err := event.Emit(ctx, event.Event{
@@ -817,6 +832,38 @@ func (h *Handler) runVLMAnalysisIfNeeded(streamCtx *sseStreamContext, reqCtx *qa
})
}
// 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
// this in a goroutine and is safe to discard the returned context.
func (h *Handler) persistLastRequestState(parentCtx context.Context, reqCtx *qaRequestContext, mode qaMode) {
// Detach from the HTTP request lifetime: this write must survive both
// SSE disconnects and the parent gin context being released after the
// handler returns.
ctx := logger.CloneContext(context.WithoutCancel(parentCtx))
agentEnabled := reqCtx.reqAgentEnabled
// Mirror the resolution rule used in AgentQA: a resolved custom agent's
// agent_mode wins over the request flag. For KnowledgeQA the request
// itself carries agent_enabled=false, so this collapses correctly.
if mode == qaModeAgent && reqCtx.customAgent != nil {
agentEnabled = reqCtx.customAgent.IsAgentMode()
}
state := &types.SessionLastRequestState{
AgentID: reqCtx.reqAgentID,
AgentEnabled: agentEnabled,
ModelID: reqCtx.summaryModelID,
KnowledgeBaseIDs: reqCtx.knowledgeBaseIDs,
KnowledgeIDs: reqCtx.knowledgeIDs,
WebSearchEnabled: reqCtx.webSearchEnabled,
}
if err := h.sessionService.UpdateSessionLastRequestState(ctx, reqCtx.sessionID, state); err != nil {
logger.Warnf(ctx, "persist last_request_state failed for session %s: %v", reqCtx.sessionID, err)
}
}
// completeAssistantMessage marks an assistant message as complete, updates it,
// and asynchronously indexes the Q&A pair into the chat history knowledge base.
func (h *Handler) completeAssistantMessage(ctx context.Context, assistantMessage *types.Message, userQuery string) {
+4 -4
View File
@@ -58,10 +58,10 @@ type CreateKnowledgeQARequest struct {
// user's personal memory setting doesn't leak into a widget
// context; older clients that still send a literal bool also
// land here (back-compat).
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.)
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
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.)
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
}
// AttachmentUpload represents a file attachment upload from the client
+8
View File
@@ -19,6 +19,10 @@ type SessionService interface {
GetPagedSessionsByTenant(ctx context.Context, page *types.Pagination) (*types.PageResult, error)
// UpdateSession updates a session
UpdateSession(ctx context.Context, session *types.Session) error
// UpdateSessionLastRequestState records the input-bar state used for the
// most recent QA request on this session. Best-effort: callers should log
// but not surface failures to the user.
UpdateSessionLastRequestState(ctx context.Context, sessionID string, state *types.SessionLastRequestState) error
// DeleteSession deletes a session
DeleteSession(ctx context.Context, id string) error
// BatchDeleteSessions deletes multiple sessions by IDs
@@ -65,6 +69,10 @@ type SessionRepository interface {
QueryPaged(ctx context.Context, q *types.SessionListQuery) ([]*types.SessionListItem, int64, error)
// Update updates a session visible to the tenant/user scope.
Update(ctx context.Context, session *types.Session, userID string) (int64, error)
// UpdateLastRequestState persists the most recent input-bar state for a
// session (agent, model, KB scope, etc.) so the chat UI can restore it
// when the session is reopened. Scope rules match Update.
UpdateLastRequestState(ctx context.Context, tenantID uint64, userID string, sessionID string, state *types.SessionLastRequestState) (int64, error)
// SetPinned pins or unpins a session row scoped by tenant.
// userID, when non-empty, is enforced so users cannot pin sessions they don't own.
// Returns the number of rows affected; 0 means the session doesn't exist or is
+56
View File
@@ -89,6 +89,14 @@ type Session struct {
// PinnedAt records when the session was pinned; nil when not pinned.
PinnedAt *time.Time `json:"pinned_at,omitempty"`
// LastRequestState records the input-bar state used the last time this
// session sent a question (agent, model, KB scope, web search, MCPs).
// Persisted on every successful POST to /knowledge-chat or /agent-chat so
// that reopening the session can restore the original request context to
// the chat UI. Stored in the legacy sessions.agent_config JSONB column to
// avoid a new migration; the shape used today is `SessionLastRequestState`.
LastRequestState *SessionLastRequestState `json:"last_request_state,omitempty" gorm:"column:agent_config;type:jsonb"`
// // Strategy configuration
// KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
// MaxRounds int `json:"max_rounds"` // 多轮保持轮数
@@ -184,6 +192,54 @@ func (c *SummaryConfig) Scan(value interface{}) error {
return json.Unmarshal(b, c)
}
// SessionLastRequestState captures the user-facing input-bar state at the
// time of the most recent QA request on a session. It is purely a UI memory
// aid — none of the fields here drive backend behaviour. They are echoed back
// to the frontend by GetSession so the chat input can restore the same agent,
// model, KB scope, etc. the user had selected last time.
type SessionLastRequestState struct {
AgentID string `json:"agent_id,omitempty"`
AgentEnabled bool `json:"agent_enabled"`
ModelID string `json:"model_id,omitempty"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
WebSearchEnabled bool `json:"web_search_enabled"`
}
// Value implements driver.Valuer for SessionLastRequestState (JSONB).
func (s *SessionLastRequestState) Value() (driver.Value, error) {
if s == nil {
return nil, nil
}
return json.Marshal(s)
}
// Scan implements sql.Scanner for SessionLastRequestState (JSONB).
// Tolerates legacy values that may not match the current schema by silently
// ignoring unmarshal errors — the stored row predates this struct.
func (s *SessionLastRequestState) Scan(value interface{}) error {
if value == nil {
return nil
}
var b []byte
switch v := value.(type) {
case []byte:
b = v
case string:
b = []byte(v)
default:
return nil
}
if len(b) == 0 {
return nil
}
if err := json.Unmarshal(b, s); err != nil {
// Tolerate legacy shapes from before this column was repurposed.
return nil
}
return nil
}
// Value implements the driver.Valuer interface, used to convert ContextConfig to database value
func (c *ContextConfig) Value() (driver.Value, error) {
return json.Marshal(c)