Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(slack): two-command channel reads — chat history (overview) + chat thread [id] (MUL-3871) (#4762)

Bohan Jiang3a6d3522c89d
diff --git a/server/cmd/multica/cmd_chat.go b/server/cmd/multica/cmd_chat.go
index 7a30d9d71d..5427857cfc 100644
--- a/server/cmd/multica/cmd_chat.go
+++ b/server/cmd/multica/cmd_chat.go
@@ -19,52 +19,80 @@ var chatCmd = &cobra.Command{
var chatHistoryCmd = &cobra.Command{
Use: "history",
- Short: "Read prior messages from the chat channel this conversation came from",
- Long: `Read the earlier messages of the chat channel (e.g. a Slack thread, channel,
-or DM) that this conversation is connected to.
-
-When you are @mentioned in a Slack thread or channel you only receive the one
-triggering message — not what was said before it. Run this to pull the
-surrounding conversation so you understand the full context.
-
-A conversation has two nested histories: the surrounding CHANNEL and your own
-THREAD within it (your first reply opens a thread on the @mention). By default
-(--scope auto) the server reads the channel on your first reply — where the
-prior context lives — and your thread on follow-ups. Use --scope channel to pull
-the wider channel during a follow-up when the thread alone is not enough, or
---scope thread to force the thread.
-
-It is the SAME command regardless of which channel the conversation came from;
-the server hides the per-platform differences. It reads only the conversation
-you are currently running for — it cannot read any other session or channel.`,
+ Short: "Overview of the channel this conversation is in (messages + thread list)",
+ Long: `Show the overview of the chat channel (e.g. Slack) this conversation is in: the
+recent top-level messages, and for each thread its thread_id, reply_count, and
+latest_reply. It does NOT expand thread contents — it is the table of contents.
+
+To read a specific thread's messages, take a thread_id from here and run
+"multica chat thread <thread_id>".
+
+It is the SAME command regardless of which channel the conversation came from,
+and it reads only the conversation you are currently running for — it cannot
+read any other session or channel.`,
Args: cobra.NoArgs,
RunE: runChatHistory,
}
+var chatThreadCmd = &cobra.Command{
+ Use: "thread [id]",
+ Short: "Read one thread's messages (the current thread, or a specific id)",
+ Long: `Read the messages of a single thread.
+
+With no id, read the thread you are currently in (the one you were @mentioned in).
+With an id — a thread_id from "multica chat history" — read that specific thread.
+Either way the thread is within the channel you are in; you cannot read another
+channel.`,
+ Args: cobra.MaximumNArgs(1),
+ RunE: runChatThread,
+}
+
func init() {
- chatHistoryCmd.Flags().String("scope", "auto", "Which history to read: auto, thread, or channel")
- chatHistoryCmd.Flags().Int("limit", 0, "Maximum number of messages to return (the server clamps the range)")
- chatHistoryCmd.Flags().String("before", "", "Opaque cursor (a next_cursor from a prior page) to read older messages")
- chatHistoryCmd.Flags().String("output", "json", "Output format: table or json")
+ for _, c := range []*cobra.Command{chatHistoryCmd, chatThreadCmd} {
+ c.Flags().Int("limit", 0, "Maximum number of messages to return (the server clamps the range)")
+ c.Flags().String("before", "", "Opaque cursor (a next_cursor from a prior page) to read older messages")
+ c.Flags().String("output", "json", "Output format: table or json")
+ }
chatCmd.AddCommand(chatHistoryCmd)
+ chatCmd.AddCommand(chatThreadCmd)
}
func runChatHistory(cmd *cobra.Command, _ []string) error {
- client, err := newAPIClient(cmd)
+ resp, err := fetchChatRead(cmd, "/api/chat/history", "")
if err != nil {
return err
}
+ return renderChatRead(cmd, resp, true)
+}
+
+func runChatThread(cmd *cobra.Command, args []string) error {
+ threadID := ""
+ if len(args) == 1 {
+ threadID = args[0]
+ }
+ resp, err := fetchChatRead(cmd, "/api/chat/thread", threadID)
+ if err != nil {
+ return err
+ }
+ return renderChatRead(cmd, resp, false)
+}
+// fetchChatRead builds the request (shared --limit/--before paging, plus the
+// optional thread id) and decodes the response.
+func fetchChatRead(cmd *cobra.Command, basePath, threadID string) (map[string]any, error) {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return nil, err
+ }
ctx, cancel := cli.APIContext(context.Background())
defer cancel()
- scope, _ := cmd.Flags().GetString("scope")
limit, _ := cmd.Flags().GetInt("limit")
before, _ := cmd.Flags().GetString("before")
q := url.Values{}
- if scope != "" && scope != "auto" {
- q.Set("scope", scope)
+ if threadID != "" {
+ q.Set("id", threadID)
}
if limit > 0 {
q.Set("limit", strconv.Itoa(limit))
@@ -72,38 +100,56 @@ func runChatHistory(cmd *cobra.Command, _ []string) error {
if before != "" {
q.Set("before", before)
}
- path := "/api/chat/history"
+ path := basePath
if encoded := q.Encode(); encoded != "" {
path += "?" + encoded
}
var resp map[string]any
if err := client.GetJSON(ctx, path, &resp); err != nil {
- return fmt.Errorf("read chat history: %w", err)
+ return nil, fmt.Errorf("read chat: %w", err)
}
+ return resp, nil
+}
+// renderChatRead prints the response as JSON (default) or a table. The overview
+// table adds the thread columns so the agent can pick a thread_id to drill into.
+func renderChatRead(cmd *cobra.Command, resp map[string]any, overview bool) error {
output, _ := cmd.Flags().GetString("output")
- if output == "table" {
- if note := strVal(resp, "note"); note != "" {
- fmt.Fprintln(os.Stdout, note)
- return nil
- }
- if s := strVal(resp, "scope"); s != "" {
- fmt.Fprintf(os.Stdout, "scope: %s\n", s)
+ if output != "table" {
+ return cli.PrintJSON(os.Stdout, resp)
+ }
+ if note := strVal(resp, "note"); note != "" {
+ fmt.Fprintln(os.Stdout, note)
+ return nil
+ }
+ msgs, _ := resp["messages"].([]any)
+ var headers []string
+ if overview {
+ headers = []string{"TS", "ROLE", "AUTHOR", "THREAD_ID", "REPLIES", "TEXT"}
+ } else {
+ headers = []string{"TS", "ROLE", "AUTHOR", "TEXT"}
+ }
+ rows := make([][]string, 0, len(msgs))
+ for _, mi := range msgs {
+ m, ok := mi.(map[string]any)
+ if !ok {
+ continue
}
- msgs, _ := resp["messages"].([]any)
- headers := []string{"TS", "ROLE", "AUTHOR", "TEXT"}
- rows := make([][]string, 0, len(msgs))
- for _, mi := range msgs {
- m, ok := mi.(map[string]any)
- if !ok {
- continue
- }
+ if overview {
+ rows = append(rows, []string{strVal(m, "ts"), strVal(m, "role"), strVal(m, "author"), strVal(m, "thread_id"), numVal(m, "reply_count"), strVal(m, "text")})
+ } else {
rows = append(rows, []string{strVal(m, "ts"), strVal(m, "role"), strVal(m, "author"), strVal(m, "text")})
}
- cli.PrintTable(os.Stdout, headers, rows)
- return nil
}
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+}
- return cli.PrintJSON(os.Stdout, resp)
+// numVal renders a numeric JSON field as a string, blank when zero/absent.
+func numVal(m map[string]any, key string) string {
+ if v, ok := m[key].(float64); ok && v != 0 {
+ return strconv.Itoa(int(v))
+ }
+ return ""
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9cc67c0079..b6c06b3aa4 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1144,12 +1144,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
r.Get("/api/chat/pending-tasks", h.ListPendingChatTasks)
- // Agent-facing unified history read: `multica chat history` resolves
- // the caller's task-scoped token to its own chat session and returns
- // the bound channel's prior messages (MUL-3871). No session id is
- // passed — the token IS the scope, so an agent can only read its own
- // conversation.
+ // Agent-facing channel reads (MUL-3871). The caller's task-scoped token
+ // resolves to its own chat session; no session/channel id is passed, so
+ // an agent can only read its own conversation. `history` is the channel
+ // overview (top-level messages + thread metadata); `thread` reads one
+ // thread (?id for a specific one, else the thread the session is in).
r.Get("/api/chat/history", h.GetChatChannelHistory)
+ r.Get("/api/chat/thread", h.GetChatThread)
// Inbox
r.Route("/api/inbox", func(r chi.Router) {
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 4fcf564286..cee8d5a530 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -193,12 +193,20 @@ func buildChatPrompt(task Task) string {
// Channel awareness (MUL-3871). When the session is backed by an IM channel,
// the agent must KNOW it is operating inside that channel — otherwise an ask
// like "what did you just talk about" sends it to read Multica instead of the
- // Slack conversation. State it explicitly and point history reads at the
- // channel, not Multica. A web-only chat session gets no such line — its
- // history is the Multica chat_session the agent already resumes.
+ // Slack conversation. State it explicitly, point reads at the channel (not
+ // Multica), and teach the two read commands, telling the agent which to start
+ // with based on where it was @mentioned. A web-only chat session gets no such
+ // block — its history is the Multica chat_session the agent already resumes.
if task.ChatChannelType != "" {
platform := channelDisplayName(task.ChatChannelType)
- fmt.Fprintf(&b, "You are operating inside a %s conversation (a channel, thread, or DM) — not the Multica web app. This conversation and its history live in %s, NOT in Multica. When the user asks about earlier messages, what was discussed, or who said what here, read it with `multica chat history --output json`; do NOT look in Multica issues or comments for this conversation's history. The message below may be only what triggered you — `multica chat history` auto-selects the right scope (the surrounding channel on your first reply, your own thread on follow-ups; add `--scope channel` to pull the wider channel when needed).\n\n", platform, platform)
+ fmt.Fprintf(&b, "You are operating inside a %s conversation — not the Multica web app. This conversation and its history live in %s, NOT in Multica; never look in Multica issues or comments for it. The message below may be only what triggered you. Read the conversation with:\n", platform, platform)
+ b.WriteString("- `multica chat history --output json` — the channel overview: recent top-level messages, each thread tagged with a `thread_id` and `reply_count`. It does NOT expand thread contents.\n")
+ b.WriteString("- `multica chat thread [<thread_id>] --output json` — read one thread's messages; omit the id to read the thread you are in, or pass a `thread_id` from the overview to read a specific thread.\n")
+ if task.ChatInThread {
+ b.WriteString("You were @mentioned inside a thread: start with `multica chat thread` to read it; if you need the wider channel, run `multica chat history` and open a specific thread with `multica chat thread <thread_id>`.\n\n")
+ } else {
+ b.WriteString("You were @mentioned at the channel top level: start with `multica chat history` to see the channel, then read a specific thread's contents with `multica chat thread <thread_id>`.\n\n")
+ }
}
if task.Agent != nil && len(task.Agent.Skills) > 0 {
refs := ExtractSlashSkills(task.ChatMessage)
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index 11bbf09303..86a19262c3 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -271,19 +271,33 @@ func TestBuildChatPromptAttachmentIDsCanBeBoundToCreatedIssues(t *testing.T) {
}
func TestBuildChatPromptChannelAwareness(t *testing.T) {
- t.Run("slack-backed session tells the agent it is in slack", func(t *testing.T) {
+ t.Run("slack-backed prompt teaches both read commands", func(t *testing.T) {
out := buildChatPrompt(Task{
ChatSessionID: "sess-1",
ChatChannelType: "slack",
ChatMessage: "你刚刚和 xxx 聊了什么",
})
- for _, want := range []string{"Slack", "multica chat history", "NOT in Multica"} {
+ for _, want := range []string{"Slack", "NOT in Multica", "multica chat history", "multica chat thread"} {
if !strings.Contains(out, want) {
t.Fatalf("slack-backed prompt missing %q\n--- output ---\n%s", want, out)
}
}
})
+ t.Run("top-level mention starts with history", func(t *testing.T) {
+ out := buildChatPrompt(Task{ChatSessionID: "s", ChatChannelType: "slack", ChatInThread: false, ChatMessage: "hi"})
+ if !strings.Contains(out, "top level: start with `multica chat history`") {
+ t.Fatalf("expected top-level guidance, got:\n%s", out)
+ }
+ })
+
+ t.Run("in-thread mention starts with thread", func(t *testing.T) {
+ out := buildChatPrompt(Task{ChatSessionID: "s", ChatChannelType: "slack", ChatInThread: true, ChatMessage: "hi"})
+ if !strings.Contains(out, "inside a thread: start with `multica chat thread`") {
+ t.Fatalf("expected in-thread guidance, got:\n%s", out)
+ }
+ })
+
t.Run("web-only session has no channel block", func(t *testing.T) {
out := buildChatPrompt(Task{
ChatSessionID: "sess-1",
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 9c1b86567c..5fd309d8b8 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -69,6 +69,7 @@ type Task struct {
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Drives the channel-awareness block in the prompt
+ ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; selects which read command the prompt tells the agent to start with
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments linked to the chat message; agent uses these to `multica attachment download <id>`
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot run_only tasks
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index f362385ee6..d31b55de20 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -278,6 +278,7 @@ type AgentTaskResponse struct {
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)
+ ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks
diff --git a/server/internal/handler/chat_history.go b/server/internal/handler/chat_history.go
index 1b0d63d1e5..c575d12478 100644
--- a/server/internal/handler/chat_history.go
+++ b/server/internal/handler/chat_history.go
@@ -17,156 +17,149 @@ import (
// ChatChannelHistoryReader reads a chat session's bound IM-channel history. The
// Slack reader (slack.History) satisfies it; a future platform registers its
-// own. Defined here as a narrow interface so the handler stays testable and so
-// the channel-agnostic contract — one shape regardless of platform — is enforced
-// at the boundary (MUL-3871).
+// own. Two operations back the two agent commands: ChannelOverview is the
+// channel table-of-contents (`multica chat history`), Thread reads one thread's
+// messages (`multica chat thread [id]`). Both are scoped server-side to the
+// session's own channel (MUL-3871).
type ChatChannelHistoryReader interface {
- Fetch(ctx context.Context, chatSessionID pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error)
+ ChannelOverview(ctx context.Context, chatSessionID pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error)
+ Thread(ctx context.Context, chatSessionID pgtype.UUID, threadID string, opts channel.HistoryOptions) (channel.HistoryPage, error)
}
-// ChatChannelHistoryResponse is the unified `multica chat history` payload. It
-// is the SAME shape no matter which channel backs the session — the agent never
-// sees a per-platform API.
+// ChatChannelHistoryResponse is the unified payload for both commands — the SAME
+// shape no matter which channel backs the session, the agent never sees a
+// per-platform API.
type ChatChannelHistoryResponse struct {
- ChannelType string `json:"channel_type"`
- Scope channel.HistoryScope `json:"scope,omitempty"`
- Messages []channel.HistoryMessage `json:"messages"`
- NextCursor string `json:"next_cursor,omitempty"`
- // Note carries a human-readable explanation when there is no history to
- // read (e.g. the session is not connected to a chat channel), so the agent
- // gets a clear answer instead of a bare empty list.
+ ChannelType string `json:"channel_type"`
+ // ThreadID is set on a thread read: which thread the messages belong to.
+ ThreadID string `json:"thread_id,omitempty"`
+ Messages []channel.HistoryMessage `json:"messages"`
+ NextCursor string `json:"next_cursor,omitempty"`
+ // Note explains an empty result (e.g. the session is not channel-backed), so
+ // the agent gets a clear answer instead of a bare empty list.
Note string `json:"note,omitempty"`
}
-// GetChatChannelHistory serves the agent-facing `multica chat history` command.
-// It is authorized by the task-scoped token alone: middleware stamps the token's
-// task into X-Task-ID (the client cannot forge it), and the endpoint reads the
-// history of THAT task's chat session — so an agent can only ever read the
-// conversation it is currently running for, never an arbitrary session/channel.
+// GetChatChannelHistory serves `multica chat history` — the channel overview:
+// recent top-level messages, each thread tagged with its id + reply count (no
+// thread contents). The agent drills into a thread with `multica chat thread`.
func (h *Handler) GetChatChannelHistory(w http.ResponseWriter, r *http.Request) {
- // X-Actor-Source is server-set only: the Auth middleware deletes any
- // client-supplied value and re-stamps "task_token" ONLY on the mat_ task
- // token branch (along with the authoritative X-Task-ID). A normal JWT / mul_
- // PAT request leaves it empty and does NOT strip a client-forged X-Task-ID,
- // so this gate is load-bearing: without it a member could forge X-Task-ID and
- // read another session's channel history. Require the task-token actor here,
- // THEN trust X-Task-ID.
+ sessionID, ok := h.chatHistorySession(w, r)
+ if !ok {
+ return
+ }
+ if h.SlackHistory == nil {
+ h.writeNoChannelIntegration(w)
+ return
+ }
+ page, err := h.SlackHistory.ChannelOverview(r.Context(), sessionID, historyOptionsFrom(r))
+ h.respondChatHistory(w, r, sessionID, page, err)
+}
+
+// GetChatThread serves `multica chat thread [id]` — one thread's messages. With
+// ?id it reads that specific thread; without, the thread the session is in. The
+// channel stays server-pinned to the session, so the id is only a within-channel
+// locator.
+func (h *Handler) GetChatThread(w http.ResponseWriter, r *http.Request) {
+ sessionID, ok := h.chatHistorySession(w, r)
+ if !ok {
+ return
+ }
+ if h.SlackHistory == nil {
+ h.writeNoChannelIntegration(w)
+ return
+ }
+ threadID := r.URL.Query().Get("id")
+ page, err := h.SlackHistory.Thread(r.Context(), sessionID, threadID, historyOptionsFrom(r))
+ h.respondChatHistory(w, r, sessionID, page, err)
+}
+
+// chatHistorySession authorizes the request and returns the caller's own chat
+// session. It is authorized by the task-scoped token alone: middleware stamps
+// the token's task into X-Actor-Source=task_token + X-Task-ID (a normal JWT /
+// mul_ PAT leaves X-Actor-Source empty and does NOT strip a client-forged
+// X-Task-ID), so requiring the task-token actor is load-bearing — without it a
+// member could forge X-Task-ID and read another session's history.
+func (h *Handler) chatHistorySession(w http.ResponseWriter, r *http.Request) (pgtype.UUID, bool) {
if r.Header.Get("X-Actor-Source") != "task_token" {
writeError(w, http.StatusForbidden, "chat history is only available from within an agent task")
- return
+ return pgtype.UUID{}, false
}
taskIDHeader := r.Header.Get("X-Task-ID")
if taskIDHeader == "" {
writeError(w, http.StatusBadRequest, "missing task context")
- return
+ return pgtype.UUID{}, false
}
taskUUID, err := util.ParseUUID(taskIDHeader)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid task id")
- return
+ return pgtype.UUID{}, false
}
task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)
if err != nil {
writeError(w, http.StatusNotFound, "task not found")
- return
+ return pgtype.UUID{}, false
}
if !task.ChatSessionID.Valid {
writeError(w, http.StatusBadRequest, "this task is not a chat task")
- return
+ return pgtype.UUID{}, false
}
// Defense in depth: load the session and confirm it lives in the token's
// stamped workspace. The token→task binding already guarantees the agent can
- // only reach its own task here; this makes a future wiring regression fail
- // closed instead of leaking another workspace's conversation.
+ // only reach its own task; this makes a future wiring regression fail closed.
session, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID)
if err != nil {
writeError(w, http.StatusNotFound, "chat session not found")
- return
+ return pgtype.UUID{}, false
}
if ws := ctxWorkspaceID(r.Context()); ws != "" && uuidToString(session.WorkspaceID) != ws {
writeError(w, http.StatusForbidden, "chat session does not belong to this workspace")
- return
- }
-
- scope := parseHistoryScope(r.URL.Query().Get("scope"))
- if scope == channel.HistoryScopeAuto {
- // First turn — the bot has not replied yet, so no thread exists — reads
- // the surrounding channel (where the prior context lives). A follow-up
- // reads the agent's own thread. The agent can override with
- // ?scope=channel|thread.
- if h.chatSessionHasBotReply(r.Context(), task.ChatSessionID) {
- scope = channel.HistoryScopeThread
- } else {
- scope = channel.HistoryScopeChannel
- }
- }
- opts := channel.HistoryOptions{
- Scope: scope,
- Limit: parseHistoryLimit(r.URL.Query().Get("limit")),
- Before: r.URL.Query().Get("before"),
- }
-
- empty := ChatChannelHistoryResponse{Messages: []channel.HistoryMessage{}}
- if h.SlackHistory == nil {
- empty.Note = "No chat channel integration is configured on this server."
- writeJSON(w, http.StatusOK, empty)
- return
+ return pgtype.UUID{}, false
}
+ return task.ChatSessionID, true
+}
- page, err := h.SlackHistory.Fetch(r.Context(), task.ChatSessionID, opts)
+// respondChatHistory writes the shared response: a note (200) when the session
+// is not channel-backed, a 502 on a real read failure, the page otherwise.
+func (h *Handler) respondChatHistory(w http.ResponseWriter, r *http.Request, sessionID pgtype.UUID, page channel.HistoryPage, err error) {
if err != nil {
if errors.Is(err, slack.ErrNoSlackSession) {
- empty.Note = "This conversation is not connected to a chat channel, so there is no prior channel history to read."
- writeJSON(w, http.StatusOK, empty)
+ writeJSON(w, http.StatusOK, ChatChannelHistoryResponse{
+ Messages: []channel.HistoryMessage{},
+ Note: "This conversation is not connected to a chat channel, so there is no channel history to read.",
+ })
return
}
- slog.Error("chat channel history fetch failed", append(logger.RequestAttrs(r),
- "error", err, "chat_session_id", uuidToString(task.ChatSessionID))...)
+ slog.Error("chat channel history read failed", append(logger.RequestAttrs(r),
+ "error", err, "chat_session_id", uuidToString(sessionID))...)
writeError(w, http.StatusBadGateway, "failed to read channel history")
return
}
-
messages := page.Messages
if messages == nil {
messages = []channel.HistoryMessage{}
}
writeJSON(w, http.StatusOK, ChatChannelHistoryResponse{
ChannelType: page.ChannelType,
- Scope: page.Scope,
+ ThreadID: page.ThreadID,
Messages: messages,
NextCursor: page.NextCursor,
})
}
-// parseHistoryScope maps the ?scope query value to a HistoryScope, defaulting to
-// auto for empty / unknown values.
-func parseHistoryScope(raw string) channel.HistoryScope {
- switch channel.HistoryScope(raw) {
- case channel.HistoryScopeThread:
- return channel.HistoryScopeThread
- case channel.HistoryScopeChannel:
- return channel.HistoryScopeChannel
- default:
- return channel.HistoryScopeAuto
- }
+func (h *Handler) writeNoChannelIntegration(w http.ResponseWriter) {
+ writeJSON(w, http.StatusOK, ChatChannelHistoryResponse{
+ Messages: []channel.HistoryMessage{},
+ Note: "No chat channel integration is configured on this server.",
+ })
}
-// chatSessionHasBotReply reports whether the bot has already replied in this
-// session — i.e. this is a follow-up, not the first turn. On Slack the bot's
-// first reply opens the thread, so an existing assistant message is the signal
-// that a thread worth reading exists. Best-effort: a query error defaults to
-// false (treat as first turn → channel), the safe, context-rich choice.
-func (h *Handler) chatSessionHasBotReply(ctx context.Context, sessionID pgtype.UUID) bool {
- msgs, err := h.Queries.ListChatMessages(ctx, sessionID)
- if err != nil {
- return false
- }
- for _, m := range msgs {
- if m.Role == "assistant" {
- return true
- }
+// historyOptionsFrom reads the shared ?limit / ?before paging params.
+func historyOptionsFrom(r *http.Request) channel.HistoryOptions {
+ return channel.HistoryOptions{
+ Limit: parseHistoryLimit(r.URL.Query().Get("limit")),
+ Before: r.URL.Query().Get("before"),
}
- return false
}
// parseHistoryLimit reads the ?limit query param, ignoring junk (the reader
diff --git a/server/internal/handler/chat_history_test.go b/server/internal/handler/chat_history_test.go
index 0e2f43e036..b525849a82 100644
--- a/server/internal/handler/chat_history_test.go
+++ b/server/internal/handler/chat_history_test.go
@@ -14,30 +14,41 @@ import (
)
type fakeChatHistoryReader struct {
- page channel.HistoryPage
- err error
- gotSession pgtype.UUID
- gotOpts channel.HistoryOptions
+ page channel.HistoryPage
+ err error
+ overviewCalls int
+ threadCalls int
+ gotSession pgtype.UUID
+ gotThreadID string
+ gotOpts channel.HistoryOptions
}
-func (f *fakeChatHistoryReader) Fetch(_ context.Context, sid pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error) {
+func (f *fakeChatHistoryReader) ChannelOverview(_ context.Context, sid pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error) {
+ f.overviewCalls++
f.gotSession = sid
f.gotOpts = opts
return f.page, f.err
}
+func (f *fakeChatHistoryReader) Thread(_ context.Context, sid pgtype.UUID, threadID string, opts channel.HistoryOptions) (channel.HistoryPage, error) {
+ f.threadCalls++
+ f.gotSession = sid
+ f.gotThreadID = threadID
+ f.gotOpts = opts
+ return f.page, f.err
+}
+
// newChatHistoryTask inserts a chat task bound to a fresh chat session and
-// returns the task id and (for chat tasks) the session id. With
-// chatSession=false it inserts a non-chat task and an empty session id.
-func newChatHistoryTask(t *testing.T, chatSession bool) (taskID, sessionID string) {
+// returns the task id. With chatSession=false it inserts a non-chat task.
+func newChatHistoryTask(t *testing.T, chatSession bool) string {
t.Helper()
agentID := createHandlerTestAgent(t, "ChatHistoryAgent", []byte("[]"))
runtimeID := handlerTestRuntimeID(t)
var sessionArg any
if chatSession {
- sessionID = createHandlerTestChatSession(t, agentID)
- sessionArg = sessionID
+ sessionArg = createHandlerTestChatSession(t, agentID)
}
+ var taskID string
if err := testPool.QueryRow(context.Background(), `
INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id)
VALUES ($1, $2, 'completed', 0, $3)
@@ -48,26 +59,14 @@ func newChatHistoryTask(t *testing.T, chatSession bool) (taskID, sessionID strin
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
})
- return taskID, sessionID
+ return taskID
}
-// addAssistantMessage records a prior bot reply in the session, so the endpoint
-// classifies the next read as a follow-up. The chat_session cleanup cascades to
-// chat_message, so no separate cleanup is needed.
-func addAssistantMessage(t *testing.T, sessionID string) {
- t.Helper()
- if _, err := testPool.Exec(context.Background(),
- `INSERT INTO chat_message (chat_session_id, role, content) VALUES ($1, 'assistant', 'prior reply')`,
- sessionID); err != nil {
- t.Fatalf("insert assistant message: %v", err)
- }
-}
-
-// taskActorRequest builds a /api/chat/history request as the Auth middleware
-// would leave it for a mat_ task token: the server-set X-Actor-Source=task_token
-// plus the authoritative X-Task-ID.
-func taskActorRequest(taskID string) *http.Request {
- req := newRequest("GET", "/api/chat/history", nil)
+// taskActorReq builds a request as the Auth middleware would leave it for a mat_
+// task token: the server-set X-Actor-Source=task_token + the authoritative
+// X-Task-ID. target may carry query params (e.g. "?id=70.0").
+func taskActorReq(target, taskID string) *http.Request {
+ req := newRequest("GET", target, nil)
req.Header.Set("X-Actor-Source", "task_token")
req.Header.Set("X-Task-ID", taskID)
return req
@@ -84,21 +83,19 @@ func TestGetChatChannelHistory_Success(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
- taskID, _ := newChatHistoryTask(t, true)
+ taskID := newChatHistoryTask(t, true)
fake := &fakeChatHistoryReader{page: channel.HistoryPage{
ChannelType: "slack",
Messages: []channel.HistoryMessage{
- {ID: "100", Author: "Alice", Role: channel.HistoryRoleUser, Text: "alert", TS: "100"},
- {ID: "101", Author: "Bot", Role: channel.HistoryRoleAssistant, Text: "on it", TS: "101"},
+ {ID: "100", Author: "Alice", Role: channel.HistoryRoleUser, Text: "deploy thread", TS: "100", ThreadID: "100", ReplyCount: 3},
+ {ID: "101", Author: "Bob", Role: channel.HistoryRoleUser, Text: "fyi", TS: "101"},
},
NextCursor: "100",
}}
withSlackHistory(t, fake)
- req := taskActorRequest(taskID)
- req.URL.RawQuery = "limit=10"
w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, req)
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history?limit=10", taskID))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
@@ -110,20 +107,64 @@ func TestGetChatChannelHistory_Success(t *testing.T) {
if resp.ChannelType != "slack" || len(resp.Messages) != 2 || resp.NextCursor != "100" {
t.Fatalf("unexpected response: %+v", resp)
}
- if !fake.gotSession.Valid {
- t.Errorf("reader was not called with a session id")
+ if resp.Messages[0].ThreadID != "100" || resp.Messages[0].ReplyCount != 3 {
+ t.Errorf("overview did not carry thread metadata: %+v", resp.Messages[0])
+ }
+ if fake.overviewCalls != 1 || fake.threadCalls != 0 {
+ t.Errorf("expected ChannelOverview, got overview=%d thread=%d", fake.overviewCalls, fake.threadCalls)
+ }
+}
+
+func TestGetChatThread_CurrentThread(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ taskID := newChatHistoryTask(t, true)
+ fake := &fakeChatHistoryReader{page: channel.HistoryPage{ChannelType: "slack", ThreadID: "50.0", Messages: []channel.HistoryMessage{{ID: "50.0", TS: "50.0", Text: "root"}}}}
+ withSlackHistory(t, fake)
+
+ w := httptest.NewRecorder()
+ testHandler.GetChatThread(w, taskActorReq("/api/chat/thread", taskID))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ if fake.threadCalls != 1 || fake.overviewCalls != 0 {
+ t.Errorf("expected Thread, got overview=%d thread=%d", fake.overviewCalls, fake.threadCalls)
+ }
+ if fake.gotThreadID != "" {
+ t.Errorf("current-thread read should pass empty id, got %q", fake.gotThreadID)
+ }
+}
+
+func TestGetChatThread_ByID(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ taskID := newChatHistoryTask(t, true)
+ fake := &fakeChatHistoryReader{page: channel.HistoryPage{ChannelType: "slack", ThreadID: "70.0"}}
+ withSlackHistory(t, fake)
+
+ w := httptest.NewRecorder()
+ testHandler.GetChatThread(w, taskActorReq("/api/chat/thread?id=70.0", taskID))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ if fake.gotThreadID != "70.0" {
+ t.Errorf("thread id passed to reader = %q, want 70.0", fake.gotThreadID)
}
}
-func TestGetChatChannelHistory_NoBindingReturnsNote(t *testing.T) {
+func TestGetChatHistory_NoBindingReturnsNote(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
- taskID, _ := newChatHistoryTask(t, true)
+ taskID := newChatHistoryTask(t, true)
withSlackHistory(t, &fakeChatHistoryReader{err: slack.ErrNoSlackSession})
w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, taskActorRequest(taskID))
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", taskID))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
@@ -135,15 +176,15 @@ func TestGetChatChannelHistory_NoBindingReturnsNote(t *testing.T) {
}
}
-func TestGetChatChannelHistory_NilReaderReturnsNote(t *testing.T) {
+func TestGetChatHistory_NilReaderReturnsNote(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
- taskID, _ := newChatHistoryTask(t, true)
+ taskID := newChatHistoryTask(t, true)
withSlackHistory(t, nil)
w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, taskActorRequest(taskID))
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", taskID))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
@@ -155,16 +196,15 @@ func TestGetChatChannelHistory_NilReaderReturnsNote(t *testing.T) {
}
}
-// TestGetChatChannelHistory_RejectsForgedTaskID is the security regression test
-// for Niko's must-fix: a normal request (no server-set X-Actor-Source) that
-// forges X-Task-ID — exactly what a workspace member could do with a JWT / mul_
-// PAT, since the Auth middleware does NOT strip a client-sent X-Task-ID — must be
-// rejected, never served another session's history.
-func TestGetChatChannelHistory_RejectsForgedTaskID(t *testing.T) {
+// TestGetChatHistory_RejectsForgedTaskID: a normal request (no server-set
+// X-Actor-Source) that forges X-Task-ID — what a member could do with a JWT /
+// mul_ PAT, since the Auth middleware does NOT strip a client-sent X-Task-ID —
+// must be rejected, never served another session's history.
+func TestGetChatHistory_RejectsForgedTaskID(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
- taskID, _ := newChatHistoryTask(t, true)
+ taskID := newChatHistoryTask(t, true)
fake := &fakeChatHistoryReader{page: channel.HistoryPage{ChannelType: "slack"}}
withSlackHistory(t, fake)
@@ -176,17 +216,16 @@ func TestGetChatChannelHistory_RejectsForgedTaskID(t *testing.T) {
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403", w.Code)
}
- if fake.gotSession.Valid {
+ if fake.overviewCalls != 0 || fake.threadCalls != 0 {
t.Fatalf("reader must not be called for a forged X-Task-ID")
}
}
-func TestGetChatChannelHistory_MissingTaskHeader(t *testing.T) {
+func TestGetChatHistory_MissingTaskHeader(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
- // Task-token actor source but no X-Task-ID: a defensive 400 (the mat_ branch
- // always stamps both, so this should not happen in practice).
+ // Task-token actor source but no X-Task-ID: a defensive 400.
req := newRequest("GET", "/api/chat/history", nil)
req.Header.Set("X-Actor-Source", "task_token")
w := httptest.NewRecorder()
@@ -196,80 +235,16 @@ func TestGetChatChannelHistory_MissingTaskHeader(t *testing.T) {
}
}
-func TestGetChatChannelHistory_NonChatTask(t *testing.T) {
+func TestGetChatHistory_NonChatTask(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
- taskID, _ := newChatHistoryTask(t, false) // task with no chat_session_id
+ taskID := newChatHistoryTask(t, false) // task with no chat_session_id
withSlackHistory(t, &fakeChatHistoryReader{})
w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, taskActorRequest(taskID))
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", taskID))
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())
}
}
-
-// TestGetChatChannelHistory_AutoFirstTurnReadsChannel: with no prior bot reply,
-// scope=auto resolves to channel (the surrounding context before the thread).
-func TestGetChatChannelHistory_AutoFirstTurnReadsChannel(t *testing.T) {
- if testHandler == nil {
- t.Skip("requires test database")
- }
- taskID, _ := newChatHistoryTask(t, true) // no assistant message => first turn
- fake := &fakeChatHistoryReader{page: channel.HistoryPage{ChannelType: "slack", Scope: channel.HistoryScopeChannel}}
- withSlackHistory(t, fake)
-
- w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, taskActorRequest(taskID)) // no ?scope => auto
- if w.Code != http.StatusOK {
- t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
- }
- if fake.gotOpts.Scope != channel.HistoryScopeChannel {
- t.Fatalf("auto first-turn scope = %q, want channel", fake.gotOpts.Scope)
- }
-}
-
-// TestGetChatChannelHistory_AutoFollowUpReadsThread: once the bot has replied,
-// scope=auto resolves to thread.
-func TestGetChatChannelHistory_AutoFollowUpReadsThread(t *testing.T) {
- if testHandler == nil {
- t.Skip("requires test database")
- }
- taskID, sessionID := newChatHistoryTask(t, true)
- addAssistantMessage(t, sessionID) // bot already replied => follow-up
- fake := &fakeChatHistoryReader{page: channel.HistoryPage{ChannelType: "slack", Scope: channel.HistoryScopeThread}}
- withSlackHistory(t, fake)
-
- w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, taskActorRequest(taskID))
- if w.Code != http.StatusOK {
- t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
- }
- if fake.gotOpts.Scope != channel.HistoryScopeThread {
- t.Fatalf("auto follow-up scope = %q, want thread", fake.gotOpts.Scope)
- }
-}
-
-// TestGetChatChannelHistory_ExplicitChannelScope: ?scope=channel overrides the
-// auto default even on a follow-up.
-func TestGetChatChannelHistory_ExplicitChannelScope(t *testing.T) {
- if testHandler == nil {
- t.Skip("requires test database")
- }
- taskID, sessionID := newChatHistoryTask(t, true)
- addAssistantMessage(t, sessionID) // follow-up, but explicit override below
- fake := &fakeChatHistoryReader{page: channel.HistoryPage{ChannelType: "slack", Scope: channel.HistoryScopeChannel}}
- withSlackHistory(t, fake)
-
- req := taskActorRequest(taskID)
- req.URL.RawQuery = "scope=channel"
- w := httptest.NewRecorder()
- testHandler.GetChatChannelHistory(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
- }
- if fake.gotOpts.Scope != channel.HistoryScopeChannel {
- t.Fatalf("explicit scope = %q, want channel", fake.gotOpts.Scope)
- }
-}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index e2537030ba..78c664c4ce 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1597,13 +1597,19 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp.ThreadName = cs.Title
// Flag a channel-backed session so the daemon makes the agent aware
// it is operating inside Slack — read this conversation's history
- // from the channel via `multica chat history`, not from Multica
- // (MUL-3871). Empty for a web-only chat session.
- if _, berr := h.Queries.GetChannelChatSessionBindingBySession(r.Context(), db.GetChannelChatSessionBindingBySessionParams{
+ // from the channel via `multica chat history` / `multica chat thread`,
+ // not from Multica (MUL-3871). Empty for a web-only chat session.
+ // ChatInThread tells the agent which command to start with: the
+ // latest trigger was a thread reply iff its reply-target thread
+ // (last_thread_id) differs from its own message id (a top-level
+ // @mention records its own ts as both).
+ if binding, berr := h.Queries.GetChannelChatSessionBindingBySession(r.Context(), db.GetChannelChatSessionBindingBySessionParams{
ChatSessionID: cs.ID,
ChannelType: string(slack.TypeSlack),
}); berr == nil {
resp.ChatChannelType = string(slack.TypeSlack)
+ resp.ChatInThread = binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
+ binding.LastThreadID.String != binding.LastMessageID.String
}
if ws, err := h.Queries.GetWorkspace(r.Context(), cs.WorkspaceID); err == nil && ws.Repos != nil {
var repos []RepoData
diff --git a/server/internal/integrations/channel/history.go b/server/internal/integrations/channel/history.go
index 1852a5244e..c1fa08fd38 100644
--- a/server/internal/integrations/channel/history.go
+++ b/server/internal/integrations/channel/history.go
@@ -1,13 +1,13 @@
package channel
// This file defines the channel-agnostic vocabulary for ON-DEMAND history
-// reads. Unlike the inbound push path (InboundMessage), history is PULLED by
-// the agent through a single unified CLI (`multica chat history`): the agent
-// asks for "the history of the conversation I'm in" and never sees a
-// per-platform API. The server resolves the session's binding to a channel
-// type and dispatches to that platform's reader, which returns these
-// normalized shapes — so adding a platform is "implement a reader", and the
-// agent-facing contract never changes (MUL-3871).
+// reads. History is PULLED by the agent through two unified CLI commands —
+// `multica chat history` (the channel OVERVIEW: top-level messages + thread
+// metadata, not thread contents) and `multica chat thread [id]` (one thread's
+// messages). The agent never sees a per-platform API: the server resolves the
+// session's binding to a channel type and dispatches to that platform's reader,
+// which returns these normalized shapes. Adding a platform is "implement a
+// reader"; the agent-facing contract never changes (MUL-3871).
// HistoryRole is the normalized author kind of a fetched message, mirroring the
// chat_message.role domain the agent already reasons about.
@@ -22,30 +22,9 @@ const (
HistoryRoleAssistant HistoryRole = "assistant"
)
-// HistoryScope selects which slice of a conversation to read. A chat platform
-// has two nested histories: the surrounding CHANNEL and the agent's own THREAD
-// within it (on Slack the bot's first reply opens a thread on the @mention, so
-// every engaged conversation has one). The agent's primary read on a follow-up
-// is its thread; the wider channel is pulled only when needed. On the first
-// turn there is no thread yet, so the channel is the relevant context.
-type HistoryScope string
-
-const (
- // HistoryScopeAuto lets the server pick: the channel on the first turn (no
- // thread exists yet), the thread on follow-ups. This is the default.
- HistoryScopeAuto HistoryScope = "auto"
- // HistoryScopeThread reads the agent's own thread (Slack
- // conversations.replies). Falls back to the channel where the platform /
- // conversation has no threads (e.g. a DM).
- HistoryScopeThread HistoryScope = "thread"
- // HistoryScopeChannel reads the surrounding channel (Slack
- // conversations.history).
- HistoryScopeChannel HistoryScope = "channel"
-)
-
-// HistoryMessage is one normalized message from a conversation's history. It is
-// the same shape regardless of platform so the agent reads a uniform list,
-// exactly like `multica issue comment list --output json`.
+// HistoryMessage is one normalized message. It is the same shape regardless of
+// platform so the agent reads a uniform list, like `multica issue comment list
+// --output json`.
type HistoryMessage struct {
// ID is the platform message identifier (Slack ts, Feishu message_id).
ID string `json:"id"`
@@ -62,19 +41,29 @@ type HistoryMessage struct {
// TS is the platform timestamp string, sortable lexicographically within a
// platform (Slack "1700000000.000100"). It doubles as the paging cursor.
TS string `json:"ts"`
+
+ // The following are set only on a CHANNEL-OVERVIEW row that heads a thread,
+ // so the agent can `multica chat thread <thread_id>` to read its contents.
+ // They are absent on a plain message and on thread-read rows.
+
+ // ThreadID is the identifier to pass to `multica chat thread <id>` to read
+ // this thread's messages. Set only when this overview row has a thread.
+ ThreadID string `json:"thread_id,omitempty"`
+ // ReplyCount is how many replies the thread has (0/omitted when none).
+ ReplyCount int `json:"reply_count,omitempty"`
+ // LatestReply is the platform timestamp of the most recent reply, when known.
+ LatestReply string `json:"latest_reply,omitempty"`
}
-// HistoryPage is one normalized page of history plus a cursor for paging
-// further back. Messages are ordered OLDEST-FIRST so the transcript reads
-// top-to-bottom like the chat does.
+// HistoryPage is one normalized page. Messages are ordered OLDEST-FIRST so the
+// transcript reads top-to-bottom like the chat does.
type HistoryPage struct {
// ChannelType is the platform the history came from ("slack"). Empty when
// the session is not bound to any channel (a web-only chat session).
ChannelType string `json:"channel_type,omitempty"`
- // Scope is the scope actually read ("thread" or "channel") after resolving
- // "auto" and any platform fallback (e.g. a DM has no thread). It lets the
- // agent know what it got and decide whether to also pull the other scope.
- Scope HistoryScope `json:"scope,omitempty"`
+ // ThreadID is set on a THREAD read: which thread these messages belong to.
+ // Empty on a channel overview.
+ ThreadID string `json:"thread_id,omitempty"`
// Messages are the fetched messages, oldest-first.
Messages []HistoryMessage `json:"messages"`
// NextCursor, when non-empty, is an opaque cursor to pass as Before to
@@ -82,14 +71,9 @@ type HistoryPage struct {
NextCursor string `json:"next_cursor,omitempty"`
}
-// HistoryOptions tune a history read. They are platform-neutral; each reader
-// maps them onto its own API's paging primitives.
+// HistoryOptions tune a read. They are platform-neutral; each reader maps them
+// onto its own API's paging primitives.
type HistoryOptions struct {
- // Scope selects thread vs channel. The handler resolves "auto" to a
- // concrete scope before calling the reader (it knows whether this is a
- // first turn or a follow-up); the reader still degrades "thread" to channel
- // where the conversation has no thread. An empty value reads the channel.
- Scope HistoryScope
// Limit caps how many messages to return. A reader clamps it to its
// platform's per-page maximum and applies a sane default for <= 0.
Limit int
diff --git a/server/internal/integrations/slack/history.go b/server/internal/integrations/slack/history.go
index df7e407c64..edd1c15a01 100644
--- a/server/internal/integrations/slack/history.go
+++ b/server/internal/integrations/slack/history.go
@@ -20,43 +20,38 @@ import (
// ErrNoSlackSession reports that the chat session has no Slack channel binding —
// it is a Feishu or web-only session. Callers surface it as an empty (not
-// failed) history read so the unified `multica chat history` command answers
-// gracefully on a non-Slack conversation.
+// failed) read so the unified `multica chat history` / `multica chat thread`
+// commands answer gracefully on a non-Slack conversation.
var ErrNoSlackSession = errors.New("slack: session has no slack channel binding")
const (
// defaultHistoryLimit is the page size used when the caller asks for none.
defaultHistoryLimit = 20
- // maxHistoryLimit caps a single page. Slack's own conversations.* limit is
- // far higher; we self-cap so a pull can't dump an unbounded transcript into
- // the agent's context (mirrors the Feishu recent-context clamp).
+ // maxHistoryLimit caps a single page so a pull can't dump an unbounded
+ // transcript into the agent's context.
maxHistoryLimit = 50
)
-// historyQueries is the slice of generated queries the history reader needs.
-// *db.Queries satisfies it. It mirrors outboundQueries: resolve the session's
-// Slack binding, then load the installation that owns the bot token.
+// historyQueries is the slice of generated queries the reader needs.
type historyQueries interface {
GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
}
// historyClient is the slice of the slack-go Web API the reader calls. The real
-// *slack.Client satisfies it; tests inject a fake so the fetch/labeling logic is
-// exercised without a live Slack.
+// *slack.Client satisfies it; tests inject a fake.
type historyClient interface {
GetConversationHistoryContext(ctx context.Context, params *slack.GetConversationHistoryParameters) (*slack.GetConversationHistoryResponse, error)
GetConversationRepliesContext(ctx context.Context, params *slack.GetConversationRepliesParameters) ([]slack.Message, bool, string, error)
GetUsersInfoContext(ctx context.Context, users ...string) (*[]slack.User, error)
}
-// History reads a Slack conversation's prior messages on demand — the pull half
-// of the unified `multica chat history` tool (MUL-3871). It mirrors Outbound:
-// given a chat_session it finds the Slack binding, decrypts the installation's
-// bot token, and calls conversations.replies (a real thread) or
-// conversations.history (DM / top-level channel context). Sessions with no
-// Slack binding return ErrNoSlackSession, so it coexists with Feishu sessions on
-// the shared endpoint.
+// History reads a Slack conversation on demand — the pull side of the unified
+// `multica chat history` (channel overview) and `multica chat thread [id]`
+// (one thread) commands (MUL-3871). Both are scoped to the session's OWN
+// channel: the channel is resolved server-side from the binding and never taken
+// from the agent, so a thread id is only a within-channel locator. Sessions with
+// no Slack binding return ErrNoSlackSession.
type History struct {
q historyQueries
decrypt Decrypter
@@ -72,83 +67,147 @@ func NewHistory(q historyQueries, decrypt Decrypter, logger *slog.Logger) *Histo
}
h := &History{q: q, decrypt: decrypt, logger: logger}
h.newClient = func(botToken string) historyClient {
- // Only the bot token is needed to read history; the app-level token is
- // for the inbound Socket Mode connection (slack_channel.go).
+ // Only the bot token is needed to read; the app-level token is for the
+ // inbound Socket Mode connection (slack_channel.go).
return slack.New(botToken)
}
return h
}
-// Fetch returns one normalized, oldest-first page of the session's Slack
-// conversation. It returns ErrNoSlackSession when the session is not Slack-bound
-// or its installation is inactive.
-func (h *History) Fetch(ctx context.Context, chatSessionID pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error) {
+// slackTarget is the resolved per-session read context: a bot-token client plus
+// the session's pinned channel and its own thread root.
+type slackTarget struct {
+ client historyClient
+ channelID string
+ threadRoot string // the session's own thread (empty for a DM)
+ botUserID string
+}
+
+// resolve maps a chat_session to its Slack channel + bot client. The channel is
+// server-derived here and never accepted from the caller — that is the security
+// boundary for `multica chat thread <id>` (the agent supplies only a
+// within-channel thread locator).
+func (h *History) resolve(ctx context.Context, chatSessionID pgtype.UUID) (slackTarget, error) {
binding, err := h.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
ChatSessionID: chatSessionID,
ChannelType: string(TypeSlack),
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- return channel.HistoryPage{}, ErrNoSlackSession
+ return slackTarget{}, ErrNoSlackSession
}
- return channel.HistoryPage{}, fmt.Errorf("lookup slack chat binding: %w", err)
+ return slackTarget{}, fmt.Errorf("lookup slack chat binding: %w", err)
}
inst, err := h.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
ID: binding.InstallationID,
ChannelType: string(TypeSlack),
})
if err != nil {
- return channel.HistoryPage{}, fmt.Errorf("load slack installation: %w", err)
+ return slackTarget{}, fmt.Errorf("load slack installation: %w", err)
}
if inst.Status != "active" {
- return channel.HistoryPage{}, ErrNoSlackSession // revoked install: nothing to read
+ return slackTarget{}, ErrNoSlackSession // revoked install: nothing to read
}
creds, err := decodeCredentials(inst.Config, h.decrypt)
if err != nil {
- return channel.HistoryPage{}, fmt.Errorf("decode slack credentials: %w", err)
+ return slackTarget{}, fmt.Errorf("decode slack credentials: %w", err)
}
channelID, threadRoot := historyTarget(binding)
- // Resolve the concrete scope to read. The handler resolves "auto" to
- // thread/channel (it knows first-turn vs follow-up); here we additionally
- // degrade "thread" to "channel" when there is no thread to read — a DM, or a
- // group whose root could not be recovered.
- scope := channel.HistoryScopeChannel
- if opts.Scope == channel.HistoryScopeThread &&
- binding.ChatType == string(channel.ChatTypeGroup) && threadRoot != "" {
- scope = channel.HistoryScopeThread
- }
+ return slackTarget{
+ client: h.newClient(creds.BotToken),
+ channelID: channelID,
+ threadRoot: threadRoot,
+ botUserID: creds.BotUserID,
+ }, nil
+}
- limit := opts.Limit
- if limit <= 0 {
- limit = defaultHistoryLimit
+// ChannelOverview returns the channel's recent top-level messages (oldest-first),
+// each thread tagged with its id + reply count. It does NOT expand thread
+// contents — it is the table of contents the agent reads to find a thread, then
+// drills into with `multica chat thread <id>`. Backs `multica chat history`.
+func (h *History) ChannelOverview(ctx context.Context, chatSessionID pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error) {
+ t, err := h.resolve(ctx, chatSessionID)
+ if err != nil {
+ return channel.HistoryPage{}, err
}
- if limit > maxHistoryLimit {
- limit = maxHistoryLimit
+ limit := clampHistoryLimit(opts.Limit)
+ resp, err := t.client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
+ ChannelID: t.channelID,
+ Latest: opts.Before,
+ Inclusive: false,
+ Limit: limit,
+ })
+ if err != nil {
+ return channel.HistoryPage{}, fmt.Errorf("read slack channel: %w", err)
}
+ page := normalizePage(ctx, t.client, h.logger, resp.Messages, t.botUserID, limit, true)
+ page.ChannelType = string(TypeSlack)
+ return page, nil
+}
- fetchThreadTS := ""
- if scope == channel.HistoryScopeThread {
- fetchThreadTS = threadRoot
- }
- client := h.newClient(creds.BotToken)
- raw, err := fetchRaw(ctx, client, channelID, fetchThreadTS, opts.Before, limit)
+// Thread returns one thread's messages (oldest-first). threadID empty reads the
+// thread the session is in (the agent's own thread); a non-empty id reads that
+// specific thread — but always within the session's pinned channel. A DM (no
+// threads) reads its linear conversation. Backs `multica chat thread [id]`.
+func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadID string, opts channel.HistoryOptions) (channel.HistoryPage, error) {
+ t, err := h.resolve(ctx, chatSessionID)
if err != nil {
- return channel.HistoryPage{}, fmt.Errorf("read slack history: %w", err)
+ return channel.HistoryPage{}, err
+ }
+ limit := clampHistoryLimit(opts.Limit)
+ ts := threadID
+ if ts == "" {
+ ts = t.threadRoot // the session's own thread
}
- page := normalizeHistory(ctx, client, h.logger, raw, creds.BotUserID, limit)
+ var raw []slack.Message
+ if ts == "" {
+ // No thread to read (a DM, or a group whose root could not be recovered):
+ // fall back to the channel's linear conversation.
+ resp, herr := t.client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
+ ChannelID: t.channelID,
+ Latest: opts.Before,
+ Inclusive: false,
+ Limit: limit,
+ })
+ if herr != nil {
+ return channel.HistoryPage{}, fmt.Errorf("read slack thread: %w", herr)
+ }
+ raw = resp.Messages
+ } else {
+ msgs, _, _, rerr := t.client.GetConversationRepliesContext(ctx, &slack.GetConversationRepliesParameters{
+ ChannelID: t.channelID,
+ Timestamp: ts,
+ Latest: opts.Before,
+ Inclusive: false,
+ Limit: limit,
+ })
+ if rerr != nil {
+ return channel.HistoryPage{}, fmt.Errorf("read slack thread: %w", rerr)
+ }
+ raw = msgs
+ }
+ page := normalizePage(ctx, t.client, h.logger, raw, t.botUserID, limit, false)
page.ChannelType = string(TypeSlack)
- page.Scope = scope
+ page.ThreadID = ts
return page, nil
}
-// historyTarget recovers the real channel id and the thread root from the
-// binding. The channel_chat_id may be a composite "channel:threadRoot"
+func clampHistoryLimit(n int) int {
+ if n <= 0 {
+ return defaultHistoryLimit
+ }
+ if n > maxHistoryLimit {
+ return maxHistoryLimit
+ }
+ return n
+}
+
+// historyTarget recovers the real channel id and the session's own thread root
+// from the binding. The channel_chat_id may be a composite "channel:threadRoot"
// isolation key, so the real channel id is read from the binding config
-// (slackBindingConfig). The thread root — present for every engaged group
-// session, since the bot's first reply opens a thread on the @mention — is the
-// recorded reply thread (last_thread_id), falling back to the composite-key
-// suffix. It is empty for a DM (no threads).
+// (slackBindingConfig). The thread root is the recorded reply thread
+// (last_thread_id), falling back to the composite-key suffix; empty for a DM.
func historyTarget(b db.ChannelChatSessionBinding) (channelID, threadRoot string) {
channelID = b.ChannelChatID
if len(b.Config) > 0 {
@@ -165,38 +224,12 @@ func historyTarget(b db.ChannelChatSessionBinding) (channelID, threadRoot string
return channelID, threadRoot
}
-// fetchRaw pulls the most recent `limit` messages older than `before` (exclusive
-// when set). A thread read uses conversations.replies anchored on the thread
-// root; a channel read uses conversations.history. Both return newest-first;
-// ordering is normalized downstream.
-func fetchRaw(ctx context.Context, client historyClient, channelID, threadTS, before string, limit int) ([]slack.Message, error) {
- if threadTS != "" {
- msgs, _, _, err := client.GetConversationRepliesContext(ctx, &slack.GetConversationRepliesParameters{
- ChannelID: channelID,
- Timestamp: threadTS,
- Latest: before,
- Inclusive: false,
- Limit: limit,
- })
- return msgs, err
- }
- resp, err := client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
- ChannelID: channelID,
- Latest: before,
- Inclusive: false,
- Limit: limit,
- })
- if err != nil {
- return nil, err
- }
- return resp.Messages, nil
-}
-
-// normalizeHistory turns raw Slack messages into a normalized, oldest-first
-// page: it resolves human display names in one batch, labels each sender, maps
-// the role, and computes the back-paging cursor.
-func normalizeHistory(ctx context.Context, client historyClient, logger *slog.Logger, raw []slack.Message, botUserID string, limit int) channel.HistoryPage {
- // Oldest-first so the transcript reads top-to-bottom like the chat does.
+// normalizePage turns raw Slack messages into a normalized, oldest-first page:
+// it resolves display names in one batch, labels senders, maps roles, and
+// computes the back-paging cursor. When overview is true, a message that heads a
+// thread (reply_count > 0) is tagged with its thread id + reply count so the
+// agent can drill in with `multica chat thread <id>`.
+func normalizePage(ctx context.Context, client historyClient, logger *slog.Logger, raw []slack.Message, botUserID string, limit int, overview bool) channel.HistoryPage {
sort.SliceStable(raw, func(i, j int) bool { return slackTSLess(raw[i].Timestamp, raw[j].Timestamp) })
names := resolveUserNames(ctx, client, logger, raw, botUserID)
@@ -205,8 +238,7 @@ func normalizeHistory(ctx context.Context, client historyClient, logger *slog.Lo
out := make([]channel.HistoryMessage, 0, len(raw))
for i := range raw {
m := raw[i]
- text := m.Text
- if text == "" {
+ if m.Text == "" {
continue // join/system/edit markers carry no readable body
}
own := m.User != "" && m.User == botUserID
@@ -214,18 +246,24 @@ func normalizeHistory(ctx context.Context, client historyClient, logger *slog.Lo
if own {
role = channel.HistoryRoleAssistant
}
- out = append(out, channel.HistoryMessage{
+ hm := channel.HistoryMessage{
ID: m.Timestamp,
Author: labeler.label(m, own),
AuthorID: m.User,
Role: role,
- Text: text,
+ Text: m.Text,
TS: m.Timestamp,
- })
+ }
+ if overview && m.ReplyCount > 0 {
+ hm.ThreadID = m.Timestamp
+ hm.ReplyCount = m.ReplyCount
+ hm.LatestReply = m.LatestReply
+ }
+ out = append(out, hm)
}
page := channel.HistoryPage{Messages: out}
- // Only advertise a cursor when the platform returned a full page (more may
+ // Advertise a cursor only when the platform returned a full page (more may
// exist older than the oldest message we just returned).
if len(raw) >= limit && len(out) > 0 {
page.NextCursor = out[0].TS
@@ -233,8 +271,8 @@ func normalizeHistory(ctx context.Context, client historyClient, logger *slog.Lo
return page
}
-// resolveUserNames batch-resolves the human senders' display names, best-effort.
-// A failure (missing users:read scope, transport error) yields a nil map so the
+// resolveUserNames batch-resolves human senders' display names, best-effort. A
+// failure (missing users:read scope, transport error) yields a nil map so the
// labeler falls back to positional "User N" rather than blocking the read.
func resolveUserNames(ctx context.Context, client historyClient, logger *slog.Logger, msgs []slack.Message, botUserID string) map[string]string {
seen := make(map[string]bool)
@@ -278,10 +316,9 @@ func slackDisplayName(u slack.User) string {
}
}
-// historyLabeler assigns stable, human-readable labels within one page, mirroring
-// the Feishu speakerLabeler: this bot is "Bot"; a resolved human gets their real
-// name; an unresolved human falls back to positional "User N"; a third-party bot
-// uses its posted username.
+// historyLabeler assigns stable, human-readable labels within one page: this bot
+// is "Bot"; a resolved human gets their real name; an unresolved human falls
+// back to positional "User N"; a third-party bot uses its posted username.
type historyLabeler struct {
names map[string]string
seen map[string]string
@@ -298,8 +335,6 @@ func (l *historyLabeler) label(m slack.Message, own bool) string {
}
key := m.User
if key == "" {
- // A third-party bot (alerting app, …) posts with a bot_id and often a
- // username but no user id; label it by that username when present.
if m.Username != "" {
return m.Username
}
@@ -321,9 +356,7 @@ func (l *historyLabeler) label(m slack.Message, own bool) string {
return lbl
}
-// slackTSLess orders two Slack timestamps ("secs.micros") chronologically. Slack
-// ts strings are not safely comparable lexicographically across widths, so parse
-// them; an unparseable value sorts as 0 (oldest).
+// slackTSLess orders two Slack timestamps ("secs.micros") chronologically.
func slackTSLess(a, b string) bool {
return parseSlackTS(a) < parseSlackTS(b)
}
diff --git a/server/internal/integrations/slack/history_test.go b/server/internal/integrations/slack/history_test.go
index 341b7867a5..dfbd2dafcc 100644
--- a/server/internal/integrations/slack/history_test.go
+++ b/server/internal/integrations/slack/history_test.go
@@ -58,12 +58,19 @@ func msg(user, text, ts string) slack.Message {
return slack.Message{Msg: slack.Msg{User: user, Text: text, Timestamp: ts}}
}
+// threadParent is a top-level message that heads a thread (reply_count > 0).
+func threadParent(user, text, ts string, replyCount int, latestReply string) slack.Message {
+ m := msg(user, text, ts)
+ m.ReplyCount = replyCount
+ m.LatestReply = latestReply
+ return m
+}
+
func activeSlackInstall() db.ChannelInstallation {
return db.ChannelInstallation{Status: "active", Config: slackInstallConfigJSON()}
}
-// groupBinding builds a group session binding rooted at threadRoot (the thread
-// the bot's reply opened on the @mention).
+// groupBinding builds a group session binding whose own thread root is threadRoot.
func groupBinding(threadRoot string) db.ChannelChatSessionBinding {
b := db.ChannelChatSessionBinding{
InstallationID: uid(2),
@@ -92,51 +99,58 @@ func newTestHistory(q historyQueries, fc historyClient) *History {
return h
}
-// TestHistoryFetchChannelScope verifies a channel-scope read uses
-// conversations.history and normalizes oldest-first with roles + labels.
-func TestHistoryFetchChannelScope(t *testing.T) {
- q := &fakeHistoryQueries{binding: groupBinding("50.000000"), inst: activeSlackInstall()}
+func findByTS(msgs []channel.HistoryMessage, ts string) *channel.HistoryMessage {
+ for i := range msgs {
+ if msgs[i].TS == ts {
+ return &msgs[i]
+ }
+ }
+ return nil
+}
+
+// TestChannelOverview verifies `chat history` reads conversations.history,
+// normalizes oldest-first, and tags thread parents with their id + reply count
+// without expanding thread contents.
+func TestChannelOverview(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
fc := &fakeHistoryClient{
- // Slack returns newest-first; the bot (UBOT) replied last.
+ // Slack returns newest-first.
historyMsgs: []slack.Message{
- msg("UBOT", "on it", "102.000000"),
- msg("U1", "@bot look into this", "101.000000"),
- msg("U2", "alert: 5xx spiking", "100.000000"),
+ threadParent("U1", "deploy discussion", "102.000000", 3, "105.000000"),
+ msg("U2", "fyi unrelated", "101.000000"),
+ msg("U3", "@bot take a look", "100.000000"),
},
- users: []slack.User{{ID: "U1", RealName: "Alice"}}, // U2 unresolved -> positional
+ users: []slack.User{{ID: "U1", RealName: "Alice"}},
}
h := newTestHistory(q, fc)
- page, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{Scope: channel.HistoryScopeChannel})
+ page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{})
if err != nil {
- t.Fatalf("Fetch: %v", err)
+ t.Fatalf("ChannelOverview: %v", err)
}
if fc.historyCalls != 1 || fc.repliesCalls != 0 {
- t.Fatalf("expected conversations.history, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
+ t.Fatalf("expected conversations.history only, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
}
if fc.lastHistory.ChannelID != "C1" {
t.Errorf("channel id = %q, want C1", fc.lastHistory.ChannelID)
}
- if page.ChannelType != "slack" || page.Scope != channel.HistoryScopeChannel {
- t.Errorf("channel_type/scope = %q/%q, want slack/channel", page.ChannelType, page.Scope)
+ if page.ChannelType != "slack" || page.ThreadID != "" {
+ t.Errorf("channel_type/thread_id = %q/%q, want slack/<empty>", page.ChannelType, page.ThreadID)
}
if len(page.Messages) != 3 || page.Messages[0].TS != "100.000000" || page.Messages[2].TS != "102.000000" {
t.Fatalf("expected 3 msgs oldest-first, got %+v", page.Messages)
}
- if got := page.Messages[0]; got.Author != "User 1" || got.Role != channel.HistoryRoleUser {
- t.Errorf("msg0 author/role = %q/%q, want User 1/user", got.Author, got.Role)
+ parent := findByTS(page.Messages, "102.000000")
+ if parent == nil || parent.ThreadID != "102.000000" || parent.ReplyCount != 3 || parent.LatestReply != "105.000000" || parent.Author != "Alice" {
+ t.Fatalf("thread parent metadata wrong: %+v", parent)
}
- if got := page.Messages[1]; got.Author != "Alice" {
- t.Errorf("msg1 author = %q, want Alice", got.Author)
- }
- if got := page.Messages[2]; got.Author != "Bot" || got.Role != channel.HistoryRoleAssistant {
- t.Errorf("msg2 author/role = %q/%q, want Bot/assistant", got.Author, got.Role)
+ if plain := findByTS(page.Messages, "101.000000"); plain == nil || plain.ThreadID != "" || plain.ReplyCount != 0 {
+ t.Fatalf("plain message should carry no thread metadata: %+v", plain)
}
}
-// TestHistoryFetchThreadScope verifies a thread-scope read uses
-// conversations.replies anchored on the session's thread root (from the binding).
-func TestHistoryFetchThreadScope(t *testing.T) {
+// TestThreadCurrent reads the session's own thread via conversations.replies.
+func TestThreadCurrent(t *testing.T) {
q := &fakeHistoryQueries{binding: groupBinding("50.000000"), inst: activeSlackInstall()}
fc := &fakeHistoryClient{repliesMsgs: []slack.Message{
msg("U1", "second", "52.000000"),
@@ -144,110 +158,105 @@ func TestHistoryFetchThreadScope(t *testing.T) {
}}
h := newTestHistory(q, fc)
- page, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{Scope: channel.HistoryScopeThread, Limit: 10})
+ page, err := h.Thread(context.Background(), uid(9), "", channel.HistoryOptions{Limit: 10})
if err != nil {
- t.Fatalf("Fetch: %v", err)
+ t.Fatalf("Thread: %v", err)
}
if fc.repliesCalls != 1 || fc.historyCalls != 0 {
- t.Fatalf("expected conversations.replies, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
+ t.Fatalf("expected conversations.replies only, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
}
if fc.lastReplies.Timestamp != "50.000000" || fc.lastReplies.ChannelID != "C1" {
t.Errorf("replies anchored at %q/%q, want C1/50.000000", fc.lastReplies.ChannelID, fc.lastReplies.Timestamp)
}
- if page.Scope != channel.HistoryScopeThread {
- t.Errorf("scope = %q, want thread", page.Scope)
+ if page.ThreadID != "50.000000" {
+ t.Errorf("thread_id = %q, want 50.000000", page.ThreadID)
}
if len(page.Messages) != 2 || page.Messages[0].TS != "50.000000" {
t.Fatalf("expected 2 msgs oldest-first, got %+v", page.Messages)
}
}
-// TestHistoryFetchDMIgnoresThreadScope confirms a DM (no threads) degrades a
-// thread request to channel history.
-func TestHistoryFetchDMIgnoresThreadScope(t *testing.T) {
- q := &fakeHistoryQueries{binding: dmBinding(), inst: activeSlackInstall()}
- fc := &fakeHistoryClient{historyMsgs: []slack.Message{msg("U1", "hi", "100.000000")}}
+// TestThreadByID reads a specific (non-current) thread within the same channel.
+func TestThreadByID(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("50.000000"), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{repliesMsgs: []slack.Message{msg("U1", "x", "77.000000")}}
h := newTestHistory(q, fc)
- page, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{Scope: channel.HistoryScopeThread})
+ page, err := h.Thread(context.Background(), uid(9), "70.000000", channel.HistoryOptions{})
if err != nil {
- t.Fatalf("Fetch: %v", err)
+ t.Fatalf("Thread: %v", err)
}
- if fc.historyCalls != 1 || fc.repliesCalls != 0 {
- t.Fatalf("DM must use conversations.history, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
+ if fc.lastReplies == nil || fc.lastReplies.Timestamp != "70.000000" {
+ t.Fatalf("expected replies anchored at the passed id 70.000000, got %+v", fc.lastReplies)
}
- if page.Scope != channel.HistoryScopeChannel {
- t.Errorf("scope = %q, want channel (DM has no thread)", page.Scope)
+ if fc.lastReplies.ChannelID != "C1" {
+ t.Errorf("channel must stay pinned to the session: got %q, want C1", fc.lastReplies.ChannelID)
+ }
+ if page.ThreadID != "70.000000" {
+ t.Errorf("thread_id = %q, want 70.000000", page.ThreadID)
}
}
-// TestHistoryFetchThreadFallsBackWithoutRoot: a group binding with no recoverable
-// thread root degrades a thread request to channel history.
-func TestHistoryFetchThreadFallsBackWithoutRoot(t *testing.T) {
- q := &fakeHistoryQueries{
- binding: db.ChannelChatSessionBinding{InstallationID: uid(2), ChannelChatID: "C1", ChatType: string(channel.ChatTypeGroup), Config: []byte(`{"channel_id":"C1"}`)},
- inst: activeSlackInstall(),
- }
- fc := &fakeHistoryClient{historyMsgs: []slack.Message{msg("U1", "x", "100.000000")}}
+// TestThreadDMUsesHistory: a DM has no threads, so a thread read falls back to
+// the linear conversation (conversations.history).
+func TestThreadDMUsesHistory(t *testing.T) {
+ q := &fakeHistoryQueries{binding: dmBinding(), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{historyMsgs: []slack.Message{msg("U1", "hi", "100.000000")}}
h := newTestHistory(q, fc)
- page, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{Scope: channel.HistoryScopeThread})
+ page, err := h.Thread(context.Background(), uid(9), "", channel.HistoryOptions{})
if err != nil {
- t.Fatalf("Fetch: %v", err)
+ t.Fatalf("Thread: %v", err)
}
if fc.historyCalls != 1 || fc.repliesCalls != 0 {
- t.Fatalf("expected fallback to history, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
- }
- if page.Scope != channel.HistoryScopeChannel {
- t.Errorf("scope = %q, want channel", page.Scope)
- }
-}
-
-// TestHistoryTargetDerivesRoot pins the channel + thread-root recovery from a
-// binding: last_thread_id first, then the composite-key suffix, empty for a DM.
-func TestHistoryTargetDerivesRoot(t *testing.T) {
- if ch, root := historyTarget(groupBinding("50.0")); ch != "C1" || root != "50.0" {
- t.Errorf("from last_thread_id: got %q/%q, want C1/50.0", ch, root)
+ t.Fatalf("DM thread must use conversations.history, got history=%d replies=%d", fc.historyCalls, fc.repliesCalls)
}
- keyOnly := db.ChannelChatSessionBinding{ChannelChatID: "C9:77.7", Config: []byte(`{"channel_id":"C9"}`)}
- if ch, root := historyTarget(keyOnly); ch != "C9" || root != "77.7" {
- t.Errorf("from key suffix: got %q/%q, want C9/77.7", ch, root)
- }
- if ch, root := historyTarget(dmBinding()); ch != "D1" || root != "" {
- t.Errorf("dm: got %q/%q, want D1/<empty>", ch, root)
+ if page.ThreadID != "" {
+ t.Errorf("DM has no thread id, got %q", page.ThreadID)
}
}
-// TestHistoryFetchNoBinding maps a missing Slack binding to ErrNoSlackSession.
-func TestHistoryFetchNoBinding(t *testing.T) {
+func TestChannelOverviewNoBinding(t *testing.T) {
q := &fakeHistoryQueries{bindingErr: pgx.ErrNoRows}
h := newTestHistory(q, &fakeHistoryClient{})
- if _, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{}); !errors.Is(err, ErrNoSlackSession) {
+ if _, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{}); !errors.Is(err, ErrNoSlackSession) {
t.Fatalf("err = %v, want ErrNoSlackSession", err)
}
}
-// TestHistoryFetchInactiveInstall treats a revoked installation as empty.
-func TestHistoryFetchInactiveInstall(t *testing.T) {
+func TestThreadInactiveInstall(t *testing.T) {
q := &fakeHistoryQueries{
binding: groupBinding("50.0"),
inst: db.ChannelInstallation{Status: "revoked", Config: slackInstallConfigJSON()},
}
h := newTestHistory(q, &fakeHistoryClient{})
- if _, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{}); !errors.Is(err, ErrNoSlackSession) {
+ if _, err := h.Thread(context.Background(), uid(9), "", channel.HistoryOptions{}); !errors.Is(err, ErrNoSlackSession) {
t.Fatalf("err = %v, want ErrNoSlackSession", err)
}
}
-// TestHistoryLimitClamp confirms an over-large limit is clamped before the call.
-func TestHistoryLimitClamp(t *testing.T) {
+func TestChannelOverviewLimitClamp(t *testing.T) {
q := &fakeHistoryQueries{binding: groupBinding("50.0"), inst: activeSlackInstall()}
fc := &fakeHistoryClient{}
h := newTestHistory(q, fc)
- if _, err := h.Fetch(context.Background(), uid(9), channel.HistoryOptions{Scope: channel.HistoryScopeChannel, Limit: 5000}); err != nil {
- t.Fatalf("Fetch: %v", err)
+ if _, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{Limit: 5000}); err != nil {
+ t.Fatalf("ChannelOverview: %v", err)
}
if fc.lastHistory.Limit != maxHistoryLimit {
t.Errorf("limit = %d, want clamp to %d", fc.lastHistory.Limit, maxHistoryLimit)
}
}
+
+// TestHistoryTargetDerivesRoot pins channel + thread-root recovery from a binding.
+func TestHistoryTargetDerivesRoot(t *testing.T) {
+ if ch, root := historyTarget(groupBinding("50.0")); ch != "C1" || root != "50.0" {
+ t.Errorf("from last_thread_id: got %q/%q, want C1/50.0", ch, root)
+ }
+ keyOnly := db.ChannelChatSessionBinding{ChannelChatID: "C9:77.7", Config: []byte(`{"channel_id":"C9"}`)}
+ if ch, root := historyTarget(keyOnly); ch != "C9" || root != "77.7" {
+ t.Errorf("from key suffix: got %q/%q, want C9/77.7", ch, root)
+ }
+ if ch, root := historyTarget(dmBinding()); ch != "D1" || root != "" {
+ t.Errorf("dm: got %q/%q, want D1/<empty>", ch, root)
+ }
+}