Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(channels): handle /new in shared router (#6251)
Wangjue Yao69d320858663
diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.gonew file mode 100644index 0000000000..0e6da6eb2c--- /dev/null+++ b/server/internal/handler/channel_new_e2e_test.go@@ -0,0 +1,332 @@+package handler++import (+ "context"+ "errors"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "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/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// This test keeps only the external IM transport outside the process. From the+// normalized inbound message onward it runs the production Router, shared chat+// session service, TaskService, PostgreSQL queue, and daemon claim handler.+// That is the repeatable server-side E2E boundary for a channel command: an+// adapter's only responsibility is translating its webhook/socket payload into+// channel.InboundMessage.+func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler test fixture is required")+ }++ tests := []struct {+ name string+ channelType channel.Type+ text string+ commandText string+ forceFresh bool+ wantStoredText string+ wantForceFresh bool+ wantPriorSession string+ wantPriorWorkDir string+ }{+ {+ name: "normal message resumes existing provider context",+ channelType: channel.Type("slack"),+ text: "what model are you?",+ commandText: "what model are you?",+ wantStoredText: "what model are you?",+ wantPriorSession: "old-provider-session",+ wantPriorWorkDir: "/tmp/old-provider-workdir",+ },+ {+ name: "Slack /new message starts without provider context",+ channelType: channel.Type("slack"),+ text: "/new what model are you?",+ commandText: "/new what model are you?",+ wantStoredText: "what model are you?",+ wantForceFresh: true,+ },+ {+ name: "Slack same-line /issue remains fresh-only",+ channelType: channel.Type("slack"),+ text: "/new /issue investigate deploy",+ commandText: "/new /issue investigate deploy",+ wantStoredText: "/issue investigate deploy",+ wantForceFresh: true,+ },+ {+ name: "Slack next-line /issue remains fresh-only",+ channelType: channel.Type("slack"),+ text: "/new\n/issue investigate deploy",+ commandText: "/new\n/issue investigate deploy",+ wantStoredText: "/issue investigate deploy",+ wantForceFresh: true,+ },+ {+ name: "Feishu same-line /issue remains fresh-only",+ channelType: channel.TypeFeishu,+ text: "/issue investigate deploy",+ commandText: "/new /issue investigate deploy",+ forceFresh: true,+ wantStoredText: "/issue investigate deploy",+ wantForceFresh: true,+ },+ {+ name: "Feishu next-line /issue remains fresh-only",+ channelType: channel.TypeFeishu,+ text: "/issue investigate deploy",+ commandText: "/new\n/issue investigate deploy",+ forceFresh: true,+ wantStoredText: "/issue investigate deploy",+ wantForceFresh: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ runChannelNewCommandE2E(t, tt.channelType, tt.text, tt.commandText, tt.forceFresh, tt.wantStoredText, tt.wantForceFresh, tt.wantPriorSession, tt.wantPriorWorkDir)+ })+ }+}++func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, commandText string, adapterForceFresh bool, wantStoredText string, wantForceFresh bool, wantPriorSession, wantPriorWorkDir string) {+ t.Helper()++ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)+ queries := db.New(testPool)++ var installationID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO channel_installation (+ workspace_id, agent_id, channel_type, config, status, installer_user_id+ )+ VALUES ($1, $2, $3, '{}'::jsonb, 'active', $4)+ RETURNING id+ `, testWorkspaceID, agentID, string(channelType), testUserID).Scan(&installationID); err != nil {+ t.Fatalf("create channel installation: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installationID)+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)+ })++ installation := engine.ResolvedInstallation{+ ID: util.MustParseUUID(installationID),+ WorkspaceID: util.MustParseUUID(testWorkspaceID),+ AgentID: util.MustParseUUID(agentID),+ InstallerUserID: util.MustParseUUID(testUserID),+ Active: true,+ }+ chatSession := engine.NewChatSession(queries, testPool, channelType, engine.SessionTitles{+ Direct: "Channel E2E conversation",+ Group: "Channel E2E group",+ Fallback: "Channel E2E conversation",+ })+ binder := &channelNewE2ESessionBinder{session: chatSession}++ // Seed the same channel conversation with a provider session/workdir. A+ // normal message resumes both; /new must leave them out of the daemon+ // claim while retaining the durable chat transcript.+ sessionID, err := binder.EnsureSession(ctx, engine.EnsureSessionParams{+ Installation: installation,+ Sender: util.MustParseUUID(testUserID),+ Message: channel.InboundMessage{Source: channel.Source{+ ChannelType: channelType,+ ChatID: t.Name(),+ ChatType: channel.ChatTypeP2P,+ }},+ })+ if err != nil {+ t.Fatalf("seed channel chat session: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE origin_type = 'test_e2e_chat' AND origin_id = $1`, sessionID)+ })+ if _, err := testPool.Exec(ctx, `+ UPDATE chat_session+ SET session_id = 'old-provider-session',+ work_dir = '/tmp/old-provider-workdir',+ runtime_id = $2+ WHERE id = $1+ `, sessionID, runtimeID); err != nil {+ t.Fatalf("seed prior provider context: %v", err)+ }++ router := engine.NewRouter(nil, testHandler.TaskService, queries, engine.RouterConfig{})+ router.Register(channelType, engine.ResolverSet{+ Installation: channelNewE2EInstallationResolver{installation: installation},+ Identity: channelNewE2EIdentityResolver{userID: util.MustParseUUID(testUserID)},+ Dedup: channelNewE2EDeduper{queries: queries},+ Session: binder,+ Audit: channelNewE2EAuditor{},+ OriginType: "test_e2e_chat",+ })++ if err := router.Handle(ctx, channel.InboundMessage{+ EventID: "event-" + t.Name(),+ MessageID: "message-" + t.Name(),+ Type: channel.MsgTypeText,+ Text: text,+ CommandText: commandText,+ ForceFresh: adapterForceFresh,+ Source: channel.Source{+ ChannelType: channelType,+ ChatID: t.Name(),+ ChatType: channel.ChatTypeP2P,+ SenderID: "platform-user-e2e",+ },+ }); err != nil {+ t.Fatalf("route channel message: %v", err)+ }++ var taskID string+ var forceFresh bool+ if err := testPool.QueryRow(ctx, `+ SELECT id, force_fresh_session+ FROM agent_task_queue+ WHERE chat_session_id = $1+ ORDER BY created_at DESC+ LIMIT 1+ `, sessionID).Scan(&taskID, &forceFresh); err != nil {+ t.Fatalf("load queued chat task: %v", err)+ }+ if forceFresh != wantForceFresh {+ t.Fatalf("queued task %s: force_fresh_session = %t, want %t", taskID, forceFresh, wantForceFresh)+ }++ var issueCount int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*)+ FROM issue+ WHERE workspace_id = $1+ AND origin_type = 'test_e2e_chat'+ AND origin_id = $2+ `, testWorkspaceID, sessionID).Scan(&issueCount); err != nil {+ t.Fatalf("count command-created issues: %v", err)+ }+ if issueCount != 0 {+ t.Fatalf("created issues = %d, want 0; /new must be mutually exclusive with /issue", issueCount)+ }++ messages, err := queries.ListChatMessages(ctx, sessionID)+ if err != nil {+ t.Fatalf("list persisted chat messages: %v", err)+ }+ if len(messages) != 1 || messages[0].Content != wantStoredText {+ t.Fatalf("persisted messages = %#v, want one user message %q", messages, wantStoredText)+ }++ claimed := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if claimed.ChatMessage != wantStoredText {+ t.Fatalf("claimed chat_message = %q, want %q", claimed.ChatMessage, wantStoredText)+ }+ if claimed.PriorSessionID != wantPriorSession {+ t.Fatalf("claimed prior_session_id = %q, want %q", claimed.PriorSessionID, wantPriorSession)+ }+ if claimed.PriorWorkDir != wantPriorWorkDir {+ t.Fatalf("claimed prior_work_dir = %q, want %q", claimed.PriorWorkDir, wantPriorWorkDir)+ }+}++type channelNewE2EInstallationResolver struct {+ installation engine.ResolvedInstallation+}++func (r channelNewE2EInstallationResolver) ResolveInstallation(context.Context, channel.InboundMessage) (engine.ResolvedInstallation, error) {+ return r.installation, nil+}++type channelNewE2EIdentityResolver struct {+ userID pgtype.UUID+}++func (r channelNewE2EIdentityResolver) ResolveSender(context.Context, engine.ResolvedInstallation, channel.InboundMessage) (engine.ResolvedIdentity, error) {+ return engine.ResolvedIdentity{UserID: r.userID}, nil+}++type channelNewE2EDeduper struct {+ queries *db.Queries+}++func (d channelNewE2EDeduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {+ claim, err := d.queries.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{+ InstallationID: installationID,+ MessageID: messageID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return pgtype.UUID{}, engine.ErrDuplicate+ }+ return claim.ClaimToken, err+}++func (d channelNewE2EDeduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {+ _, err := d.queries.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{+ InstallationID: installationID,+ MessageID: messageID,+ ClaimToken: claimToken,+ })+ return err+}++func (d channelNewE2EDeduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {+ _, err := d.queries.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{+ InstallationID: installationID,+ MessageID: messageID,+ ClaimToken: claimToken,+ })+ return err+}++type channelNewE2ESessionBinder struct {+ session *engine.ChatSession+}++func (b *channelNewE2ESessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {+ return b.session.EnsureSession(ctx, engine.EnsureSessionInput{+ WorkspaceID: p.Installation.WorkspaceID,+ AgentID: p.Installation.AgentID,+ InstallationID: p.Installation.ID,+ Sender: p.Sender,+ BindingKey: p.Message.Source.ChatID,+ ChatType: p.Message.Source.ChatType,+ })+}++func (b *channelNewE2ESessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {+ return b.session.AppendUserMessage(ctx, engine.AppendInput{+ SessionID: p.SessionID,+ Sender: p.Sender,+ InstallationID: p.InstallationID,+ Body: p.Message.Text,+ CommandText: p.Message.CommandText,+ MessageID: p.Message.MessageID,+ ThreadID: p.Message.Source.ThreadID,+ ClaimToken: p.ClaimToken,+ MediaPendingSeconds: p.MediaPendingSeconds,+ })+}++func (b *channelNewE2ESessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {+ return b.session.BindMediaRefs(ctx, engine.BindMediaInput{+ MessageID: p.MessageID,+ SessionID: p.SessionID,+ WorkspaceID: p.WorkspaceID,+ Sender: p.Sender,+ MediaRefs: p.MediaRefs,+ })+}++type channelNewE2EAuditor struct{}++func (channelNewE2EAuditor) RecordDrop(context.Context, pgtype.UUID, channel.InboundMessage, engine.DropReason) error {+ return nil+}diff --git a/server/internal/integrations/channel/engine/fresh_command.go b/server/internal/integrations/channel/engine/fresh_command.gonew file mode 100644index 0000000000..34ed0f72f3--- /dev/null+++ b/server/internal/integrations/channel/engine/fresh_command.go@@ -0,0 +1,49 @@+package engine++import "strings"++const freshSessionCommandPrefix = "/new"++// ParseFreshSessionCommand extracts a first-line /new command from a channel+// message. It returns the user prompt with the directive removed. The command+// is shared product behavior: every channel that reaches Router gets the same+// fresh-session affordance without reimplementing parsing in its adapter.+//+// Matching follows the /issue command rules: case-sensitive, token-bounded,+// and only the first non-empty line can be a command. That means /new and+// /issue are mutually exclusive on the same first line.+func ParseFreshSessionCommand(body string) (string, bool) {+ lines := strings.Split(body, "\n")++ firstIdx := -1+ for i, line := range lines {+ if strings.TrimSpace(line) != "" {+ firstIdx = i+ break+ }+ }+ if firstIdx == -1 {+ return "", false+ }++ trimmed := strings.TrimLeft(lines[firstIdx], " \t")+ if !strings.HasPrefix(trimmed, freshSessionCommandPrefix) {+ return "", false+ }++ rest := trimmed[len(freshSessionCommandPrefix):]+ if rest != "" {+ if r0 := rest[0]; r0 != ' ' && r0 != '\t' {+ return "", false+ }+ }++ bodyParts := make([]string, 0, 2)+ if firstLineBody := strings.TrimSpace(rest); firstLineBody != "" {+ bodyParts = append(bodyParts, firstLineBody)+ }+ if firstIdx+1 < len(lines) {+ bodyParts = append(bodyParts, strings.Join(lines[firstIdx+1:], "\n"))+ }+ return strings.TrimRight(strings.Join(bodyParts, "\n"), " \t\n"), true+}diff --git a/server/internal/integrations/channel/engine/fresh_command_test.go b/server/internal/integrations/channel/engine/fresh_command_test.gonew file mode 100644index 0000000000..398a88da16--- /dev/null+++ b/server/internal/integrations/channel/engine/fresh_command_test.go@@ -0,0 +1,33 @@+package engine++import "testing"++func TestParseFreshSessionCommand(t *testing.T) {+ tests := []struct {+ name string+ body string+ wantMatch bool+ wantBody string+ }{+ {name: "new with same-line body", body: "/new start from scratch", wantMatch: true, wantBody: "start from scratch"},+ {name: "leading blank lines tolerated", body: "\n\n/new re-check the deploy", wantMatch: true, wantBody: "re-check the deploy"},+ {name: "multi-line body preserved", body: "/new title\nline one\nline two", wantMatch: true, wantBody: "title\nline one\nline two"},+ {name: "command alone produces empty body", body: "/new", wantMatch: true, wantBody: ""},+ {name: "prefix of token rejected", body: "/newness is not a command", wantMatch: false},+ {name: "mid-sentence command rejected", body: "please /new this run", wantMatch: false},+ {name: "wrong case rejected", body: "/New help", wantMatch: false},+ {name: "normal body rejected", body: "help me normally", wantMatch: false},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ body, ok := ParseFreshSessionCommand(tc.body)+ if ok != tc.wantMatch {+ t.Fatalf("match=%v want %v (body=%q)", ok, tc.wantMatch, body)+ }+ if body != tc.wantBody {+ t.Errorf("body=%q want %q", body, tc.wantBody)+ }+ })+ }+}diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex f452e08026..cac4c4de48 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -179,6 +179,24 @@ var ErrNoResolverSet = errors.New("channel router: no resolver set for channel t// infrastructure failures (the adapter reconnects). Product outcomes (dropped,// 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.+ if msg.CommandText == "" {+ msg.CommandText = msg.Text+ }++ // /new is a channel-wide product command, not an adapter capability. Parse+ // it here so every adapter that delivers it as message text gets the same+ // fresh-session behavior. Feishu already strips /new before its context+ // enricher runs and sets ForceFresh; the guard preserves that enriched body.+ if !msg.ForceFresh {+ if body, ok := ParseFreshSessionCommand(msg.CommandText); ok {+ msg.ForceFresh = true+ msg.Text = body+ }+ }+r.mu.RLock()set, ok := r.sets[msg.Source.ChannelType]r.mu.RUnlock()diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 931dcd6e89..6ac223e6b3 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -72,6 +72,7 @@ type fakeBinder struct {ensureID pgtype.UUIDensureErr errorappendResult AppendResult+ parseIssue boolappendErr errorappendDelay time.DurationbindErr error@@ -89,6 +90,13 @@ func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendResdelay := f.appendDelayf.lastAppend = pres, err := f.appendResult, f.appendErr+ if f.parseIssue {+ commandSource := p.Message.CommandText+ if commandSource == "" {+ commandSource = p.Message.Text+ }+ res.IssueCommand, _ = ParseIssueCommand(commandSource)+ }f.mu.Unlock()if delay > 0 {time.Sleep(delay)@@ -876,6 +884,117 @@ func TestRouter_ForceFresh_Propagates(t *testing.T) {}}+func TestRouter_NewCommand_ForcesFreshAndStripsDirective(t *testing.T) {+ h := newHarness(t)+ msg := p2pMessage(t)+ msg.Source.ChannelType = channel.Type("test-channel")+ msg.Text = "/new answer with the current model"+ h.router.Register(msg.Source.ChannelType, ResolverSet{+ Installation: h.inst,+ Identity: h.ident,+ Dedup: h.dedup,+ Session: h.binder,+ Audit: h.audit,+ OriginType: "test_chat",+ })++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !h.tasks.freshArg() {+ t.Fatal("/new must enqueue a fresh provider session")+ }+ if got := h.binder.lastAppend.Message.Text; got != "answer with the current model" {+ t.Fatalf("appended text=%q, want command stripped", got)+ }+ if got := h.binder.lastAppend.Message.CommandText; got != "/new answer with the current model" {+ t.Fatalf("command text=%q, want original user text", got)+ }+}++func TestRouter_NewCommandDoesNotReparseStrippedBodyAsIssue(t *testing.T) {+ tests := []struct {+ name string+ channelType channel.Type+ text string+ commandText string+ forceFresh bool+ }{+ {+ name: "Slack same line",+ channelType: channel.Type("slack"),+ text: "/new /issue investigate deploy",+ commandText: "/new /issue investigate deploy",+ },+ {+ name: "Slack next line",+ channelType: channel.Type("slack"),+ text: "/new\n/issue investigate deploy",+ commandText: "/new\n/issue investigate deploy",+ },+ {+ name: "Feishu same line",+ channelType: channel.TypeFeishu,+ text: "/issue investigate deploy",+ commandText: "/new /issue investigate deploy",+ forceFresh: true,+ },+ {+ name: "Feishu next line",+ channelType: channel.TypeFeishu,+ text: "/issue investigate deploy",+ commandText: "/new\n/issue investigate deploy",+ forceFresh: true,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ h := newHarness(t)+ h.binder.parseIssue = true+ msg := p2pMessage(t)+ msg.Source.ChannelType = tc.channelType+ msg.Text = tc.text+ msg.CommandText = tc.commandText+ msg.ForceFresh = tc.forceFresh+ if tc.channelType == channel.Type("slack") {+ h.router.Register(channel.Type("slack"), ResolverSet{+ Installation: h.inst,+ Identity: h.ident,+ Dedup: h.dedup,+ Session: h.binder,+ Audit: h.audit,+ OriginType: "slack_chat",+ })+ }++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if h.issues.called {+ t.Fatal("/new must not be re-parsed as /issue after its directive is stripped")+ }+ if !h.binder.lastAppend.Message.ForceFresh {+ t.Fatal("/new must still request a fresh provider session")+ }+ })+ }+}++func TestRouter_AdapterFreshBodyIsNotParsedAgain(t *testing.T) {+ h := newHarness(t)+ msg := p2pMessage(t)+ msg.ForceFresh = true+ msg.Text = "<recent_context>\n/new from history\n</recent_context>\n\ncurrent prompt"++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if got := h.binder.lastAppend.Message.Text; got != msg.Text {+ t.Fatalf("adapter-enriched body changed: got %q want %q", got, msg.Text)+ }+}+func TestRouter_DrainJoinsReplies(t *testing.T) {h := newHarness(t)h.ident.err = ErrSenderUnbound // triggers a NeedsBinding reply goroutinediff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.goindex ca3f16d344..17c1efb2b4 100644--- a/server/internal/integrations/channel/message.go+++ b/server/internal/integrations/channel/message.go@@ -128,11 +128,17 @@ type InboundMessage struct {// Type is the normalized message kind.Type MsgType- // Text is the human-readable content, flattened by the adapter. For- // non-text messages it may be empty or a short placeholder; the media+ // Text is the agent-readable content, flattened by the adapter. Router or+ // an adapter may strip a command directive or enrich it with quoted context.+ // For non-text messages it may be empty or a short placeholder; the media// itself is in MediaRefs.Text string+ // CommandText is the user's normalized text before command stripping or+ // contextual enrichment. Shared command classifiers read this field so a+ // rewritten Text is never interpreted as a second command. Empty means Text.+ CommandText string+// MediaRefs is the OUTPUT channel of engine.MediaResolver.ResolveMedia:// the objects it downloaded and uploaded for this message, each covered// by an intent-ledger row written before its PUT. Inbound messages always@@ -151,10 +157,9 @@ type InboundMessage struct {// arrays, parent ids) stay in Raw.AddressedToBot bool- // ForceFresh asks the core to start a fresh agent session for this- // message instead of resuming the prior one (the platform's "/fresh"- // affordance). The adapter normalizes its platform-specific trigger- // into this boolean; the core only reads the flag.+ // ForceFresh asks the core to start a fresh agent session for this message+ // instead of resuming the prior one. Router recognizes the shared /new text+ // command; adapters may also set this flag for a native platform affordance.ForceFresh bool// Raw is the untouched platform payload. Adapters stash platform-diff --git a/server/internal/integrations/lark/feishu_channel.go b/server/internal/integrations/lark/feishu_channel.goindex b56bc8bb08..2f8445d65f 100644--- a/server/internal/integrations/lark/feishu_channel.go+++ b/server/internal/integrations/lark/feishu_channel.go@@ -123,7 +123,8 @@ func installationCredentialsFor(inst Installation, resolver CredentialsResolver)// channelMessageFromLark normalizes a decoded Feishu InboundMessage into the// cross-platform channel.InboundMessage. The original struct is stashed in Raw// so the Feishu resolvers can read the platform-specific fields (app_id,-// event_type, command body, create time) the envelope does not carry.+// event_type, create time) the envelope does not carry. CommandBody maps to+// the normalized CommandText field because command classification is shared.func channelMessageFromLark(lm InboundMessage) channel.InboundMessage {raw, _ := json.Marshal(lm)var reply *channel.ReplyCtx@@ -135,6 +136,7 @@ func channelMessageFromLark(lm InboundMessage) channel.InboundMessage {MessageID: lm.MessageID,Type: channelMsgType(lm.MessageType),Text: lm.Body,+ CommandText: lm.CommandBody,ReplyTo: reply,AddressedToBot: lm.AddressedToBot,ForceFresh: lm.ForceFreshSession,diff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.goindex f3b5942816..64b14f146a 100644--- a/server/internal/integrations/lark/feishu_channel_test.go+++ b/server/internal/integrations/lark/feishu_channel_test.go@@ -716,7 +716,7 @@ func TestChannelMessageFromLark_NormalizesAndStashesRaw(t *testing.T) {}cm := channelMessageFromLark(lm)- if cm.EventID != "evt" || cm.MessageID != "om" || cm.Text != "enriched body" {+ if cm.EventID != "evt" || cm.MessageID != "om" || cm.Text != "enriched body" || cm.CommandText != "/issue do it" {t.Fatalf("scalar fields not mapped: %+v", cm)}if cm.Type != channel.MsgTypeText {@@ -733,7 +733,8 @@ func TestChannelMessageFromLark_NormalizesAndStashesRaw(t *testing.T) {t.Fatalf("reply context not mapped: %+v", cm.ReplyTo)}// Raw must round-trip back to the original lark message (the boundary the- // Feishu resolvers read app_id / command_body / event_type from).+ // Feishu resolvers read platform-specific fields such as app_id/event_type+ // from); CommandBody is also projected onto normalized CommandText.got, err := larkMsgFromRaw(cm)if err != nil {t.Fatalf("larkMsgFromRaw: %v", err)diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.goindex 2aaad3b338..b8f27ea7fd 100644--- a/server/internal/integrations/lark/feishu_resolvers.go+++ b/server/internal/integrations/lark/feishu_resolvers.go@@ -17,10 +17,10 @@ import (// the channel-agnostic engine.Router runs the inbound pipeline through. Each// resolver translates between the engine's normalized channel.InboundMessage /// engine types and the Feishu store / services. Platform-specific fields the-// normalized envelope does not carry (app_id, event_type, the un-enriched-// command body, create time) are read from the original InboundMessage the-// feishuChannel stashes in channel.InboundMessage.Raw — the documented adapter-// boundary (the core never reads Raw).+// normalized envelope does not carry (app_id, event_type, create time) are read+// from the original InboundMessage that feishuChannel stashes in+// channel.InboundMessage.Raw — the documented adapter boundary (the core never+// reads Raw).// originFeishuChat is the issue.origin_type label written for issues created// via the Feishu /issue command. Kept as "lark_chat" (unchanged from the@@ -203,19 +203,16 @@ func (r *feishuSessionBinder) EnsureSession(ctx context.Context, p engine.Ensure}func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {- // CommandText is the user's OWN typed text: the Feishu enricher inlines- // quoted/forwarded context into Body, so /issue parsing must use the- // un-enriched command body stashed in Raw, not Body.- lm, err := larkMsgFromRaw(p.Message)- if err != nil {- return engine.AppendResult{}, err+ commandText := p.Message.CommandText+ if commandText == "" {+ commandText = p.Message.Text}return r.session.AppendUserMessage(ctx, engine.AppendInput{SessionID: p.SessionID,Sender: p.Sender,InstallationID: p.InstallationID,Body: p.Message.Text,- CommandText: lm.CommandBody,+ CommandText: commandText,MessageID: p.Message.MessageID,ThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken,diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.goindex 26d2be798f..045bf49e86 100644--- a/server/internal/integrations/lark/feishu_resolvers_test.go+++ b/server/internal/integrations/lark/feishu_resolvers_test.go@@ -126,19 +126,18 @@ func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {f := &fakeChatSession{}b := &feishuSessionBinder{session: f}- // Raw carries the original lark InboundMessage; CommandBody is the user's- // un-enriched text used for /issue parsing (Body has quoted context inlined).- raw, _ := json.Marshal(InboundMessage{CommandBody: "/issue Real intent"})+ // CommandText is the user's un-enriched text used for /issue parsing while+ // Text contains the body after quoted context is inlined.if _, err := b.AppendMessage(context.Background(), engine.AppendParams{SessionID: binderUUID(1),Sender: binderUUID(7),InstallationID: binderUUID(2),ClaimToken: binderUUID(9),Message: channel.InboundMessage{- MessageID: "om_1",- Text: "> quoted context\n/issue Real intent",- Source: channel.Source{ChatID: "oc", ThreadID: "th_1"},- Raw: raw,+ MessageID: "om_1",+ Text: "> quoted context\n/issue Real intent",+ CommandText: "/issue Real intent",+ Source: channel.Source{ChatID: "oc", ThreadID: "th_1"},},}); err != nil {t.Fatalf("AppendMessage: %v", err)@@ -146,7 +145,7 @@ func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {got := f.appendInif got.CommandText != "/issue Real intent" {- t.Errorf("CommandText must be the un-enriched CommandBody from Raw, got %q", got.CommandText)+ t.Errorf("CommandText must be the normalized un-enriched text, got %q", got.CommandText)}if got.Body != "> quoted context\n/issue Real intent" {t.Errorf("Body must be the (enriched) Message.Text, got %q", got.Body)diff --git a/server/internal/integrations/lark/fresh_command.go b/server/internal/integrations/lark/fresh_command.godeleted file mode 100644index 193a74b2ff..0000000000--- a/server/internal/integrations/lark/fresh_command.go+++ /dev/null@@ -1,66 +0,0 @@-package lark--import "strings"--const (- newCommandPrefix = "/new"-)--// FreshSessionCommand is the normalized fresh-start directive extracted from a-// Lark inbound message. Body is the user prompt with the directive removed.-type FreshSessionCommand struct {- Body string-}--// parseFreshSessionCommand extracts a first-line /new command from a message-// body. Matching follows the /issue command rules: case-sensitive,-// token-bounded, and only the first non-empty line can be a command. That-// means /new and /issue are mutually exclusive on the same first line.-func parseFreshSessionCommand(body string) (*FreshSessionCommand, bool) {- lines := strings.Split(body, "\n")-- firstIdx := -1- for i, line := range lines {- if strings.TrimSpace(line) != "" {- firstIdx = i- break- }- }- if firstIdx == -1 {- return nil, false- }-- first := lines[firstIdx]- trimmed := strings.TrimLeft(first, " \t")- prefix, ok := matchedFreshPrefix(trimmed)- if !ok {- return nil, false- }-- rest := trimmed[len(prefix):]- if rest != "" {- r0 := rest[0]- if r0 != ' ' && r0 != '\t' {- return nil, false- }- }-- bodyParts := make([]string, 0, 2)- if firstLineBody := strings.TrimSpace(rest); firstLineBody != "" {- bodyParts = append(bodyParts, firstLineBody)- }- if firstIdx+1 < len(lines) {- bodyParts = append(bodyParts, strings.Join(lines[firstIdx+1:], "\n"))- }- stripped := strings.TrimRight(strings.Join(bodyParts, "\n"), " \t\n")- return &FreshSessionCommand{Body: stripped}, true-}--func matchedFreshPrefix(line string) (string, bool) {- switch {- case strings.HasPrefix(line, newCommandPrefix):- return newCommandPrefix, true- default:- return "", false- }-}diff --git a/server/internal/integrations/lark/fresh_command_test.go b/server/internal/integrations/lark/fresh_command_test.godeleted file mode 100644index b7beef9053..0000000000--- a/server/internal/integrations/lark/fresh_command_test.go+++ /dev/null@@ -1,75 +0,0 @@-package lark--import "testing"--func TestParseFreshSessionCommand(t *testing.T) {- tests := []struct {- name string- body string- wantMatch bool- wantBody string- }{- {- name: "new with same-line body",- body: "/new start from scratch",- wantMatch: true,- wantBody: "start from scratch",- },- {- name: "leading blank lines tolerated",- body: "\n\n/new re-check the deploy",- wantMatch: true,- wantBody: "re-check the deploy",- },- {- name: "multi-line body preserved",- body: "/new title\nline one\nline two",- wantMatch: true,- wantBody: "title\nline one\nline two",- },- {- name: "command alone produces empty body",- body: "/new",- wantMatch: true,- wantBody: "",- },- {- name: "prefix of token rejected",- body: "/newness is not a command",- wantMatch: false,- },- {- name: "mid-sentence command rejected",- body: "please /new this run",- wantMatch: false,- },- {- name: "wrong case rejected",- body: "/New help",- wantMatch: false,- },- {- name: "normal body rejected",- body: "help me normally",- wantMatch: false,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- cmd, ok := parseFreshSessionCommand(tc.body)- if ok != tc.wantMatch {- t.Fatalf("match=%v want %v (cmd=%+v)", ok, tc.wantMatch, cmd)- }- if !tc.wantMatch {- if cmd != nil {- t.Fatalf("expected nil command, got %+v", cmd)- }- return- }- if cmd.Body != tc.wantBody {- t.Errorf("body=%q want %q", cmd.Body, tc.wantBody)- }- })- }-}diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.goindex b7ee43f0d5..03593d6c39 100644--- a/server/internal/integrations/lark/inbound_enricher.go+++ b/server/internal/integrations/lark/inbound_enricher.go@@ -9,6 +9,8 @@ import ("sort""strconv""strings"++ "github.com/multica-ai/multica/server/internal/integrations/channel/engine")// larkMsgTypeMergeForward is the msg_type of a "merged & forwarded"@@ -150,9 +152,9 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, credsif freshSource == "" {freshSource = msg.Body}- if cmd, ok := parseFreshSessionCommand(freshSource); ok {+ if body, ok := engine.ParseFreshSessionCommand(freshSource); ok {msg.ForceFreshSession = true- msg.Body = cmd.Body+ msg.Body = body}isForward := msg.MessageType == larkMsgTypeMergeForwarddiff --git a/server/internal/integrations/slack/inbound.go b/server/internal/integrations/slack/inbound.goindex b9e12a5363..8390ce37ff 100644--- a/server/internal/integrations/slack/inbound.go+++ b/server/internal/integrations/slack/inbound.go@@ -122,11 +122,13 @@ func buildInbound(e slackevents.EventsAPIEvent, p buildInboundParams, mentionReif p.threadTS != "" && p.threadTS != p.ts {reply = &channel.ReplyCtx{MessageID: p.threadTS, RootID: p.threadTS}}+ text := cleanText(p.text, mentionRe)return channel.InboundMessage{EventID: p.ts,MessageID: p.ts,Type: channel.MsgTypeText,- Text: cleanText(p.text, mentionRe),+ Text: text,+ CommandText: text,ReplyTo: reply,AddressedToBot: p.addressed,Source: channel.Source{diff --git a/server/internal/integrations/slack/inbound_test.go b/server/internal/integrations/slack/inbound_test.goindex fb9d02acf0..77984cf0c7 100644--- a/server/internal/integrations/slack/inbound_test.go+++ b/server/internal/integrations/slack/inbound_test.go@@ -58,6 +58,9 @@ func TestInboundFromMessage_DM(t *testing.T) {if msg.Text != "hello bot" {t.Errorf("Text = %q", msg.Text)}+ if msg.CommandText != "hello bot" {+ t.Errorf("CommandText = %q, want normalized original text", msg.CommandText)+ }// team_id must be in Raw so the installation resolver can route.var raw slackRawEventif err := json.Unmarshal(msg.Raw, &raw); err != nil {@@ -88,6 +91,9 @@ func TestInboundFromMessage_ChannelMention(t *testing.T) {if msg.Text != "create an issue" {t.Errorf("Text = %q, want mention stripped", msg.Text)}+ if msg.CommandText != "create an issue" {+ t.Errorf("CommandText = %q, want the same pre-rewrite text", msg.CommandText)+ }}func TestInboundFromMessage_ChannelNoMention(t *testing.T) {diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.goindex c8a3210551..464106bb99 100644--- a/server/internal/integrations/slack/resolvers.go+++ b/server/internal/integrations/slack/resolvers.go@@ -334,13 +334,16 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessiofunc (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {_, _, replyThread := slackSessionRouting(p.Message)+ commandText := p.Message.CommandText+ if commandText == "" {+ commandText = p.Message.Text+ }return r.session.AppendUserMessage(ctx, engine.AppendInput{- SessionID: p.SessionID,- Sender: p.Sender,- InstallationID: p.InstallationID,- Body: p.Message.Text,- // Slack text is not enriched, so the command source is the body itself.- CommandText: p.Message.Text,+ SessionID: p.SessionID,+ Sender: p.Sender,+ InstallationID: p.InstallationID,+ Body: p.Message.Text,+ CommandText: commandText,MessageID: p.Message.MessageID,ThreadID: replyThread,ClaimToken: p.ClaimToken,