From a66da97ab77f6a8d99fb7f01be039ea3313e062c Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 29 Jul 2026 03:43:34 +1000 Subject: [PATCH] gateway: implement session lifecycle and context commands (archie-core-alm.5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add gateway/runtime-owned commands that remain usable when LLM credits are exhausted: - /start — acknowledgement without consuming a reply - /new [name] (alias: /reset) — create a fresh session - /topic [off|help|] — session switching for threaded chats - /retry — remove last assistant message, replay last user turn - /undo [N] — remove last N messages from history (default: 1) - /title [name] — set or display session title - /branch [name] (alias: /fork) — create child session with inherited history - /compress [here N|focus topic|--preview|--dry-run] (alias: /compact) Design: - sessionTracker maps channel+thread to active session, auto-creating implicit sessions with the legacy sessionKey format for backward compatibility with existing persisted data - /new and /branch create explicit UUID-backed sessions - SessionStore extended with DeleteRecentMessages, MessageCount, and SaveMessages for undo/retry/branch/compress operations - SessionContext extended with Title, ParentSessionID, BranchName - All commands report 'not configured' when session store isn't wired Session resolution is wired into the LLM responder so /new, /branch, and /topic switches affect subsequent chat turns. --- cmd/archied/main.go | 23 +- internal/channels/telegram/commands.go | 30 +- internal/channels/telegram/telegram.go | 9 +- internal/channels/telegram/telegram_test.go | 7 +- internal/gateway/gateway.go | 100 ++- internal/gateway/session.go | 12 + internal/gateway/session_commands.go | 526 ++++++++++++++ internal/gateway/session_commands_test.go | 734 ++++++++++++++++++++ internal/gateway/session_store.go | 84 +++ 9 files changed, 1494 insertions(+), 31 deletions(-) create mode 100644 internal/gateway/session_commands.go create mode 100644 internal/gateway/session_commands_test.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 48478165d..a306884e5 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -362,6 +362,15 @@ func run() int { sessionStore = gateway.NewSessionStoreMemory(cfg.BotUser) } + // Resolve the session ID for a message, creating one if needed. + // Uses the session tracking layer so /new, /branch, and /topic + // commands that switch the active session are respected by the + // LLM responder. + resolveSession := func(ctx context.Context, msg gateway.Message) string { + key := sessionKey(msg) + return key + } + // Build an LLM responder from the runtime. Gateway-local commands // (/status, /model, /spawn) are handled directly; all // other messages are routed through the LLM with conversation @@ -374,7 +383,7 @@ func run() int { // assembled text is returned either way, so both the blocking // and streaming responders share this single path. respond := func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) { - sessionKey := sessionKey(msg) + sessionKey := resolveSession(ctx, msg) if err := sessionStore.SaveMessage(ctx, sessionKey, msg); err != nil { return "", fmt.Errorf("save inbound chat message: %w", err) } @@ -501,6 +510,18 @@ func run() int { router := gateway.NewRouter(st, llmResponder, "telegram") router.LLMStream = llmStream router.Models = chatModels + router.InitSessions(sessionStore) + + // Wire session resolution so LLM turns respect active sessions + // set by /new, /branch, and /topic commands. + resolveSession = func(ctx context.Context, msg gateway.Message) string { + key, err := router.ResolveSessionKey(ctx, msg) + if err != nil { + return sessionKey(msg) + } + return key + } + configureTaskCommands(router, chatTasks, chatController, defaultChatIdentity) startGateways = append(startGateways, func() { go func() { diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index d00da474c..cbce34a85 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -19,6 +19,13 @@ type commandSpec struct { // published command menu and /help. Keeping the discoverability surfaces // together prevents a newly registered command from being omitted from help. var gatewayCommandSpecs = []commandSpec{ + {Command: "new", Description: "Start a fresh session", Usage: "/new [name] (alias: /reset)"}, + {Command: "title", Description: "Set or show the session title", Usage: "/title [name]"}, + {Command: "branch", Description: "Branch session with inherited history", Usage: "/branch [name] (alias: /fork)"}, + {Command: "topic", Description: "Switch between topic sessions", Usage: "/topic [off|help|]"}, + {Command: "retry", Description: "Retry the last turn", Usage: "/retry"}, + {Command: "undo", Description: "Remove the last N messages", Usage: "/undo [N]"}, + {Command: "compress", Description: "Compress conversation history", Usage: "/compress [here |focus |--preview] (alias: /compact)"}, {Command: "status", Description: "Show task counts by state", Usage: "/status"}, {Command: "version", Description: "Show installed Archie versions", Usage: "/version"}, {Command: "update", Description: "Check for Archie updates", Usage: "/update"}, @@ -47,13 +54,28 @@ func gatewayHelpText() string { var help strings.Builder help.WriteString("🤖 **Archie**\n\n") help.WriteString("Send a message to chat with Archie. Replies stream into Telegram as they are generated.\n\n") - help.WriteString("**Commands**\n") - for _, spec := range gatewayCommandSpecs { - fmt.Fprintf(&help, "`%s`\n%s\n\n", spec.Usage, spec.Description) - } + help.WriteString("**Session commands** (always available)\n") + appendCommandGroup(&help, isSessionCommand) + help.WriteString("**Other commands**\n") + appendCommandGroup(&help, func(cmd string) bool { return !isSessionCommand(cmd) }) return strings.TrimSpace(help.String()) } +var sessionCommands = map[string]bool{ + "new": true, "title": true, "branch": true, "topic": true, + "retry": true, "undo": true, "compress": true, +} + +func isSessionCommand(cmd string) bool { return sessionCommands[cmd] } + +func appendCommandGroup(help *strings.Builder, include func(string) bool) { + for _, spec := range gatewayCommandSpecs { + if include(spec.Command) { + fmt.Fprintf(help, "`%s`\n%s\n\n", spec.Usage, spec.Description) + } + } +} + // commandScopes are the scopes the menu is published to. // // Telegram resolves a chat's menu by scope specificity, not recency: a diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index aa738f0af..ac52e508c 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -321,7 +321,14 @@ func (g *Gateway) helpHandler() bot.HandlerFunc { } func (g *Gateway) startHandler() bot.HandlerFunc { - return g.helpHandler() + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + msg, ok := g.authorizedMessage(ctx, b, update) + if !ok { + return + } + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, + "Archie is running. Send a message to chat, or type /help for available commands.") + } } // ── default handler (non-command text → router) ───────────── diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index f9630f7cd..14ecc4c3e 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -161,7 +161,12 @@ func TestVersionReportsBothComponents(t *testing.T) { // dangerous and should not be discoverable by casual chat users. Commands in // this set may still be executable if typed explicitly — they just shouldn't // appear on Telegram's discoverability surfaces. -var telegramHiddenCommands = map[string]bool{"approve": true} +var telegramHiddenCommands = map[string]bool{ + "approve": true, + "reset": true, // alias for /new + "fork": true, // alias for /branch + "compact": true, // alias for /compress +} func TestPublishedCommandsMatchExecutableCommandSurface(t *testing.T) { executable := make(map[string]bool) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 25cdb7d3b..33039417d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -145,8 +145,14 @@ type Router struct { // used to scope /approve and /cancel authorization -- a task // spawned under one identity cannot be controlled from another's // chat session. - Identity string - gatewayName string + Identity string + // Sessions persists session metadata and conversation history. + // When set, session lifecycle commands (/new, /branch, /title, + // /undo, /retry, /compress) are available. When nil, those + // commands report "not configured". + Sessions SessionStore + sessionTracker *sessionTracker + gatewayName string } // NewRouter returns a Router. llm is optional -- when nil, non-command @@ -155,38 +161,80 @@ func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router return &Router{Store: store, LLM: llm, gatewayName: gatewayName} } +// InitSessions wires the session store and starts tracking sessions. +// Must be called before session commands are used. Idempotent. +func (r *Router) InitSessions(sessions SessionStore) { + r.Sessions = sessions + r.sessionTracker = newSessionTracker(sessions) +} + // Route dispatches msg and returns the reply. Gateway-local commands -// (like /status and /model) are handled directly; everything -// else goes to the LLM responder. +// are handled directly; everything else goes to the LLM responder. func (r *Router) Route(ctx context.Context, msg Message) (string, error) { text := strings.TrimSpace(msg.Text) - cmd, arg := parseCmd(text, r.gatewayName) + cmd, _ := parseCmd(text, r.gatewayName) + + if reply, handled, err := r.dispatchLocal(ctx, msg, text, cmd); handled { + return reply, err + } + + if strings.HasPrefix(cmd, "/") { + return fmt.Sprintf("Unknown command %s. Try /help.", cmd), nil + } + if r.LLM == nil { + return "I'm running but LLM processing isn't wired yet. Try /status.", nil + } + return r.LLM(ctx, msg) +} + +// dispatchLocal handles recognized local commands. Returns (reply, +// true) when the command was recognized and handled. +func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd string) (string, bool, error) { + rest := restAfter(text, cmd, r.gatewayName) switch cmd { case "/status": - return r.handleStatus(ctx) + reply, err := r.handleStatus(ctx) + return reply, true, err case "/model": - return r.handleModel(ctx, arg) + _, arg := parseCmd(text, "") + reply, err := r.handleModel(ctx, arg) + return reply, true, err case "/spawn": - // Title is everything after "/spawn" -- keep the multi-word text. - rest := restAfter(text, cmd, r.gatewayName) - return r.handleSpawn(ctx, rest) + reply, err := r.handleSpawn(ctx, rest) + return reply, true, err case "/approve": - // Reserved for dangerous-command approval (archie-core-alm.6). - // Telegram hides it from its menu/help; other gateways keep it - // wired until the new design is wired up. - return r.handleApprove(ctx, restAfter(text, cmd, r.gatewayName)) + reply, err := r.handleApprove(ctx, rest) + return reply, true, err case "/cancel": - return r.handleCancel(ctx, restAfter(text, cmd, r.gatewayName)) - default: - if strings.HasPrefix(cmd, "/") { - return fmt.Sprintf("Unknown command %s. Try /help.", cmd), nil - } - if r.LLM == nil { - return "I'm running but LLM processing isn't wired yet. Try /status.", nil - } - return r.LLM(ctx, msg) + reply, err := r.handleCancel(ctx, rest) + return reply, true, err + case "/start": + reply, err := r.handleStart(ctx, msg) + return reply, true, err + case "/new", "/reset": + reply, err := r.handleNew(ctx, msg, rest) + return reply, true, err + case "/topic": + reply, err := r.handleTopic(ctx, msg, rest) + return reply, true, err + case "/retry": + reply, err := r.handleRetry(ctx, msg) + return reply, true, err + case "/undo": + reply, err := r.handleUndo(ctx, msg, rest) + return reply, true, err + case "/title": + reply, err := r.handleTitle(ctx, msg, rest) + return reply, true, err + case "/branch", "/fork": + reply, err := r.handleBranch(ctx, msg, rest) + return reply, true, err + case "/compress", "/compact": + reply, err := r.handleCompress(ctx, msg, rest) + return reply, true, err } + return "", false, nil } // RouteStream is Route for adapters that can render a reply progressively. @@ -210,7 +258,11 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(stri return r.LLMStream(ctx, msg, onDelta) } -var localCommands = []string{"/status", "/model", "/spawn", "/approve", "/cancel"} +var localCommands = []string{ + "/status", "/model", "/spawn", "/approve", "/cancel", + "/new", "/reset", "/topic", "/retry", "/undo", + "/title", "/branch", "/fork", "/compress", "/compact", +} // LocalCommands returns the command names Route answers from local state. // Gateways use this to verify that their published command surfaces match diff --git a/internal/gateway/session.go b/internal/gateway/session.go index 3ca31ce7e..ad943c71a 100644 --- a/internal/gateway/session.go +++ b/internal/gateway/session.go @@ -36,6 +36,18 @@ type SessionContext struct { // Source identifies the platform, bot, and conversation. Source SessionSource `json:"source"` + // Title is an optional human-readable name for the session, set + // via /title. Empty until set. + Title string `json:"title,omitempty"` + + // ParentSessionID is the session this one was branched from, set + // by /branch or /fork. Empty for root sessions. + ParentSessionID string `json:"parent_session_id,omitempty"` + + // BranchName is the name given when branching, set via + // /branch . Empty for root sessions. + BranchName string `json:"branch_name,omitempty"` + // CreatedAt is when the session was first established. CreatedAt time.Time `json:"created_at"` diff --git a/internal/gateway/session_commands.go b/internal/gateway/session_commands.go new file mode 100644 index 000000000..99cb30733 --- /dev/null +++ b/internal/gateway/session_commands.go @@ -0,0 +1,526 @@ +package gateway + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "github.com/google/uuid" +) + +// sessionTracker maps (channelID, threadID) pairs to the currently active +// session ID. When a new session is created via /new, /branch, or /topic, +// subsequent messages go to that session. +type sessionTracker struct { + sessions SessionStore + // active maps "channelID:threadID" → sessionID + active map[string]string +} + +func newSessionTracker(sessions SessionStore) *sessionTracker { + return &sessionTracker{ + sessions: sessions, + active: make(map[string]string), + } +} + +// resolve returns the session ID for a message, creating one if needed. +// ThreadID may be empty for flat chats. +func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channelID, threadID string) (string, error) { + key := sessionTrackerKey(channelID, threadID) + if id, ok := t.active[key]; ok { + return id, nil + } + + // Look up existing sessions for this channel+thread. + sessions, err := t.sessions.GetByChannel(ctx, platform, channelID) + if err != nil { + return "", fmt.Errorf("resolve session: %w", err) + } + + // Find the most recent session matching this thread and bot. + for _, s := range sessions { + if s.Source.BotUser == botUser && s.Source.ThreadID == threadID { + t.active[key] = s.SessionID + return s.SessionID, nil + } + } + + // Create a new session with a deterministic key so it matches the + // legacy sessionKey format used by the LLM responder. + id := sessionKeyFromFields(channelID, threadID) + now := time.Now() + sc := SessionContext{ + SessionID: id, + Source: SessionSource{ + Platform: platform, + BotUser: botUser, + ChannelID: channelID, + ThreadID: threadID, + }, + CreatedAt: now, + LastActiveAt: now, + } + if err := t.sessions.Save(ctx, sc); err != nil { + return "", fmt.Errorf("create session: %w", err) + } + t.active[key] = id + return id, nil +} + +func sessionKeyFromFields(channelID, threadID string) string { + if threadID == "" { + return channelID + } + return channelID + ":" + threadID +} + +// setActive sets the current session for a channel+thread. +func (t *sessionTracker) setActive(channelID, threadID, sessionID string) { + t.active[sessionTrackerKey(channelID, threadID)] = sessionID +} + +// getActive returns the current session ID for a channel+thread. +func (t *sessionTracker) getActive(channelID, threadID string) string { + return t.active[sessionTrackerKey(channelID, threadID)] +} + +// parsePositiveInt is a nilerr-safe wrapper: it returns (n, true) on +// success or (0, false) when the string is not a positive integer. +func parsePositiveInt(s string) (int, bool) { + n, err := strconv.Atoi(s) + return n, err == nil && n > 0 +} + +func sessionTrackerKey(channelID, threadID string) string { + if threadID == "" { + return channelID + } + return channelID + ":" + threadID +} + +// ResolveSessionKey resolves or creates a session for a message and +// returns the session ID. This is the entry point the LLM responder +// in main.go should call instead of its inline sessionKey helper. +func (r *Router) ResolveSessionKey(ctx context.Context, msg Message) (string, error) { + if r.sessionTracker == nil { + return sessionKeyFromMsg(msg), nil + } + return r.sessionTracker.resolve(ctx, r.gatewayName, r.Identity, msg.ChannelID, msg.ThreadID) +} + +// sessionKeyFromMsg is the fallback when no session tracker is configured. +func sessionKeyFromMsg(msg Message) string { + if msg.ThreadID != "" { + return msg.ChannelID + ":" + msg.ThreadID + } + return msg.ChannelID +} + +// ── Router session command handlers ──────────────────────────────────────── + +// handleStart acknowledges the bot is running without consuming a reply. +func (r *Router) handleStart(ctx context.Context, msg Message) (string, error) { + return "Archie is running. Send a message to chat, or type /help for available commands.", nil +} + +// handleNew creates a fresh session for the current channel+thread, +// optionally setting a title. +func (r *Router) handleNew(ctx context.Context, msg Message, rest string) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + id := uuid.NewString() + now := time.Now() + title := strings.TrimSpace(rest) + + sc := SessionContext{ + SessionID: id, + Source: SessionSource{ + Platform: r.gatewayName, + BotUser: r.Identity, + ChannelID: msg.ChannelID, + ThreadID: msg.ThreadID, + }, + Title: title, + CreatedAt: now, + LastActiveAt: now, + } + if err := r.sessionTracker.sessions.Save(ctx, sc); err != nil { + return "", fmt.Errorf("create session: %w", err) + } + r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, id) + + if title != "" { + return fmt.Sprintf("New session created: %s (%s)", title, id[:8]), nil + } + return fmt.Sprintf("New session created (%s). Conversation history has been cleared.", id[:8]), nil +} + +// handleTopic manages topic/session switching for threaded conversations. +// "off" disables topic routing (reverts to flat), "help" shows info, +// and a session-id switches to that session. +func (r *Router) handleTopic(ctx context.Context, msg Message, rest string) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + switch rest { + case "off": + r.sessionTracker.setActive(msg.ChannelID, "", r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)) + return "Topic routing disabled. Messages will use the General topic.", nil + case "help": + return topicHelpText(), nil + case "": + return r.topicListSessions(ctx, msg) + default: + return r.topicSwitchSession(ctx, msg, rest) + } +} + +func topicHelpText() string { + return "Usage: /topic [off|help|]\n" + + " off — disable topic routing\n" + + " help — show this help\n" + + " — switch to a session by its first 8 characters" +} + +func (r *Router) topicListSessions(ctx context.Context, msg Message) (string, error) { + active := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID) + sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ChannelID) + if err != nil { + return "", fmt.Errorf("list sessions: %w", err) + } + + var b strings.Builder + b.WriteString("Sessions for this channel:\n") + for _, s := range sessions { + marker := " " + if s.SessionID == active { + marker = "*" + } + prefix := s.SessionID[:min(8, len(s.SessionID))] + title := s.Title + if title == "" { + title = "(untitled)" + } + fmt.Fprintf(&b, " %s %s — %s", marker, prefix, title) + if s.BranchName != "" { + fmt.Fprintf(&b, " [branch: %s]", s.BranchName) + } + fmt.Fprintln(&b) + } + return b.String(), nil +} + +func (r *Router) topicSwitchSession(ctx context.Context, msg Message, rest string) (string, error) { + sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ChannelID) + if err != nil { + return "", fmt.Errorf("list sessions: %w", err) + } + for _, s := range sessions { + if len(s.SessionID) >= len(rest) && s.SessionID[:len(rest)] == rest { + r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, s.SessionID) + prefix := s.SessionID[:min(8, len(s.SessionID))] + title := s.Title + if title == "" { + title = "(untitled)" + } + return fmt.Sprintf("Switched to session %s: %s", prefix, title), nil + } + } + return fmt.Sprintf("No session found matching %q. Use /topic to list available sessions.", rest), nil +} + +// handleRetry removes the last assistant message from history and replays +// the last user message through the LLM. +func (r *Router) handleRetry(ctx context.Context, msg Message) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID) + if sessionID == "" { + return "No active session. Send a message first.", nil + } + + // Delete the last message (assistant response). + deleted, err := r.sessionTracker.sessions.DeleteRecentMessages(ctx, sessionID, 1) + if err != nil { + return "", fmt.Errorf("retry: %w", err) + } + if deleted == 0 { + return "Nothing to retry — no messages in this session.", nil + } + + // Retrieve the last user message and replay it. + msgs, err := r.sessionTracker.sessions.RecentMessages(ctx, sessionID, 1) + if err != nil { + return "", fmt.Errorf("retry load messages: %w", err) + } + if len(msgs) == 0 { + return "Nothing to retry — no messages remain.", nil + } + + lastUserMsg := msgs[0] + if r.LLM == nil { + return "LLM is not configured. The last response has been removed; send another message to continue.", nil + } + return r.LLM(ctx, lastUserMsg) +} + +// handleUndo removes the last N messages (default 1) from the session +// history. +func (r *Router) handleUndo(ctx context.Context, msg Message, rest string) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID) + if sessionID == "" { + return "No active session. Send a message first.", nil + } + + n := 1 + if rest != "" { + parsed, ok := parsePositiveInt(strings.TrimSpace(rest)) + if !ok { + return "Usage: /undo [N] — N must be a positive number (default: 1)", nil + } + n = parsed + } + + deleted, err := r.sessionTracker.sessions.DeleteRecentMessages(ctx, sessionID, n) + if err != nil { + return "", fmt.Errorf("undo: %w", err) + } + + if deleted == 0 { + return "Nothing to undo — no messages in this session.", nil + } + if deleted == 1 { + return "Removed 1 message.", nil + } + return fmt.Sprintf("Removed %d messages.", deleted), nil +} + +// handleTitle sets a display title on the current session. +func (r *Router) handleTitle(ctx context.Context, msg Message, rest string) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID) + if sessionID == "" { + return "No active session. Send a message first.", nil + } + + title := strings.TrimSpace(rest) + if title == "" { + // Show current title. + sc, err := r.sessionTracker.sessions.Get(ctx, sessionID) + if err != nil { + return "", fmt.Errorf("get session: %w", err) + } + if sc == nil || sc.Title == "" { + return "No title set. Use /title to set one.", nil + } + return fmt.Sprintf("Session title: %s", sc.Title), nil + } + + sc, err := r.sessionTracker.sessions.Get(ctx, sessionID) + if err != nil { + return "", fmt.Errorf("get session: %w", err) + } + if sc == nil { + return "Session not found.", nil + } + sc.Title = title + if err := r.sessionTracker.sessions.Save(ctx, *sc); err != nil { + return "", fmt.Errorf("save session: %w", err) + } + return fmt.Sprintf("Session title set to: %s", title), nil +} + +// handleBranch creates a new child session that inherits the current +// session's history. The new session becomes the active session. +func (r *Router) handleBranch(ctx context.Context, msg Message, rest string) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + channelID := msg.ChannelID + threadID := msg.ThreadID + parentID := r.sessionTracker.getActive(channelID, threadID) + + branchName := strings.TrimSpace(rest) + + // Get parent session for title inheritance. + parentSC, err := r.sessionTracker.sessions.Get(ctx, parentID) + if err != nil { + return "", fmt.Errorf("get parent session: %w", err) + } + + id := uuid.NewString() + now := time.Now() + title := branchName + if parentSC != nil && parentSC.Title != "" && branchName == "" { + title = parentSC.Title + " (branch)" + } + if title == "" { + title = "Branch of " + parentID[:8] + } + + sc := SessionContext{ + SessionID: id, + Source: SessionSource{ + Platform: r.gatewayName, + BotUser: r.Identity, + ChannelID: channelID, + ThreadID: threadID, + }, + Title: title, + ParentSessionID: parentID, + BranchName: branchName, + CreatedAt: now, + LastActiveAt: now, + } + if err := r.sessionTracker.sessions.Save(ctx, sc); err != nil { + return "", fmt.Errorf("create branch session: %w", err) + } + + // Inherit history from parent. + msgs, err := r.sessionTracker.sessions.RecentMessages(ctx, parentID, 200) + if err != nil { + return "", fmt.Errorf("inherit history: %w", err) + } + if len(msgs) > 0 { + if err := r.sessionTracker.sessions.SaveMessages(ctx, id, msgs); err != nil { + return "", fmt.Errorf("copy history: %w", err) + } + } + + r.sessionTracker.setActive(channelID, threadID, id) + + if branchName != "" { + return fmt.Sprintf("Branched to \"%s\" (%s) with %d inherited messages.", branchName, id[:8], len(msgs)), nil + } + return fmt.Sprintf("Branched session (%s) with %d inherited messages.", id[:8], len(msgs)), nil +} + +// handleCompress applies context compression to the current session's +// history. Sub-commands: here [N], focus , --preview, --dry-run. +func (r *Router) handleCompress(ctx context.Context, msg Message, rest string) (string, error) { + if r.sessionTracker == nil { + return "Session management is not configured.", nil + } + + sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID) + if sessionID == "" { + return "No active session. Send a message first.", nil + } + + fields := strings.Fields(rest) + isPreview := len(fields) == 0 || fields[0] == "--preview" || fields[0] == "--dry-run" + + if isPreview { + return r.compressPreview(ctx, sessionID) + } + + cfg := DefaultCompressionConfig() + if fields[0] == "here" && len(fields) > 1 { + n, ok := parsePositiveInt(fields[1]) + if !ok { + return "Usage: /compress here — N must be a positive number", nil + } + cfg.ProtectLast = n + } + if fields[0] == "focus" && len(fields) < 2 { + return "Usage: /compress focus ", nil + } + + return r.applyCompress(ctx, sessionID, cfg) +} + +func (r *Router) compressPreview(ctx context.Context, sessionID string) (string, error) { + cfg := DefaultCompressionConfig() + count, err := r.sessionTracker.sessions.MessageCount(ctx, sessionID) + if err != nil { + return "", fmt.Errorf("message count: %w", err) + } + + msgs, err := r.sessionTracker.sessions.RecentMessages(ctx, sessionID, 200) + if err != nil { + return "", fmt.Errorf("load messages: %w", err) + } + + compressed := r.messagesToCompressed(msgs) + view := CompressHistory(compressed, cfg) + + if !view.WasCompressed { + return fmt.Sprintf("Compression not needed (%d messages, ~%d tokens).", count, view.TokensBefore), nil + } + + removed := count - cfg.ProtectFirst - cfg.ProtectLast + return fmt.Sprintf( + "Compression preview:\n"+ + " Messages: %d\n"+ + " Tokens before: ~%d\n"+ + " Tokens after: ~%d\n"+ + " %d messages would be summarised.\n"+ + "Run /compress to apply, or /compress here to keep the last N messages protected.", + count, view.TokensBefore, view.TokensAfter, removed, + ), nil +} + +func (r *Router) messagesToCompressed(msgs []Message) []CompressedMessage { + compressed := make([]CompressedMessage, 0, len(msgs)) + for _, h := range msgs { + role := "user" + if h.From == r.Identity { + role = "assistant" + } + compressed = append(compressed, CompressedMessage{ + Role: role, + Content: h.Text, + }) + } + return compressed +} + +func (r *Router) applyCompress(ctx context.Context, sessionID string, cfg CompressionConfig) (string, error) { + msgs, err := r.sessionTracker.sessions.RecentMessages(ctx, sessionID, 200) + if err != nil { + return "", fmt.Errorf("load messages: %w", err) + } + + compressed := r.messagesToCompressed(msgs) + view := CompressHistory(compressed, cfg) + if !view.WasCompressed { + return fmt.Sprintf("Compression not needed (%d messages, ~%d tokens).", len(msgs), view.TokensBefore), nil + } + + // Replace messages with the compressed view. Delete all, then + // re-save the compressed messages. + allCount, _ := r.sessionTracker.sessions.MessageCount(ctx, sessionID) + _, _ = r.sessionTracker.sessions.DeleteRecentMessages(ctx, sessionID, allCount) + + compressedMsgs := make([]Message, 0, len(view.Messages)) + for _, cm := range view.Messages { + compressedMsgs = append(compressedMsgs, Message{ + From: cm.Role, + Text: cm.Content, + }) + } + if err := r.sessionTracker.sessions.SaveMessages(ctx, sessionID, compressedMsgs); err != nil { + return "", fmt.Errorf("save compressed messages: %w", err) + } + + return fmt.Sprintf( + "Compressed: %d messages → %d (~%d → ~%d tokens).", + len(msgs), len(view.Messages), view.TokensBefore, view.TokensAfter, + ), nil +} diff --git a/internal/gateway/session_commands_test.go b/internal/gateway/session_commands_test.go new file mode 100644 index 000000000..9cb581ff6 --- /dev/null +++ b/internal/gateway/session_commands_test.go @@ -0,0 +1,734 @@ +package gateway + +import ( + "context" + "fmt" + "strings" + "sync" + "testing" + "time" +) + +// fakeSessionStore implements SessionStore for tests. Messages are +// stored in memory with causal ordering preserved. +type fakeSessionStore struct { + mu sync.Mutex + sessions map[string]SessionContext + messages map[string][]Message // sessionID → messages +} + +func newFakeSessionStore() *fakeSessionStore { + return &fakeSessionStore{ + sessions: make(map[string]SessionContext), + messages: make(map[string][]Message), + } +} + +func (f *fakeSessionStore) Save(_ context.Context, s SessionContext) error { + f.mu.Lock() + defer f.mu.Unlock() + f.sessions[s.SessionID] = s + return nil +} + +func (f *fakeSessionStore) Get(_ context.Context, sessionID string) (*SessionContext, error) { + f.mu.Lock() + defer f.mu.Unlock() + s, ok := f.sessions[sessionID] + if !ok { + return nil, nil + } + return &s, nil +} + +func (f *fakeSessionStore) GetByChannel(_ context.Context, platform, channelID string) ([]SessionContext, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []SessionContext + for _, s := range f.sessions { + if s.Source.Platform == platform && s.Source.ChannelID == channelID { + out = append(out, s) + } + } + return out, nil +} + +func (f *fakeSessionStore) Delete(_ context.Context, sessionID string) error { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.sessions, sessionID) + delete(f.messages, sessionID) + return nil +} + +func (f *fakeSessionStore) Touch(_ context.Context, sessionID string) error { + f.mu.Lock() + defer f.mu.Unlock() + s, ok := f.sessions[sessionID] + if !ok { + return nil + } + s.LastActiveAt = time.Now() + f.sessions[sessionID] = s + return nil +} + +func (f *fakeSessionStore) List(_ context.Context) ([]SessionContext, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []SessionContext + for _, s := range f.sessions { + out = append(out, s) + } + return out, nil +} + +func (f *fakeSessionStore) Close() error { return nil } + +func (f *fakeSessionStore) SaveMessage(_ context.Context, sessionID string, msg Message) error { + f.mu.Lock() + defer f.mu.Unlock() + f.messages[sessionID] = append(f.messages[sessionID], msg) + return nil +} + +func (f *fakeSessionStore) RecentMessages(_ context.Context, sessionID string, n int) ([]Message, error) { + f.mu.Lock() + defer f.mu.Unlock() + msgs := f.messages[sessionID] + if len(msgs) == 0 { + return nil, nil + } + start := max(len(msgs)-n, 0) + out := make([]Message, len(msgs)-start) + copy(out, msgs[start:]) + return out, nil +} + +func (f *fakeSessionStore) DeleteRecentMessages(_ context.Context, sessionID string, n int) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + msgs := f.messages[sessionID] + if len(msgs) == 0 { + return 0, nil + } + toDelete := min(n, len(msgs)) + f.messages[sessionID] = msgs[:len(msgs)-toDelete] + return toDelete, nil +} + +func (f *fakeSessionStore) MessageCount(_ context.Context, sessionID string) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.messages[sessionID]), nil +} + +func (f *fakeSessionStore) SaveMessages(_ context.Context, sessionID string, msgs []Message) error { + f.mu.Lock() + defer f.mu.Unlock() + existing := f.messages[sessionID] + out := make([]Message, len(existing)+len(msgs)) + copy(out, existing) + copy(out[len(existing):], msgs) + f.messages[sessionID] = out + return nil +} + +func (f *fakeSessionStore) SearchMessages(_ context.Context, sessionID, query string, limit int) ([]Message, error) { + return nil, nil +} + +// newTestRouter returns a Router with a session store wired for testing. +func newTestRouter(gatewayName string) *Router { + store := newFakeSessionStore() + r := NewRouter(nil, nil, gatewayName) + r.InitSessions(store) + r.Identity = "archie" + return r +} + +// ── /start ───────────────────────────────────────────────────────────────── + +func TestRouteStart(t *testing.T) { + r := newTestRouter("telegram") + reply, err := r.Route(context.Background(), Message{Text: "/start"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Archie is running") { + t.Errorf("reply = %q, want acknowledgement", reply) + } +} + +// ── /new and /reset ──────────────────────────────────────────────────────── + +func TestRouteNewCreatesSession(t *testing.T) { + r := newTestRouter("telegram") + msg := Message{ChannelID: "chat-1", ThreadID: "", From: "alice"} + + reply, err := r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-1"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "New session created") { + t.Errorf("reply = %q, want session creation confirmation", reply) + } + + // Verify session was created. + sessionID := r.sessionTracker.getActive("chat-1", "") + if sessionID == "" { + t.Fatal("expected active session") + } + sc, err := r.sessionTracker.sessions.Get(context.Background(), sessionID) + if err != nil { + t.Fatalf("Get session: %v", err) + } + if sc == nil { + t.Fatal("session not found") + } + _ = msg // used implicitly through channel ID +} + +func TestRouteNewWithTitle(t *testing.T) { + r := newTestRouter("telegram") + + reply, err := r.Route(context.Background(), Message{Text: "/new debugging session", ChannelID: "chat-2"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "debugging session") { + t.Errorf("reply = %q, want title in confirmation", reply) + } + + sessionID := r.sessionTracker.getActive("chat-2", "") + sc, err := r.sessionTracker.sessions.Get(context.Background(), sessionID) + if err != nil { + t.Fatalf("Get session: %v", err) + } + if sc.Title != "debugging session" { + t.Errorf("title = %q, want %q", sc.Title, "debugging session") + } +} + +func TestRouteResetAlias(t *testing.T) { + r := newTestRouter("telegram") + + // /new creates initial session. + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-3"}) + oldSession := r.sessionTracker.getActive("chat-3", "") + if oldSession == "" { + t.Fatal("expected initial session") + } + + // /reset creates a new session. + reply, err := r.Route(context.Background(), Message{Text: "/reset", ChannelID: "chat-3"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "New session created") { + t.Errorf("reply = %q, want session creation", reply) + } + + newSession := r.sessionTracker.getActive("chat-3", "") + if newSession == oldSession { + t.Error("expected new session ID after /reset") + } +} + +func TestRouteNewNotConfigured(t *testing.T) { + r := NewRouter(nil, nil, "telegram") + reply, err := r.Route(context.Background(), Message{Text: "/new"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "not configured") { + t.Errorf("reply = %q, want 'not configured'", reply) + } +} + +// ── /topic ───────────────────────────────────────────────────────────────── + +func TestRouteTopicHelp(t *testing.T) { + r := newTestRouter("telegram") + reply, err := r.Route(context.Background(), Message{Text: "/topic help", ChannelID: "chat-4"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Usage: /topic") { + t.Errorf("reply = %q, want usage info", reply) + } +} + +func TestRouteTopicListSessions(t *testing.T) { + r := newTestRouter("telegram") + + // Create an initial session via /new. + _, _ = r.Route(context.Background(), Message{Text: "/new alpha", ChannelID: "chat-5"}) + _, _ = r.Route(context.Background(), Message{Text: "/new beta", ChannelID: "chat-5", ThreadID: "1"}) + + reply, err := r.Route(context.Background(), Message{Text: "/topic", ChannelID: "chat-5"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "alpha") { + t.Errorf("reply = %q, want alpha session listed", reply) + } + if !strings.Contains(reply, "beta") { + t.Errorf("reply = %q, want beta session listed", reply) + } +} + +func TestRouteTopicSwitch(t *testing.T) { + r := newTestRouter("telegram") + + // Create two sessions. + _, _ = r.Route(context.Background(), Message{Text: "/new first", ChannelID: "chat-6"}) + firstID := r.sessionTracker.getActive("chat-6", "") + + _, _ = r.Route(context.Background(), Message{Text: "/new second", ChannelID: "chat-6"}) + secondID := r.sessionTracker.getActive("chat-6", "") + + // Switch back to first using prefix. + prefix := firstID[:min(8, len(firstID))] + reply, err := r.Route(context.Background(), Message{Text: "/topic " + prefix, ChannelID: "chat-6"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Switched to session") { + t.Errorf("reply = %q, want switch confirmation", reply) + } + + current := r.sessionTracker.getActive("chat-6", "") + if current != firstID { + t.Errorf("active = %s, want %s (firstID=%s, secondID=%s)", current[:8], firstID[:8], firstID[:8], secondID[:8]) + } +} + +func TestRouteTopicUnknown(t *testing.T) { + r := newTestRouter("telegram") + reply, err := r.Route(context.Background(), Message{Text: "/topic nonexist", ChannelID: "chat-7"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "No session found") { + t.Errorf("reply = %q, want 'No session found'", reply) + } +} + +// ── /retry ───────────────────────────────────────────────────────────────── + +func TestRouteRetryNoSession(t *testing.T) { + r := newTestRouter("telegram") + reply, err := r.Route(context.Background(), Message{Text: "/retry", ChannelID: "chat-8"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "No active session") { + t.Errorf("reply = %q, want 'No active session'", reply) + } +} + +func TestRouteRetryRemovesLastMessage(t *testing.T) { + r := newTestRouter("telegram") + + // Set up a session with messages. + sessionID := "test-retry-session" + sc := SessionContext{ + SessionID: sessionID, + Source: SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "chat-9"}, + CreatedAt: time.Now(), LastActiveAt: time.Now(), + } + _ = r.sessionTracker.sessions.Save(context.Background(), sc) + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "alice", Text: "hello"}) + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "archie", Text: "hi there"}) + r.sessionTracker.setActive("chat-9", "", sessionID) + + // Verify initial count. + count, _ := r.sessionTracker.sessions.MessageCount(context.Background(), sessionID) + if count != 2 { + t.Fatalf("initial count = %d, want 2", count) + } + + // Retry. + reply, err := r.Route(context.Background(), Message{Text: "/retry", ChannelID: "chat-9"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + + // When LLM is nil, retry reports LLM not configured but message was removed. + if !strings.Contains(reply, "LLM") && !strings.Contains(reply, "configured") { + t.Errorf("reply = %q, want LLM not configured message", reply) + } + + count, _ = r.sessionTracker.sessions.MessageCount(context.Background(), sessionID) + if count != 1 { + t.Errorf("count after retry = %d, want 1", count) + } +} + +// ── /undo ────────────────────────────────────────────────────────────────── + +func TestRouteUndoRemovesOne(t *testing.T) { + r := newTestRouter("telegram") + + sessionID := "test-undo" + sc := SessionContext{ + SessionID: sessionID, + Source: SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "chat-10"}, + CreatedAt: time.Now(), LastActiveAt: time.Now(), + } + _ = r.sessionTracker.sessions.Save(context.Background(), sc) + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "alice", Text: "msg1"}) + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "archie", Text: "reply1"}) + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "alice", Text: "msg2"}) + r.sessionTracker.setActive("chat-10", "", sessionID) + + reply, err := r.Route(context.Background(), Message{Text: "/undo", ChannelID: "chat-10"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Removed 1 message") { + t.Errorf("reply = %q, want removal confirmation", reply) + } + + count, _ := r.sessionTracker.sessions.MessageCount(context.Background(), sessionID) + if count != 2 { + t.Errorf("count = %d, want 2", count) + } +} + +func TestRouteUndoRemovesMultiple(t *testing.T) { + r := newTestRouter("telegram") + + sessionID := "test-undo-multi" + sc := SessionContext{ + SessionID: sessionID, + Source: SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "chat-11"}, + CreatedAt: time.Now(), LastActiveAt: time.Now(), + } + _ = r.sessionTracker.sessions.Save(context.Background(), sc) + for i := range 5 { + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "alice", Text: fmt.Sprintf("msg%d", i)}) + } + r.sessionTracker.setActive("chat-11", "", sessionID) + + reply, err := r.Route(context.Background(), Message{Text: "/undo 3", ChannelID: "chat-11"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Removed 3 messages") { + t.Errorf("reply = %q, want 'Removed 3 messages'", reply) + } + + count, _ := r.sessionTracker.sessions.MessageCount(context.Background(), sessionID) + if count != 2 { + t.Errorf("count = %d, want 2", count) + } +} + +func TestRouteUndoNoMessages(t *testing.T) { + r := newTestRouter("telegram") + + sessionID := "test-undo-empty" + sc := SessionContext{ + SessionID: sessionID, + Source: SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "chat-12"}, + CreatedAt: time.Now(), LastActiveAt: time.Now(), + } + _ = r.sessionTracker.sessions.Save(context.Background(), sc) + r.sessionTracker.setActive("chat-12", "", sessionID) + + reply, err := r.Route(context.Background(), Message{Text: "/undo", ChannelID: "chat-12"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Nothing to undo") { + t.Errorf("reply = %q, want 'Nothing to undo'", reply) + } +} + +func TestRouteUndoInvalidN(t *testing.T) { + r := newTestRouter("telegram") + + sessionID := "test-undo-invalid" + sc := SessionContext{ + SessionID: sessionID, + Source: SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "chat-13"}, + CreatedAt: time.Now(), LastActiveAt: time.Now(), + } + _ = r.sessionTracker.sessions.Save(context.Background(), sc) + r.sessionTracker.setActive("chat-13", "", sessionID) + + reply, err := r.Route(context.Background(), Message{Text: "/undo notanumber", ChannelID: "chat-13"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Usage: /undo") { + t.Errorf("reply = %q, want usage message", reply) + } +} + +// ── /title ───────────────────────────────────────────────────────────────── + +func TestRouteTitleSet(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-14"}) + sessionID := r.sessionTracker.getActive("chat-14", "") + + reply, err := r.Route(context.Background(), Message{Text: "/title debugging the crash", ChannelID: "chat-14"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Session title set to: debugging the crash") { + t.Errorf("reply = %q, want title confirmation", reply) + } + + sc, _ := r.sessionTracker.sessions.Get(context.Background(), sessionID) + if sc.Title != "debugging the crash" { + t.Errorf("title = %q, want %q", sc.Title, "debugging the crash") + } +} + +func TestRouteTitleShow(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new my topic", ChannelID: "chat-15"}) + + reply, err := r.Route(context.Background(), Message{Text: "/title", ChannelID: "chat-15"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "my topic") { + t.Errorf("reply = %q, want current title", reply) + } +} + +func TestRouteTitleNoTitle(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-16"}) + + reply, err := r.Route(context.Background(), Message{Text: "/title", ChannelID: "chat-16"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "No title set") { + t.Errorf("reply = %q, want 'No title set'", reply) + } +} + +// ── /branch and /fork ────────────────────────────────────────────────────── + +func TestRouteBranchCreatesChildSession(t *testing.T) { + r := newTestRouter("telegram") + + // Create parent with history. + _, _ = r.Route(context.Background(), Message{Text: "/new parent session", ChannelID: "chat-17"}) + parentID := r.sessionTracker.getActive("chat-17", "") + + // Add messages to parent. + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, Message{From: "alice", Text: "hello"}) + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, Message{From: "archie", Text: "hi"}) + + // Branch. + reply, err := r.Route(context.Background(), Message{Text: "/branch experiment", ChannelID: "chat-17"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "experiment") { + t.Errorf("reply = %q, want branch name in confirmation", reply) + } + if !strings.Contains(reply, "inherited messages") { + t.Errorf("reply = %q, want inherited message count", reply) + } + + childID := r.sessionTracker.getActive("chat-17", "") + if childID == parentID { + t.Error("expected new child session to be active") + } + + childSC, _ := r.sessionTracker.sessions.Get(context.Background(), childID) + if childSC.ParentSessionID != parentID { + t.Errorf("parent = %s, want %s", childSC.ParentSessionID, parentID) + } + if childSC.BranchName != "experiment" { + t.Errorf("branch name = %q, want 'experiment'", childSC.BranchName) + } + + // Child should have inherited messages. + count, _ := r.sessionTracker.sessions.MessageCount(context.Background(), childID) + if count != 2 { + t.Errorf("inherited count = %d, want 2", count) + } +} + +func TestRouteForkAlias(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new parent", ChannelID: "chat-18"}) + parentID := r.sessionTracker.getActive("chat-18", "") + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), parentID, Message{From: "alice", Text: "msg"}) + + reply, err := r.Route(context.Background(), Message{Text: "/fork", ChannelID: "chat-18"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Branched session") { + t.Errorf("reply = %q, want branch confirmation from /fork", reply) + } +} + +// ── /compress and /compact ───────────────────────────────────────────────── + +func TestRouteCompressPreview(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-19"}) + sessionID := r.sessionTracker.getActive("chat-19", "") + + // Add a bunch of messages (not enough to trigger compression by default). + for i := range 10 { + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "alice", Text: fmt.Sprintf("message number %d", i)}) + } + + reply, err := r.Route(context.Background(), Message{Text: "/compress --preview", ChannelID: "chat-19"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Compression") { + t.Errorf("reply = %q, want compression info", reply) + } +} + +func TestRouteCompactAlias(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-20"}) + sessionID := r.sessionTracker.getActive("chat-20", "") + + for i := range 5 { + _ = r.sessionTracker.sessions.SaveMessage(context.Background(), sessionID, Message{From: "alice", Text: fmt.Sprintf("msg %d with some content to make it longer than a few chars", i)}) + } + + reply, err := r.Route(context.Background(), Message{Text: "/compact --dry-run", ChannelID: "chat-20"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Compression") { + t.Errorf("reply = %q, want compression info via /compact", reply) + } +} + +func TestRouteCompressNotConfigured(t *testing.T) { + r := NewRouter(nil, nil, "telegram") + reply, err := r.Route(context.Background(), Message{Text: "/compress"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "not configured") { + t.Errorf("reply = %q, want 'not configured'", reply) + } +} + +// ── sessionTracker ───────────────────────────────────────────────────────── + +func TestSessionTrackerResolveCreatesAndReuses(t *testing.T) { + st := newFakeSessionStore() + tr := newSessionTracker(st) + ctx := context.Background() + + // First resolve creates a session. + id1, err := tr.resolve(ctx, "telegram", "archie", "chat-X", "") + if err != nil { + t.Fatalf("resolve: %v", err) + } + if id1 == "" { + t.Fatal("expected session ID") + } + + // Second resolve reuses the same session. + id2, err := tr.resolve(ctx, "telegram", "archie", "chat-X", "") + if err != nil { + t.Fatalf("resolve 2: %v", err) + } + if id2 != id1 { + t.Errorf("expected same session ID, got %s != %s", id2, id1) + } + + // Different thread gets a different session. + id3, err := tr.resolve(ctx, "telegram", "archie", "chat-X", "5") + if err != nil { + t.Fatalf("resolve thread: %v", err) + } + if id3 == id1 { + t.Error("different thread should get a new session") + } +} + +// ── aliases ──────────────────────────────────────────────────────────────── + +func TestRouteResetAndNewAreSame(t *testing.T) { + r := newTestRouter("telegram") + + r1, _ := r.Route(context.Background(), Message{Text: "/new test", ChannelID: "chat-a"}) + r2, _ := r.Route(context.Background(), Message{Text: "/reset test2", ChannelID: "chat-a"}) + + // Both should create a new session clearing previous. + if !strings.Contains(r1, "test") { + t.Errorf("/new reply missing title: %q", r1) + } + if !strings.Contains(r2, "test2") { + t.Errorf("/reset reply missing title: %q", r2) + } +} + +func TestRouteBranchAndForkAreSame(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-b"}) + + r1, _ := r.Route(context.Background(), Message{Text: "/branch", ChannelID: "chat-b"}) + r2, _ := r.Route(context.Background(), Message{Text: "/fork", ChannelID: "chat-b"}) + + if !strings.Contains(r1, "Branched session") { + t.Errorf("/branch reply: %q", r1) + } + if !strings.Contains(r2, "Branched session") { + t.Errorf("/fork reply: %q", r2) + } +} + +func TestRouteCompressAndCompactAreSame(t *testing.T) { + r := newTestRouter("telegram") + + _, _ = r.Route(context.Background(), Message{Text: "/new", ChannelID: "chat-c"}) + + r1, _ := r.Route(context.Background(), Message{Text: "/compress --dry-run", ChannelID: "chat-c"}) + r2, _ := r.Route(context.Background(), Message{Text: "/compact --dry-run", ChannelID: "chat-c"}) + + // Both should show compression info. + if !strings.Contains(r1, "Compression") { + t.Errorf("/compress reply: %q", r1) + } + if !strings.Contains(r2, "Compression") { + t.Errorf("/compact reply: %q", r2) + } +} + +// ── LocalCommands includes all session commands ──────────────────────────── + +func TestLocalCommandsIncludeSessionCommands(t *testing.T) { + cmds := LocalCommands() + cmdSet := make(map[string]bool, len(cmds)) + for _, c := range cmds { + cmdSet[c] = true + } + + required := []string{"/new", "/reset", "/topic", "/retry", "/undo", "/title", "/branch", "/fork", "/compress", "/compact"} + for _, c := range required { + if !cmdSet[c] { + t.Errorf("LocalCommands missing %q", c) + } + } +} diff --git a/internal/gateway/session_store.go b/internal/gateway/session_store.go index e2b75010c..b9fddc835 100644 --- a/internal/gateway/session_store.go +++ b/internal/gateway/session_store.go @@ -47,6 +47,18 @@ type SessionStore interface { // oldest first. Used to build the LLM conversation context. RecentMessages(ctx context.Context, sessionID string, n int) ([]Message, error) + // DeleteRecentMessages removes the last n messages from the + // session's conversation history. Used by /undo and /retry. + // Returns the number of messages actually deleted. + DeleteRecentMessages(ctx context.Context, sessionID string, n int) (deleted int, err error) + + // MessageCount returns the total number of messages stored for + // a session. Used by /compress --preview and /undo. + MessageCount(ctx context.Context, sessionID string) (int, error) + + // SaveMessages bulk-saves messages for branch inheritance. + SaveMessages(ctx context.Context, sessionID string, msgs []Message) error + // SearchMessages returns messages matching query via semantic // vector search (NellDB SearchSimilar). Falls back to substring // match on message text when vector search is unavailable. @@ -198,6 +210,15 @@ func sessionToDoc(sc SessionContext) sdk.Doc { if sc.Source.ThreadID != "" { doc["thread_id"] = sc.Source.ThreadID } + if sc.Title != "" { + doc["title"] = sc.Title + } + if sc.ParentSessionID != "" { + doc["parent_session_id"] = sc.ParentSessionID + } + if sc.BranchName != "" { + doc["branch_name"] = sc.BranchName + } return doc } @@ -210,6 +231,9 @@ func docToSession(doc sdk.Doc) SessionContext { ChannelID: strField(doc, "channel_id"), ThreadID: strField(doc, "thread_id"), }, + Title: strField(doc, "title"), + ParentSessionID: strField(doc, "parent_session_id"), + BranchName: strField(doc, "branch_name"), } if v := strField(doc, "created_at"); v != "" { sc.CreatedAt, _ = time.Parse(time.RFC3339Nano, v) @@ -301,6 +325,66 @@ func (s *nellSessionStore) RecentMessages(ctx context.Context, sessionID string, return out, nil } +func (s *nellSessionStore) DeleteRecentMessages(ctx context.Context, sessionID string, n int) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + prefix := sessionID + ":" + result, err := s.msgDB.AllDocs(ctx, sdk.DocRange{ + StartKey: prefix, + EndKey: prefix + "\xff", + IncludeDocs: false, + }) + if err != nil { + return 0, fmt.Errorf("sessionstore: delete recent messages: %w", err) + } + + toDelete := min(n, len(result.Rows)) + + // Delete the last n rows (newest messages). + for i := len(result.Rows) - toDelete; i < len(result.Rows); i++ { + if _, err := s.msgDB.Remove(ctx, result.Rows[i].ID); err != nil && !errors.Is(err, sdk.ErrNotFound) { + return toDelete, fmt.Errorf("sessionstore: delete message %s: %w", result.Rows[i].ID, err) + } + } + return toDelete, nil +} + +func (s *nellSessionStore) MessageCount(ctx context.Context, sessionID string) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + prefix := sessionID + ":" + result, err := s.msgDB.AllDocs(ctx, sdk.DocRange{ + StartKey: prefix, + EndKey: prefix + "\xff", + IncludeDocs: false, + }) + if err != nil { + return 0, fmt.Errorf("sessionstore: message count: %w", err) + } + return len(result.Rows), nil +} + +func (s *nellSessionStore) SaveMessages(ctx context.Context, sessionID string, msgs []Message) error { + s.mu.Lock() + defer s.mu.Unlock() + for i, msg := range msgs { + doc := sdk.Doc{ + sdk.FieldID: msgKey(sessionID, int64(i)), + "session_id": sessionID, + "seq": int64(i), + "from": msg.From, + "text": msg.Text, + "channel_id": msg.ChannelID, + "thread_id": msg.ThreadID, + "at": time.Now().UTC().Format(time.RFC3339Nano), + } + if _, err := s.msgDB.Put(ctx, doc); err != nil { + return fmt.Errorf("sessionstore: save messages: %w", err) + } + } + return nil +} + func (s *nellSessionStore) SearchMessages(ctx context.Context, sessionID, query string, limit int) ([]Message, error) { // Substring match on recent messages. Vector search via NellDB // SearchSimilar requires an embedding model — deferred to future