refactor: introduce multi-session chat support (#session) (#267)

* refactor: introduce multi-session chat support (#session)

Replace the single-context-per-bot model with multiple chat sessions.

Database:
- Add bot_sessions table (route_id, channel_type, title, metadata, soft delete)
- Migrate bot_history_messages from (route_id, channel_type) to session_id
- Add active_session_id to bot_channel_routes
- Migration 0036 handles data migration from existing messages

Backend:
- New internal/session service for session CRUD
- Update message service/types to use session_id instead of route_id
- Update conversation flow (resolver, history, store) for session context
- Channel inbound auto-creates/retrieves active session via SessionEnsurer
- New REST endpoints: /bots/:bot_id/sessions (CRUD)
- WebSocket and message handlers accept optional session_id
- Wire session service into FX dependency graph (agent + memoh)

Frontend:
- Refactor chat store: sessions replaces chats, sessionId replaces chatId
- Session-aware message loading, sending, and pagination
- WebSocket sends include session_id
- New session sidebar component with select/delete
- Chat area header shows active session title + new session button
- API layer updated: fetchSessions, createSession, deleteSession
- i18n strings for session management (en + zh)

SDK:
- Regenerated TypeScript SDK and Swagger docs with session endpoints

* fix: update tests for session refactoring (RouteID → SessionID)

Remove references to removed RouteID and Platform fields from
PersistInput/Message in channel_test.go and service_integration_test.go.

* fix: restore accidentally deleted SDK files and guard migration 0032

- Restore packages/sdk/src/container-stream.ts and extra/index.ts that
  were accidentally removed during SDK regeneration
- Wrap migration 0032 route_id index creation in a column existence check
  to avoid failure on fresh databases where 0001_init.up.sql no longer
  has route_id

* fix: guard migration 0036 data steps for fresh databases

Wrap steps 3-7 (which reference route_id/channel_type on
bot_history_messages) in a column existence check so the migration
is safe on fresh databases where 0001_init.up.sql already reflects
the final schema without those columns.

* feat: add title model setting and auto-generate session titles on user input

- Add title_model_id to bots table (migration 0037) and bot settings API
- Implement async title generation triggered at user message time (not after
  assistant response) for faster title availability
- Publish session_title_updated events via SSE event hub for real-time
  frontend updates without page refresh
- Fix SSE message event parsing: use direct JSON.parse instead of
  normalizeStreamEvent which silently dropped non-chat-stream event types
- Add title model selector in bot settings UI with i18n support

* fix: session-scoped message filtering and URL-based chat routing

- Filter realtime SSE messages by session_id to prevent cross-session
  message leakage after page refresh
- Add /chat/:sessionId? route with bidirectional URL ↔ store sync
- Visiting /chat shows a clean state with no bot or session pre-selected
- Visiting /chat/:sessionId loads the specific session directly
- Session switches from sidebar automatically update the URL
- Fix stale RouteID field in dedupe test (removed during session refactor)

* fix: skip cross-channel stream events to prevent session leakage

The bot-level web stream pushes events from all channels (Telegram,
Discord, etc.) without session_id context. Previously these were
rendered inline in the current chat view regardless of session.

Now cross-channel events are ignored in handleLocalStreamEvent;
persisted messages arrive via the SSE message events stream with
proper session_id filtering through appendRealtimeMessage.

* feat: show IM avatars and platform badges on session sidebar

- Add sender_avatar_url to route metadata from identity resolution
- Resolve group avatar and handle via directory adapter for group chats
- JOIN bot_channel_routes in ListSessionsByBot to return route metadata
- Display avatar with ChannelBadge on IM session items (group avatar
  for groups, sender avatar for private chats)
- Show @groupname or @username as session sub-label

* fix: clean up RunConfig unused fields, fix skill system and copy bug

- Remove unused RunConfig fields: Tools, Channels, CurrentChannel,
  ActiveContextTime
- Remove unused SessionContext fields: DisplayName, ConversationType
- Fix EnabledSkillNames copy bug: make([]string, 0, n) + copy copies
  zero elements; changed to make([]string, n)
- Fix prepareRunConfig dead code: remove no-op loop over
  CurrentPlatform runes; compute supportsImageInput from model's
  InputModalities
- Fix EnabledSkills always nil in system prompt: resolve enabled skill
  entries from EnabledSkillNames + Skills
- Fix use_skill tool returning empty response: now returns full skill
  content (description + instructions) so LLM gets it in the same turn
- Skip use_skill tool registration when no skills are available
- Conditionally render Skills section in system prompt (hidden when
  no skills exist)

* feat: add session type field and bind sessions to heartbeat/schedule executions

- Add `type` column to `bot_sessions` (chat | heartbeat | schedule)
- Add `session_id` to `bot_heartbeat_logs` for per-execution session tracking
- Create `schedule_logs` table binding schedule_id + session_id
- Heartbeat and schedule runs now create independent sessions and persist
  agent messages via storeRound, enabling full conversation replay
- Add schedule logs API endpoints (list by bot, list by schedule, delete)
- Update Triggerer interfaces to return TriggerResult with status/usage/model

* refactor: modular system prompts per session type (chat/heartbeat/schedule)

Split the monolithic system.md into three type-specific system prompts
with shared fragments via {{include:_xxx}} syntax, so each session type
gets a focused prompt without irrelevant instructions.

* fix: prevent message duplication after task completion

message_created events from Persist() had an empty platform field because
toMessageFromCreate() didn't extract it from the session. This caused
appendRealtimeMessage to fail the platform === 'web' guard, and
hasMessageWithId to fail because local IDs differ from server UUIDs,
resulting in all messages being appended as duplicates.

- Extract platform from metadata in toMessageFromCreate so published events
  carry the correct value
- Pass channel_type: 'web' when creating sessions from the web frontend so
  List queries return the correct platform via the session JOIN

* fix: use per-message usage from SDK instead of misaligned step-level usages

Previously, token usage was stored via a separate per-step usages array
that didn't align with messages (off-by-one from prepending user message,
step count != message count). This caused:
- User messages incorrectly receiving usage data
- Usage values shifted across messages in multi-step rounds
- Last assistant message getting the accumulated total instead of its own step usage
- InputTokenDetails/OutputTokenDetails lost during manual accumulation

Now each sdk.Message carries its own per-step Usage (set by the SDK in
buildStepMessages), which is extracted in sdkMessagesToModelMessages and
stored directly via ModelMessage.Usage. The storeRound/storeMessages path
no longer needs external usage/usages parameters.

Also fixes the totalUsage accumulation in runStream to include all detail
fields (InputTokenDetails, OutputTokenDetails).

* feat: add /new slash command to create a new active session from IM channels

Users in Telegram/Discord/Feishu can now send /new to start a fresh
conversation, resetting the session context for the current chat thread.
The command resolves the channel route, creates a new session, sets it as
the active session on the route, and replies with a confirmation message.

* feat: distinguish heartbeat and schedule sessions with dedicated icons in sidebar

Heartbeat sessions show a heart-pulse icon (rose), schedule sessions
show a clock icon (amber), and both display a type label beneath the
session title.

* refactor: remove enabledSkills system prompt injection, keep sorted skill listing

use_skill now returns skill content directly as tool output, so there is
no need to inject enabled skill body text into the system prompt. Remove
the entire enabledSkills tracking chain (RunConfig.EnabledSkillNames,
StreamEvent.Skills, GenerateResult.Skills, ChatRequest/Response.Skills,
enableSkill closures in runStream/runGenerate, prepareRunConfig matching).

Keep a lightweight skills listing (name + description only) in the system
prompt so the model knows which skills are available. Sort entries by name
to guarantee deterministic ordering and maximize KV cache reuse.

* refactor: remove inbox system, persist passive messages directly to history

Replace the bot_inbox table and service with direct writes to
bot_history_messages for group conversations where the bot is not
@mentioned. Trigger-path messages continue to be persisted after the
agent responds (unchanged).

- Drop bot_inbox table and max_inbox_items column (migration 0039)
- Delete internal/inbox/, handlers/inbox.go, command/inbox.go,
  agent/tools/inbox.go and the MCP message provider
- Add persistPassiveMessage() in channel inbound to write user
  messages into the active session immediately
- Rewrite ListObservedConversationsByChannelIdentity to query
  bot_history_messages + bot_sessions instead of bot_inbox
- Extract shared send/react logic into internal/messaging/executor.go;
  agent/tools/message.go is now a thin SDK adapter
- Clean up all inbox references from agent prompts, flow resolver,
  email trigger, settings, commands, DI wiring, and frontend
- Regenerate sqlc, swagger, and SDK

* feat: add list_sessions and search_messages agent tools

Provide agents with the ability to query session metadata and search
message history across all sessions. search_messages supports filtering
by time range, keyword (JSONB-aware ILIKE), session, contact, and role,
with a default 7-day lookback when no start_time is given.

* feat: inject last_heartbeat time and improve heartbeat search guidance

Query the previous heartbeat's started_at timestamp and pass it through
TriggerPayload into the heartbeat prompt template. Update system prompt
and HEARTBEAT.md checklist to guide agents to use search_messages with
start_time=last_heartbeat for efficient cross-session message review.

* fix: pass BridgeProvider to FSClient and store full heartbeat prompt

FSClient was always created with nil provider, causing all container
file reads (IDENTITY.md, SOUL.md, MEMORY.md, HEARTBEAT.md, etc.) to
silently return empty strings. Expose Agent.BridgeProvider() and wire
it into Resolver. Also fix heartbeat trigger to store the full prompt
template as the user message instead of the literal "heartbeat" string.

* feat: add line numbers to container file read output

Move line-number formatting from the bridge gRPC server to the agent
tool layer so that the raw content stored and transmitted via gRPC
remains clean, while the read_file tool output includes numbered lines
for easier reference by the agent.

* chore(deps): update twilight-ai to v0.3.2

* fix: lint, test
This commit is contained in:
Acbox Liu
2026-03-21 15:57:22 +08:00
committed by GitHub
parent ad08f335eb
commit 7d7d0e4b51
152 changed files with 7674 additions and 4922 deletions
+240 -62
View File
@@ -24,7 +24,6 @@ import (
"github.com/memohai/memoh/internal/command"
"github.com/memohai/memoh/internal/conversation"
"github.com/memohai/memoh/internal/conversation/flow"
"github.com/memohai/memoh/internal/inbox"
"github.com/memohai/memoh/internal/media"
messagepkg "github.com/memohai/memoh/internal/message"
)
@@ -72,6 +71,19 @@ type ttsModelResolver interface {
ResolveTtsModelID(ctx context.Context, botID string) (string, error)
}
// SessionEnsurer resolves or creates an active session for a route.
type SessionEnsurer interface {
EnsureActiveSession(ctx context.Context, botID, routeID, channelType string) (SessionResult, error)
// CreateNewSession always creates a fresh session and sets it as the
// active session for the given route, replacing any previous one.
CreateNewSession(ctx context.Context, botID, routeID, channelType string) (SessionResult, error)
}
// SessionResult carries the minimum fields needed from a session.
type SessionResult struct {
ID string
}
// ChannelInboundProcessor routes channel inbound messages to the chat gateway.
type ChannelInboundProcessor struct {
runner flow.Runner
@@ -79,7 +91,6 @@ type ChannelInboundProcessor struct {
message messagepkg.Writer
mediaService mediaIngestor
reactor channelReactor
inboxService *inbox.Service
commandHandler *command.Handler
registry *channel.Registry
logger *slog.Logger
@@ -91,6 +102,7 @@ type ChannelInboundProcessor struct {
observer channel.StreamObserver
ttsService ttsSynthesizer
ttsModelResolver ttsModelResolver
sessionEnsurer SessionEnsurer
}
// NewChannelInboundProcessor creates a processor with channel identity-based resolution.
@@ -167,15 +179,6 @@ func (p *ChannelInboundProcessor) SetStreamObserver(observer channel.StreamObser
p.observer = observer
}
// SetInboxService configures the inbox service for storing non-mentioned
// group messages as inbox items.
func (p *ChannelInboundProcessor) SetInboxService(service *inbox.Service) {
if p == nil {
return
}
p.inboxService = service
}
// SetTtsService configures the TTS synthesizer and settings reader for handling
// <speech> tag events (speech_delta) that require server-side audio synthesis.
func (p *ChannelInboundProcessor) SetTtsService(synth ttsSynthesizer, modelResolver ttsModelResolver) {
@@ -186,6 +189,14 @@ func (p *ChannelInboundProcessor) SetTtsService(synth ttsSynthesizer, modelResol
p.ttsModelResolver = modelResolver
}
// SetSessionEnsurer configures the session ensurer for auto-creating sessions on routes.
func (p *ChannelInboundProcessor) SetSessionEnsurer(ensurer SessionEnsurer) {
if p == nil {
return
}
p.sessionEnsurer = ensurer
}
// SetCommandHandler configures the slash command handler for intercepting
// /command messages before they reach the LLM.
func (p *ChannelInboundProcessor) SetCommandHandler(handler *command.Handler) {
@@ -252,6 +263,13 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
// In group chats, only process if the message is directed at this bot
// (via @mention or reply) to avoid all bots responding to the same command.
cmdText := rawTextForCommand(msg, text)
// /new requires route context, so it is handled separately from the
// general command handler (which runs before route resolution).
if isNewSessionCommand(cmdText) && isDirectedAtBot(msg) {
return p.handleNewSessionCommand(ctx, cfg, msg, sender, identity)
}
if p.commandHandler != nil && p.commandHandler.IsCommand(cmdText) && isDirectedAtBot(msg) {
reply, err := p.commandHandler.Execute(ctx, strings.TrimSpace(identity.BotID), strings.TrimSpace(identity.ChannelIdentityID), cmdText)
if err != nil {
@@ -273,6 +291,7 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
return errors.New("route resolver not configured")
}
routeMetadata := buildRouteMetadata(msg, identity)
p.enrichConversationAvatar(ctx, cfg, msg, routeMetadata)
resolved, err := p.routeResolver.ResolveConversation(ctx, route.ResolveInput{
BotID: identity.BotID,
Platform: msg.Channel.String(),
@@ -287,18 +306,28 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
if err != nil {
return fmt.Errorf("resolve route conversation: %w", err)
}
// Resolve or auto-create the active session for this route.
sessionID := ""
if p.sessionEnsurer != nil {
sess, sessErr := p.sessionEnsurer.EnsureActiveSession(ctx, identity.BotID, resolved.RouteID, msg.Channel.String())
if sessErr != nil {
if p.logger != nil {
p.logger.Warn("ensure active session failed", slog.Any("error", sessErr))
}
} else {
sessionID = sess.ID
}
}
// Bot-centric history container:
// always persist channel traffic under bot_id so WebUI can view unified cross-platform history.
activeChatID := strings.TrimSpace(identity.BotID)
if activeChatID == "" {
activeChatID = strings.TrimSpace(resolved.ChatID)
}
// Determine inbox action: trigger (immediate response) or notify (passive).
inboxAction := inbox.ActionNotify
if shouldTriggerAssistantResponse(msg) || identity.ForceReply {
inboxAction = inbox.ActionTrigger
}
if inboxAction == inbox.ActionTrigger && p.acl != nil {
shouldTrigger := shouldTriggerAssistantResponse(msg) || identity.ForceReply
if shouldTrigger && p.acl != nil {
allowed, err := p.acl.CanPerformChatTrigger(ctx, acl.ChatTriggerRequest{
BotID: identity.BotID,
UserID: identity.UserID,
@@ -314,7 +343,7 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
return fmt.Errorf("authorize chat trigger: %w", err)
}
if !allowed {
inboxAction = inbox.ActionNotify
shouldTrigger = false
if p.logger != nil {
p.logger.Info(
"inbound trigger denied by acl",
@@ -328,10 +357,8 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
}
}
// All messages go through inbox first.
inboxItem := p.createInboxItem(ctx, identity, msg, text, attachments, resolved.RouteID, inboxAction)
if inboxAction != inbox.ActionTrigger {
if !shouldTrigger {
p.persistPassiveMessage(ctx, identity, msg, text, attachments, resolved.RouteID, sessionID)
if p.logger != nil {
p.logger.Info(
"inbound not triggering assistant (group trigger condition not met)",
@@ -348,11 +375,6 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
return nil
}
// Mark the trigger inbox item as read immediately.
if inboxItem.ID != "" {
p.markInboxItemRead(ctx, inboxItem)
}
// Issue chat token for reply routing.
chatToken := ""
if p.jwtSecret != "" && strings.TrimSpace(msg.ReplyTarget) != "" {
@@ -498,6 +520,7 @@ func (p *ChannelInboundProcessor) HandleInbound(ctx context.Context, cfg channel
chunkCh, streamErrCh := p.runner.StreamChat(ctx, conversation.ChatRequest{
BotID: identity.BotID,
ChatID: activeChatID,
SessionID: sessionID,
Token: token,
UserID: identity.UserID,
SourceChannelIdentityID: identity.ChannelIdentityID,
@@ -720,69 +743,91 @@ func metadataBool(metadata map[string]any, key string) bool {
}
}
func (p *ChannelInboundProcessor) createInboxItem(
// persistPassiveMessage writes a user message directly into bot_history_messages
// for group conversations where the bot was not @mentioned. This replaces the
// old inbox system — the message is stored in the route's active session so it
// becomes part of the conversation history the next time the agent is triggered.
func (p *ChannelInboundProcessor) persistPassiveMessage(
ctx context.Context,
ident InboundIdentity,
msg channel.InboundMessage,
text string,
attachments []conversation.ChatAttachment,
routeID string,
action string,
) inbox.Item {
if p.inboxService == nil {
return inbox.Item{}
routeID, sessionID string,
) {
if p.message == nil {
return
}
botID := strings.TrimSpace(ident.BotID)
if botID == "" {
return inbox.Item{}
return
}
trimmedText := strings.TrimSpace(text)
if trimmedText == "" && len(attachments) == 0 {
return inbox.Item{}
}
displayName := strings.TrimSpace(ident.DisplayName)
if displayName == "" {
displayName = "Unknown"
return
}
var attachmentPaths []string
for _, att := range attachments {
if p := strings.TrimSpace(att.Path); p != "" {
attachmentPaths = append(attachmentPaths, p)
if ap := strings.TrimSpace(att.Path); ap != "" {
attachmentPaths = append(attachmentPaths, ap)
}
}
meta := flow.BuildUserMessageMeta(
headerifiedText := flow.FormatUserHeader(
strings.TrimSpace(msg.Message.ID),
strings.TrimSpace(ident.ChannelIdentityID),
displayName,
strings.TrimSpace(ident.DisplayName),
msg.Channel.String(),
strings.TrimSpace(msg.Conversation.Type),
strings.TrimSpace(msg.Conversation.Name),
attachmentPaths,
trimmedText,
)
header := meta.ToMap()
header["route_id"] = strings.TrimSpace(routeID)
item, err := p.inboxService.Create(ctx, inbox.CreateRequest{
BotID: botID,
Source: msg.Channel.String(),
Header: header,
Content: trimmedText,
Action: action,
})
if err != nil && p.logger != nil {
p.logger.Warn("create inbox item failed", slog.Any("error", err), slog.String("bot_id", botID))
}
return item
}
func (p *ChannelInboundProcessor) markInboxItemRead(ctx context.Context, item inbox.Item) {
if p.inboxService == nil || item.ID == "" {
modelMsg := conversation.ModelMessage{Role: "user", Content: conversation.NewTextContent(headerifiedText)}
serialized, err := json.Marshal(modelMsg)
if err != nil {
if p.logger != nil {
p.logger.Warn("marshal passive message failed", slog.Any("error", err))
}
return
}
if err := p.inboxService.MarkRead(ctx, item.BotID, []string{item.ID}); err != nil && p.logger != nil {
p.logger.Warn("mark inbox item read failed", slog.Any("error", err), slog.String("item_id", item.ID))
meta := map[string]any{
"route_id": strings.TrimSpace(routeID),
"platform": msg.Channel.String(),
}
var assets []messagepkg.AssetRef
for i, att := range attachments {
ch := strings.TrimSpace(att.ContentHash)
if ch == "" {
continue
}
assets = append(assets, messagepkg.AssetRef{
ContentHash: ch,
Role: "attachment",
Ordinal: i,
Mime: strings.TrimSpace(att.Mime),
SizeBytes: att.Size,
Name: strings.TrimSpace(att.Name),
Metadata: att.Metadata,
})
}
if _, err := p.message.Persist(ctx, messagepkg.PersistInput{
BotID: botID,
SessionID: sessionID,
SenderChannelIdentityID: strings.TrimSpace(ident.ChannelIdentityID),
SenderUserID: strings.TrimSpace(ident.UserID),
ExternalMessageID: strings.TrimSpace(msg.Message.ID),
Role: "user",
Content: serialized,
Metadata: meta,
Assets: assets,
}); err != nil && p.logger != nil {
p.logger.Warn("persist passive message failed", slog.Any("error", err), slog.String("bot_id", botID))
}
}
@@ -2138,6 +2183,9 @@ func buildRouteMetadata(msg channel.InboundMessage, identity InboundIdentity) ma
if v := strings.TrimSpace(identity.DisplayName); v != "" {
m["sender_display_name"] = v
}
if v := strings.TrimSpace(identity.AvatarURL); v != "" {
m["sender_avatar_url"] = v
}
if v := strings.TrimSpace(msg.Sender.SubjectID); v != "" {
m["sender_id"] = v
}
@@ -2157,3 +2205,133 @@ func buildRouteMetadata(msg channel.InboundMessage, identity InboundIdentity) ma
return m
}
// enrichConversationAvatar resolves group-level metadata (avatar, handle) via
// the directory adapter and stores them in the route metadata map.
func (p *ChannelInboundProcessor) enrichConversationAvatar(ctx context.Context, cfg channel.ChannelConfig, msg channel.InboundMessage, meta map[string]any) {
convType := strings.TrimSpace(msg.Conversation.Type)
if convType != "group" && convType != "supergroup" && convType != "channel" {
return
}
if p.registry == nil {
return
}
directoryAdapter, ok := p.registry.DirectoryAdapter(msg.Channel)
if !ok || directoryAdapter == nil {
return
}
convID := strings.TrimSpace(msg.Conversation.ID)
if convID == "" {
return
}
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
entry, err := directoryAdapter.ResolveEntry(lookupCtx, cfg, convID, channel.DirectoryEntryGroup)
if err != nil {
if p.logger != nil {
p.logger.Debug("resolve conversation directory entry failed",
slog.String("channel", msg.Channel.String()),
slog.String("conversation_id", convID),
slog.Any("error", err),
)
}
return
}
if v := strings.TrimSpace(entry.AvatarURL); v != "" {
meta["conversation_avatar_url"] = v
}
if v := strings.TrimSpace(entry.Handle); v != "" {
meta["conversation_handle"] = v
}
}
// isNewSessionCommand returns true when the command text is "/new" (with
// optional Telegram-style @botname suffix and trailing whitespace).
func isNewSessionCommand(cmdText string) bool {
extracted := command.ExtractCommandText(cmdText)
if extracted == "" {
return false
}
parsed, err := command.Parse(extracted)
if err != nil {
return false
}
return parsed.Resource == "new"
}
// handleNewSessionCommand resolves the route for the current message and
// creates a brand-new active session, effectively starting a fresh
// conversation in the same IM thread/chat.
func (p *ChannelInboundProcessor) handleNewSessionCommand(
ctx context.Context,
cfg channel.ChannelConfig,
msg channel.InboundMessage,
sender channel.StreamReplySender,
identity InboundIdentity,
) error {
target := strings.TrimSpace(msg.ReplyTarget)
if target == "" {
return errors.New("reply target missing for /new command")
}
if p.routeResolver == nil {
return sender.Send(ctx, channel.OutboundMessage{
Target: target,
Message: channel.Message{Text: "Error: route resolver not configured."},
})
}
if p.sessionEnsurer == nil {
return sender.Send(ctx, channel.OutboundMessage{
Target: target,
Message: channel.Message{Text: "Error: session service not configured."},
})
}
threadID := extractThreadID(msg)
routeMetadata := buildRouteMetadata(msg, identity)
p.enrichConversationAvatar(ctx, cfg, msg, routeMetadata)
resolved, err := p.routeResolver.ResolveConversation(ctx, route.ResolveInput{
BotID: identity.BotID,
Platform: msg.Channel.String(),
ConversationID: msg.Conversation.ID,
ThreadID: threadID,
ConversationType: msg.Conversation.Type,
ChannelIdentityID: identity.UserID,
ChannelConfigID: identity.ChannelConfigID,
ReplyTarget: target,
Metadata: routeMetadata,
})
if err != nil {
if p.logger != nil {
p.logger.Warn("resolve route for /new command failed", slog.Any("error", err))
}
return sender.Send(ctx, channel.OutboundMessage{
Target: target,
Message: channel.Message{Text: "Error: failed to resolve conversation route."},
})
}
sess, err := p.sessionEnsurer.CreateNewSession(ctx, identity.BotID, resolved.RouteID, msg.Channel.String())
if err != nil {
if p.logger != nil {
p.logger.Warn("create new session via /new command failed", slog.Any("error", err))
}
return sender.Send(ctx, channel.OutboundMessage{
Target: target,
Message: channel.Message{Text: "Error: failed to create new session."},
})
}
if p.logger != nil {
p.logger.Info("new session created via /new command",
slog.String("bot_id", strings.TrimSpace(identity.BotID)),
slog.String("route_id", strings.TrimSpace(resolved.RouteID)),
slog.String("session_id", strings.TrimSpace(sess.ID)),
slog.String("channel", msg.Channel.String()),
)
}
return sender.Send(ctx, channel.OutboundMessage{
Target: target,
Message: channel.Message{Text: "New conversation started."},
})
}
+23 -12
View File
@@ -64,8 +64,8 @@ func (f *fakeChatGateway) StreamChat(_ context.Context, req conversation.ChatReq
return chunks, errs
}
func (*fakeChatGateway) TriggerSchedule(_ context.Context, _ string, _ schedule.TriggerPayload, _ string) error {
return nil
func (*fakeChatGateway) TriggerSchedule(_ context.Context, _ string, _ schedule.TriggerPayload, _ string) (schedule.TriggerResult, error) {
return schedule.TriggerResult{}, nil
}
type fakeReplySender struct {
@@ -321,10 +321,9 @@ func (f *fakeChatService) Persist(_ context.Context, input messagepkg.PersistInp
f.persistedIn = append(f.persistedIn, input)
msg := messagepkg.Message{
BotID: input.BotID,
RouteID: input.RouteID,
SessionID: input.SessionID,
SenderChannelIdentityID: input.SenderChannelIdentityID,
SenderUserID: input.SenderUserID,
Platform: input.Platform,
ExternalMessageID: input.ExternalMessageID,
SourceReplyToMessageID: input.SourceReplyToMessageID,
Role: input.Role,
@@ -455,8 +454,11 @@ func TestChannelInboundProcessorACLGuestDeniedDowngradesToNotify(t *testing.T) {
if len(sender.sent) != 0 {
t.Fatalf("ACL denied guest should not send reply, got %+v", sender.sent)
}
if len(chatSvc.persistedIn) != 0 {
t.Fatalf("ACL denied guest should not persist trigger message, got %d", len(chatSvc.persistedIn))
if len(chatSvc.persistedIn) != 1 {
t.Fatalf("ACL denied guest should persist 1 passive message (replacing inbox), got %d", len(chatSvc.persistedIn))
}
if chatSvc.persistedIn[0].Role != "user" {
t.Fatalf("passive message role should be user, got %q", chatSvc.persistedIn[0].Role)
}
}
@@ -685,8 +687,11 @@ func TestChannelInboundProcessorGroupPassiveSync(t *testing.T) {
if len(sender.sent) != 0 {
t.Fatalf("group passive sync should not send reply: %+v", sender.sent)
}
if len(chatSvc.persisted) != 0 {
t.Fatalf("group passive sync should not persist to messages directly, got: %d", len(chatSvc.persisted))
if len(chatSvc.persisted) != 1 {
t.Fatalf("group passive sync should persist 1 passive message (replacing inbox), got: %d", len(chatSvc.persisted))
}
if chatSvc.persisted[0].Role != "user" {
t.Fatalf("passive message role should be user, got %q", chatSvc.persisted[0].Role)
}
}
@@ -1067,8 +1072,11 @@ func TestChannelInboundProcessorPersonalGroupNonOwnerIgnored(t *testing.T) {
if len(sender.sent) != 0 {
t.Fatalf("non-owner should be ignored silently: %+v", sender.sent)
}
if len(chatSvc.persisted) != 0 {
t.Fatalf("ignored message should not persist in passive mode")
if len(chatSvc.persisted) != 1 {
t.Fatalf("non-owner group message should persist 1 passive message (replacing inbox), got %d", len(chatSvc.persisted))
}
if chatSvc.persisted[0].Role != "user" {
t.Fatalf("passive message role should be user, got %q", chatSvc.persisted[0].Role)
}
}
@@ -1109,8 +1117,11 @@ func TestChannelInboundProcessorPersonalGroupOwnerWithoutMentionUsesPassivePersi
if len(sender.sent) != 0 {
t.Fatalf("owner group message without mention should not send reply")
}
if len(chatSvc.persisted) != 0 {
t.Fatalf("non-mentioned message should not persist to messages (only inbox), got: %d", len(chatSvc.persisted))
if len(chatSvc.persisted) != 1 {
t.Fatalf("owner non-mentioned message should persist 1 passive message (replacing inbox), got: %d", len(chatSvc.persisted))
}
if chatSvc.persisted[0].Role != "user" {
t.Fatalf("passive message role should be user, got %q", chatSvc.persisted[0].Role)
}
}