Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7074 fix(channels): derive chat titles from the current user instruction (#8059)
YYClaw7b60248d7ec5
diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.goindex b1df168cce..bf8dd62172 100644--- a/server/internal/handler/channel_new_e2e_test.go+++ b/server/internal/handler/channel_new_e2e_test.go@@ -704,6 +704,11 @@ func TestSlackNativeClearCommandKeepsChatAndAdvancesContextAtomically(t *testingif sessionID == "" || routeRevision != 1 || contextRevision != 2 || content != "/issue investigate native clear" || messageKind != "message" || !forceFresh || !boundaryPending || taskCount != 1 || deliveryCount != 1 || routeCount != 1 || !dedupProcessed {t.Fatalf("native /clear message state: session=%s route=%d context=%d content=%q kind=%q fresh=%t pending=%t tasks=%d deliveries=%d routes=%d dedup=%t", sessionID, routeRevision, contextRevision, content, messageKind, forceFresh, boundaryPending, taskCount, deliveryCount, routeCount, dedupProcessed)}+ var title string+ dbfx.QueryRow(t, `SELECT title FROM chat_session WHERE id = $1`, sessionID).Scan(&title)+ if title != "/issue investigate native cle…" {+ t.Fatalf("native /clear first-turn title = %q, want the literal command body", title)+ }if err := starter.ClearSlackDMContext(ctx, installation, util.MustParseUUID(testUserID), slackapi.SlashCommand{ChannelID: "D-native-clear",@@ -741,6 +746,10 @@ func TestSlackNativeClearCommandKeepsChatAndAdvancesContextAtomically(t *testingif currentSessionID != sessionID || currentContextRevision != 3 || !currentBoundaryPending || currentTaskCount != 1 || currentMessageCount != 1 || currentRouteCount != 1 || !bareDedupProcessed {t.Fatalf("bare native /clear state: session=%s/%s context=%d pending=%t tasks=%d messages=%d routes=%d dedup=%t", currentSessionID, sessionID, currentContextRevision, currentBoundaryPending, currentTaskCount, currentMessageCount, currentRouteCount, bareDedupProcessed)}+ dbfx.QueryRow(t, `SELECT title FROM chat_session WHERE id = $1`, sessionID).Scan(&title)+ if title != "/issue investigate native cle…" {+ t.Fatalf("bare native /clear changed the existing title to %q", title)+ }}func runChannelClearCommandE2E(t *testing.T, channelType channel.Type, text, commandText string, adapterForceFresh bool, followUpText, wantStoredText string, wantForceFresh bool, wantPriorSession, wantPriorWorkDir string) {diff --git a/server/internal/handler/channel_title_regression_test.go b/server/internal/handler/channel_title_regression_test.gonew file mode 100644index 0000000000..8cf1d8ad39--- /dev/null+++ b/server/internal/handler/channel_title_regression_test.go@@ -0,0 +1,76 @@+package handler++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/llm"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestChannelChatTitle_UsesCurrentSourceForLLMAndPublishesAfterCAS(t *testing.T) {+ requireDB(t)+ fx := testutil.New(testPool, testWorkspaceID, testUserID)+ const current = "Investigate the login redirect"+ sessionID := parseUUID(fx.ChatSession(t, uuidToString(chatTitleTestAgentID(t)), testutil.Cols{"title": current}))+ requests := make(chan string, 1)+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var payload struct {+ Messages []struct {+ Role string `json:"role"`+ Content string `json:"content"`+ } `json:"messages"`+ }+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Error(err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ for _, message := range payload.Messages {+ if message.Role == "user" {+ requests <- message.Content+ }+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"Login redirect investigation"},"finish_reason":"stop"}]}`)+ }))+ defer upstream.Close()+ h := *testHandler+ h.Bus = events.New()+ h.LLM = llm.New(llm.Config{APIKey: "test-key", BaseURL: upstream.URL})+ updates := make(chan protocol.ChatSessionUpdatedPayload, 1)+ h.Bus.Subscribe(protocol.EventChatSessionUpdated, func(event events.Event) {+ payload, ok := event.Payload.(protocol.ChatSessionUpdatedPayload)+ if ok && payload.ChatSessionID == uuidToString(sessionID) {+ stored, err := h.Queries.GetChatSession(context.Background(), sessionID)+ if err != nil || stored.Title != payload.Title {+ t.Errorf("title event preceded committed CAS: stored=%q event=%q err=%v", stored.Title, payload.Title, err)+ }+ updates <- payload+ }+ })+ h.GenerateChannelChatTitle(parseUUID(testWorkspaceID), parseUUID(testUserID), sessionID, current, current)+ select {+ case source := <-requests:+ if source != current {+ t.Fatalf("LLM user source = %q, want exact current turn %q", source, current)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("channel title hook did not call the LLM")+ }+ select {+ case payload := <-updates:+ if payload.Title != "Login redirect investigation" {+ t.Fatalf("channel title update = %+v", payload)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("channel title hook did not publish the committed title")+ }+}diff --git a/server/internal/integrations/channel/engine/channel_title_adapters_db_test.go b/server/internal/integrations/channel/engine/channel_title_adapters_db_test.gonew file mode 100644index 0000000000..6f173c9699--- /dev/null+++ b/server/internal/integrations/channel/engine/channel_title_adapters_db_test.go@@ -0,0 +1,93 @@+package engine_test++import (+ "context"+ "os"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/integrations/dingtalk"+ "github.com/multica-ai/multica/server/internal/integrations/lark"+ "github.com/multica-ai/multica/server/internal/integrations/slack"+ "github.com/multica-ai/multica/server/internal/integrations/telegram"+ "github.com/multica-ai/multica/server/internal/integrations/wecom"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Every adapter must forward the current instruction on the /new path. Testing+// the real binders also covers Slack, whose session dependency is concrete.+func TestChannelStartTitleCommandMappingDB(t *testing.T) {+ ctx := context.Background()+ dsn := os.Getenv("DATABASE_URL")+ if dsn == "" {+ t.Skip("DATABASE_URL is required for the channel title integration test")+ }+ pool, err := pgxpool.New(ctx, dsn)+ if err != nil {+ t.Fatal(err)+ }+ defer pool.Close()+ if err := pool.Ping(ctx); err != nil {+ t.Fatal(err)+ }+ for _, platform := range []string{"feishu", "telegram", "dingtalk", "slack", "wecom"} {+ t.Run(platform, func(t *testing.T) {+ fx := dbfx.New(pool, "", "")+ suffix := uuid.NewString()+ fx.UserID = fx.User(t, "Title tester", "title-"+suffix+"@multica.test")+ fx.WorkspaceID = fx.Workspace(t, "Title workspace", "title-"+suffix)+ fx.Member(t, fx.WorkspaceID, fx.UserID, "owner")+ agent := fx.Agent(t, "Title agent", "")+ installType := platform+ if installType == "feishu" {+ installType = "lark"+ }+ installation := fx.Insert(t, "channel_installation", dbfx.Cols{"workspace_id": fx.WorkspaceID, "agent_id": agent, "channel_type": installType, "config": dbfx.Raw("'{}'::jsonb"), "status": "active", "installer_user_id": fx.UserID})+ fx.Cleanup(t, `DELETE FROM chat_session WHERE workspace_id=$1`, fx.WorkspaceID)+ fx.Cleanup(t, `DELETE FROM channel_chat_session_binding WHERE installation_id=$1`, installation)+ fx.Cleanup(t, `DELETE FROM channel_chat_context_generation WHERE chat_session_id IN (SELECT id FROM chat_session WHERE workspace_id=$1)`, fx.WorkspaceID)+ fx.Cleanup(t, `DELETE FROM chat_message WHERE chat_session_id IN (SELECT id FROM chat_session WHERE workspace_id=$1)`, fx.WorkspaceID)+ asUUID := func(s string) pgtype.UUID {+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ t.Fatal(err)+ }+ return u+ }+ q := db.New(pool)+ session := engine.NewChatSession(q, pool, channel.Type(platform), engine.SessionTitles{})+ var binder engine.SessionBinder+ switch platform {+ case "feishu":+ binder = lark.NewFeishuResolverSet(nil, session, nil, nil, nil, nil).Session+ case "telegram":+ binder = telegram.NewTelegramResolverSet(q, pool, nil, nil).Session+ case "dingtalk":+ binder = dingtalk.NewDingTalkResolverSet(q, pool, nil, nil, nil, nil).Session+ case "slack":+ binder = slack.NewSlackResolverSet(q, pool, nil, nil, nil).Session+ case "wecom":+ binder = wecom.NewResolverSet(nil, session, nil, nil).Session+ }+ msg := channel.InboundMessage{MessageID: "current", CommandText: "Current instruction", Text: "<quoted_message>\nHistorical subject\n</quoted_message>\n\nCurrent instruction", Source: channel.Source{ChannelType: channel.Type(platform), ChatType: channel.ChatTypeP2P, ChatID: suffix, SenderID: "sender"}}+ result, err := binder.StartSession(ctx, engine.StartSessionParams{Installation: engine.ResolvedInstallation{ID: asUUID(installation), WorkspaceID: asUUID(fx.WorkspaceID), AgentID: asUUID(agent)}, Creator: asUUID(fx.UserID), Sender: asUUID(fx.UserID), Message: msg, PersistMessage: true})+ if err != nil {+ t.Fatal(err)+ }+ var title, body string+ fx.QueryRow(t, `SELECT s.title,m.content FROM chat_session s JOIN chat_message m ON m.chat_session_id=s.id WHERE s.id=$1`, result.SessionID).Scan(&title, &body)+ if title != "Current instruction" || result.Append.InitialTitle != title {+ t.Errorf("title DB=%q result=%q, want current instruction", title, result.Append.InitialTitle)+ }+ if body != msg.Text {+ t.Errorf("persisted context=%q, want %q", body, msg.Text)+ }+ })+ }+}diff --git a/server/internal/integrations/channel/engine/channel_title_regression_test.go b/server/internal/integrations/channel/engine/channel_title_regression_test.gonew file mode 100644index 0000000000..321dc5108f--- /dev/null+++ b/server/internal/integrations/channel/engine/channel_title_regression_test.go@@ -0,0 +1,58 @@+package engine++import (+ "context"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "testing"+)++func TestRouterTitleUsesCurrentInstruction(t *testing.T) {+ for _, tc := range []struct {+ name, body, command, want string+ start, fresh bool+ }{+ {name: "quoted reply", body: "<quoted_message>\nOld subject\n</quoted_message>\n\nCompare alternatives", command: "Compare alternatives", want: "Compare alternatives"},+ {name: "recent context", body: "<recent_context>\nOld subject\n</recent_context>\n\nCompare alternatives", command: "Compare alternatives", want: "Compare alternatives"},+ {name: "consumed clear", body: "<quoted_message>\nOld subject\n</quoted_message>\n\nCompare alternatives", command: "/clear Compare alternatives", fresh: true, want: "Compare alternatives"},+ {name: "new chat", body: "<quoted_message>\nOld subject\n</quoted_message>\n\nCompare alternatives", command: "/new Compare alternatives", start: true, want: "Compare alternatives"},+ {name: "new body literal clear", body: "<quoted_message>\nOld subject\n</quoted_message>\n\n/clear literal", command: "/new /clear literal", start: true, want: "/clear literal"},+ {name: "missing command", body: "Compare alternatives", want: "Compare alternatives"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ h := newHarness(t)+ h.binder.appendResult.InitialTitle = tc.want+ msg := p2pMessage(t)+ msg.Text = tc.body+ msg.CommandText = tc.command+ msg.ForceFresh = tc.fresh+ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatal(err)+ }+ h.lifecycle.mu.Lock()+ defer h.lifecycle.mu.Unlock()+ if len(h.lifecycle.generatedSourceTexts) != 1 || h.lifecycle.generatedSourceTexts[0] != tc.want {+ t.Errorf("LLM title source = %q, want only current instruction %q", h.lifecycle.generatedSourceTexts, tc.want)+ }+ })+ }+}++func TestContextualMediaOpeningWaitsForFilenameTitle(t *testing.T) {+ f := newFake()+ session := newTestSession(f)+ body := "<quoted_message>\nHistorical subject\n</quoted_message>\n\n[Image]"+ result, err := session.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Sender: uid(7), Body: body, CommandText: "[Image]", MessageID: "image-current", MediaPendingSeconds: 45})+ if err != nil {+ t.Fatal(err)+ }+ if result.InitialTitle != "" {+ t.Fatalf("context initialized title before media metadata: %q", result.InitialTitle)+ }+ bound, err := session.BindMediaRefsWithResult(context.Background(), BindMediaInput{MessageID: result.MessageID, SessionID: uid(1), WorkspaceID: uid(9), Sender: uid(7), Body: body, MediaRefs: []channel.MediaRef{{Type: channel.MsgTypeImage, StorageKey: "image-key", StorageURL: "https://cdn.example.test/image-key", Filename: "incident screenshot.png", MimeType: "image/png"}}})+ if err != nil {+ t.Fatal(err)+ }+ if f.initializedMediaTitle != "incident screenshot.png" || bound.InitialTitle != "incident screenshot.png" || bound.TitleSource != "incident screenshot.png" {+ t.Fatalf("media title stored=%q result=%+v", f.initializedMediaTitle, bound)+ }+}diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 18d2b1c595..bec4027913 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -192,8 +192,19 @@ var ErrNoResolverSet = errors.New("channel router: no resolver set for channel t// needs-binding, …) are not errors.func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {// Preserve the user's original normalized text before any shared command- // rewrites. Session binders pass this source to command classifiers while- // Text remains the agent-readable body.+ // rewrites. Session binders pass this source to command classifiers and to+ // first-title selection (chatTitleSource) while Text remains the+ // agent-readable body.+ //+ // INVARIANT: an adapter that enriches Text with content the member did not+ // type — a quoted reply, recent group history — MUST set CommandText itself+ // before its message reaches Router. This fallback assigns the ALREADY+ // enriched Text, so an enriching adapter that leaves CommandText empty+ // silently reinstates #8058 (the enrichment prefix becomes the Chat title)+ // while every title test stays green. lark and telegram are today's only+ // enriching adapters and both comply: lark maps the decoder's+ // pre-enrichment CommandBody, telegram the cleaned instruction captured+ // before enrichWithQuotedHumanMessage.if msg.CommandText == "" {msg.CommandText = msg.Text}@@ -664,7 +675,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channeif !startChat && !appendRes.BecameVisible {r.lifecycle.ChannelChatTitleInitialized(inst.WorkspaceID, sessionCreator, sessionID, appendRes.InitialTitle)}- r.lifecycle.GenerateChannelChatTitle(inst.WorkspaceID, sessionCreator, sessionID, appendRes.InitialTitle, msg.Text)+ r.lifecycle.GenerateChannelChatTitle(inst.WorkspaceID, sessionCreator, sessionID, appendRes.InitialTitle, chatTitleSource(msg.Text, msg.CommandText, !startChat && msg.ForceFresh))}return res, postAppendFinalize, nil}diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 3f1cdfdb4b..7485b963a9 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -424,8 +424,10 @@ type fakeReader struct {}type fakeChannelChatLifecycle struct {- mu sync.Mutex- started []ChannelChatStartedEvent+ mu sync.Mutex+ started []ChannelChatStartedEvent+ generatedSourceTexts []string+ initializedTitles []string}func (f *fakeChannelChatLifecycle) ChannelChatStarted(event ChannelChatStartedEvent) {@@ -433,9 +435,15 @@ func (f *fakeChannelChatLifecycle) ChannelChatStarted(event ChannelChatStartedEvdefer f.mu.Unlock()f.started = append(f.started, event)}-func (*fakeChannelChatLifecycle) ChannelChatTitleInitialized(pgtype.UUID, pgtype.UUID, pgtype.UUID, string) {+func (f *fakeChannelChatLifecycle) ChannelChatTitleInitialized(_ pgtype.UUID, _ pgtype.UUID, _ pgtype.UUID, title string) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.initializedTitles = append(f.initializedTitles, title)}-func (*fakeChannelChatLifecycle) GenerateChannelChatTitle(pgtype.UUID, pgtype.UUID, pgtype.UUID, string, string) {+func (f *fakeChannelChatLifecycle) GenerateChannelChatTitle(_ pgtype.UUID, _ pgtype.UUID, _ pgtype.UUID, _ string, source string) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.generatedSourceTexts = append(f.generatedSourceTexts, source)}func (f *fakeReader) GetChatSession(_ context.Context, _ pgtype.UUID) (db.ChatSession, error) {diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex c997115b25..e79ac91128 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -359,9 +359,19 @@ func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSess// AppendInput is the channel-agnostic input for AppendUserMessage. Body is the// full stored text (including any platform enrichment); CommandText is the-// user's OWN typed text used for `/issue` parsing (empty falls back to Body) —-// the adapter supplies it because enrichment is platform-specific. ClaimToken-// is the dedup owner-fence: when valid, the Mark runs inside this method's tx.+// user's OWN typed text, used for `/issue` parsing AND for first-title+// selection (empty falls back to Body) — the adapter supplies it because+// enrichment is platform-specific. ClaimToken is the dedup owner-fence: when+// valid, the Mark runs inside this method's tx.+//+// With ForceFresh set, CommandText must carry the WHOLE original source+// INCLUDING the leading /clear directive rather than the bare directive:+// chatTitleSource consumes exactly one already-applied directive from it, so a+// bare "/clear" leaves nothing behind and the Chat silently keeps an empty+// title. Router-driven channels satisfy this because Router never rewrites+// CommandText for /clear; an adapter handling a native slash command has+// already split the two and must rejoin them (slackDMControlStarter's+// ClearSlackDMContext is the one such caller today).//// MessageID and ThreadID are the REAL platform message id and thread id of this// trigger — the outbound reply target recorded on the binding (last_message_id /@@ -392,8 +402,12 @@ type StartSessionInput struct {EnsureSessionInput// Initiator is the authenticated sender of the /new command. Sender in the// embedded EnsureSessionInput remains the owner of the newly created Chat.- Initiator pgtype.UUID- Body string+ Initiator pgtype.UUID+ Body string+ // CommandText is the current member-authored instruction before adapter+ // context enrichment. It is used only for the initial Chat title; Body+ // remains the canonical persisted/agent-visible content.+ CommandText stringMessageID stringDedupMessageID stringThreadID string@@ -468,7 +482,7 @@ func (s *ChatSession) StartSession(ctx context.Context, in StartSessionInput) (Stitle := ""if in.PersistMessage {- title = deriveFirstMessageTitle(in.Body, in.MediaPendingSeconds > 0)+ title = deriveFirstMessageTitle(chatTitleSource(in.Body, in.CommandText, false), in.MediaPendingSeconds > 0)}session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{ID: dbid.NewV7(), WorkspaceID: in.WorkspaceID, AgentID: in.AgentID,@@ -645,7 +659,7 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (ApbecameVisible := cmd == nil && !hadPublicUserMessage && !currentSession.ExplicitlyCreatedAt.ValidinitializedTitle := ""if cmd == nil {- title := deriveFirstMessageTitle(in.Body, in.MediaPendingSeconds > 0)+ title := deriveFirstMessageTitle(chatTitleSource(in.Body, in.CommandText, in.ForceFresh), in.MediaPendingSeconds > 0)if becameVisible {if _, err := qtx.ReplaceImplicitChatSessionTitle(ctx, db.ReplaceImplicitChatSessionTitleParams{ID: in.SessionID, Title: title}); err != nil {return AppendResult{}, fmt.Errorf("replace implicit chat title: %w", err)diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.goindex e51df878f2..a2ef6e7c11 100644--- a/server/internal/integrations/channel/engine/session_test.go+++ b/server/internal/integrations/channel/engine/session_test.go@@ -410,6 +410,9 @@ func TestStartSessionCreatesExplicitEmptyGeneration(t *testing.T) {if !result.SessionID.Valid || len(f.messages) != 0 {t.Fatalf("session=%v messages=%v", result.SessionID.Valid, f.messages)}+ if f.lastSessionCreate.Title != "" || result.Append.InitialTitle != "" {+ t.Fatalf("empty Chat title = stored %q result %q, want empty", f.lastSessionCreate.Title, result.Append.InitialTitle)+ }if f.createdSessions != 1 || f.markRows != 1 {t.Fatalf("created=%d markRows=%d", f.createdSessions, f.markRows)}@@ -434,6 +437,9 @@ func TestStartSessionBodyCreatesOrdinaryFirstMessageAndTitle(t *testing.T) {if len(f.messages) != 1 || f.messages[0] != "# 发布检查" {t.Fatalf("messages=%v", f.messages)}+ if f.lastSessionCreate.Title != "发布检查" || result.Append.InitialTitle != "发布检查" {+ t.Fatalf("first-turn title = stored %q result %q, want body-derived fallback", f.lastSessionCreate.Title, result.Append.InitialTitle)+ }if f.lastCreate.MessageKind.Valid {t.Fatalf("message kind=%q, want ordinary", f.lastCreate.MessageKind.String)}diff --git a/server/internal/integrations/channel/engine/title.go b/server/internal/integrations/channel/engine/title.goindex 65cba8c982..919c2d524f 100644--- a/server/internal/integrations/channel/engine/title.go+++ b/server/internal/integrations/channel/engine/title.go@@ -13,6 +13,22 @@ func DeriveChatTitle(body string) string {return chattitle.Derive(body)}+// chatTitleSource prefers the user's own typed text over the contextual body.+// CommandText excludes quoted/recent context but deliberately retains /clear+// for command classification. Only an already-consumed fresh directive is+// removed here; a /new body beginning with /clear remains ordinary text.+func chatTitleSource(body, commandText string, consumedFresh bool) string {+ if strings.TrimSpace(commandText) != "" {+ if consumedFresh {+ if current, ok := ParseFreshSessionCommand(commandText); ok {+ return current+ }+ }+ return commandText+ }+ return body+}+func deriveFirstMessageTitle(body string, hasMedia bool) string {if hasMedia {body = withoutMediaPlaceholderLines(body)diff --git a/server/internal/integrations/channel/engine/title_test.go b/server/internal/integrations/channel/engine/title_test.goindex 22d82cc2ea..6c106bf57c 100644--- a/server/internal/integrations/channel/engine/title_test.go+++ b/server/internal/integrations/channel/engine/title_test.go@@ -34,3 +34,30 @@ func TestDeriveFirstMessageTitle_MediaPlaceholderWaitsForFilename(t *testing.T)t.Fatalf("literal text title = %q, want the user-authored text", got)}}++func TestChatTitleSourceConsumesOnlyAppliedFreshDirective(t *testing.T) {+ for _, tc := range []struct {+ name, body, command, want string+ fresh bool+ }{+ {"enriched fresh", "<quoted_message>history</quoted_message>\n\nanswer", "/clear answer", "answer", true},+ {"nested fresh", "/clear answer", "/clear /clear answer", "/clear answer", true},+ {"new body is literal", "<recent_context>history</recent_context>\n\n/clear answer", "/clear answer", "/clear answer", false},+ {"native fresh", "<recent_context>history</recent_context>\n\nanswer", "answer", "answer", true},+ {"media fresh", "[Image]", "/clear", "", true},+ // Known gap, NOT desired behavior: with no current source the selector+ // falls back to Body, which is the enriched text this fix exists to keep+ // out of titles. Still reachable when a directive consumes the whole+ // instruction and only media follows; #8058 records it as out of scope.+ // Do not read this row as a contract — a later fix that returns "" here+ // and lets the attachment path name the Chat should change this+ // expectation rather than work around it.+ {"missing current text", "body fallback", " ", "body fallback", true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := chatTitleSource(tc.body, tc.command, tc.fresh); got != tc.want {+ t.Fatalf("title source = %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.goindex e87b03a317..e9ce7db43a 100644--- a/server/internal/integrations/dingtalk/resolvers.go+++ b/server/internal/integrations/dingtalk/resolvers.go@@ -329,7 +329,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionPBindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,},Initiator: p.Sender,- Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,+ Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,BeforeCommit: p.BeforeCommit,diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.goindex 23d502523c..be458fd587 100644--- a/server/internal/integrations/dingtalk/resolvers_test.go+++ b/server/internal/integrations/dingtalk/resolvers_test.go@@ -150,7 +150,7 @@ func TestSessionBinder_StartSessionCarriesDingTalkRouteAndFirstTurn(t *testing.TCreator: pgtype.UUID{Bytes: [16]byte{4}, Valid: true},Sender: pgtype.UUID{Bytes: [16]byte{5}, Valid: true},Message: channel.InboundMessage{- MessageID: "m1", Text: "first turn",+ MessageID: "m1", Text: "first turn", CommandText: "current instruction",Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup, ThreadID: "thread-1"},},PersistMessage: true,@@ -159,7 +159,7 @@ func TestSessionBinder_StartSessionCarriesDingTalkRouteAndFirstTurn(t *testing.Tt.Fatalf("StartSession: %v", err)}got := capture.start- if got.BindingKey != "cid-platform" || got.MessageID != "m1" || got.ThreadID != "thread-1" || got.Body != "first turn" || !got.PersistMessage {+ if got.BindingKey != "cid-platform" || got.MessageID != "m1" || got.ThreadID != "thread-1" || got.Body != "first turn" || got.CommandText != "current instruction" || !got.PersistMessage {t.Fatalf("start mapping wrong: %+v", got)}if got.Sender != (pgtype.UUID{Bytes: [16]byte{4}, Valid: true}) || got.Initiator != (pgtype.UUID{Bytes: [16]byte{5}, Valid: true}) {diff --git a/server/internal/integrations/lark/channel_title_db_test.go b/server/internal/integrations/lark/channel_title_db_test.gonew file mode 100644index 0000000000..644759dd3e--- /dev/null+++ b/server/internal/integrations/lark/channel_title_db_test.go@@ -0,0 +1,118 @@+package lark++import (+ "context"+ "os"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// This regression uses the existing Feishu producer format. It must not depend+// on a quote-format migration to keep context out of a user's Chat title.+func TestFeishuChannelTitleUsesCurrentInstructionDB(t *testing.T) {+ ctx := context.Background()+ dsn := os.Getenv("DATABASE_URL")+ if dsn == "" {+ t.Skip("DATABASE_URL is required for the channel title integration test")+ }+ pool, err := pgxpool.New(ctx, dsn)+ if err != nil {+ t.Fatal(err)+ }+ defer pool.Close()+ if err := pool.Ping(ctx); err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ name string+ start, recent, fresh bool+ command, want string+ }{+ {name: "quoted first turn", command: "Compare current alternatives", want: "Compare current alternatives"},+ {name: "recent group first turn", recent: true, command: "Compare current alternatives", want: "Compare current alternatives"},+ {name: "new chat with quote", start: true, command: "/new Compare current alternatives", want: "Compare current alternatives"},+ {name: "consumed clear with quote", fresh: true, command: "/clear Compare current alternatives", want: "Compare current alternatives"},+ {name: "new body keeps literal clear", start: true, command: "/new /clear literal instruction", want: "/clear literal instruction"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ fx := dbfx.New(pool, "", "")+ suffix := uuid.NewString()+ fx.UserID = fx.User(t, "Title tester", "title-"+suffix+"@multica.test")+ fx.WorkspaceID = fx.Workspace(t, "Title workspace", "title-"+suffix)+ fx.Member(t, fx.WorkspaceID, fx.UserID, "owner")+ agentID := fx.Agent(t, "Title agent", "")+ installationID := fx.Insert(t, "channel_installation", dbfx.Cols{"workspace_id": fx.WorkspaceID, "agent_id": agentID, "channel_type": "lark", "config": dbfx.Raw("'{}'::jsonb"), "status": "active", "installer_user_id": fx.UserID})+ // Sessions/messages are created by the production binder, so clean their+ // workspace scope before the fixture removes the installation and owner.+ fx.Cleanup(t, `DELETE FROM chat_session WHERE workspace_id = $1`, fx.WorkspaceID)+ fx.Cleanup(t, `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)+ fx.Cleanup(t, `DELETE FROM channel_chat_context_generation WHERE chat_session_id IN (SELECT id FROM chat_session WHERE workspace_id = $1)`, fx.WorkspaceID)+ fx.Cleanup(t, `DELETE FROM chat_message WHERE chat_session_id IN (SELECT id FROM chat_session WHERE workspace_id = $1)`, fx.WorkspaceID)+ asUUID := func(s string) pgtype.UUID {+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ t.Fatal(err)+ }+ return u+ }+ inst := engine.ResolvedInstallation{ID: asUUID(installationID), WorkspaceID: asUUID(fx.WorkspaceID), AgentID: asUUID(agentID)}+ sender := asUUID(fx.UserID)+ fake := newEnricherFake()+ fake.byID["parent"] = []LarkMessage{textMsg("parent", "other", "Old unrelated discussion", "1000")}+ fake.byChat[ChatID(suffix)] = []LarkMessage{textMsg("recent", "other", "Old unrelated discussion", "1000")}+ in := InboundMessage{MessageID: "current", MessageType: "text", ChatID: ChatID(suffix), ChatType: ChatTypeGroup, SenderOpenID: "current-user", Body: tc.command, CommandBody: tc.command, AddressedToBot: true}+ cfg := InboundEnricherConfig{}+ if tc.recent {+ cfg.RecentContextSize = 10+ } else {+ in.ParentID = "parent"+ }+ msg := channelMessageFromLark(enrich(t, fake, in, cfg))+ if !strings.Contains(msg.Text, "Old unrelated discussion") || msg.CommandText != tc.command {+ t.Fatalf("producer lost context/source: %+v", msg)+ }+ // Router consumes /new in CommandText before calling StartSession. Text+ // has already been enriched by the real adapter and must remain intact.+ if tc.start {+ msg.CommandText, _ = engine.ParseNewChatCommand(msg.CommandText)+ }+ binder := &feishuSessionBinder{session: engine.NewChatSession(db.New(pool), pool, channel.TypeFeishu, engine.SessionTitles{})}+ var sessionID pgtype.UUID+ var result engine.AppendResult+ if tc.start {+ started, e := binder.StartSession(ctx, engine.StartSessionParams{Installation: inst, Creator: sender, Sender: sender, Message: msg, PersistMessage: true})+ if e != nil {+ t.Fatal(e)+ }+ sessionID = started.SessionID+ result = started.Append+ } else {+ sessionID, err = binder.EnsureSession(ctx, engine.EnsureSessionParams{Installation: inst, Sender: sender, Message: msg})+ if err != nil {+ t.Fatal(err)+ }+ result, err = binder.AppendMessage(ctx, engine.AppendParams{InstallationID: inst.ID, Sender: sender, SessionID: sessionID, Message: msg})+ if err != nil {+ t.Fatal(err)+ }+ }+ var title, body string+ fx.QueryRow(t, `SELECT s.title,m.content FROM chat_session s JOIN chat_message m ON m.chat_session_id=s.id WHERE s.id=$1`, sessionID).Scan(&title, &body)+ if body != msg.Text {+ t.Errorf("persisted agent context changed: got %q want %q", body, msg.Text)+ }+ if title != tc.want || result.InitialTitle != tc.want {+ t.Errorf("title = DB %q result %q; want current instruction %q", title, result.InitialTitle, tc.want)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.goindex 09a563637a..fe46b62354 100644--- a/server/internal/integrations/lark/feishu_resolvers.go+++ b/server/internal/integrations/lark/feishu_resolvers.go@@ -174,7 +174,7 @@ func (r *feishuSessionBinder) StartSession(ctx context.Context, p engine.StartSeBindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,},Initiator: p.Sender,- Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,+ Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,BeforeCommit: p.BeforeCommit,diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.goindex e11353105c..7c4c8e981e 100644--- a/server/internal/integrations/lark/feishu_resolvers_test.go+++ b/server/internal/integrations/lark/feishu_resolvers_test.go@@ -116,7 +116,7 @@ func TestFeishuSessionBinder_StartSessionMapping(t *testing.T) {Sender: binderUUID(7),ClaimToken: binderUUID(9),Message: channel.InboundMessage{- MessageID: "om_1", Text: "first turn",+ MessageID: "om_1", Text: "first turn", CommandText: "current instruction",Source: channel.Source{ChatID: "oc_chat", ChatType: channel.ChatTypeGroup, ThreadID: "omt_topic1"},},MediaPendingSeconds: 45,@@ -131,7 +131,7 @@ func TestFeishuSessionBinder_StartSessionMapping(t *testing.T) {t.Fatalf("SessionID = %+v, want shared-session result", result.SessionID)}got := f.startIn- if got.BindingKey != "oc_chat:omt_topic1" || got.ThreadID != "omt_topic1" || got.Body != "first turn" || got.MessageID != "om_1" {+ if got.BindingKey != "oc_chat:omt_topic1" || got.ThreadID != "omt_topic1" || got.Body != "first turn" || got.CommandText != "current instruction" || got.MessageID != "om_1" {t.Fatalf("start route/message mapping wrong: %+v", got)}if got.Sender != binderUUID(6) || got.Initiator != binderUUID(7) {diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.goindex 915a4ac76b..d47d7ae087 100644--- a/server/internal/integrations/slack/resolvers.go+++ b/server/internal/integrations/slack/resolvers.go@@ -340,7 +340,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionPBindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,},Initiator: p.Sender,- Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: replyThread,+ Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: replyThread,ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,BeforeCommit: p.BeforeCommit,diff --git a/server/internal/integrations/slack/slash_control.go b/server/internal/integrations/slack/slash_control.goindex c9d628c22c..d226a22906 100644--- a/server/internal/integrations/slack/slash_control.go+++ b/server/internal/integrations/slack/slash_control.go@@ -73,7 +73,7 @@ func (s *slackDMControlStarter) StartSlackDMChat(ctx context.Context, inst enginSender: userID, BindingKey: cmd.ChannelID, ChatType: channel.ChatTypeP2P,},Initiator: userID,- Body: body, DedupMessageID: envelopeID, ClaimToken: claim,+ Body: body, CommandText: body, DedupMessageID: envelopeID, ClaimToken: claim,PersistMessage: body != "", HistoryBoundaryPending: true,BeforeCommit: func(ctx context.Context, tx pgx.Tx, session db.ChatSession) error {if body == "" {@@ -158,7 +158,7 @@ func (s *slackDMControlStarter) ClearSlackDMContext(ctx context.Context, inst en} else {_, err = s.session.AppendUserMessage(ctx, engine.AppendInput{SessionID: sessionID, Sender: userID, InstallationID: inst.ID,- Body: body, CommandText: clearSlashCommand,+ Body: body, CommandText: clearSlashCommand + " " + body,DedupMessageID: envelopeID, ClaimToken: claim, ForceFresh: true,BeforeCommit: func(ctx context.Context, tx pgx.Tx, session db.ChatSession, contextRevision int64, _ pgtype.UUID, _ int64) error {var enqueueErr errordiff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.goindex a7249a6ffe..e1cad0dc38 100644--- a/server/internal/integrations/telegram/resolvers.go+++ b/server/internal/integrations/telegram/resolvers.go@@ -227,7 +227,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionPBindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,},Initiator: p.Sender,- Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: replyThread,+ Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: replyThread,ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,BeforeCommit: p.BeforeCommit,diff --git a/server/internal/integrations/telegram/resolvers_test.go b/server/internal/integrations/telegram/resolvers_test.goindex d030913002..edd66f4e60 100644--- a/server/internal/integrations/telegram/resolvers_test.go+++ b/server/internal/integrations/telegram/resolvers_test.go@@ -2,6 +2,7 @@ package telegramimport ("context"+ "strings""testing""github.com/jackc/pgx/v5/pgtype"@@ -69,8 +70,9 @@ func TestTelegramSessionBinder_StartSessionPreservesRouteAndFirstTurn(t *testingCreator: telegramTestUUID(6),Sender: telegramTestUUID(7),Message: channel.InboundMessage{- MessageID: "-100200:10",- Text: "summarize this",+ MessageID: "-100200:10",+ Text: "summarize this",+ CommandText: "current instruction",Source: channel.Source{ChatID: "-100200",ChatType: channel.ChatTypeGroup,@@ -96,6 +98,9 @@ func TestTelegramSessionBinder_StartSessionPreservesRouteAndFirstTurn(t *testingif got := session.startIn.Body; got != "summarize this" {t.Fatalf("Body = %q, want first /new turn", got)}+ if session.startIn.CommandText != "current instruction" {+ t.Fatalf("CommandText = %q", session.startIn.CommandText)+ }if !session.startIn.PersistMessage || !session.startIn.HistoryBoundaryPending {t.Fatalf("start flags = persist:%t history:%t, want both true", session.startIn.PersistMessage, session.startIn.HistoryBoundaryPending)}@@ -103,3 +108,39 @@ func TestTelegramSessionBinder_StartSessionPreservesRouteAndFirstTurn(t *testingt.Fatalf("creator/initiator mapping wrong: %+v", session.startIn)}}++func TestTelegramQuotedTitleSourceReachesSession(t *testing.T) {+ for _, start := range []bool{false, true} {+ t.Run(map[bool]string{false: "append", true: "new"}[start], func(t *testing.T) {+ command := "Compare alternatives"+ if start {+ command = "/new " + command+ }+ msg, ok := inboundFromUpdate(Update{UpdateID: 1, Message: &Message{MessageID: 10, From: &User{ID: 111, FirstName: "Grace"}, Chat: Chat{ID: -100200, Type: "supergroup"}, Text: "@my_bot " + command, ReplyToMessage: &Message{MessageID: 9, From: &User{ID: 222, FirstName: "Ada"}, Text: "Old unrelated discussion"}}}, 999, "my_bot")+ if !ok || !msg.AddressedToBot {+ t.Fatal("quoted request was not accepted")+ }+ if !strings.Contains(msg.Text, "Old unrelated discussion") || !strings.Contains(msg.Text, "Compare alternatives") {+ t.Fatalf("producer body=%q", msg.Text)+ }+ session := &captureChatSession{}+ binder := &sessionBinder{session: session}+ if start {+ msg.CommandText, _ = engine.ParseNewChatCommand(msg.CommandText)+ if _, err := binder.StartSession(context.Background(), engine.StartSessionParams{Message: msg, PersistMessage: true}); err != nil {+ t.Fatal(err)+ }+ if session.startIn.CommandText != "Compare alternatives" || session.startIn.Body != msg.Text {+ t.Fatalf("start instruction/context=%q/%q", session.startIn.CommandText, session.startIn.Body)+ }+ } else {+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{Message: msg}); err != nil {+ t.Fatal(err)+ }+ if session.appendIn.CommandText != "Compare alternatives" || session.appendIn.Body != msg.Text {+ t.Fatalf("append instruction/context=%q/%q", session.appendIn.CommandText, session.appendIn.Body)+ }+ }+ })+ }+}diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.goindex bb11938d62..959f4c8687 100644--- a/server/internal/integrations/wecom/resolvers_test.go+++ b/server/internal/integrations/wecom/resolvers_test.go@@ -89,7 +89,7 @@ func TestSessionBinder_StartSessionMapsWeComRouteAndFirstTurn(t *testing.T) {Sender: sender,ClaimToken: claim,Message: channel.InboundMessage{- MessageID: "m1", Text: "first turn",+ MessageID: "m1", Text: "first turn", CommandText: "current instruction",Source: channel.Source{ChatID: "GROUP_1", ChatType: channel.ChatTypeGroup},},MediaPendingSeconds: 45,@@ -102,7 +102,7 @@ func TestSessionBinder_StartSessionMapsWeComRouteAndFirstTurn(t *testing.T) {t.Fatal("StartSession lost shared-session result")}got := fb.startIn- if got.BindingKey != "GROUP_1" || got.Body != "first turn" || got.MessageID != "m1" || got.ClaimToken != claim || got.MediaPendingSeconds != 45 || !got.PersistMessage {+ if got.BindingKey != "GROUP_1" || got.Body != "first turn" || got.CommandText != "current instruction" || got.MessageID != "m1" || got.ClaimToken != claim || got.MediaPendingSeconds != 45 || !got.PersistMessage {t.Fatalf("start mapping wrong: %+v", got)}if got.Sender != creator || got.Initiator != sender {diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.goindex 59b6cbc5b0..e543b51f56 100644--- a/server/internal/integrations/wecom/wecom_resolvers.go+++ b/server/internal/integrations/wecom/wecom_resolvers.go@@ -98,7 +98,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionPBindingKey: p.Message.Source.ChatID, ChatType: p.Message.Source.ChatType,},Initiator: p.Sender,- Body: p.Message.Text, MessageID: p.Message.MessageID,+ Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID,ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,BeforeCommit: p.BeforeCommit,