WeKnora/internal/handler/message.go

441 lines
17 KiB
Go
Raw Normal View History

2025-08-05 07:08:07 +00:00
package handler
import (
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) * feat(agent): persist human-in-the-loop prompts with a shared broker Tool approvals and MCP OAuth prompts are now rows in agent_prompts, awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind answer validation). Resolve is bound to session and kind. This is P1 of the suspend/resume design; runs still block as before. * feat(agent): suspend runs whose prompt outlives a short in-memory wait Behind agent.prompt_suspend_enabled (off by default). A run raised from the HTTP stream saves its state when a tool approval is raised; after the hot wait the prompt moves to suspended and the assistant message is saved as awaiting_input instead of blocking. A reaper takes over prompts whose waiting replica stopped renewing its lease. Resume comes in a later change. * feat(agent): resume suspended runs once their prompt is answered The replica that records the answer resumes the run in process under the prompt's lease. Superseded, expired and abandoned runs are closed with a result for every tool call, and approved tools are never replayed. * feat(agent): let users answer suspended tool approvals and follow the resumed run * feat(agent): ask_user tool and generic prompt answer endpoint - ask_user built-in tool: options, short forms or free text; validated answers, decline, suspend/resume like tool approval; non-interactive callers (IM, API keys) are told to ask in the reply instead - POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt - agent_prompt_required/resolved events; AskUserCard sharing the countdown with ToolApprovalCard; answered questions rebuilt as cards from history - awaiting-input messages keep their steps expanded so the pending card stays visible; prompt cards keyed by their own id - i18n for all locales; design doc updated * fix(agent): keep prompt answers that race a suspending or vanished owner - Resolve suspends a pending prompt whose owner's lease lapsed, as the reaper would, so the answer resumes the run instead of waking nobody. - Resuming waits for the suspending run to persist its message and clear its live-run marker; a marker left by a vanished owner is cleared. - A resumed run that suspends again on a new prompt no longer has its message closed from the old state. - tool_approval answers are decoded strictly and require "approved"; fix the SDK doc that showed {"decision": "approve"}. - API-key runs block instead of suspending, since they cannot answer. - A run state that cannot be saved falls back to an in-memory wait, and NUL escapes are stripped from snapshots for jsonb. * style(chat): align the ask_user card with the other interaction cards Question and answer use the timeline's step text styles instead of primary-colored and monospace text; options and form controls use the compact step size, the number input spans the row, and the free-text character counter is hidden. * feat(chat): dock pending agent prompts above the composer Tool approvals, ask_user questions and MCP OAuth prompts were answered inline in the agent timeline, where a long answer or scrolling back pushes them out of view. Open prompts of a streaming or suspended run now gather in a dock above the composer (main chat and embed), one at a time with a pager, lettered options and Enter to submit. The timeline keeps a one-line record with a link back to the dock and the outcome once answered. Views without a dock still answer inline. * fix(agent): fence prompt ownership and preserve resumed turn context * fix(agent): keep runs through consume errors and file prompts under the caller Consume reported a store error as a lost claim, so an answer consumed during a database hiccup detached its run: the message was never persisted, the live-run marker stayed, and the reaper skipped the row because the waiter had already dropped the snapshot. Consume now retries, then decides from the row, and gives a run up only when the prompt is known to have moved on. Tool approvals and OAuth prompts of a shared agent were filed under the agent's workspace, so the user's answer failed the tenant check and the prompt timed out. Like ask_user, they now use the caller's workspace; policy and token lookups stay in the agent's. Enter on a picked option submits it instead of toggling it off, and resume errors no longer report a nil cause. * fix(agent): validate prompt choices and require durable approval claims Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices. * fix(agent): resolve prompt workflow lint errors
2026-10-14 12:37:28 +00:00
"context"
fix(session): map ErrSessionNotFound to 404 across all handlers PR #1309 plumbed user-scope into the session/message service layer so non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at every entry point that goes through sessionRepo.Get. The handler-side mapping, however, only existed in 4 of the 8 affected sites: - handler/session/handler.go:GetSession ✓ already mapped (with `==`) - handler/session/handler.go:UpdateSession ✓ already mapped (with `==`) - handler/session/handler.go:DeleteSession ✓ already mapped (with `==`) - handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`) - handler/session/handler.go:ClearSessionMessages ✗ always 500 - handler/session/stream.go:ContinueStream session lookup ✓ (with `==`) - handler/session/stream.go:ContinueStream message lookup ✗ always 500 - handler/message.go:LoadMessages (recent + before-time) ✗ always 500 - handler/message.go:DeleteMessage ✗ always 500 Result: a Contributor in tenant A asking for a Contributor B's session messages got a 500 instead of 404 — the wire response leaked "something is broken" rather than "you can't see this URL", which breaks SDK / frontend axios interceptor error handling that keys on HTTP status. Two changes: 1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it (ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's two paths, DeleteMessage). 2. Replace `err == errors.ErrSessionNotFound` with `stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel error comparison must use errors.Is so wrapped errors (`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no service-layer caller wraps, but a future refactor that does would silently turn 404s into 500s with no test catching it. Tests: - internal/handler/message_session_not_found_test.go covers the four new mapping sites in handler/message.go (LoadMessages-recent, LoadMessages-before-time, DeleteMessage) and pins the wrapped-error behaviour with a dedicated regression test that fmt.Errorf("%w") a sentinel must still be detected as ErrSessionNotFound. The bare handler is hit through gin.Engine + middleware.ErrorHandler so the response shape matches production exactly. - PR #1309's existing service-level tests (session_user_scope_test, session_test on the repository) still pass — this PR is a strictly handler-layer follow-up.
2026-05-14 08:44:55 +00:00
stderrors "errors"
2025-08-05 07:08:07 +00:00
"net/http"
"strconv"
"strings"
2025-08-05 07:08:07 +00:00
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/storageurl"
"github.com/Tencent/WeKnora/internal/types"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
2025-08-05 07:08:07 +00:00
)
const (
// defaultMessagesPageSize is the page size used when a client omits the
// limit or sends a non-positive one.
defaultMessagesPageSize = 20
// maxMessagesPageSize bounds the client-supplied page size of the message
// read endpoints. Without an upper bound a single request can ask for an
// arbitrarily large page; the search path additionally multiplies the
// forwarded value for a bounded over-fetch.
maxMessagesPageSize = 200
)
// clampMessagesPageSize bounds a client-supplied page size to
// [1, maxMessagesPageSize], substituting defaultMessagesPageSize for
// non-positive input. Callers must clamp at the edge: the repository only
// guards `limit <= 0` upstream and GORM omits the LIMIT clause entirely for
// negative values, so an unclamped -1 reads the whole table.
func clampMessagesPageSize(limit int) int {
if limit < 1 {
return defaultMessagesPageSize
}
if limit > maxMessagesPageSize {
return maxMessagesPageSize
}
return limit
}
2025-08-05 07:08:07 +00:00
// MessageHandler handles HTTP requests related to messages within chat sessions
// It provides endpoints for loading and managing message history
type MessageHandler struct {
MessageService interfaces.MessageService // Service that implements message business logic
// FileService and StorageResolver back the optional `resource_urls=public`
// mode, which returns loadable HTTP URLs instead of internal
// `resource://` handles. Both may be nil, in which case only the default
// handle mode is available.
FileService interfaces.FileService
StorageResolver interfaces.StorageBackendResolver
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) * feat(agent): persist human-in-the-loop prompts with a shared broker Tool approvals and MCP OAuth prompts are now rows in agent_prompts, awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind answer validation). Resolve is bound to session and kind. This is P1 of the suspend/resume design; runs still block as before. * feat(agent): suspend runs whose prompt outlives a short in-memory wait Behind agent.prompt_suspend_enabled (off by default). A run raised from the HTTP stream saves its state when a tool approval is raised; after the hot wait the prompt moves to suspended and the assistant message is saved as awaiting_input instead of blocking. A reaper takes over prompts whose waiting replica stopped renewing its lease. Resume comes in a later change. * feat(agent): resume suspended runs once their prompt is answered The replica that records the answer resumes the run in process under the prompt's lease. Superseded, expired and abandoned runs are closed with a result for every tool call, and approved tools are never replayed. * feat(agent): let users answer suspended tool approvals and follow the resumed run * feat(agent): ask_user tool and generic prompt answer endpoint - ask_user built-in tool: options, short forms or free text; validated answers, decline, suspend/resume like tool approval; non-interactive callers (IM, API keys) are told to ask in the reply instead - POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt - agent_prompt_required/resolved events; AskUserCard sharing the countdown with ToolApprovalCard; answered questions rebuilt as cards from history - awaiting-input messages keep their steps expanded so the pending card stays visible; prompt cards keyed by their own id - i18n for all locales; design doc updated * fix(agent): keep prompt answers that race a suspending or vanished owner - Resolve suspends a pending prompt whose owner's lease lapsed, as the reaper would, so the answer resumes the run instead of waking nobody. - Resuming waits for the suspending run to persist its message and clear its live-run marker; a marker left by a vanished owner is cleared. - A resumed run that suspends again on a new prompt no longer has its message closed from the old state. - tool_approval answers are decoded strictly and require "approved"; fix the SDK doc that showed {"decision": "approve"}. - API-key runs block instead of suspending, since they cannot answer. - A run state that cannot be saved falls back to an in-memory wait, and NUL escapes are stripped from snapshots for jsonb. * style(chat): align the ask_user card with the other interaction cards Question and answer use the timeline's step text styles instead of primary-colored and monospace text; options and form controls use the compact step size, the number input spans the row, and the free-text character counter is hidden. * feat(chat): dock pending agent prompts above the composer Tool approvals, ask_user questions and MCP OAuth prompts were answered inline in the agent timeline, where a long answer or scrolling back pushes them out of view. Open prompts of a streaming or suspended run now gather in a dock above the composer (main chat and embed), one at a time with a pager, lettered options and Enter to submit. The timeline keeps a one-line record with a link back to the dock and the outcome once answered. Views without a dock still answer inline. * fix(agent): fence prompt ownership and preserve resumed turn context * fix(agent): keep runs through consume errors and file prompts under the caller Consume reported a store error as a lost claim, so an answer consumed during a database hiccup detached its run: the message was never persisted, the live-run marker stayed, and the reaper skipped the row because the waiter had already dropped the snapshot. Consume now retries, then decides from the row, and gives a run up only when the prompt is known to have moved on. Tool approvals and OAuth prompts of a shared agent were filed under the agent's workspace, so the user's answer failed the tenant check and the prompt timed out. Like ask_user, they now use the caller's workspace; policy and token lookups stay in the agent's. Enter on a picked option submits it instead of toggling it off, and resume errors no longer report a nil cause. * fix(agent): validate prompt choices and require durable approval claims Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices. * fix(agent): resolve prompt workflow lint errors
2026-10-14 12:37:28 +00:00
// Prompts supplies the pending prompt of messages awaiting input. May be
// nil, in which case such messages carry none.
Prompts interfaces.AgentPromptRepository
2025-08-05 07:08:07 +00:00
}
// NewMessageHandler creates a new message handler instance with the required service
// Parameters:
// - messageService: Service that implements message business logic
// - fileService: Storage access used to sign public resource URLs
// - storageResolver: Resolves per-tenant storage backends for those URLs
2025-08-05 07:08:07 +00:00
//
// Returns a pointer to a new MessageHandler
func NewMessageHandler(
messageService interfaces.MessageService,
fileService interfaces.FileService,
storageResolver interfaces.StorageBackendResolver,
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) * feat(agent): persist human-in-the-loop prompts with a shared broker Tool approvals and MCP OAuth prompts are now rows in agent_prompts, awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind answer validation). Resolve is bound to session and kind. This is P1 of the suspend/resume design; runs still block as before. * feat(agent): suspend runs whose prompt outlives a short in-memory wait Behind agent.prompt_suspend_enabled (off by default). A run raised from the HTTP stream saves its state when a tool approval is raised; after the hot wait the prompt moves to suspended and the assistant message is saved as awaiting_input instead of blocking. A reaper takes over prompts whose waiting replica stopped renewing its lease. Resume comes in a later change. * feat(agent): resume suspended runs once their prompt is answered The replica that records the answer resumes the run in process under the prompt's lease. Superseded, expired and abandoned runs are closed with a result for every tool call, and approved tools are never replayed. * feat(agent): let users answer suspended tool approvals and follow the resumed run * feat(agent): ask_user tool and generic prompt answer endpoint - ask_user built-in tool: options, short forms or free text; validated answers, decline, suspend/resume like tool approval; non-interactive callers (IM, API keys) are told to ask in the reply instead - POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt - agent_prompt_required/resolved events; AskUserCard sharing the countdown with ToolApprovalCard; answered questions rebuilt as cards from history - awaiting-input messages keep their steps expanded so the pending card stays visible; prompt cards keyed by their own id - i18n for all locales; design doc updated * fix(agent): keep prompt answers that race a suspending or vanished owner - Resolve suspends a pending prompt whose owner's lease lapsed, as the reaper would, so the answer resumes the run instead of waking nobody. - Resuming waits for the suspending run to persist its message and clear its live-run marker; a marker left by a vanished owner is cleared. - A resumed run that suspends again on a new prompt no longer has its message closed from the old state. - tool_approval answers are decoded strictly and require "approved"; fix the SDK doc that showed {"decision": "approve"}. - API-key runs block instead of suspending, since they cannot answer. - A run state that cannot be saved falls back to an in-memory wait, and NUL escapes are stripped from snapshots for jsonb. * style(chat): align the ask_user card with the other interaction cards Question and answer use the timeline's step text styles instead of primary-colored and monospace text; options and form controls use the compact step size, the number input spans the row, and the free-text character counter is hidden. * feat(chat): dock pending agent prompts above the composer Tool approvals, ask_user questions and MCP OAuth prompts were answered inline in the agent timeline, where a long answer or scrolling back pushes them out of view. Open prompts of a streaming or suspended run now gather in a dock above the composer (main chat and embed), one at a time with a pager, lettered options and Enter to submit. The timeline keeps a one-line record with a link back to the dock and the outcome once answered. Views without a dock still answer inline. * fix(agent): fence prompt ownership and preserve resumed turn context * fix(agent): keep runs through consume errors and file prompts under the caller Consume reported a store error as a lost claim, so an answer consumed during a database hiccup detached its run: the message was never persisted, the live-run marker stayed, and the reaper skipped the row because the waiter had already dropped the snapshot. Consume now retries, then decides from the row, and gives a run up only when the prompt is known to have moved on. Tool approvals and OAuth prompts of a shared agent were filed under the agent's workspace, so the user's answer failed the tenant check and the prompt timed out. Like ask_user, they now use the caller's workspace; policy and token lookups stay in the agent's. Enter on a picked option submits it instead of toggling it off, and resume errors no longer report a nil cause. * fix(agent): validate prompt choices and require durable approval claims Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices. * fix(agent): resolve prompt workflow lint errors
2026-10-14 12:37:28 +00:00
prompts interfaces.AgentPromptRepository,
) *MessageHandler {
2025-08-05 07:08:07 +00:00
return &MessageHandler{
MessageService: messageService,
FileService: fileService,
StorageResolver: storageResolver,
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) * feat(agent): persist human-in-the-loop prompts with a shared broker Tool approvals and MCP OAuth prompts are now rows in agent_prompts, awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind answer validation). Resolve is bound to session and kind. This is P1 of the suspend/resume design; runs still block as before. * feat(agent): suspend runs whose prompt outlives a short in-memory wait Behind agent.prompt_suspend_enabled (off by default). A run raised from the HTTP stream saves its state when a tool approval is raised; after the hot wait the prompt moves to suspended and the assistant message is saved as awaiting_input instead of blocking. A reaper takes over prompts whose waiting replica stopped renewing its lease. Resume comes in a later change. * feat(agent): resume suspended runs once their prompt is answered The replica that records the answer resumes the run in process under the prompt's lease. Superseded, expired and abandoned runs are closed with a result for every tool call, and approved tools are never replayed. * feat(agent): let users answer suspended tool approvals and follow the resumed run * feat(agent): ask_user tool and generic prompt answer endpoint - ask_user built-in tool: options, short forms or free text; validated answers, decline, suspend/resume like tool approval; non-interactive callers (IM, API keys) are told to ask in the reply instead - POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt - agent_prompt_required/resolved events; AskUserCard sharing the countdown with ToolApprovalCard; answered questions rebuilt as cards from history - awaiting-input messages keep their steps expanded so the pending card stays visible; prompt cards keyed by their own id - i18n for all locales; design doc updated * fix(agent): keep prompt answers that race a suspending or vanished owner - Resolve suspends a pending prompt whose owner's lease lapsed, as the reaper would, so the answer resumes the run instead of waking nobody. - Resuming waits for the suspending run to persist its message and clear its live-run marker; a marker left by a vanished owner is cleared. - A resumed run that suspends again on a new prompt no longer has its message closed from the old state. - tool_approval answers are decoded strictly and require "approved"; fix the SDK doc that showed {"decision": "approve"}. - API-key runs block instead of suspending, since they cannot answer. - A run state that cannot be saved falls back to an in-memory wait, and NUL escapes are stripped from snapshots for jsonb. * style(chat): align the ask_user card with the other interaction cards Question and answer use the timeline's step text styles instead of primary-colored and monospace text; options and form controls use the compact step size, the number input spans the row, and the free-text character counter is hidden. * feat(chat): dock pending agent prompts above the composer Tool approvals, ask_user questions and MCP OAuth prompts were answered inline in the agent timeline, where a long answer or scrolling back pushes them out of view. Open prompts of a streaming or suspended run now gather in a dock above the composer (main chat and embed), one at a time with a pager, lettered options and Enter to submit. The timeline keeps a one-line record with a link back to the dock and the outcome once answered. Views without a dock still answer inline. * fix(agent): fence prompt ownership and preserve resumed turn context * fix(agent): keep runs through consume errors and file prompts under the caller Consume reported a store error as a lost claim, so an answer consumed during a database hiccup detached its run: the message was never persisted, the live-run marker stayed, and the reaper skipped the row because the waiter had already dropped the snapshot. Consume now retries, then decides from the row, and gives a run up only when the prompt is known to have moved on. Tool approvals and OAuth prompts of a shared agent were filed under the agent's workspace, so the user's answer failed the tenant check and the prompt timed out. Like ask_user, they now use the caller's workspace; policy and token lookups stay in the agent's. Enter on a picked option submits it instead of toggling it off, and resume errors no longer report a nil cause. * fix(agent): validate prompt choices and require durable approval claims Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices. * fix(agent): resolve prompt workflow lint errors
2026-10-14 12:37:28 +00:00
Prompts: prompts,
}
}
// attachPendingPrompts sets PendingPrompt on messages awaiting input. Only
// prompts raised for the caller are shown; the messages themselves were
// already scoped to the caller's session.
func (h *MessageHandler) attachPendingPrompts(ctx context.Context, sessionID string, messages []*types.Message) {
if h.Prompts == nil {
return
}
awaiting := false
for _, m := range messages {
awaiting = awaiting || m.RunState == types.MessageRunStateAwaitingInput
}
if !awaiting {
return
}
rows, err := h.Prompts.ListBySession(ctx, sessionID, []string{types.AgentPromptSuspended})
if err != nil {
logger.Warnf(ctx, "list pending prompts of session %s: %v", sessionID, err)
return
}
principal, _ := types.PrincipalFromContext(ctx)
caller := principal.StorageID()
byMessage := make(map[string]*types.AgentPrompt, len(rows))
for _, p := range rows {
if p.UserID == "" || p.UserID == caller {
byMessage[p.AssistantMessageID] = p
}
}
for _, m := range messages {
p := byMessage[m.ID]
if p == nil || m.RunState != types.MessageRunStateAwaitingInput {
continue
}
m.PendingPrompt = &types.PendingPromptView{
ID: p.ID, Kind: p.Kind, ToolCallID: p.ToolCallID,
Request: p.Request, ExpiresAt: p.ExpiresAt, CreatedAt: p.CreatedAt,
}
2025-08-05 07:08:07 +00:00
}
}
// resolveResourceRewriter builds the storage-reference rewriter for one response
// from the request's `resource_urls` parameter, falling back to the deployment
fix(api): close the resource_urls=public gaps found in review Follow-up on resource_urls=public. Review turned up one authorization gap plus a set of correctness problems in the streaming path. Authorization: - Embed channels were documented as excluded, but nothing enforced it. The delegating handlers hand the visitor's own gin context to the shared handlers, so ?resource_urls=public — and a deployment-wide RESOURCE_URL_MODE=public — reached anonymous traffic and produced shareable, credential-free URLs that bypass the channel-scoped /embed/:channel_id/files proxy. ensureEmbedSession now pins the request context to handle mode, which covers every delegated endpoint including future ones. The downgrade is silent so a client that forwards the parameter keeps working. - A knowledge-base-restricted API key is refused with 403. Such a key is already denied /files because a raw storage path cannot be bound to its allow-list, so handing it anonymous file URLs would reopen that hole from the other side. The default handle mode stays available to it. Streaming: - Rewriter.ref holds its lock across resolution. Resolver implementations keep an unsynchronised per-provider cache, so the previous unlocked window was a real data race for any caller sharing a StreamRewriter between goroutines — which its own doc comment invited. Serialising also collapses a concurrent duplicate into one signature. - Release the holdback buffer on every path that ends a stream while the client is still connected: a user-requested stop, an error event, and giving up on the event store. Only completion flushed before, so the tail generated just before a stop was silently dropped. - A released tail carries the metadata of the event it was cut from instead of a bare event_id. - The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting a character in half, and an unclosed "![…](" only holds back a whitespace-free destination under 2048 bytes, so prose that merely mentions Markdown image syntax no longer stalls the stream behind the buffer. Also resolves the mode before running a knowledge search instead of after, so an invalid value no longer costs a full retrieval, and warns once per distinct bad RESOURCE_URL_MODE value instead of once per process. Co-authored-by: lyingbug <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
// default. The returned error is already an AppError the caller can hand to
// c.Error: a rejected scope is a 403, a typo in the parameter is a 400.
func (h *MessageHandler) resolveResourceRewriter(c *gin.Context) (*storageurl.Rewriter, error) {
ctx := c.Request.Context()
mode, err := storageurl.ResolveMode(ctx, c.Query(storageurl.QueryParam))
if err != nil {
fix(api): close the resource_urls=public gaps found in review Follow-up on resource_urls=public. Review turned up one authorization gap plus a set of correctness problems in the streaming path. Authorization: - Embed channels were documented as excluded, but nothing enforced it. The delegating handlers hand the visitor's own gin context to the shared handlers, so ?resource_urls=public — and a deployment-wide RESOURCE_URL_MODE=public — reached anonymous traffic and produced shareable, credential-free URLs that bypass the channel-scoped /embed/:channel_id/files proxy. ensureEmbedSession now pins the request context to handle mode, which covers every delegated endpoint including future ones. The downgrade is silent so a client that forwards the parameter keeps working. - A knowledge-base-restricted API key is refused with 403. Such a key is already denied /files because a raw storage path cannot be bound to its allow-list, so handing it anonymous file URLs would reopen that hole from the other side. The default handle mode stays available to it. Streaming: - Rewriter.ref holds its lock across resolution. Resolver implementations keep an unsynchronised per-provider cache, so the previous unlocked window was a real data race for any caller sharing a StreamRewriter between goroutines — which its own doc comment invited. Serialising also collapses a concurrent duplicate into one signature. - Release the holdback buffer on every path that ends a stream while the client is still connected: a user-requested stop, an error event, and giving up on the event store. Only completion flushed before, so the tail generated just before a stop was silently dropped. - A released tail carries the metadata of the event it was cut from instead of a bare event_id. - The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting a character in half, and an unclosed "![…](" only holds back a whitespace-free destination under 2048 bytes, so prose that merely mentions Markdown image syntax no longer stalls the stream behind the buffer. Also resolves the mode before running a knowledge search instead of after, so an invalid value no longer costs a full retrieval, and warns once per distinct bad RESOURCE_URL_MODE value instead of once per process. Co-authored-by: lyingbug <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
if stderrors.Is(err, storageurl.ErrPublicModeForbidden) {
return nil, errors.NewForbiddenError(err.Error())
}
return nil, errors.NewBadRequestError(err.Error())
}
return storageurl.NewRequestRewriter(ctx, mode, h.FileService, h.StorageResolver), nil
}
// LoadMessages godoc
// @Summary 加载消息历史
// @Description 加载会话的消息历史,支持分页和时间筛选
// @Tags 消息
// @Accept json
// @Produce json
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
// @Param session_id path string true "会话ID" extensions(x-agent)
// @Param limit query int false "返回数量" default(20) minimum(1) extensions(x-agent,x-agent-maximum=20)
// @Param before_time query string false "在此时间之前的消息(RFC3339Nano格式)" extensions(x-agent)
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
docs(swagger): document the real request and response types (#4304) * docs(swagger): add shared response envelope types * docs(swagger): type knowledge base responses * docs(swagger): add concrete response body types * docs(swagger): type chunk list responses * docs(swagger): type knowledge mutation responses * docs(swagger): type wiki search and autofix responses * docs(swagger): type FAQ responses * docs(swagger): type tag responses * docs(swagger): type message responses and SSE schemas * docs(swagger): type agent responses * docs(swagger): type remaining handler responses * docs(swagger): regenerate OpenAPI spec * docs(swagger): type knowledge, activity and wiki maintenance endpoints Covers the endpoints left out of the earlier passes: knowledge base detail, document list/detail/spans/reparse/cancel/delete, knowledge base activity and the Wiki stats, issues, lint and rebuild-links endpoints. The spans handler now writes the documented structs instead of gin.H, so the schema cannot drift from the body; the JSON is unchanged. List filters gain their real enums and bounds, including the finalizing, cancelled and deleting parse states. * docs(swagger): document JSON-valued fields as JSON, not byte arrays types.JSON and json.RawMessage are byte slices, so swag rendered every metadata, details and config field as an array of integers. A swag overrides file documents them as objects; the four fields that hold arrays (relation chunk ids, allowed origins, image refs) say so with a swaggertype tag. * chore(lint): exempt swag annotation lines from the line-length limit swag reads each @Param, @Success and @Failure as a single line, so an enum list or a composed response type cannot be wrapped to fit. * chore(lint): exempt struct tags carrying swag attributes from the line limit Struct tags cannot wrap either; a field documented with swaggertype or extensions keeps its tags on the declaration line.
2026-10-14 17:41:42 +00:00
// @Success 200 {object} handler.DataResponse{data=[]types.Message} "消息列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
// @x-agent {"id":"message.list","risk":"read"}
// @x-agent-hint "The latest messages of one of the user's conversations, oldest first. For earlier ones, pass the created_at of the first message as before_time."
// @Router /messages/{session_id}/load [get]
2025-08-05 07:08:07 +00:00
func (h *MessageHandler) LoadMessages(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start loading messages")
// Get path parameters and query parameters
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
limit := secutils.SanitizeForLog(c.DefaultQuery("limit", strconv.Itoa(defaultMessagesPageSize)))
beforeTimeStr := secutils.SanitizeForLog(c.DefaultQuery("before_time", ""))
2025-08-05 07:08:07 +00:00
logger.Infof(ctx, "Loading messages params, session ID: %s, limit: %s, before time: %s",
sessionID, limit, beforeTimeStr)
rewriter, err := h.resolveResourceRewriter(c)
2025-08-05 07:08:07 +00:00
if err != nil {
fix(api): close the resource_urls=public gaps found in review Follow-up on resource_urls=public. Review turned up one authorization gap plus a set of correctness problems in the streaming path. Authorization: - Embed channels were documented as excluded, but nothing enforced it. The delegating handlers hand the visitor's own gin context to the shared handlers, so ?resource_urls=public — and a deployment-wide RESOURCE_URL_MODE=public — reached anonymous traffic and produced shareable, credential-free URLs that bypass the channel-scoped /embed/:channel_id/files proxy. ensureEmbedSession now pins the request context to handle mode, which covers every delegated endpoint including future ones. The downgrade is silent so a client that forwards the parameter keeps working. - A knowledge-base-restricted API key is refused with 403. Such a key is already denied /files because a raw storage path cannot be bound to its allow-list, so handing it anonymous file URLs would reopen that hole from the other side. The default handle mode stays available to it. Streaming: - Rewriter.ref holds its lock across resolution. Resolver implementations keep an unsynchronised per-provider cache, so the previous unlocked window was a real data race for any caller sharing a StreamRewriter between goroutines — which its own doc comment invited. Serialising also collapses a concurrent duplicate into one signature. - Release the holdback buffer on every path that ends a stream while the client is still connected: a user-requested stop, an error event, and giving up on the event store. Only completion flushed before, so the tail generated just before a stop was silently dropped. - A released tail carries the metadata of the event it was cut from instead of a bare event_id. - The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting a character in half, and an unclosed "![…](" only holds back a whitespace-free destination under 2048 bytes, so prose that merely mentions Markdown image syntax no longer stalls the stream behind the buffer. Also resolves the mode before running a knowledge search instead of after, so an invalid value no longer costs a full retrieval, and warns once per distinct bad RESOURCE_URL_MODE value instead of once per process. Co-authored-by: lyingbug <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
logger.Warnf(ctx, "Rejected resource URL mode: %v", err)
_ = c.Error(err)
return
}
// Parse limit parameter with fallback to default, then clamp it. A
// non-positive value must not reach the repository: GORM only emits a
// LIMIT clause for `limit >= 0`, so `limit=-1` would load the entire
// session history (and attach artifacts for every row) in one request.
limitInt, convErr := strconv.Atoi(limit)
if convErr != nil {
// Note: on out-of-range input Atoi returns the boundary value rather
// than zero, so the default has to be assigned explicitly here.
logger.Warnf(ctx, "Invalid limit value, using default value %d, input: %s", defaultMessagesPageSize, limit)
limitInt = defaultMessagesPageSize
2025-08-05 07:08:07 +00:00
}
limitInt = clampMessagesPageSize(limitInt)
2025-08-05 07:08:07 +00:00
// If no beforeTime is provided, retrieve the most recent messages
if beforeTimeStr == "" {
logger.Infof(ctx, "Getting recent messages for session, session ID: %s, limit: %d", sessionID, limitInt)
messages, err := h.MessageService.GetRecentMessagesBySession(ctx, sessionID, limitInt)
if err != nil {
fix(session): map ErrSessionNotFound to 404 across all handlers PR #1309 plumbed user-scope into the session/message service layer so non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at every entry point that goes through sessionRepo.Get. The handler-side mapping, however, only existed in 4 of the 8 affected sites: - handler/session/handler.go:GetSession ✓ already mapped (with `==`) - handler/session/handler.go:UpdateSession ✓ already mapped (with `==`) - handler/session/handler.go:DeleteSession ✓ already mapped (with `==`) - handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`) - handler/session/handler.go:ClearSessionMessages ✗ always 500 - handler/session/stream.go:ContinueStream session lookup ✓ (with `==`) - handler/session/stream.go:ContinueStream message lookup ✗ always 500 - handler/message.go:LoadMessages (recent + before-time) ✗ always 500 - handler/message.go:DeleteMessage ✗ always 500 Result: a Contributor in tenant A asking for a Contributor B's session messages got a 500 instead of 404 — the wire response leaked "something is broken" rather than "you can't see this URL", which breaks SDK / frontend axios interceptor error handling that keys on HTTP status. Two changes: 1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it (ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's two paths, DeleteMessage). 2. Replace `err == errors.ErrSessionNotFound` with `stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel error comparison must use errors.Is so wrapped errors (`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no service-layer caller wraps, but a future refactor that does would silently turn 404s into 500s with no test catching it. Tests: - internal/handler/message_session_not_found_test.go covers the four new mapping sites in handler/message.go (LoadMessages-recent, LoadMessages-before-time, DeleteMessage) and pins the wrapped-error behaviour with a dedicated regression test that fmt.Errorf("%w") a sentinel must still be detected as ErrSessionNotFound. The bare handler is hit through gin.Engine + middleware.ErrorHandler so the response shape matches production exactly. - PR #1309's existing service-level tests (session_user_scope_test, session_test on the repository) still pass — this PR is a strictly handler-layer follow-up.
2026-05-14 08:44:55 +00:00
if stderrors.Is(err, errors.ErrSessionNotFound) {
// PR #1309 plumbed user-scope into the message service's
// session existence check; non-owner / wrong-tenant lookups
// surface as ErrSessionNotFound. Map to 404 so clients can
// tell "wrong URL" from a real 5xx.
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
2025-08-05 07:08:07 +00:00
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(
ctx,
"Successfully retrieved recent messages, session ID: %s, message count: %d",
sessionID, len(messages),
)
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) * feat(agent): persist human-in-the-loop prompts with a shared broker Tool approvals and MCP OAuth prompts are now rows in agent_prompts, awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind answer validation). Resolve is bound to session and kind. This is P1 of the suspend/resume design; runs still block as before. * feat(agent): suspend runs whose prompt outlives a short in-memory wait Behind agent.prompt_suspend_enabled (off by default). A run raised from the HTTP stream saves its state when a tool approval is raised; after the hot wait the prompt moves to suspended and the assistant message is saved as awaiting_input instead of blocking. A reaper takes over prompts whose waiting replica stopped renewing its lease. Resume comes in a later change. * feat(agent): resume suspended runs once their prompt is answered The replica that records the answer resumes the run in process under the prompt's lease. Superseded, expired and abandoned runs are closed with a result for every tool call, and approved tools are never replayed. * feat(agent): let users answer suspended tool approvals and follow the resumed run * feat(agent): ask_user tool and generic prompt answer endpoint - ask_user built-in tool: options, short forms or free text; validated answers, decline, suspend/resume like tool approval; non-interactive callers (IM, API keys) are told to ask in the reply instead - POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt - agent_prompt_required/resolved events; AskUserCard sharing the countdown with ToolApprovalCard; answered questions rebuilt as cards from history - awaiting-input messages keep their steps expanded so the pending card stays visible; prompt cards keyed by their own id - i18n for all locales; design doc updated * fix(agent): keep prompt answers that race a suspending or vanished owner - Resolve suspends a pending prompt whose owner's lease lapsed, as the reaper would, so the answer resumes the run instead of waking nobody. - Resuming waits for the suspending run to persist its message and clear its live-run marker; a marker left by a vanished owner is cleared. - A resumed run that suspends again on a new prompt no longer has its message closed from the old state. - tool_approval answers are decoded strictly and require "approved"; fix the SDK doc that showed {"decision": "approve"}. - API-key runs block instead of suspending, since they cannot answer. - A run state that cannot be saved falls back to an in-memory wait, and NUL escapes are stripped from snapshots for jsonb. * style(chat): align the ask_user card with the other interaction cards Question and answer use the timeline's step text styles instead of primary-colored and monospace text; options and form controls use the compact step size, the number input spans the row, and the free-text character counter is hidden. * feat(chat): dock pending agent prompts above the composer Tool approvals, ask_user questions and MCP OAuth prompts were answered inline in the agent timeline, where a long answer or scrolling back pushes them out of view. Open prompts of a streaming or suspended run now gather in a dock above the composer (main chat and embed), one at a time with a pager, lettered options and Enter to submit. The timeline keeps a one-line record with a link back to the dock and the outcome once answered. Views without a dock still answer inline. * fix(agent): fence prompt ownership and preserve resumed turn context * fix(agent): keep runs through consume errors and file prompts under the caller Consume reported a store error as a lost claim, so an answer consumed during a database hiccup detached its run: the message was never persisted, the live-run marker stayed, and the reaper skipped the row because the waiter had already dropped the snapshot. Consume now retries, then decides from the row, and gives a run up only when the prompt is known to have moved on. Tool approvals and OAuth prompts of a shared agent were filed under the agent's workspace, so the user's answer failed the tenant check and the prompt timed out. Like ask_user, they now use the caller's workspace; policy and token lookups stay in the agent's. Enter on a picked option submits it instead of toggling it off, and resume errors no longer report a nil cause. * fix(agent): validate prompt choices and require durable approval claims Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices. * fix(agent): resolve prompt workflow lint errors
2026-10-14 12:37:28 +00:00
h.attachPendingPrompts(ctx, sessionID, messages)
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": rewriter.RewriteMessagesResponse(ctx, messages),
2025-08-05 07:08:07 +00:00
})
return
}
// If beforeTime is provided, parse the timestamp (RFC3339Nano or RFC3339).
beforeTime, err := parseMessageBeforeTime(beforeTimeStr)
2025-08-05 07:08:07 +00:00
if err != nil {
logger.Errorf(
ctx,
"Invalid time format, please use RFC3339/RFC3339Nano format, err: %v, beforeTimeStr: %s",
2025-08-05 07:08:07 +00:00
err, beforeTimeStr,
)
c.Error(errors.NewBadRequestError("Invalid time format, please use RFC3339 or RFC3339Nano format"))
2025-08-05 07:08:07 +00:00
return
}
// Retrieve messages before the specified timestamp
logger.Infof(ctx, "Getting messages before specific time, session ID: %s, before time: %s, limit: %d",
sessionID, beforeTime.Format(time.RFC3339Nano), limitInt)
messages, err := h.MessageService.GetMessagesBySessionBeforeTime(ctx, sessionID, beforeTime, limitInt)
if err != nil {
fix(session): map ErrSessionNotFound to 404 across all handlers PR #1309 plumbed user-scope into the session/message service layer so non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at every entry point that goes through sessionRepo.Get. The handler-side mapping, however, only existed in 4 of the 8 affected sites: - handler/session/handler.go:GetSession ✓ already mapped (with `==`) - handler/session/handler.go:UpdateSession ✓ already mapped (with `==`) - handler/session/handler.go:DeleteSession ✓ already mapped (with `==`) - handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`) - handler/session/handler.go:ClearSessionMessages ✗ always 500 - handler/session/stream.go:ContinueStream session lookup ✓ (with `==`) - handler/session/stream.go:ContinueStream message lookup ✗ always 500 - handler/message.go:LoadMessages (recent + before-time) ✗ always 500 - handler/message.go:DeleteMessage ✗ always 500 Result: a Contributor in tenant A asking for a Contributor B's session messages got a 500 instead of 404 — the wire response leaked "something is broken" rather than "you can't see this URL", which breaks SDK / frontend axios interceptor error handling that keys on HTTP status. Two changes: 1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it (ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's two paths, DeleteMessage). 2. Replace `err == errors.ErrSessionNotFound` with `stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel error comparison must use errors.Is so wrapped errors (`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no service-layer caller wraps, but a future refactor that does would silently turn 404s into 500s with no test catching it. Tests: - internal/handler/message_session_not_found_test.go covers the four new mapping sites in handler/message.go (LoadMessages-recent, LoadMessages-before-time, DeleteMessage) and pins the wrapped-error behaviour with a dedicated regression test that fmt.Errorf("%w") a sentinel must still be detected as ErrSessionNotFound. The bare handler is hit through gin.Engine + middleware.ErrorHandler so the response shape matches production exactly. - PR #1309's existing service-level tests (session_user_scope_test, session_test on the repository) still pass — this PR is a strictly handler-layer follow-up.
2026-05-14 08:44:55 +00:00
if stderrors.Is(err, errors.ErrSessionNotFound) {
// See note on the GetRecentMessagesBySession path above.
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
2025-08-05 07:08:07 +00:00
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(
ctx,
"Successfully retrieved messages before time, session ID: %s, message count: %d",
sessionID, len(messages),
)
feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) * feat(agent): persist human-in-the-loop prompts with a shared broker Tool approvals and MCP OAuth prompts are now rows in agent_prompts, awaited through hitl.Broker (lease, DB polling, Redis wake-up, per-kind answer validation). Resolve is bound to session and kind. This is P1 of the suspend/resume design; runs still block as before. * feat(agent): suspend runs whose prompt outlives a short in-memory wait Behind agent.prompt_suspend_enabled (off by default). A run raised from the HTTP stream saves its state when a tool approval is raised; after the hot wait the prompt moves to suspended and the assistant message is saved as awaiting_input instead of blocking. A reaper takes over prompts whose waiting replica stopped renewing its lease. Resume comes in a later change. * feat(agent): resume suspended runs once their prompt is answered The replica that records the answer resumes the run in process under the prompt's lease. Superseded, expired and abandoned runs are closed with a result for every tool call, and approved tools are never replayed. * feat(agent): let users answer suspended tool approvals and follow the resumed run * feat(agent): ask_user tool and generic prompt answer endpoint - ask_user built-in tool: options, short forms or free text; validated answers, decline, suspend/resume like tool approval; non-interactive callers (IM, API keys) are told to ask in the reply instead - POST /agent/prompts/{prompt_id} (and embed variant) answers ask_user and tool_approval prompts, returns resumed; SDK ResolveAgentPrompt - agent_prompt_required/resolved events; AskUserCard sharing the countdown with ToolApprovalCard; answered questions rebuilt as cards from history - awaiting-input messages keep their steps expanded so the pending card stays visible; prompt cards keyed by their own id - i18n for all locales; design doc updated * fix(agent): keep prompt answers that race a suspending or vanished owner - Resolve suspends a pending prompt whose owner's lease lapsed, as the reaper would, so the answer resumes the run instead of waking nobody. - Resuming waits for the suspending run to persist its message and clear its live-run marker; a marker left by a vanished owner is cleared. - A resumed run that suspends again on a new prompt no longer has its message closed from the old state. - tool_approval answers are decoded strictly and require "approved"; fix the SDK doc that showed {"decision": "approve"}. - API-key runs block instead of suspending, since they cannot answer. - A run state that cannot be saved falls back to an in-memory wait, and NUL escapes are stripped from snapshots for jsonb. * style(chat): align the ask_user card with the other interaction cards Question and answer use the timeline's step text styles instead of primary-colored and monospace text; options and form controls use the compact step size, the number input spans the row, and the free-text character counter is hidden. * feat(chat): dock pending agent prompts above the composer Tool approvals, ask_user questions and MCP OAuth prompts were answered inline in the agent timeline, where a long answer or scrolling back pushes them out of view. Open prompts of a streaming or suspended run now gather in a dock above the composer (main chat and embed), one at a time with a pager, lettered options and Enter to submit. The timeline keeps a one-line record with a link back to the dock and the outcome once answered. Views without a dock still answer inline. * fix(agent): fence prompt ownership and preserve resumed turn context * fix(agent): keep runs through consume errors and file prompts under the caller Consume reported a store error as a lost claim, so an answer consumed during a database hiccup detached its run: the message was never persisted, the live-run marker stayed, and the reaper skipped the row because the waiter had already dropped the snapshot. Consume now retries, then decides from the row, and gives a run up only when the prompt is known to have moved on. Tool approvals and OAuth prompts of a shared agent were filed under the agent's workspace, so the user's answer failed the tenant check and the prompt timed out. Like ask_user, they now use the caller's workspace; policy and token lookups stay in the agent's. Enter on a picked option submits it instead of toggling it off, and resume errors no longer report a nil cause. * fix(agent): validate prompt choices and require durable approval claims Reject malformed serialized option lists so the model can retry with valid arguments. Distinguish prompt consumption failures from lost ownership without authorizing side effects, and preserve native Enter selection for unselected choices. * fix(agent): resolve prompt workflow lint errors
2026-10-14 12:37:28 +00:00
h.attachPendingPrompts(ctx, sessionID, messages)
2025-08-05 07:08:07 +00:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": rewriter.RewriteMessagesResponse(ctx, messages),
2025-08-05 07:08:07 +00:00
})
}
// DeleteMessage godoc
// @Summary 删除消息
// @Description 从会话中删除指定消息
// @Tags 消息
// @Accept json
// @Produce json
// @Param session_id path string true "会话ID"
// @Param id path string true "消息ID"
docs(swagger): document the real request and response types (#4304) * docs(swagger): add shared response envelope types * docs(swagger): type knowledge base responses * docs(swagger): add concrete response body types * docs(swagger): type chunk list responses * docs(swagger): type knowledge mutation responses * docs(swagger): type wiki search and autofix responses * docs(swagger): type FAQ responses * docs(swagger): type tag responses * docs(swagger): type message responses and SSE schemas * docs(swagger): type agent responses * docs(swagger): type remaining handler responses * docs(swagger): regenerate OpenAPI spec * docs(swagger): type knowledge, activity and wiki maintenance endpoints Covers the endpoints left out of the earlier passes: knowledge base detail, document list/detail/spans/reparse/cancel/delete, knowledge base activity and the Wiki stats, issues, lint and rebuild-links endpoints. The spans handler now writes the documented structs instead of gin.H, so the schema cannot drift from the body; the JSON is unchanged. List filters gain their real enums and bounds, including the finalizing, cancelled and deleting parse states. * docs(swagger): document JSON-valued fields as JSON, not byte arrays types.JSON and json.RawMessage are byte slices, so swag rendered every metadata, details and config field as an array of integers. A swag overrides file documents them as objects; the four fields that hold arrays (relation chunk ids, allowed origins, image refs) say so with a swaggertype tag. * chore(lint): exempt swag annotation lines from the line-length limit swag reads each @Param, @Success and @Failure as a single line, so an enum list or a composed response type cannot be wrapped to fit. * chore(lint): exempt struct tags carrying swag attributes from the line limit Struct tags cannot wrap either; a field documented with swaggertype or extensions keeps its tags on the declaration line.
2026-10-14 17:41:42 +00:00
// @Success 200 {object} handler.MessageResponse "删除成功"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /messages/{session_id}/{id} [delete]
2025-08-05 07:08:07 +00:00
func (h *MessageHandler) DeleteMessage(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start deleting message")
// Get path parameters for session and message identification
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
messageID := secutils.SanitizeForLog(c.Param("id"))
2025-08-05 07:08:07 +00:00
logger.Infof(ctx, "Deleting message, session ID: %s, message ID: %s", sessionID, messageID)
// Delete the message using the message service
if err := h.MessageService.DeleteMessage(ctx, sessionID, messageID); err != nil {
fix(session): map ErrSessionNotFound to 404 across all handlers PR #1309 plumbed user-scope into the session/message service layer so non-owner / wrong-tenant lookups now surface as ErrSessionNotFound at every entry point that goes through sessionRepo.Get. The handler-side mapping, however, only existed in 4 of the 8 affected sites: - handler/session/handler.go:GetSession ✓ already mapped (with `==`) - handler/session/handler.go:UpdateSession ✓ already mapped (with `==`) - handler/session/handler.go:DeleteSession ✓ already mapped (with `==`) - handler/session/handler.go:BatchDeleteSessions ✓ already mapped (with `==`) - handler/session/handler.go:ClearSessionMessages ✗ always 500 - handler/session/stream.go:ContinueStream session lookup ✓ (with `==`) - handler/session/stream.go:ContinueStream message lookup ✗ always 500 - handler/message.go:LoadMessages (recent + before-time) ✗ always 500 - handler/message.go:DeleteMessage ✗ always 500 Result: a Contributor in tenant A asking for a Contributor B's session messages got a 500 instead of 404 — the wire response leaked "something is broken" rather than "you can't see this URL", which breaks SDK / frontend axios interceptor error handling that keys on HTTP status. Two changes: 1. Add ErrSessionNotFound → 404 mapping to the 4 sites that lacked it (ClearSessionMessages, ContinueStream's GetMessage, LoadMessages's two paths, DeleteMessage). 2. Replace `err == errors.ErrSessionNotFound` with `stderrors.Is(err, errors.ErrSessionNotFound)` everywhere. Sentinel error comparison must use errors.Is so wrapped errors (`fmt.Errorf("...: %w", ErrSessionNotFound)`) still match. Today no service-layer caller wraps, but a future refactor that does would silently turn 404s into 500s with no test catching it. Tests: - internal/handler/message_session_not_found_test.go covers the four new mapping sites in handler/message.go (LoadMessages-recent, LoadMessages-before-time, DeleteMessage) and pins the wrapped-error behaviour with a dedicated regression test that fmt.Errorf("%w") a sentinel must still be detected as ErrSessionNotFound. The bare handler is hit through gin.Engine + middleware.ErrorHandler so the response shape matches production exactly. - PR #1309's existing service-level tests (session_user_scope_test, session_test on the repository) still pass — this PR is a strictly handler-layer follow-up.
2026-05-14 08:44:55 +00:00
if stderrors.Is(err, errors.ErrSessionNotFound) {
// See note on LoadMessages above — message-service operations
// surface ErrSessionNotFound when the caller can't see the
// owning session (post-#1309 user scope).
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
if stderrors.Is(err, gorm.ErrRecordNotFound) {
// The message_id doesn't exist under this session — a client error,
// not a server fault. 404 so callers read resource.not_found (a
// permanent condition, not retryable) instead of a 5xx. Mirrors the
// ContinueStream / kb / doc / chunk not-found handling.
logger.Warnf(ctx, "Message not found, session ID: %s, message ID: %s", sessionID, messageID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
2025-08-05 07:08:07 +00:00
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Message deleted successfully, session ID: %s, message ID: %s", sessionID, messageID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Message deleted successfully",
})
}
// SearchMessages godoc
// @Summary 搜索历史对话
// @Description 通过关键词和/或向量相似度搜索历史对话记录,支持关键词、向量、混合三种模式
// @Tags 消息
// @Accept json
// @Produce json
// @Param request body SearchMessagesRequest true "搜索请求"
docs(swagger): document the real request and response types (#4304) * docs(swagger): add shared response envelope types * docs(swagger): type knowledge base responses * docs(swagger): add concrete response body types * docs(swagger): type chunk list responses * docs(swagger): type knowledge mutation responses * docs(swagger): type wiki search and autofix responses * docs(swagger): type FAQ responses * docs(swagger): type tag responses * docs(swagger): type message responses and SSE schemas * docs(swagger): type agent responses * docs(swagger): type remaining handler responses * docs(swagger): regenerate OpenAPI spec * docs(swagger): type knowledge, activity and wiki maintenance endpoints Covers the endpoints left out of the earlier passes: knowledge base detail, document list/detail/spans/reparse/cancel/delete, knowledge base activity and the Wiki stats, issues, lint and rebuild-links endpoints. The spans handler now writes the documented structs instead of gin.H, so the schema cannot drift from the body; the JSON is unchanged. List filters gain their real enums and bounds, including the finalizing, cancelled and deleting parse states. * docs(swagger): document JSON-valued fields as JSON, not byte arrays types.JSON and json.RawMessage are byte slices, so swag rendered every metadata, details and config field as an array of integers. A swag overrides file documents them as objects; the four fields that hold arrays (relation chunk ids, allowed origins, image refs) say so with a swaggertype tag. * chore(lint): exempt swag annotation lines from the line-length limit swag reads each @Param, @Success and @Failure as a single line, so an enum list or a composed response type cannot be wrapped to fit. * chore(lint): exempt struct tags carrying swag attributes from the line limit Struct tags cannot wrap either; a field documented with swaggertype or extensions keeps its tags on the declaration line.
2026-10-14 17:41:42 +00:00
// @Success 200 {object} handler.DataResponse{data=types.MessageSearchResult} "搜索结果"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
// @x-agent {"id":"message.search","risk":"probe","root":"data.items","max_items":20}
// @x-agent-hint "Finds exchanges in the user's own past conversations by what was said, each with its session_id. Matching is by meaning only when message indexing is on (see message.chat_history_stats); otherwise words must appear verbatim, so retry with the user's exact wording before concluding nothing matches."
// @Router /messages/search [post]
func (h *MessageHandler) SearchMessages(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start searching messages")
var request SearchMessagesRequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse search request", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if request.Query == "" {
logger.Error(ctx, "Query content is empty")
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
return
}
// Clamp the requested page size before it reaches the service. The
// service later applies a bounded over-fetch (limit*3) to the keyword
// search so it has enough candidates to rank; that multiplier is
// intentional and is left untouched, so the SQL LIMIT is at most
// 3*maxMessagesPageSize. Without this clamp an unbounded request would
// inflate the query by the same factor.
request.Limit = clampMessagesPageSize(request.Limit)
params := &types.MessageSearchParams{
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
Query: request.Query,
Mode: types.MessageSearchMode(request.Mode),
Limit: request.Limit,
SessionIDs: request.SessionIDs,
}
logger.Infof(ctx, "Searching messages with params: query=%s, mode=%s, limit=%d, session_ids=%v",
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
secutils.SanitizeForLog(params.Query), secutils.SanitizeForLog(string(params.Mode)), params.Limit,
secutils.SanitizeForLogArray(params.SessionIDs))
result, err := h.MessageService.SearchMessages(ctx, params)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Message search completed, found %d results", result.Total)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result,
})
}
// SearchMessagesRequest defines the request structure for searching messages
type SearchMessagesRequest struct {
// Query text for search
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
Query string `json:"query" binding:"required" extensions:"x-agent"`
// Search mode: "keyword", "vector", "hybrid" (default: "hybrid")
Mode string `json:"mode"`
// Maximum number of results to return (default: 20)
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
Limit int `json:"limit" minimum:"1" extensions:"x-agent,x-agent-maximum=20"`
// Filter by specific session IDs (optional)
SessionIDs []string `json:"session_ids"`
}
// GetChatHistoryKBStats godoc
// @Summary 获取聊天历史知识库统计
// @Description 获取聊天历史知识库的统计信息(已索引消息数、知识库大小等)
// @Tags 消息
// @Accept json
// @Produce json
docs(swagger): document the real request and response types (#4304) * docs(swagger): add shared response envelope types * docs(swagger): type knowledge base responses * docs(swagger): add concrete response body types * docs(swagger): type chunk list responses * docs(swagger): type knowledge mutation responses * docs(swagger): type wiki search and autofix responses * docs(swagger): type FAQ responses * docs(swagger): type tag responses * docs(swagger): type message responses and SSE schemas * docs(swagger): type agent responses * docs(swagger): type remaining handler responses * docs(swagger): regenerate OpenAPI spec * docs(swagger): type knowledge, activity and wiki maintenance endpoints Covers the endpoints left out of the earlier passes: knowledge base detail, document list/detail/spans/reparse/cancel/delete, knowledge base activity and the Wiki stats, issues, lint and rebuild-links endpoints. The spans handler now writes the documented structs instead of gin.H, so the schema cannot drift from the body; the JSON is unchanged. List filters gain their real enums and bounds, including the finalizing, cancelled and deleting parse states. * docs(swagger): document JSON-valued fields as JSON, not byte arrays types.JSON and json.RawMessage are byte slices, so swag rendered every metadata, details and config field as an array of integers. A swag overrides file documents them as objects; the four fields that hold arrays (relation chunk ids, allowed origins, image refs) say so with a swaggertype tag. * chore(lint): exempt swag annotation lines from the line-length limit swag reads each @Param, @Success and @Failure as a single line, so an enum list or a composed response type cannot be wrapped to fit. * chore(lint): exempt struct tags carrying swag attributes from the line limit Struct tags cannot wrap either; a field documented with swaggertype or extensions keeps its tags on the declaration line.
2026-10-14 17:41:42 +00:00
// @Success 200 {object} handler.DataResponse{data=types.ChatHistoryKBStats} "统计信息"
// @Security Bearer
// @Security ApiKeyAuth
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375) * feat(assistant): let the assistant check MCP services and retrieval Add a probe risk for operations that change nothing but do real work (connecting to a service, running a retrieval). Probes use POST, run without approval at every access level, and are capped per run. Open three operations on top of it: - mcp_service.test: connect with the saved settings and report why not - mcp_service.list_tools: list what a service offers before binding it - knowledge_base.search: raw hybrid recall with thresholds, to explain why a document is or is not found x-agent can now name one method when a handler documents several, and catalog parameters accept numbers. * feat(assistant): let the assistant try an agent it set up Add try_agent: the assistant asks an agent one question the way a user would and gets back its answer, the tools it called and the documents it cited, so it can check a setup before calling it done. - The trial runs as the signed-in user in a new agent_trial session kind, which ordinary listings already exclude and the API cannot create, and the session is removed afterwards. Runs are non-interactive, so tools that would ask the user are refused. Long-term memory is untouched: it is written only by the HTTP handler. - The assistant itself, the Wiki fixer and the skill installer cannot be tried, nor any agent granted the operation catalog. - A trial spends model calls and runs the agent's own tools, so it is a write for the access level: confirm asks, auto_write runs, read_only does not offer it. The confirmation card names the agent and question; ConfirmedTool now lets a wrapped tool supply that text. - At most 3 trials per turn, 4 minutes each; the tool timeout is raised above that. Answers, tool errors and references are capped. - The runner is bound to the session service after the container builds it, since the session service depends on the agent service. * feat(assistant): let the user allow similar changes for the conversation The confirmation card for a recoverable change now offers "allow this for the rest of the conversation". Once chosen, later calls of the same kind in the same session run without asking, so a batch tidy-up no longer needs a click per item. - What a grant covers is derived on the server, never taken from the model: the same catalog operation on the same knowledge bases (a document's knowledge base comes from the target read) or the same agent; the same Wiki tool on the run's Wiki knowledge bases; trials of the same agent. Deletions and operations without such a scope, such as creating a knowledge base, always ask. - No new storage: the gate looks for an earlier approved prompt in the session with the same grant and allow_in_session set, for the same tenant and user. Grants therefore survive suspend/resume and replicas, and end with the conversation. A failed lookup asks again. - The response validator accepts allow_in_session only on approval and only when the prompt offered a grant, so a client cannot widen it. - The card shows the scope in the user's language. The model is told such calls may run without a card and that deletions always ask. - describeTarget now returns its target read so the grant reuses it instead of reading again. * feat(assistant): tell the assistant about settings pages and chat answers Pages now report which page is open and, for the agent editor, which section. The model and MCP settings name the model or service open for editing, and chat answers gain an "ask the assistant" button that attaches that answer. The backend resolves these for the assistant only: models and MCP services in the caller's tenant without endpoints or credentials, and messages through the caller's session read access, with the question, an answer excerpt and cited sources quoted as data. * feat(assistant): link the user to pages and filled-in forms The assistant gains open_page, which shows a button to a knowledge base or document, a Wiki page, an agent's editor at a tab, a model or MCP service to edit, or a new model or MCP service with its form filled in. Targets are read through the operation catalog as the user, so a link never points at something they cannot open. Drafts take no credentials and only http(s) endpoints without user info; the card shows the endpoint, and the user enters keys and saves the form themselves. * feat(assistant): manage MCP services, model names and skills * fix(assistant): prefill model drafts on initial navigation * feat(assistant): document tags, model catalog reads, clearer cards, live page refresh - Operations project lists of objects; knowledge.get/list report tags. - model.get shows provider, endpoint and capabilities; new model.list_providers and model.get_provider read the model catalog, including vendors an admin added. - open_page and ask_user guidance: offer page buttons whenever the next step is the user's, word choices for the user. - Chat cards: redesigned open-page card pinned under the final answer, ask-user inputs in the dock style, approval card with aligned fields, translated labels and a question built from the operation summary. - Open pages reload after assistant changes: deletes and moves wait for the background task, Wiki edits now report their changes, KB list counts, tags and chat model selectors refresh. - The assistant panel stays open across reloads within the tab. * fix(ci): format assistant operation code and wrap long lines * feat(assistant): let the assistant see, fill and open the page beside it - read_page / fill_page tools answered by the browser over a page_action prompt, with refs, redaction, in-place text edits, undo card and a page-access switch - composer shows the open page, dialog and selection; a selection bubble and an editor toolbar entry ask the assistant about the selected text - edits scroll into view with a highlight and an inline undo bar - open_page reaches any settings section, toolbox tool and list page, and can navigate there itself to read it, keeping the button when edits are unsaved * feat(assistant): let the assistant open the tab it needs A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab. * feat(assistant): expose read-only conversation operations Add session.list, message.list, message.search and message.chat_history_stats to the operation catalog, restrict the sessions and messages areas to non-mutating operations, and search messages with the raw query instead of the log-sanitized one. * style(chat): restyle open-page and page-edit cards * fix(ci): comply with assistant card styles and Go line limits
2026-10-16 15:36:01 +00:00
// @x-agent {"id":"message.chat_history_stats","risk":"read"}
// @x-agent-hint "Whether the workspace indexes conversations for search by meaning, and how many messages are indexed. When it is off, message.search only matches exact words; the setting is under settings section chathistory."
// @Router /messages/chat-history-stats [get]
func (h *MessageHandler) GetChatHistoryKBStats(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Getting chat history KB stats")
stats, err := h.MessageService.GetChatHistoryKBStats(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": stats,
})
}
// parseMessageBeforeTime parses the `before_time` query used by LoadMessages.
// Frontend cursors may be RFC3339 (no fractional seconds) or RFC3339Nano.
func parseMessageBeforeTime(raw string) (time.Time, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return time.Time{}, stderrors.New("empty before_time")
}
layouts := []string{time.RFC3339Nano, time.RFC3339}
var lastErr error
for _, layout := range layouts {
if t, err := time.Parse(layout, raw); err == nil {
return t, nil
} else {
lastErr = err
}
}
return time.Time{}, lastErr
}