Skip to content

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

Go

MUL-5963: feat(server): let web chat read back history via `multica chat history` (#6680)

build-the-robot8d292ef7ceaf
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index fdf84cceb7..bc03525a16 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -812,10 +812,12 @@ func TestBuildPromptContainsIssueID(t *testing.T) {
// TestSessionContinuityNoticeMatchesSurface locks the MUL-5722 split. The same
// event costs each surface something different, so it cannot be reported with
// one sentence. The dividing question is whether the conversation can still be
-// READ, not whether it is a chat: an issue's comments and a Slack channel's
-// history both can, a web chat's and a Feishu channel's cannot. Announcing a
-// loss on the first two describes something that did not happen — the user
-// hears "the discussion is gone" when every word survives.
+// READ, not whether it is a chat: an issue's comments, a Slack channel's
+// history, and a web chat's / Feishu's / WeCom's / DingTalk's stored
+// chat_message transcript all can; only a surface Multica stores no transcript
+// for cannot. Announcing a loss on the readable ones describes something that
+// did not happen — the user hears "the discussion is gone" when every word
+// survives.
func TestSessionContinuityNoticeMatchesSurface(t *testing.T) {
t.Parallel()
@@ -841,19 +843,37 @@ func TestSessionContinuityNoticeMatchesSurface(t *testing.T) {
wantMentions: "multica chat history",
},
{
- // Web chat history lived only in the provider session.
- name: "web chat is unrecoverable",
+ // Web chat history is persisted in chat_message, which `multica chat
+ // history` reads back — recoverable, just from Multica's store.
+ name: "web chat rebuilds from the stored transcript",
task: Task{ChatSessionID: "chat-1"},
- tellUser: true,
- wantMentions: "not readable from anywhere",
+ tellUser: false,
+ wantMentions: "multica chat history",
},
{
- // Multica ships no history reader for Feishu, so despite being a
- // channel it is in the same position as a web chat.
- name: "feishu has no history reader",
+ // Feishu's conversation is persisted to chat_message too, and the
+ // handler's non-Slack fallback reads it back via `multica chat history`.
+ name: "feishu rebuilds from the stored transcript",
task: Task{ChatSessionID: "chat-1", ChatChannelType: execenv.ChannelTypeFeishu},
- tellUser: true,
- wantMentions: "not readable from anywhere",
+ tellUser: false,
+ wantMentions: "multica chat history",
+ },
+ {
+ // WeCom is fully wired on main (persists chat_message, stamps
+ // ChatChannelType="wecom"), so its transcript is readable too — the
+ // handler's non-Slack fallback serves it just like Feishu's.
+ name: "wecom rebuilds from the stored transcript",
+ task: Task{ChatSessionID: "chat-1", ChatChannelType: execenv.ChannelTypeWecom},
+ tellUser: false,
+ wantMentions: "multica chat history",
+ },
+ {
+ // DingTalk persists to chat_message through the same AppendUserMessage
+ // path as Feishu/WeCom, so its transcript is readable the same way.
+ name: "dingtalk rebuilds from the stored transcript",
+ task: Task{ChatSessionID: "chat-1", ChatChannelType: execenv.ChannelTypeDingtalk},
+ tellUser: false,
+ wantMentions: "multica chat history",
},
}
diff --git a/server/internal/daemon/execenv/channel_type.go b/server/internal/daemon/execenv/channel_type.go
index 0b5e07d88c..2a33f8636d 100644
--- a/server/internal/daemon/execenv/channel_type.go
+++ b/server/internal/daemon/execenv/channel_type.go
@@ -13,11 +13,29 @@ package execenv
// agree on the wire strings below. WeCom keeps its reserved wire discriminator
// here until its adapter lands.
const (
- ChannelTypeSlack = "slack"
- ChannelTypeFeishu = "feishu"
- ChannelTypeWecom = "wecom"
+ ChannelTypeSlack = "slack"
+ ChannelTypeFeishu = "feishu"
+ ChannelTypeWecom = "wecom"
+ ChannelTypeDingtalk = "dingtalk"
)
+// SurfacePersistsTranscript reports whether a chat surface stores its
+// conversation in Multica's chat_message table, readable back via `multica chat
+// history` (handler/chat_history.go's non-Slack fallback). Web chat (empty
+// discriminator), Feishu, WeCom and DingTalk all persist via the shared
+// AppendUserMessage path; Slack reads the live channel instead. It is the single
+// source of truth for "which surfaces are readable", shared by the
+// continuity-notice router, the chat-prompt history copy, and the surface list —
+// so a future non-persisting channel is never told "read it back".
+func SurfacePersistsTranscript(channelType string) bool {
+ switch channelType {
+ case "", ChannelTypeFeishu, ChannelTypeWecom, ChannelTypeDingtalk:
+ return true
+ default:
+ return false
+ }
+}
+
// Room-shape discriminators, mirroring channel_chat_session_binding.chat_type
// (channel.ChatTypeP2P / channel.ChatTypeGroup). Every adapter persists this
// column, so the shape of a conversation is known off one read whatever the
@@ -108,6 +126,8 @@ func ChannelDisplayName(channelType string) string {
return "Feishu/Lark"
case ChannelTypeWecom:
return "WeCom"
+ case ChannelTypeDingtalk:
+ return "DingTalk"
default:
return channelType
}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 8b9715c168..a126134547 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -405,17 +405,21 @@ func writeInstructionPrecedence(b *strings.Builder) {
// - Slack: the conversation lives in the channel and `multica chat history` /
// `multica chat thread` can fetch it — see buildChatPrompt, which hands the
// agent exactly those commands. Recoverable, just from a different place.
-// - Web chat and Feishu: nothing can fetch it. A web chat's history lived only
-// in the provider session, and Multica ships no history reader for Feishu
-// (handler/chat_history.go is hardwired to Slack), so the run has only the
-// inbound context for this turn.
-//
-// Only the last group warrants telling the user. On the first two the discussion
-// survives, so announcing "the previous context was lost" describes a loss that
-// did not happen — the user reasonably hears "the discussion is gone" when not a
-// word of it is. There the notice informs the agent and leaves mentioning it to
-// the agent's judgement. What is actually gone on every surface is the agent's
-// own unrecorded working memory, and each variant says so.
+// - Web chat, Feishu, WeCom and DingTalk: the conversation is persisted in
+// Multica's chat_message table and `multica chat history` reads it back —
+// see handler/chat_history.go's chat_message fallback for non-Slack
+// sessions. Recoverable, just from a different place. The readable set is
+// decided in one place, SurfacePersistsTranscript.
+//
+// Only a surface whose conversation Multica never stored (so there is nothing
+// to read back) warrants telling the user; no current surface is in that
+// group, so SessionContinuityNoticeUnrecoverable is a defensive fallback. On
+// the readable ones the discussion survives, so announcing "the previous
+// context was lost" describes a loss that did not happen — the user reasonably
+// hears "the discussion is gone" when not a word of it is. There the notice
+// informs the agent and leaves mentioning it to the agent's judgement. What is
+// actually gone on every surface is the agent's own unrecorded working memory,
+// and each variant says so.
//
// Emitted into the per-turn user message rather than the runtime brief: it is
// true of one run and false of the next on the same issue, so rendering it into
@@ -426,6 +430,17 @@ const SessionContinuityNoticeIssue = "## Session Continuity Notice\n\n" +
const SessionContinuityNoticeChannelHistory = "## Session Continuity Notice\n\n" +
"This run was meant to continue an earlier conversation, but that provider session could not be restored, so you are on a fresh one. The channel conversation itself is unaffected — read it back with `multica chat history` / `multica chat thread` before acting, and treat what you find there as the authoritative version. What is gone is only your own working memory from earlier turns: what you already tried, what you ruled out, and how far you had got. Re-derive what you need instead of assuming it. Do not open your reply by announcing this — raise it only where it actually matters.\n\n"
+const SessionContinuityNoticeChatTranscript = "## Session Continuity Notice\n\n" +
+ "This run was meant to continue an earlier conversation, but that provider session could not be restored, so you are on a fresh one. The conversation itself is unaffected — Multica stored it, and you can read it back with `multica chat history` before acting; treat what you find there as the authoritative version. What is gone is only your own working memory from earlier turns: what you already tried, what you ruled out, and how far you had got. Re-derive what you need instead of assuming it. Do not open your reply by announcing this — raise it only where it actually matters.\n\n"
+
+// SessionContinuityNoticeUnrecoverable is the defensive fallback for a surface
+// whose conversation Multica never stored and cannot read back. Every current
+// chat surface (web chat, Feishu, WeCom, DingTalk, Slack) persists a transcript
+// that `multica chat history` can fetch, so no surface routes here today — it
+// exists so a future channel that stores no transcript degrades to an honest
+// "this is a new session" instead of silently pretending continuity. Unlike the
+// readable variants it scripts the user-facing disclosure, because here the
+// loss is real and the user must hear it.
const SessionContinuityNoticeUnrecoverable = "## Session Continuity Notice\n\n" +
"This run was meant to continue an earlier conversation, but that session's context could NOT be restored — you are starting fresh with no memory of the previous turns. That history is not readable from anywhere now: there is no command that fetches it, and only the context already in this message survives. **When you reply, tell the user up front (one short sentence) that the previous conversation context was unavailable and this is a new session**, so they understand why the thread did not carry over.\n\n"
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 0ad9ec6250..0781661fbe 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -327,6 +327,19 @@ func TestSessionContinuityNoticeLivesOutsideBrief(t *testing.T) {
t.Errorf("issue variant must state the real loss:\n%s", SessionContinuityNoticeIssue)
}
+ // The web-chat / Feishu transcript variant points at the read-back command
+ // and must NOT order an announcement — the conversation survives in
+ // chat_message, so "the previous context was lost" would be a false alarm.
+ if !strings.Contains(SessionContinuityNoticeChatTranscript, "multica chat history") {
+ t.Error("transcript variant must point at the read-back command")
+ }
+ if strings.Contains(SessionContinuityNoticeChatTranscript, "tell the user") {
+ t.Errorf("transcript variant must not script an apology:\n%s", SessionContinuityNoticeChatTranscript)
+ }
+ if !strings.Contains(SessionContinuityNoticeChatTranscript, "your own working memory") {
+ t.Errorf("transcript variant must state the real loss:\n%s", SessionContinuityNoticeChatTranscript)
+ }
+
lost := TaskContextForEnv{
IssueID: "11111111-2222-3333-4444-555555555555",
TriggerCommentID: "trigger-1",
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index d3ca47b00d..c6dd023a81 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -10,8 +10,8 @@ import (
// sessionContinuityNoticeFor picks the notice matching what this surface
// actually lost. See the constants in execenv for the full reasoning; the
// question is whether the conversation is still READABLE, not whether it is a
-// chat — an issue's comments and a Slack channel's history both are, a web
-// chat's and a Feishu channel's are not (MUL-5722).
+// chat — an issue's comments, a Slack channel's history, and a web chat's /
+// Feishu's / WeCom's / DingTalk's chat_message transcript all are (MUL-5722).
func sessionContinuityNoticeFor(task Task) string {
if task.ChatSessionID == "" {
return execenv.SessionContinuityNoticeIssue
@@ -19,7 +19,13 @@ func sessionContinuityNoticeFor(task Task) string {
if task.ChatChannelType == execenv.ChannelTypeSlack {
return execenv.SessionContinuityNoticeChannelHistory
}
- // Web chat (no channel type) and every channel Multica cannot read back.
+ // Every other chat session that persists a transcript (web chat, Feishu,
+ // WeCom, DingTalk) reads it back via `multica chat history`; Slack alone
+ // reads the live channel. Only a surface that never stored a transcript
+ // falls through to Unrecoverable — see SurfacePersistsTranscript.
+ if execenv.SurfacePersistsTranscript(task.ChatChannelType) {
+ return execenv.SessionContinuityNoticeChatTranscript
+ }
return execenv.SessionContinuityNoticeUnrecoverable
}
@@ -455,14 +461,20 @@ func buildChatPrompt(task Task) string {
// channel conversation. A web-only chat session gets no such block — its
// history is the Multica chat_session the agent already resumes.
//
- // The history half is Slack-only, and that is a real server constraint, not a
- // simplification: `multica chat history` / `multica chat thread` are served by
- // handlers hardwired to h.SlackHistory (handler/chat_history.go), so on a
- // Feishu session both commands return "no channel integration". Teaching them
- // there would send the agent down a path that always fails. A Feishu run works
- // from the context the inbound enricher already injected, so it gets the
- // awareness statement without the commands, and ChatInThread — which only ever
- // picks between those two commands — does not apply to it (MUL-4899).
+ // The history half: `multica chat history` is served by handler/chat_history.go,
+ // which reads the live channel for Slack and falls back to the stored
+ // chat_message transcript for every other surface — so Slack, Feishu, WeCom
+ // and DingTalk can all read the conversation back. Slack additionally has
+ // `multica chat thread` (thread expansion); the transcript surfaces have no
+ // thread reader, so they get the transcript command without the thread
+ // drill-down (MUL-4899).
+ //
+ // WHERE the conversation lives is therefore per-branch, not shared: only the
+ // unconditional "don't go looking in issues/comments" survives up top. Saying
+ // "its history lives in the channel, NOT in Multica" for every channel type
+ // contradicted the very next line on a transcript surface, which tells the
+ // agent Multica stored it and hands it the command to read it back. An agent
+ // given both reasonably believes the read cannot work and skips it.
//
// The no-narration rule is a THIRD axis and belongs to neither half: it is a
// property of delivering to an IM channel at all, so it is emitted for every
@@ -471,9 +483,9 @@ func buildChatPrompt(task Task) string {
// silently dropped it for Feishu/Lark (GH #6006).
if task.ChatChannelType != "" {
platform := channelDisplayName(task.ChatChannelType)
- 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.\n", platform, platform)
+ fmt.Fprintf(&b, "You are operating inside a %s conversation — not the Multica web app. Never look in Multica issues or comments for this conversation.\n", platform)
if task.ChatChannelType == execenv.ChannelTypeSlack {
- b.WriteString("The message below may be only what triggered you. Read the conversation with:\n")
+ fmt.Fprintf(&b, "This conversation and its history live in %s, NOT in Multica. The message below may be only what triggered you. Read the conversation with:\n", 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 {
@@ -485,8 +497,10 @@ func buildChatPrompt(task Task) string {
// into a chat reply reads as noise (the user reported every reply being
// prefixed with "我先读取…"). Tell the agent to keep them out of its answer.
b.WriteString("Do these reads SILENTLY as an internal step — they are how you gather context, not part of your answer.\n")
+ } else if execenv.SurfacePersistsTranscript(task.ChatChannelType) {
+ fmt.Fprintf(&b, "The conversation happens in %s, and Multica stores a transcript of it. The message below may be only what triggered you — read it back with `multica chat history` when you need earlier context that is not below.\n", platform)
} else {
- fmt.Fprintf(&b, "Work from the context already provided to you below — Multica has no history reader for %s, so there is no command that can fetch more of this conversation. If you genuinely need earlier context that is not here, ask the user for it rather than guessing.\n", platform)
+ fmt.Fprintf(&b, "This conversation and its history live in %s, NOT in Multica, and Multica has no history reader for it. Work from the context already provided to you below — no command can fetch more of this conversation. If you genuinely need earlier context that is not here, ask the user for it rather than guessing.\n", platform)
}
// Scoped to process, not results — a completion confirmation IS the deliverable.
fmt.Fprintf(&b, "Reply to %s with the final outcome only. Do NOT narrate planned or in-progress steps (\"我先读取…\"); completed actions are part of the outcome.\n", platform)
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index 94bc70c943..64429c103a 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -503,11 +503,40 @@ func TestBuildChatPromptChannelAwareness(t *testing.T) {
t.Fatalf("web-only chat prompt should not mention channel history, got:\n%s", out)
}
})
+
+ // A transcript surface must not be told its history is "NOT in Multica" and
+ // then handed a Multica command to read that history. The claim used to be
+ // unconditional, so every Feishu/WeCom/DingTalk prompt carried both halves;
+ // an agent that believes the first one has no reason to run the second.
+ for _, channelType := range []string{
+ execenv.ChannelTypeFeishu,
+ execenv.ChannelTypeWecom,
+ execenv.ChannelTypeDingtalk,
+ } {
+ t.Run(channelType+" transcript prompt does not contradict itself", func(t *testing.T) {
+ out := buildChatPrompt(Task{
+ ChatSessionID: "sess-1",
+ ChatChannelType: channelType,
+ ChatMessage: "刚刚聊到哪了",
+ })
+ if !strings.Contains(out, "multica chat history") {
+ t.Fatalf("transcript surface lost its read-back command\n--- output ---\n%s", out)
+ }
+ if strings.Contains(out, "NOT in Multica") {
+ t.Errorf("transcript surface told its history is NOT in Multica, then told to read it from Multica\n--- output ---\n%s", out)
+ }
+ // The useful half of the original sentence must survive: the agent
+ // still must not go hunting through issues and comments.
+ if !strings.Contains(out, "Never look in Multica issues or comments") {
+ t.Errorf("lost the issues/comments prohibition\n--- output ---\n%s", out)
+ }
+ })
+ }
}
// TestBuildChatPromptNoNarrationOnEveryChannel pins the THIRD axis of the chat
// channel policy: the no-narration delivery rule keys off "is there a channel at
-// all", like the upload axis and unlike the Slack-only history axis.
+// all", like the upload axis and unlike the Slack/Feishu history axis.
//
// Regression guard for GH #6006. #4776 introduced the rule for every channel;
// the MUL-4899 split moved it into the Slack branch along with the read commands
@@ -569,17 +598,18 @@ func TestBuildChatPromptNoNarrationOnEveryChannel(t *testing.T) {
// guidance only where the adapter goes back for the bound attachment AND
// that deployment has the object storage to go back to
// (integrations/wecom/outbound_media.go, cmd/server/router.go).
-// - history: the `chat history` / `chat thread` commands are injected iff the
-// channel is Slack. Those endpoints are hardwired to h.SlackHistory
-// (handler/chat_history.go) — on Feishu they answer "no channel
-// integration", so teaching them there sends the agent down a dead path.
+// - history: `multica chat history` is injected for Slack (live channel) and
+// for every surface that persists a transcript (Feishu, WeCom, DingTalk);
+// `multica chat thread` is Slack-only. handler/chat_history.go reads the
+// live channel for Slack and falls back to the stored chat_message
+// transcript for every other session.
//
-// Three cases prove the axes are separate. Feishu has no upload AND no history,
-// so a single gate cannot express it. WeCom on a deployment that can deliver is
-// the mirror image — upload but no history — which is why the delivery axis
-// cannot be `ChatChannelType != ""`. And the same WeCom chat on a deployment
-// that cannot deliver flips back to text-only, which is why it cannot be the
-// channel type either.
+// Three cases prove the axes are separate. Feishu has no upload AND has
+// transcript history, so a single gate cannot express it. WeCom on a deployment
+// that can deliver is the mirror image — upload AND transcript history — which
+// is why the delivery axis cannot be `ChatChannelType != ""`. And the same WeCom
+// chat on a deployment that cannot deliver flips back to text-only, which is
+// why it cannot be the channel type either.
func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
// Match the IMPERATIVE, not the bare command name. An IM prompt names
// `multica attachment upload` on purpose — to state that it does not apply
@@ -622,13 +652,13 @@ func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
wantPhrases: []string{"Slack", "delivered to Slack as text", "You cannot attach a file to it"},
},
{
- name: "feishu: no upload, no history",
+ name: "feishu: no upload, has transcript history",
channelType: execenv.ChannelTypeFeishu,
wantUpload: false,
- wantHistory: false,
+ wantHistory: true,
wantPhrases: []string{
"Feishu/Lark",
- "no history reader for Feishu/Lark",
+ "read it back with `multica chat history`",
"delivered to Feishu/Lark as text",
"You cannot attach a file to it",
},
@@ -639,16 +669,19 @@ func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
// back for the bound file and this deployment has the storage, so
// the upload guidance applies — with the caveat that the file lands
// as its own message, since an agent told only "files work here"
- // writes "see the chart below" and nothing appears below.
- name: "wecom on a deployment that delivers: upload, no history",
+ // writes "see the chart below" and nothing appears below. WeCom
+ // also persists a transcript, so the history copy is present
+ // alongside the delivery copy.
+ name: "wecom on a deployment that delivers: upload, has history",
channelType: execenv.ChannelTypeWecom,
deliversFiles: true,
wantUpload: true,
- wantHistory: false,
+ wantHistory: true,
wantPhrases: []string{
"WeCom",
"sends it into the WeCom conversation as a separate message",
"there is no way to place it inline",
+ "read it back with `multica chat history`",
},
},
{
@@ -657,15 +690,33 @@ func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
// because an absent field decodes as false. Either way there is no
// last hop, so the agent is told to describe the file in words.
// This row is what fails if the capability is ever inferred from
- // the channel type again.
- name: "wecom on a deployment that cannot deliver: no upload",
+ // the channel type again. History is unaffected by the delivery
+ // axis: WeCom still reads its stored transcript back.
+ name: "wecom on a deployment that cannot deliver: no upload, has history",
channelType: execenv.ChannelTypeWecom,
deliversFiles: false,
wantUpload: false,
- wantHistory: false,
+ wantHistory: true,
wantPhrases: []string{
+ "WeCom",
"delivered to WeCom as text",
"You cannot attach a file to it",
+ "read it back with `multica chat history`",
+ },
+ },
+ {
+ // DingTalk persists to chat_message through the same AppendUserMessage
+ // path, so it gets the transcript reader copy too, not the
+ // "no history reader for dingtalk" else-branch.
+ name: "dingtalk: no upload, has transcript history",
+ channelType: execenv.ChannelTypeDingtalk,
+ wantUpload: false,
+ wantHistory: true,
+ wantPhrases: []string{
+ "DingTalk",
+ "read it back with `multica chat history`",
+ "delivered to DingTalk as text",
+ "You cannot attach a file to it",
},
},
}
@@ -693,9 +744,9 @@ func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
}
}
-// ChatInThread only ever selects between `chat history` and `chat thread`. With
-// no Feishu history reader there is nothing to select between, so the flag must
-// not leak either command into a Feishu prompt even if the server sets it.
+// ChatInThread only ever selects between `chat history` and `chat thread`. Feishu
+// has a transcript reader (`chat history`) but no thread expansion, so the flag
+// must not leak `chat thread` into a Feishu prompt even if the server sets it.
func TestBuildChatPromptFeishuIgnoresChatInThread(t *testing.T) {
out := buildChatPrompt(Task{
ChatSessionID: "sess-1",
@@ -703,10 +754,8 @@ func TestBuildChatPromptFeishuIgnoresChatInThread(t *testing.T) {
ChatInThread: true,
ChatMessage: "hi",
})
- for _, unwanted := range []string{"multica chat thread", "multica chat history"} {
- if strings.Contains(out, unwanted) {
- t.Errorf("feishu prompt must not teach %q (no Feishu history reader exists)\n--- output ---\n%s", unwanted, out)
- }
+ if strings.Contains(out, "multica chat thread") {
+ t.Errorf("feishu prompt must not teach `multica chat thread` (no thread reader)\n--- output ---\n%s", out)
}
}
diff --git a/server/internal/handler/chat_channel_command_visibility_test.go b/server/internal/handler/chat_channel_command_visibility_test.go
index b9e591178c..12934ca046 100644
--- a/server/internal/handler/chat_channel_command_visibility_test.go
+++ b/server/internal/handler/chat_channel_command_visibility_test.go
@@ -13,14 +13,21 @@ import (
)
func insertChatVisibilityMessage(t *testing.T, sessionID, content, messageKind string, channelIngested bool, createdAt time.Time) {
+ t.Helper()
+ insertChatMessageRole(t, sessionID, "user", content, messageKind, channelIngested, createdAt)
+}
+
+// insertChatMessageRole inserts a chat_message row with an explicit role, for
+// tests that need a non-user row (e.g. the transcript read-back role mapping).
+func insertChatMessageRole(t *testing.T, sessionID, role, content, messageKind string, channelIngested bool, createdAt time.Time) {
t.Helper()
if _, err := testPool.Exec(context.Background(), `
INSERT INTO chat_message (
chat_session_id, role, content, message_kind, channel_ingested, created_at
)
- VALUES ($1, 'user', $2, $3, $4, $5)
- `, sessionID, content, messageKind, channelIngested, createdAt); err != nil {
- t.Fatalf("insert chat visibility message %q: %v", content, err)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ `, sessionID, role, content, messageKind, channelIngested, createdAt); err != nil {
+ t.Fatalf("insert chat message role=%q %q: %v", role, content, err)
}
}
diff --git a/server/internal/handler/chat_history.go b/server/internal/handler/chat_history.go
index aea4adc4ad..25facd8e16 100644
--- a/server/internal/handler/chat_history.go
+++ b/server/internal/handler/chat_history.go
@@ -3,9 +3,12 @@ package handler
import (
"context"
"errors"
+ "fmt"
"log/slog"
"net/http"
"strconv"
+ "strings"
+ "time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -14,6 +17,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/slack"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// ChatChannelHistoryReader reads a chat session's bound IM-channel history. The
@@ -44,19 +48,146 @@ type ChatChannelHistoryResponse struct {
// 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`.
+//
+// A chat session that is NOT backed by an IM channel has no channel overview to
+// read — its history is the chat_message table itself (web chat, Feishu). For
+// those, this endpoint falls back to returning that transcript, so the agent can
+// reconstruct the conversation after a lost resume instead of being told nothing
+// is readable (see the continuity-notice split in execenv).
func (h *Handler) GetChatChannelHistory(w http.ResponseWriter, r *http.Request) {
sessionID, ok := h.chatHistorySession(w, r)
if !ok {
return
}
+ var page channel.HistoryPage
+ var err error
if h.SlackHistory == nil {
- h.writeNoChannelIntegration(w)
- return
+ // No Slack integration configured, so the session cannot be Slack-backed:
+ // serve the stored transcript directly. Without this a no-Slack deployment
+ // — the exact one this feature targets — would dead-end on a "no channel
+ // integration" note and never reach the transcript.
+ page, err = h.chatMessageHistory(r, sessionID)
+ } else {
+ page, err = h.SlackHistory.ChannelOverview(r.Context(), sessionID, historyOptionsFrom(r))
+ if errors.Is(err, slack.ErrNoSlackSession) {
+ // Not Slack-backed: read the session's own stored transcript instead.
+ page, err = h.chatMessageHistory(r, sessionID)
+ }
}
- page, err := h.SlackHistory.ChannelOverview(r.Context(), sessionID, historyOptionsFrom(r))
h.respondChatHistory(w, r, sessionID, page, err)
}
+// chatMessageHistory reads a chat session's own stored transcript (chat_message)
+// as a channel.HistoryPage, oldest-first, honoring the shared ?limit / ?before
+// paging contract. It backs `multica chat history` for sessions with no IM
+// channel (web chat, Feishu, WeCom, DingTalk), whose history lives only in
+// Multica — there is no platform to read back. It pages through the same
+// (created_at, id) cursor the frontend's message list uses, so an agent can walk
+// a long session back without re-reading the recent window each time.
+func (h *Handler) chatMessageHistory(r *http.Request, sessionID pgtype.UUID) (channel.HistoryPage, error) {
+ limit := clampTranscriptLimit(parseHistoryLimit(r.URL.Query().Get("limit")))
+ beforeCreatedAt, beforeID := parseTranscriptCursor(r.URL.Query().Get("before"))
+ messages, err := h.Queries.ListChatMessagesPage(r.Context(), db.ListChatMessagesPageParams{
+ ChatSessionID: sessionID,
+ Limit: int32(limit),
+ BeforeCreatedAt: beforeCreatedAt,
+ BeforeID: beforeID,
+ })
+ if err != nil {
+ return channel.HistoryPage{}, err
+ }
+ // ListChatMessagesPage returns newest-first; the channel contract is
+ // oldest-first, so emit the rows in reverse.
+ out := make([]channel.HistoryMessage, 0, len(messages))
+ for i := len(messages) - 1; i >= 0; i-- {
+ m := messages[i]
+ role := channel.HistoryRoleUser
+ if m.Role == "assistant" {
+ role = channel.HistoryRoleAssistant
+ }
+ out = append(out, channel.HistoryMessage{
+ ID: uuidToString(m.ID),
+ Role: role,
+ Text: m.Content,
+ Author: transcriptAuthor(role),
+ TS: m.CreatedAt.Time.UTC().Format(time.RFC3339Nano),
+ })
+ }
+ // Name the platform the transcript came from. HistoryPage.ChannelType is
+ // documented as empty ONLY for a session bound to no channel, so leaving it
+ // unset here would tell a Feishu/WeCom/DingTalk agent it is in a web-only
+ // chat — and would disagree with the empty-read path below, which already
+ // reports the bound platform for the very same session.
+ channelType, err := h.sessionChannelType(r.Context(), sessionID)
+ if err != nil {
+ return channel.HistoryPage{}, fmt.Errorf("%w: %w", errChannelBindingRead, err)
+ }
+ page := channel.HistoryPage{ChannelType: channelType, Messages: out}
+ // Advertise a cursor when a full page came back, so the agent can page to
+ // older messages (mirrors the Slack reader's "more may exist" signal).
+ if len(messages) == limit && len(out) > 0 {
+ oldest := messages[len(messages)-1]
+ page.NextCursor = transcriptCursor(oldest.CreatedAt.Time, oldest.ID)
+ }
+ return page, nil
+}
+
+// Transcript paging bounds, mirroring the Slack reader's clamp so an agent
+// cannot dump a long session's whole transcript into its context.
+const (
+ defaultTranscriptLimit = 30
+ maxTranscriptLimit = 50
+)
+
+func clampTranscriptLimit(n int) int {
+ if n <= 0 {
+ return defaultTranscriptLimit
+ }
+ if n > maxTranscriptLimit {
+ return maxTranscriptLimit
+ }
+ return n
+}
+
+// transcriptCursor encodes a (created_at, id) pair into the opaque ?before
+// cursor the channel contract uses. The transcript pages by the same
+// (created_at, id) tuple as the frontend's message list, so the cursor must
+// carry both halves; RFC3339Nano keeps the timestamp lossless and readable to
+// an agent that inspects it.
+func transcriptCursor(createdAt time.Time, id pgtype.UUID) string {
+ return createdAt.UTC().Format(time.RFC3339Nano) + "|" + uuidToString(id)
+}
+
+// parseTranscriptCursor splits a ?before cursor back into the (created_at, id)
+// tuple ListChatMessagesPage pages by. A missing or malformed cursor returns
+// zero values so the read starts at the most recent messages.
+func parseTranscriptCursor(before string) (pgtype.Timestamptz, pgtype.UUID) {
+ ts, id, ok := strings.Cut(before, "|")
+ if !ok {
+ return pgtype.Timestamptz{}, pgtype.UUID{}
+ }
+ t, err := time.Parse(time.RFC3339Nano, ts)
+ if err != nil {
+ return pgtype.Timestamptz{}, pgtype.UUID{}
+ }
+ uid, err := util.ParseUUID(id)
+ if err != nil {
+ return pgtype.Timestamptz{}, pgtype.UUID{}
+ }
+ return pgtype.Timestamptz{Time: t, Valid: true}, uid
+}
+
+// transcriptAuthor labels a chat_message row with the channel vocabulary
+// ("Bot" / "User") rather than the raw role string, so an agent reading the
+// transcript sees the same author kinds as the Slack path instead of literal
+// "user" / "assistant".
+func transcriptAuthor(role channel.HistoryRole) string {
+ if role == channel.HistoryRoleAssistant {
+ return "Bot"
+ }
+ return "User"
+}
+
// 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
@@ -143,6 +274,12 @@ func (h *Handler) respondChatHistory(w http.ResponseWriter, r *http.Request, ses
})
return
}
+ if errors.Is(err, errChannelBindingRead) {
+ slog.Error("chat session channel binding read failed", append(logger.RequestAttrs(r),
+ "error", err, "chat_session_id", uuidToString(sessionID))...)
+ writeError(w, http.StatusInternalServerError, "failed to read chat session channel binding")
+ return
+ }
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")
@@ -205,6 +342,13 @@ func noHistoryNote(channelType string) string {
return "This conversation is on " + channelType + ", whose backlog this server cannot read. You can see the messages addressed to you in this session, but not the rest of the room."
}
+// errChannelBindingRead marks a transcript read whose MESSAGES were fetched but
+// whose channel binding could not be. It is not an upstream channel failure, so
+// respondChatHistory answers it like the empty-read path answers the same
+// failure — one status code for one cause, whether or not the session happened
+// to have messages.
+var errChannelBindingRead = errors.New("chat session channel binding read failed")
+
// sessionChannelType names the platform behind a session, or "" when there is
// none. Channel-agnostic on purpose: a per-platform lookup here would go blind
// the next time a channel is added, which is exactly how the note above came
diff --git a/server/internal/handler/chat_history_test.go b/server/internal/handler/chat_history_test.go
index b525849a82..f25d83a099 100644
--- a/server/internal/handler/chat_history_test.go
+++ b/server/internal/handler/chat_history_test.go
@@ -5,7 +5,11 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "net/url"
+ "strconv"
+ "strings"
"testing"
+ "time"
"github.com/jackc/pgx/v5/pgtype"
@@ -62,6 +66,26 @@ func newChatHistoryTask(t *testing.T, chatSession bool) string {
return taskID
}
+// newChatHistoryTaskForSession inserts a chat task bound to a specific chat
+// session and returns the task id.
+func newChatHistoryTaskForSession(t *testing.T, sessionID string) string {
+ t.Helper()
+ agentID := createHandlerTestAgent(t, "ChatHistorySessionAgent", []byte("[]"))
+ runtimeID := handlerTestRuntimeID(t)
+ 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)
+ RETURNING id
+ `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("insert chat history task for session: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
+
// 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").
@@ -156,7 +180,11 @@ func TestGetChatThread_ByID(t *testing.T) {
}
}
-func TestGetChatHistory_NoBindingReturnsNote(t *testing.T) {
+// TestGetChatHistory_NoSlackBindingFallsBackToTranscript: a session with no
+// Slack binding (web chat / Feishu) is served from its stored chat_message
+// transcript instead of "no channel integration". A fresh session has no
+// messages, so the fallback returns an empty page with no note.
+func TestGetChatHistory_NoSlackBindingFallsBackToTranscript(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
@@ -171,12 +199,68 @@ func TestGetChatHistory_NoBindingReturnsNote(t *testing.T) {
}
var resp ChatChannelHistoryResponse
_ = json.Unmarshal(w.Body.Bytes(), &resp)
- if resp.Note == "" || len(resp.Messages) != 0 {
- t.Fatalf("expected empty messages + a note, got %+v", resp)
+ if resp.Note != "" || len(resp.Messages) != 0 {
+ t.Fatalf("expected empty transcript with no note, got %+v", resp)
+ }
+}
+
+// TestGetChatHistory_NoSlackBindingReadsStoredTranscript: when the session has
+// no Slack binding but DOES have stored chat_message rows, the fallback returns
+// those messages (oldest-first), so an agent can rebuild a web chat / Feishu
+// conversation instead of being told nothing is readable. Channel-command rows
+// are excluded, matching what the frontend shows.
+func TestGetChatHistory_NoSlackBindingReadsStoredTranscript(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ agentID := createHandlerTestAgent(t, "ChatHistoryTranscriptAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := newChatHistoryTaskForSession(t, sessionID)
+ withSlackHistory(t, &fakeChatHistoryReader{err: slack.ErrNoSlackSession})
+
+ base := time.Date(2026, 8, 10, 1, 0, 0, 0, time.UTC)
+ insertChatVisibilityMessage(t, sessionID, "first user turn", "message", true, base)
+ insertChatMessageRole(t, sessionID, "assistant", "assistant reply", "message", true, base.Add(time.Second))
+ insertChatVisibilityMessage(t, sessionID, "/issue hidden", "channel_command", true, base.Add(2*time.Second))
+ insertChatVisibilityMessage(t, sessionID, "second user turn", "message", true, base.Add(3*time.Second))
+
+ w := httptest.NewRecorder()
+ 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())
+ }
+ var resp ChatChannelHistoryResponse
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp.Note != "" {
+ t.Fatalf("expected no note when a transcript is served, got %q", resp.Note)
+ }
+ if len(resp.Messages) != 3 {
+ t.Fatalf("expected 3 visible messages, got %d: %+v", len(resp.Messages), resp.Messages)
+ }
+ if resp.Messages[0].Text != "first user turn" || resp.Messages[1].Text != "assistant reply" || resp.Messages[2].Text != "second user turn" {
+ t.Fatalf("transcript not oldest-first / channel_command leaked: %+v", resp.Messages)
+ }
+ if resp.Messages[1].Role != channel.HistoryRoleAssistant {
+ t.Errorf("assistant row role = %q, want %q", resp.Messages[1].Role, channel.HistoryRoleAssistant)
+ }
+ // Author uses the channel vocabulary ("Bot" / "User"), not the raw role
+ // string, and TS is the row's RFC3339 creation time.
+ if resp.Messages[0].Author != "User" || resp.Messages[1].Author != "Bot" || resp.Messages[2].Author != "User" {
+ t.Errorf("transcript authors = %q/%q/%q, want User/Bot/User",
+ resp.Messages[0].Author, resp.Messages[1].Author, resp.Messages[2].Author)
+ }
+ if got := resp.Messages[0].TS; got != base.UTC().Format(time.RFC3339Nano) {
+ t.Errorf("transcript TS = %q, want %q", got, base.UTC().Format(time.RFC3339Nano))
}
}
-func TestGetChatHistory_NilReaderReturnsNote(t *testing.T) {
+// TestGetChatHistory_NilReaderServesTranscript: a deployment with no Slack
+// integration has SlackHistory == nil, but a web chat / Feishu / WeCom /
+// DingTalk session's history still lives in chat_message — so the transcript is
+// served instead of a "no channel integration" note. A fresh session has no
+// messages, so the fallback returns an empty page with no note.
+func TestGetChatHistory_NilReaderServesTranscript(t *testing.T) {
if testHandler == nil {
t.Skip("requires test database")
}
@@ -191,8 +275,211 @@ func TestGetChatHistory_NilReaderReturnsNote(t *testing.T) {
}
var resp ChatChannelHistoryResponse
_ = json.Unmarshal(w.Body.Bytes(), &resp)
- if resp.Note == "" {
- t.Fatalf("expected a note when no reader configured, got %+v", resp)
+ if resp.Note != "" || len(resp.Messages) != 0 {
+ t.Fatalf("expected empty transcript with no note when no reader configured, got %+v", resp)
+ }
+}
+
+// TestGetChatHistory_NilReaderServesStoredTranscript is the regression for the
+// no-Slack deployment: SlackHistory == nil AND the session has stored rows. The
+// transcript must still be served — a no-Slack self-host is exactly the target
+// of the transcript read-back feature, and must not dead-end on a
+// "no channel integration" note.
+func TestGetChatHistory_NilReaderServesStoredTranscript(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ agentID := createHandlerTestAgent(t, "ChatHistoryNilReaderAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := newChatHistoryTaskForSession(t, sessionID)
+ withSlackHistory(t, nil)
+
+ base := time.Date(2026, 8, 11, 1, 0, 0, 0, time.UTC)
+ insertChatVisibilityMessage(t, sessionID, "nil reader still reads me", "message", true, base)
+ insertChatMessageRole(t, sessionID, "assistant", "and my reply", "message", true, base.Add(time.Second))
+
+ w := httptest.NewRecorder()
+ 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())
+ }
+ var resp ChatChannelHistoryResponse
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp.Note != "" {
+ t.Fatalf("expected no note when the transcript is served, got %q", resp.Note)
+ }
+ if len(resp.Messages) != 2 || resp.Messages[0].Text != "nil reader still reads me" || resp.Messages[1].Text != "and my reply" {
+ t.Fatalf("nil reader did not serve the stored transcript: %+v", resp.Messages)
+ }
+}
+
+// TestGetChatHistory_TranscriptNamesItsChannel: a served transcript reports the
+// platform the session is bound to. HistoryPage.ChannelType is documented as
+// empty ONLY for a session on no channel, so omitting it here would tell a
+// WeCom/Feishu/DingTalk agent it is in a web-only chat — and would contradict
+// the empty-read path, which already names the platform for the same session.
+// One session, asserted both ways round, so the two paths cannot drift apart.
+func TestGetChatHistory_TranscriptNamesItsChannel(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "ChatHistoryChannelTypeAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := newChatHistoryTaskForSession(t, sessionID)
+ withSlackHistory(t, nil)
+
+ var instID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, status, installer_user_id)
+ VALUES ($1, $2, 'wecom', '{"app_id":"bot-transcript-channel"}'::jsonb, 'active', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&instID); err != nil {
+ t.Fatalf("create installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, instID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+ VALUES ($1, $2, 'wecom', 'GROUP_TRANSCRIPT', 'group')
+ `, sessionID, instID); err != nil {
+ t.Fatalf("bind session: %v", err)
+ }
+
+ // Empty read first: this leg already named the platform before this change.
+ w := httptest.NewRecorder()
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", taskID))
+ var empty ChatChannelHistoryResponse
+ _ = json.Unmarshal(w.Body.Bytes(), &empty)
+
+ base := time.Date(2026, 8, 12, 1, 0, 0, 0, time.UTC)
+ insertChatVisibilityMessage(t, sessionID, "a wecom turn", "message", true, base)
+
+ w = httptest.NewRecorder()
+ 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())
+ }
+ var served ChatChannelHistoryResponse
+ _ = json.Unmarshal(w.Body.Bytes(), &served)
+
+ if len(served.Messages) != 1 {
+ t.Fatalf("expected the stored transcript, got %+v", served.Messages)
+ }
+ if served.ChannelType != "wecom" {
+ t.Errorf("served transcript channel_type = %q, want wecom", served.ChannelType)
+ }
+ if served.ChannelType != empty.ChannelType {
+ t.Errorf("same session reports channel_type %q when it has messages and %q when it does not",
+ served.ChannelType, empty.ChannelType)
+ }
+}
+
+// TestGetChatHistory_WebOnlyTranscriptHasNoChannelType: the other half of the
+// contract — a session bound to nothing must still report an empty channel_type.
+func TestGetChatHistory_WebOnlyTranscriptHasNoChannelType(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ agentID := createHandlerTestAgent(t, "ChatHistoryWebOnlyTypeAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := newChatHistoryTaskForSession(t, sessionID)
+ withSlackHistory(t, nil)
+ insertChatVisibilityMessage(t, sessionID, "a web turn", "message", true, time.Date(2026, 8, 12, 1, 0, 0, 0, time.UTC))
+
+ w := httptest.NewRecorder()
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", taskID))
+
+ var resp ChatChannelHistoryResponse
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp.ChannelType != "" {
+ t.Errorf("web-only session channel_type = %q, want empty", resp.ChannelType)
+ }
+ if len(resp.Messages) != 1 {
+ t.Fatalf("expected the stored transcript, got %+v", resp.Messages)
+ }
+}
+
+// TestGetChatHistory_TranscriptPagesWithoutDuplicatesOrGaps: the transcript
+// honors the ?limit / ?before paging contract — walking back page by page with
+// next_cursor yields every stored message exactly once, and a full page
+// advertises a cursor while a short page does not.
+func TestGetChatHistory_TranscriptPagesWithoutDuplicatesOrGaps(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ agentID := createHandlerTestAgent(t, "ChatHistoryPagingAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := newChatHistoryTaskForSession(t, sessionID)
+ withSlackHistory(t, nil)
+
+ base := time.Date(2026, 8, 11, 2, 0, 0, 0, time.UTC)
+ const total = 7
+ for i := 0; i < total; i++ {
+ insertChatVisibilityMessage(t, sessionID, "msg "+strconv.Itoa(i), "message", true, base.Add(time.Duration(i)*time.Second))
+ }
+
+ seen := make([]string, 0, total)
+ before := ""
+ for page := 0; ; page++ {
+ target := "/api/chat/history?limit=3"
+ if before != "" {
+ target += "&before=" + url.QueryEscape(before)
+ }
+ w := httptest.NewRecorder()
+ testHandler.GetChatChannelHistory(w, taskActorReq(target, taskID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("page %d status = %d, want 200: %s", page, w.Code, w.Body.String())
+ }
+ var resp ChatChannelHistoryResponse
+ _ = json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp.Note != "" {
+ t.Fatalf("page %d unexpected note %q", page, resp.Note)
+ }
+ // Within a page the transcript is oldest-first.
+ prev := -1
+ for _, m := range resp.Messages {
+ seen = append(seen, m.Text)
+ n, _ := strconv.Atoi(strings.TrimPrefix(m.Text, "msg "))
+ if n <= prev {
+ t.Fatalf("page %d not oldest-first: %v", page, resp.Messages)
+ }
+ prev = n
+ }
+ if len(resp.Messages) < 3 {
+ // A short page is the last one: no cursor advertised.
+ if resp.NextCursor != "" {
+ t.Fatalf("last page advertised a cursor: %q", resp.NextCursor)
+ }
+ break
+ }
+ if resp.NextCursor == "" {
+ t.Fatalf("full page %d advertised no cursor", page)
+ }
+ before = resp.NextCursor
+ }
+
+ // The union of all pages is exactly the full transcript: no duplicates, no
+ // gaps. (Across pages the sequence is NOT monotonic — paging to older
+ // messages means each later page is older than the previous one.)
+ if len(seen) != total {
+ t.Fatalf("paged %d messages, want %d: %v", len(seen), total, seen)
+ }
+ dup := map[string]bool{}
+ for _, text := range seen {
+ if dup[text] {
+ t.Fatalf("duplicate message %q across pages: %v", text, seen)
+ }
+ dup[text] = true
+ }
+ for i := 0; i < total; i++ {
+ want := "msg " + strconv.Itoa(i)
+ if !dup[want] {
+ t.Fatalf("missing %q across pages: %v", want, seen)
+ }
}
}