Skip to content

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

Go

MUL-5904: fix(wecom): no slash command works in a group at all (#6603)

Xichang(Seacen) Zhao7509d80cdff0
diff --git a/packages/core/types/wecom.ts b/packages/core/types/wecom.ts
index cf1adc86ea..86b4fea6ea 100644
--- a/packages/core/types/wecom.ts
+++ b/packages/core/types/wecom.ts
@@ -27,14 +27,21 @@ export interface ListWecomInstallationsResponse {
install_supported?: boolean;
}
-/** Request body for the Web UI's BYO Connect dialog. Two fields, both copied
- * from the WeCom admin console's smart-bot page: the bot's stable
+/** Request body for the Web UI's BYO Connect dialog. The first two fields are
+ * copied from the WeCom admin console's smart-bot page: the bot's stable
* identifier and its long-connection secret. The backend seals the secret
* with the deployment's MULTICA_WECOM_SECRET_KEY before writing it, so
* plaintext never lands in the DB. */
export interface RegisterWecomBYORequest {
bot_id: string;
secret: string;
+ /** The bot's name as it appears in a chat. Optional, and used for one
+ * thing: recognising the bot's own @-mention in a group. WeCom delivers a
+ * mention as literal text with no structured mention list, so a name
+ * containing a space ("Multica Bot") otherwise swallows the slash command
+ * typed after it. Omitting it on a re-install of the same bot keeps the
+ * name already stored. */
+ bot_name?: string;
}
/** Post-redemption echo: the WeCom aibot userid the token carried is now
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index e3e939ee69..47ef81db3c 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -759,6 +759,9 @@
"byo_bot_id_placeholder": "e.g. aibot_xxxxxxxxxxxxxxxx",
"byo_secret_label": "Long-connection secret",
"byo_secret_placeholder": "Paste the secret shown once in the console",
+ "byo_bot_name_label": "Bot name in chat (optional)",
+ "byo_bot_name_placeholder": "e.g. Multica Bot",
+ "byo_bot_name_hint": "Only needed if the name has a space in it, so the bot can tell its own @-mention apart from the command typed after it. To change it later — including after renaming the bot in the WeCom console — disconnect this bot and connect it again.",
"byo_submit": "Connect",
"byo_submitting": "Connecting…",
"byo_cancel": "Cancel",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 7607d27df2..2074023fcc 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -758,6 +758,9 @@
"byo_bot_id_placeholder": "例: aibot_xxxxxxxxxxxxxxxx",
"byo_secret_label": "ロングコネクション Secret",
"byo_secret_placeholder": "管理コンソールに一度だけ表示される Secret を貼り付けます",
+ "byo_bot_name_label": "チャットでのボット名(任意)",
+ "byo_bot_name_placeholder": "例: Multica Bot",
+ "byo_bot_name_hint": "名前にスペースが含まれる場合のみ必要です。自分宛ての @ メンションと、その後に入力されたコマンドを区別するために使います。あとから変更するとき(WeCom 管理コンソールで改名した場合を含む)は、いったん接続を解除してから接続し直してください。",
"byo_submit": "接続",
"byo_submitting": "接続中…",
"byo_cancel": "キャンセル",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index e3127fce59..f4cc05b845 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -863,6 +863,9 @@
"byo_bot_id_placeholder": "예: aibot_xxxxxxxxxxxxxxxx",
"byo_secret_label": "롱 커넥션 Secret",
"byo_secret_placeholder": "관리자 콘솔에 한 번만 표시되는 Secret을 붙여넣으세요",
+ "byo_bot_name_label": "채팅에 표시되는 봇 이름 (선택)",
+ "byo_bot_name_placeholder": "예: Multica Bot",
+ "byo_bot_name_hint": "이름에 공백이 있을 때만 필요해요. 봇이 자기 @멘션과 뒤에 입력된 명령어를 구분하는 데 씁니다. 나중에 바꾸려면(WeCom 콘솔에서 이름을 바꾼 경우 포함) 연결을 끊었다가 다시 연결해 주세요.",
"byo_submit": "연결",
"byo_submitting": "연결 중…",
"byo_cancel": "취소",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index b6b2b8f67a..d8b6ad9f07 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -758,6 +758,9 @@
"byo_bot_id_placeholder": "例如:aibot_xxxxxxxxxxxxxxxx",
"byo_secret_label": "长连接 Secret",
"byo_secret_placeholder": "粘贴在管理后台仅显示一次的 Secret",
+ "byo_bot_name_label": "机器人在聊天里的名字(可选)",
+ "byo_bot_name_placeholder": "例如 Multica Bot",
+ "byo_bot_name_hint": "名字里有空格时才需要填,机器人靠它把自己的 @ 和后面的命令分开。之后想改(包括在企业微信后台改名后),要先断开这个机器人再重新连接。",
"byo_submit": "连接",
"byo_submitting": "连接中…",
"byo_cancel": "取消",
diff --git a/packages/views/settings/components/wecom-tab.test.tsx b/packages/views/settings/components/wecom-tab.test.tsx
index cd8afeb5b7..4c63715261 100644
--- a/packages/views/settings/components/wecom-tab.test.tsx
+++ b/packages/views/settings/components/wecom-tab.test.tsx
@@ -133,6 +133,39 @@ describe("WecomAgentBindButton", () => {
);
});
+ // The bot's chat name reaches the server, and only when it was typed.
+ //
+ // WeCom delivers a group @-mention as literal text with no structured
+ // mention list, so a name containing a space ("Multica Bot") swallows the
+ // slash command typed after it. The name is the only way to tell where the
+ // mention ends — and it cannot be discovered, because the smart bot exposes
+ // no REST surface to ask. Left blank, the request omits it entirely so a
+ // re-install keeps whatever name the row already carries.
+ it("sends the bot's chat name when one is given, and omits it when not", async () => {
+ mockRegisterBYO.mockResolvedValue({ id: "i-1" });
+ renderUI(<WecomAgentBindButton agentId="agent-1" />);
+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));
+ await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aib94");
+ await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cret");
+ await userEvent.type(screen.getByTestId("wecom-byo-bot-name"), " Multica Bot ");
+ await userEvent.click(screen.getByTestId("wecom-byo-submit"));
+
+ await waitFor(() => expect(mockRegisterBYO).toHaveBeenCalled());
+ expect(mockRegisterBYO.mock.calls[0]?.[2].bot_name).toBe("Multica Bot");
+
+ cleanup();
+ mockRegisterBYO.mockClear();
+ mockRegisterBYO.mockResolvedValue({ id: "i-2" });
+ renderUI(<WecomAgentBindButton agentId="agent-2" />);
+ await userEvent.click(screen.getByTestId("wecom-agent-connect"));
+ await userEvent.type(await screen.findByTestId("wecom-byo-bot-id"), "aib95");
+ await userEvent.type(screen.getByTestId("wecom-byo-secret"), "s3cret");
+ await userEvent.click(screen.getByTestId("wecom-byo-submit"));
+
+ await waitFor(() => expect(mockRegisterBYO).toHaveBeenCalled());
+ expect(mockRegisterBYO.mock.calls[0]?.[2].bot_name).toBeUndefined();
+ });
+
it("shows the connected badge (not the CTA) when the agent has an active install", () => {
installationsRef.current = {
installations: [{ id: "i1", agent_id: "agent-1", bot_id: "aibot_x", status: "active" }],
diff --git a/packages/views/settings/components/wecom-tab.tsx b/packages/views/settings/components/wecom-tab.tsx
index 2cd007bd49..508fb34b3b 100644
--- a/packages/views/settings/components/wecom-tab.tsx
+++ b/packages/views/settings/components/wecom-tab.tsx
@@ -258,6 +258,7 @@ export function WecomAgentBindButton({
const [dialogOpen, setDialogOpen] = useState(false);
const [botId, setBotId] = useState("");
const [secret, setSecret] = useState("");
+ const [botName, setBotName] = useState("");
const [submitting, setSubmitting] = useState(false);
const { data: listing } = useQuery({
@@ -297,6 +298,7 @@ export function WecomAgentBindButton({
setDialogOpen(false);
setBotId("");
setSecret("");
+ setBotName("");
}
async function handleSubmit() {
@@ -305,12 +307,17 @@ export function WecomAgentBindButton({
if (submitting || !agentId || !bot_id || !secretTrimmed) return;
setSubmitting(true);
try {
- await api.registerWecomBYO(wsId, agentId, { bot_id, secret: secretTrimmed });
+ await api.registerWecomBYO(wsId, agentId, {
+ bot_id,
+ secret: secretTrimmed,
+ bot_name: botName.trim() || undefined,
+ });
await qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
toast.success(t(($) => $.wecom.byo_success_toast));
setDialogOpen(false);
setBotId("");
setSecret("");
+ setBotName("");
} catch (e) {
toast.error(
e instanceof Error ? e.message : t(($) => $.wecom.byo_failed_toast),
@@ -386,6 +393,25 @@ export function WecomAgentBindButton({
disabled={submitting}
/>
</div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="wecom-byo-bot-name">
+ {t(($) => $.wecom.byo_bot_name_label)}
+ </Label>
+ <Input
+ id="wecom-byo-bot-name"
+ data-testid="wecom-byo-bot-name"
+ value={botName}
+ onChange={(e) => setBotName(e.target.value)}
+ placeholder={t(($) => $.wecom.byo_bot_name_placeholder)}
+ autoComplete="off"
+ spellCheck={false}
+ disabled={submitting}
+ />
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.wecom.byo_bot_name_hint)}
+ </p>
+ </div>
</div>
<DialogFooter>
diff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.go
index 4af9d12d5b..45b3b44659 100644
--- a/server/internal/handler/wecom_web.go
+++ b/server/internal/handler/wecom_web.go
@@ -106,13 +106,19 @@ func (h *Handler) ListWecomInstallations(w http.ResponseWriter, r *http.Request)
}
// RegisterWecomBYORequest is the body an admin submits from the Web UI's
-// BYO dialog. Two fields: the bot's stable identifier (BotID) and its
-// long-connection secret. The secret is written straight through the
-// secretbox so plaintext never lives on this file's stack past the
-// wecom.InstallationService.Upsert call.
+// BYO dialog. The bot's stable identifier (BotID) and its long-connection
+// secret are copied from the WeCom admin console; the secret is written
+// straight through the secretbox so plaintext never lives on this file's
+// stack past the wecom.InstallationService.Upsert call.
type RegisterWecomBYORequest struct {
BotID string `json:"bot_id"`
Secret string `json:"secret"`
+
+ // BotName is the bot's name as it appears in a chat. Optional, and used
+ // for one thing: recognising the bot's own @-mention in a group, which
+ // WeCom delivers as literal text. Omitting it on a re-install of the same
+ // bot keeps whatever name the row already carries.
+ BotName string `json:"bot_name,omitempty"`
}
// RegisterWecomBYO (POST /api/workspaces/{id}/wecom/install/byo?agent_id=…)
@@ -168,6 +174,7 @@ func (h *Handler) RegisterWecomBYO(w http.ResponseWriter, r *http.Request) {
InstallerUserID: initiatorUUID,
BotID: strings.TrimSpace(body.BotID),
Secret: strings.TrimSpace(body.Secret),
+ BotDisplayName: strings.TrimSpace(body.BotName),
})
if err != nil {
// One bot is one live long connection, so the (wecom, bot_id) slot has
diff --git a/server/internal/integrations/wecom/installation.go b/server/internal/integrations/wecom/installation.go
index ee283cdbfc..f93fa6c684 100644
--- a/server/internal/integrations/wecom/installation.go
+++ b/server/internal/integrations/wecom/installation.go
@@ -36,6 +36,12 @@ type InstallationParams struct {
// Secret is the plaintext long-connection secret shown once at bot
// creation on the admin console. Sealed at the service boundary.
Secret string
+
+ // BotDisplayName is the bot's name as it appears in a chat. Optional;
+ // see Installation.BotDisplayName for why it exists and what an empty
+ // value falls back to. Empty on a re-install of the SAME bot keeps
+ // whatever is already on the row.
+ BotDisplayName string
}
// InstallationService creates, refreshes and revokes wecom smart-bot
@@ -181,13 +187,6 @@ func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams)
if err != nil {
return Installation{}, fmt.Errorf("wecom: encrypt secret: %w", err)
}
- cfg, err := encodeInstallConfig(Installation{
- BotID: p.BotID,
- SecretEncrypted: sealed,
- })
- if err != nil {
- return Installation{}, err
- }
// Reclaim-then-upsert. UpsertChannelInstallation conflicts on
// (workspace_id, agent_id, channel_type), but the (channel_type, app_id)
@@ -216,6 +215,31 @@ func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams)
return Installation{}, fmt.Errorf("wecom: reclaim dead installation: %w", err)
}
+ // The row this upsert is about to overwrite, read on the tx handle so it is
+ // serialized with the write. Zero when this is a first install.
+ carried, err := currentInstallation(ctx, qtx.Queries, p.WorkspaceID, p.AgentID)
+ if err != nil {
+ return Installation{}, err
+ }
+ // The chat name is optional in the dialog, so an admin rotating a leaked
+ // secret leaves it blank — and blanking it would put group slash commands
+ // back to the whitespace guess that this field exists to replace. Keep what
+ // is on the row. A bot SWAP is different: the old name belongs to the old
+ // bot, and carrying it would make the new bot answer to a mention that is
+ // not its own.
+ displayName := p.BotDisplayName
+ if displayName == "" && carried.BotID == p.BotID {
+ displayName = carried.BotDisplayName
+ }
+ cfg, err := encodeInstallConfig(Installation{
+ BotID: p.BotID,
+ SecretEncrypted: sealed,
+ BotDisplayName: displayName,
+ })
+ if err != nil {
+ return Installation{}, err
+ }
+
row, err := qtx.Queries.UpsertChannelInstallation(ctx, db.UpsertChannelInstallationParams{
WorkspaceID: p.WorkspaceID,
AgentID: p.AgentID,
@@ -238,6 +262,29 @@ func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams)
return installationFromRow(row)
}
+// currentInstallation reads the (workspace, agent, wecom) row an upsert is
+// about to replace, or the zero Installation when there is none.
+//
+// There is no query keyed on that triple — the conflict key of the upsert is
+// not something any read path needed until now — so this filters the
+// workspace's wecom rows, of which there are a handful. Running it on the
+// caller's queries handle is what makes it serializable with the write.
+func currentInstallation(ctx context.Context, q *db.Queries, workspaceID, agentID pgtype.UUID) (Installation, error) {
+ rows, err := q.ListChannelInstallationsByWorkspace(ctx, db.ListChannelInstallationsByWorkspaceParams{
+ WorkspaceID: workspaceID,
+ ChannelType: channelTypeWecom,
+ })
+ if err != nil {
+ return Installation{}, fmt.Errorf("wecom: read current installation: %w", err)
+ }
+ for _, row := range rows {
+ if row.AgentID == agentID {
+ return installationFromRow(row)
+ }
+ }
+ return Installation{}, nil
+}
+
// Sentinels for the one conflict Upsert cannot resolve: the bot is already
// connected somewhere else. UpsertChannelInstallation conflicts on
// (workspace_id, agent_id, channel_type), but idx_channel_installation_type_appid
diff --git a/server/internal/integrations/wecom/installation_bot_name_test.go b/server/internal/integrations/wecom/installation_bot_name_test.go
new file mode 100644
index 0000000000..5d6f597c1c
--- /dev/null
+++ b/server/internal/integrations/wecom/installation_bot_name_test.go
@@ -0,0 +1,142 @@
+package wecom
+
+// installation_bot_name_test.go — the bot's chat name survives a re-install and
+// does not survive a bot swap. DB-backed, because the whole point is what the
+// config JSONB holds after the upsert; skips when no migrated database is
+// reachable, like installation_reclaim_test.go beside it.
+//
+// Why it matters: the name is optional in the Connect dialog, so an admin
+// rotating a leaked secret leaves it blank. Blanking the stored name on that
+// write puts group slash commands back to the whitespace guess this field
+// exists to replace — silently, months after anyone typed it.
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ wcNameWS = "5c09e201-0000-4000-8000-000000000001"
+ wcNameRuntime = "5c09e201-0000-4000-8000-000000000003"
+ wcNameAgent = "5c09e201-0000-4000-8000-00000000000a"
+ wcNameUser = "5c09e201-0000-4000-8000-000000000005"
+
+ wcNameBotA = "bot_name_a"
+ wcNameBotB = "bot_name_b"
+)
+
+func setupBotName(t *testing.T) (context.Context, *pgxpool.Pool, *InstallationService) {
+ t.Helper()
+ pool := reclaimTestDB(t)
+ ctx := context.Background()
+ clean := func() {
+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE config->>'app_id' = ANY($1)`,
+ []string{wcNameBotA, wcNameBotB})
+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wcNameWS)
+ }
+ clean()
+ exec := func(q string, args ...any) {
+ if _, err := pool.Exec(ctx, q, args...); err != nil {
+ t.Fatalf("seed bot-name fixture: %v", err)
+ }
+ }
+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'wecom bot name', 'wecom-bot-name', '') ON CONFLICT (id) DO NOTHING`, wcNameWS)
+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)
+VALUES ($1, $2, 'wecom bot name runtime', 'local', 'multica_daemon') ON CONFLICT (id) DO NOTHING`, wcNameRuntime, wcNameWS)
+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)
+VALUES ($1, $2, 'wecom bot name agent', 'local', $3) ON CONFLICT (id) DO NOTHING`, wcNameAgent, wcNameWS, wcNameRuntime)
+ t.Cleanup(clean)
+ // The probe is the reclaim tests' always-succeeds fake; these tests are
+ // about what the config JSONB holds, not about the proof of control.
+ svc, _ := newReclaimSvc(t, pool)
+ return ctx, pool, svc
+}
+
+func botNameParams(bot, displayName string) InstallationParams {
+ return InstallationParams{
+ WorkspaceID: mustUUID(wcNameWS),
+ AgentID: mustUUID(wcNameAgent),
+ InstallerUserID: mustUUID(wcNameUser),
+ BotID: bot,
+ Secret: "s3cr3t",
+ BotDisplayName: displayName,
+ }
+}
+
+// TestRotatingTheSecretKeepsTheBotName: the admin re-opens Connect to paste a
+// fresh secret and does not retype the optional name. Losing it here breaks
+// every group slash command for a bot whose name has a space in it, with
+// nothing on screen to say so.
+func TestRotatingTheSecretKeepsTheBotName(t *testing.T) {
+ ctx, _, svc := setupBotName(t)
+
+ if _, err := svc.Upsert(ctx, botNameParams(wcNameBotA, "Multica Bot")); err != nil {
+ t.Fatalf("first install: %v", err)
+ }
+ again, err := svc.Upsert(ctx, botNameParams(wcNameBotA, ""))
+ if err != nil {
+ t.Fatalf("secret rotation: %v", err)
+ }
+ if again.BotDisplayName != "Multica Bot" {
+ t.Fatalf("BotDisplayName after rotation = %q, want it kept — a blank optional field "+
+ "erased the name, and every group slash command goes back to the whitespace guess", again.BotDisplayName)
+ }
+}
+
+// TestRenamingTheBotOverwritesTheStoredName: the carry-forward must not make
+// the field unchangeable. Renaming in the WeCom console and retyping it here
+// has to take effect.
+func TestRenamingTheBotOverwritesTheStoredName(t *testing.T) {
+ ctx, _, svc := setupBotName(t)
+
+ if _, err := svc.Upsert(ctx, botNameParams(wcNameBotA, "Multica Bot")); err != nil {
+ t.Fatalf("first install: %v", err)
+ }
+ renamed, err := svc.Upsert(ctx, botNameParams(wcNameBotA, "Acme Support Bot"))
+ if err != nil {
+ t.Fatalf("rename: %v", err)
+ }
+ if renamed.BotDisplayName != "Acme Support Bot" {
+ t.Fatalf("BotDisplayName after rename = %q, want Acme Support Bot", renamed.BotDisplayName)
+ }
+}
+
+// TestSwappingTheBotDoesNotInheritTheOldName: swapping which bot an agent uses
+// reuses the same installation row. Carrying the name across would make the new
+// bot strip a mention that belongs to a bot nobody is talking to.
+func TestSwappingTheBotDoesNotInheritTheOldName(t *testing.T) {
+ ctx, _, svc := setupBotName(t)
+
+ if _, err := svc.Upsert(ctx, botNameParams(wcNameBotA, "Multica Bot")); err != nil {
+ t.Fatalf("first install: %v", err)
+ }
+ swapped, err := svc.Upsert(ctx, botNameParams(wcNameBotB, ""))
+ if err != nil {
+ t.Fatalf("bot swap: %v", err)
+ }
+ if swapped.BotDisplayName != "" {
+ t.Fatalf("the new bot inherited the previous bot's chat name %q", swapped.BotDisplayName)
+ }
+}
+
+// TestTheBotNameSurvivesTheConfigRoundTrip: the field has to reach the JSONB
+// and come back, or nothing above proves anything about what the WS connector
+// reads at boot.
+func TestTheBotNameSurvivesTheConfigRoundTrip(t *testing.T) {
+ t.Parallel()
+ cfg, err := encodeInstallConfig(Installation{BotID: "bot-xyz", BotDisplayName: "Multica Bot"})
+ if err != nil {
+ t.Fatalf("encode: %v", err)
+ }
+ out, err := installationFromRow(db.ChannelInstallation{Config: cfg, Status: "active"})
+ if err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if out.BotDisplayName != "Multica Bot" {
+ t.Fatalf("BotDisplayName round trip = %q, want Multica Bot", out.BotDisplayName)
+ }
+}
diff --git a/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go b/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go
new file mode 100644
index 0000000000..122a8afbe3
--- /dev/null
+++ b/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go
@@ -0,0 +1,229 @@
+package wecom
+
+// regression_group_mention_swallows_command_test.go — a slash command typed
+// after an @-mention has to still be a command.
+//
+// In a WeCom group the ONLY way to reach the bot is to @-mention it, and the
+// mention is delivered as part of the message text: "@Multica Bot /issue 登录
+// 失败". The shared command parsers read the first non-empty line and want the
+// directive at the start of it, so with the mention still in front they see
+// "@Multica" and decide this is ordinary prose. Every slash command in every
+// group was silently dropped: no issue filed, no fresh session, and nothing
+// said to the person about it.
+//
+// Slack strips its mention token before classifying (slack/inbound.go
+// cleanText, wired to CommandText at slack/inbound.go:131) and Feishu is handed
+// an already-clean command body by the platform (lark/feishu_channel.go:139).
+// WeCom was the one adapter passing the raw text straight through.
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// groupCallbackFrame is a real group delivery: WeCom only forwards a group
+// message to the bot when the bot was addressed, so the mention is always
+// there.
+func groupCallbackFrame(t *testing.T, content string) frameEnvelope {
+ t.Helper()
+ mc := aibotMsgCallback{MsgID: "m-group", ChatID: "GROUP_1", ChatType: "group", MsgType: "text"}
+ mc.From.UserID = "T-alex"
+ mc.Text.Content = content
+ body, err := json.Marshal(mc)
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ return frameEnvelope{Cmd: cmdMsgCallback, Body: body}
+}
+
+// dispatchGroupMessage runs one group frame through the real read-loop
+// dispatch and returns what the engine's inbound handler was handed.
+func dispatchGroupMessage(t *testing.T, botName, content string) channel.InboundMessage {
+ t.Helper()
+ var got channel.InboundMessage
+ called := false
+ c := &wecomChannel{
+ botID: "bot-1",
+ botDisplayName: botName,
+ handler: func(_ context.Context, m channel.InboundMessage) error {
+ called, got = true, m
+ return nil
+ },
+ }
+ if err := c.dispatchFrame(context.Background(), groupCallbackFrame(t, content), newWSSender(&recordingConn{}, nil), slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if !called {
+ t.Fatal("the inbound handler was never called for a group text message")
+ }
+ return got
+}
+
+// TestAnIssueCommandAfterAMentionIsStillACommand: what a person experiences
+// when this regresses is that /issue in a group does nothing whatsoever — no
+// issue is filed and the bot answers as if they had just been chatting.
+func TestAnIssueCommandAfterAMentionIsStillACommand(t *testing.T) {
+ t.Parallel()
+ msg := dispatchGroupMessage(t, "", "@Andrew /issue 登录失败")
+
+ cmd, ok := engine.ParseIssueCommand(msg.CommandText)
+ if !ok {
+ t.Fatalf("the shared parser did not see /issue.\nCommandText = %q — the @-mention is still in "+
+ "front of the directive, so no issue is filed and nothing tells the person why.", msg.CommandText)
+ }
+ if cmd.Title != "登录失败" {
+ t.Errorf("issue title = %q, want 登录失败", cmd.Title)
+ }
+ // A pure /issue must not also run the agent, exactly as in a 1:1 chat —
+ // otherwise the group gets the confirmation AND "I don't know this slash
+ // command" underneath it.
+ if !msg.SkipAgentRun {
+ t.Error("SkipAgentRun = false for a pure group /issue; the agent would answer the command text too")
+ }
+}
+
+// TestAFreshSessionCommandAfterAMentionIsStillACommand: /new is the other
+// shared directive. When it is dropped the agent keeps the previous thread and
+// answers with a conversation the person was trying to leave behind.
+func TestAFreshSessionCommandAfterAMentionIsStillACommand(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct{ name, body string }{
+ {"mention then command", "@Andrew /new 重新分析一下"},
+ {"two mentions then command", "@Andrew @Bowen /new 重新分析一下"},
+ {"mention, full-width space, command", "@Andrew /new 重新分析一下"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ msg := dispatchGroupMessage(t, "", tc.body)
+ if _, ok := engine.ParseFreshSessionCommand(msg.CommandText); !ok {
+ t.Fatalf("the shared parser did not see /new in %q.\nCommandText = %q — the request for a "+
+ "fresh session is silently dropped and the agent answers with the old conversation "+
+ "still in hand.", tc.body, msg.CommandText)
+ }
+ })
+ }
+}
+
+// TestAMultiWordBotNameDoesNotSwallowTheCommand: a bot named "Multica Bot" is
+// mentioned as "@Multica Bot", and cutting the mention at the first space
+// leaves "Bot /issue …", which is not a command either. The configured name is
+// the only way to know where the mention ends — the callback carries no
+// structured mention list, and the smart bot exposes no REST surface to ask.
+func TestAMultiWordBotNameDoesNotSwallowTheCommand(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ botName string
+ in string
+ want string
+ }{
+ {"two-word name", "Multica Bot", "@Multica Bot /new 重新分析这批数据", "/new 重新分析这批数据"},
+ {"three-word name", "Acme Support Bot", "@Acme Support Bot /issue 登录失败", "/issue 登录失败"},
+ {"one-word name still works", "Andrew", "@Andrew /new 重新分析", "/new 重新分析"},
+ {"chinese name", "小助手", "@小助手 /issue 报销单不对", "/issue 报销单不对"},
+ {"a colleague's mention before ours", "Multica Bot", "@李雷 @Multica Bot /new 分析", "/new 分析"},
+ {"no name configured falls back to the space", "", "@Andrew /new 重新分析", "/new 重新分析"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := stripLeadingMentions(tc.in, tc.botName); got != tc.want {
+ t.Fatalf("stripLeadingMentions(%q, %q) = %q, want %q", tc.in, tc.botName, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestAMultiWordBotNameReachesTheParser is the same defect one level up: the
+// configured name has to travel from the installation config to the point
+// where the mention is recognised, or the table above proves nothing.
+func TestAMultiWordBotNameReachesTheParser(t *testing.T) {
+ t.Parallel()
+ msg := dispatchGroupMessage(t, "Multica Bot", "@Multica Bot /issue 登录失败")
+ cmd, ok := engine.ParseIssueCommand(msg.CommandText)
+ if !ok || cmd.Title != "登录失败" {
+ t.Fatalf("CommandText = %q — the bot's configured name never reached the mention strip", msg.CommandText)
+ }
+}
+
+// TestAGroupMentionKeepsTheWordsAndTheTranscript: stripping the addressing
+// must not eat the message, and the stored body still has to show who was
+// addressed.
+func TestAGroupMentionKeepsTheWordsAndTheTranscript(t *testing.T) {
+ t.Parallel()
+ msg := dispatchGroupMessage(t, "", "@Andrew 昨天的日志里有什么报错")
+
+ if !strings.Contains(msg.Text, "@Andrew") {
+ t.Errorf("the stored message lost the addressing: %q", msg.Text)
+ }
+ if !strings.Contains(msg.CommandText, "昨天的日志里有什么报错") {
+ t.Errorf("the command source lost the question: %q", msg.CommandText)
+ }
+ if msg.SkipAgentRun {
+ t.Error("an ordinary question must still run the agent")
+ }
+}
+
+// TestAMentionOfSomebodyElseIsNotStripped: only the addressing at the very
+// front is a mention of the bot. A message that talks ABOUT a colleague keeps
+// their name — rewriting it would change what the person said.
+func TestAMentionOfSomebodyElseIsNotStripped(t *testing.T) {
+ t.Parallel()
+ msg := dispatchGroupMessage(t, "", "@Andrew 帮我问一下 @李雷 昨天那个数")
+ if !strings.Contains(msg.CommandText, "@李雷") {
+ t.Fatalf("a mention inside the sentence was stripped too: %q", msg.CommandText)
+ }
+}
+
+// TestAConfiguredNameDoesNotManufactureACommand: the strip only ever removes
+// what the operator actually named, so prose cannot be promoted into a
+// directive by configuring a name.
+func TestAConfiguredNameDoesNotManufactureACommand(t *testing.T) {
+ t.Parallel()
+ const in = "@李雷 ask him about /issue tracking"
+ got := stripLeadingMentions(in, "Multica Bot")
+ if strings.HasPrefix(got, "/issue") {
+ t.Fatalf("prose became a command: %q -> %q", in, got)
+ }
+}
+
+// TestAWholeMessageOfNothingButAMentionIsLeftAlone: with no words after the
+// mention there is no command to find. Returning an empty string here would
+// hand the parsers a body the person never typed.
+func TestAWholeMessageOfNothingButAMentionIsLeftAlone(t *testing.T) {
+ t.Parallel()
+ if got := stripLeadingMentions("@Andrew", ""); got != "@Andrew" {
+ t.Fatalf("stripLeadingMentions(%q, \"\") = %q, want it untouched", "@Andrew", got)
+ }
+}
+
+// TestSessionBinder_AdapterCommandTextWins: the binder is the last link. It
+// used to overwrite the adapter's command source with the stored body, which
+// threw away the mention-stripped line just above and handed the /issue parser
+// "@Multica Bot /issue …" again. Same two lines as
+// lark/feishu_resolvers.go:206 and slack/resolvers.go:337.
+func TestSessionBinder_AdapterCommandTextWins(t *testing.T) {
+ t.Parallel()
+ fb := &fakeSessionBinder{}
+ b := &sessionBinder{session: fb}
+ _, err := b.AppendMessage(context.Background(), engine.AppendParams{
+ SessionID: mustTestUUID(t),
+ Message: channel.InboundMessage{
+ Text: "@Multica Bot /issue 登录失败",
+ CommandText: "/issue 登录失败",
+ MessageID: "m9",
+ },
+ })
+ if err != nil {
+ t.Fatalf("AppendMessage: %v", err)
+ }
+ if fb.appendIn.Body != "@Multica Bot /issue 登录失败" {
+ t.Errorf("stored body = %q, want the message exactly as it arrived", fb.appendIn.Body)
+ }
+ if fb.appendIn.CommandText != "/issue 登录失败" {
+ t.Errorf("CommandText = %q, want the adapter's stripped command source", fb.appendIn.CommandText)
+ }
+}
diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.go
index a678de5338..307feafe2f 100644
--- a/server/internal/integrations/wecom/resolvers_test.go
+++ b/server/internal/integrations/wecom/resolvers_test.go
@@ -73,7 +73,7 @@ func TestSessionBinder_AppendUsesTextAsCommand(t *testing.T) {
t.Fatalf("AppendMessage: %v", err)
}
if fb.appendIn.Body != "/issue do a thing" || fb.appendIn.CommandText != "/issue do a thing" {
- t.Errorf("append body/command = %q/%q, want both to equal the text (wecom has no enrichment)", fb.appendIn.Body, fb.appendIn.CommandText)
+ t.Errorf("append body/command = %q/%q, want both to equal the text (no adapter command source to prefer)", fb.appendIn.Body, fb.appendIn.CommandText)
}
}
diff --git a/server/internal/integrations/wecom/types.go b/server/internal/integrations/wecom/types.go
index 3a0cbd8cda..c22c008b2e 100644
--- a/server/internal/integrations/wecom/types.go
+++ b/server/internal/integrations/wecom/types.go
@@ -85,6 +85,17 @@ type Installation struct {
// distinct from the token/EncodingAESKey used by callback-mode bots
// (which we do not use). Rotated via re-install.
SecretEncrypted []byte
+
+ // BotDisplayName is what the bot is called in a chat. A WeCom group
+ // mention arrives as literal text — "@Multica Bot /new 重新分析" — with no
+ // structured mention list anywhere in the payload, so recognising where
+ // the mention ends is the only way a name containing a space does not
+ // swallow the command after it.
+ //
+ // Optional. Empty falls back to the whitespace heuristic in
+ // stripLeadingMentions, which is correct for a single-word name and is
+ // what every existing installation gets.
+ BotDisplayName string
}
// InstallationCredentials is the plaintext-bearing view the WebSocket
@@ -103,6 +114,12 @@ type installConfig struct {
AppID string `json:"app_id"`
BotID string `json:"bot_id"`
SecretEncrypted []byte `json:"secret_encrypted"`
+
+ // BotDisplayName is the bot's name as it appears in a chat, used only to
+ // recognise its own @-mention (ws_frame.go). Optional and absent on every
+ // existing row; absent means the whitespace heuristic, which is what the
+ // adapter did before this field existed.
+ BotDisplayName string `json:"bot_display_name,omitempty"`
}
// encodeInstallConfig marshals an Installation's config-bearing fields into
@@ -115,6 +132,7 @@ func encodeInstallConfig(inst Installation) ([]byte, error) {
AppID: inst.BotID,
BotID: inst.BotID,
SecretEncrypted: inst.SecretEncrypted,
+ BotDisplayName: inst.BotDisplayName,
})
}
@@ -136,5 +154,6 @@ func installationFromRow(row db.ChannelInstallation) (Installation, error) {
Status: InstallationStatus(row.Status),
BotID: cfg.BotID,
SecretEncrypted: cfg.SecretEncrypted,
+ BotDisplayName: cfg.BotDisplayName,
}, nil
}
diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.go
index 3691c05772..1185d0e6fb 100644
--- a/server/internal/integrations/wecom/wecom_channel.go
+++ b/server/internal/integrations/wecom/wecom_channel.go
@@ -68,6 +68,10 @@ type wecomChannel struct {
installationID pgtype.UUID
botID string
secret string
+ // botDisplayName is what this bot is called in a chat, from the
+ // installation config. Empty on every installation that has not filled it
+ // in; see stripLeadingMentions for what an empty name falls back to.
+ botDisplayName string
handler channel.InboundHandler
dialer Dialer
wsURL string
@@ -368,7 +372,7 @@ func (c *wecomChannel) dispatchFrame(ctx context.Context, env frameEnvelope, sen
log.Warn("wecom: bad aibot_msg_callback body", "error", err)
return nil
}
- msg := channelMessageFromCallback(c.botID, mc, env.Headers.ReqID)
+ msg := channelMessageFromCallback(c.botID, c.botDisplayName, mc, env.Headers.ReqID)
if mc.MsgType != "text" {
// Iteration 1 routes only text. Rather than drop other types
// (voice / image / file) silently — which reads as a broken bot —
@@ -552,6 +556,7 @@ func newWecomFactory(deps ChannelDeps) channel.Factory {
installationID: cfg.ID,
botID: creds.BotID,
secret: creds.Secret,
+ botDisplayName: ic.BotDisplayName,
handler: cfg.Handler,
dialer: deps.Dialer,
wsURL: deps.WSURL,
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
index a8fa730ca5..1983827994 100644
--- a/server/internal/integrations/wecom/wecom_resolvers.go
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -215,12 +215,21 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
}
func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ // The adapter's own command source wins, and Text is only the fallback.
+ // Overwriting it with Text — which this used to do — threw away the
+ // mention-stripped line the adapter had already worked out, so in a group
+ // the /issue parser was handed "@Multica Bot /issue …" and saw prose.
+ // Same two lines as lark/feishu_resolvers.go:206 and slack/resolvers.go:337.
+ 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: p.Message.Text, // wecom has no enrichment; command == body
+ CommandText: commandText,
MessageID: p.Message.MessageID,
ClaimToken: p.ClaimToken,
})
diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.go
index 35df1757e3..cb52fc8a06 100644
--- a/server/internal/integrations/wecom/ws_frame.go
+++ b/server/internal/integrations/wecom/ws_frame.go
@@ -14,6 +14,7 @@ import (
"encoding/json"
"errors"
"strings"
+ "unicode"
"github.com/multica-ai/multica/server/internal/integrations/channel"
)
@@ -148,7 +149,11 @@ type InboundMessage struct {
// A user @-mentioning the bot in a group is not distinguishable from a raw
// group message on the wire — WeCom only forwards to the bot when it was
// addressed, so any received group message counts as addressed.
-func channelMessageFromCallback(botID string, mc aibotMsgCallback, reqID string) channel.InboundMessage {
+//
+// botDisplayName is the bot's name in a chat, from the installation config. It
+// is used for one thing: recognising where the sender's @-mention ends. Empty
+// is fine and falls back to a whitespace heuristic; see stripLeadingMentions.
+func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallback, reqID string) channel.InboundMessage {
chatType := channel.ChatTypeP2P
if strings.EqualFold(mc.ChatType, "group") {
chatType = channel.ChatTypeGroup
@@ -160,6 +165,22 @@ func channelMessageFromCallback(botID string, mc aibotMsgCallback, reqID string)
chatID = senderID
}
+ // The command source is the sender's own words. In a group the @-mention IS
+ // how you reach the bot, so it arrives glued to whatever was typed after it
+ // — "@Andrew /new" is a person asking for a fresh session, not prose that
+ // happens to contain a word — and the addressing comes off the front.
+ //
+ // Groups only. In a 1:1 nobody has to address the bot, so a leading "@" is
+ // the sender naming a colleague they are talking ABOUT: "@李雷 /issue 帮我
+ // 问问他" is a question, and stripping the name would turn it into a filed
+ // issue nobody asked for plus, via SkipAgentRun below, no answer at all.
+ // Passing the raw content through keeps p2p exactly where it was before
+ // CommandText was set here.
+ command := mc.Text.Content
+ if chatType == channel.ChatTypeGroup {
+ command = stripLeadingMentions(mc.Text.Content, botDisplayName)
+ }
+
wm := InboundMessage{
BotID: botID,
MsgID: mc.MsgID,
@@ -178,6 +199,15 @@ func channelMessageFromCallback(botID string, mc aibotMsgCallback, reqID string)
Type: channelMsgType(mc.MsgType),
Text: mc.Text.Content,
AddressedToBot: true,
+ // The sender's own words, with a group's addressing removed. Command
+ // classification is shared (channel/message.go) and falls back to Text
+ // when this is empty — and in a group Text starts with the mention, so
+ // every slash command read as ordinary prose. Lark sets this from its
+ // command body (feishu_channel.go:139) and Slack from its cleaned text
+ // (slack/inbound.go:131); WeCom was the one adapter leaving it empty.
+ // In a p2p chat this is Text verbatim, which is what the fallback was
+ // already producing.
+ CommandText: command,
// A pure /issue command in WeCom should NOT trigger the
// agent — the engine already creates the issue and the
// OutboundReplier already sends "✅ 已创建 #N". Letting the agent
@@ -185,7 +215,13 @@ func channelMessageFromCallback(botID string, mc aibotMsgCallback, reqID string)
// command" reply that just clutters the conversation. wecom is
// alone on this — Slack/Lark keep the historical "let the agent
// see /issue and respond too" behaviour.
- SkipAgentRun: isIssueCommand(mc.Text.Content),
+ //
+ // Read off the same source the engine will parse, so a group /issue
+ // behaves like the p2p one instead of filing the issue and then also
+ // asking the agent about it. It has to be the same source: read off the
+ // raw text instead and a p2p "@李雷 /issue …" would file an issue and
+ // stay silent, which is the whole reason the strip above is gated.
+ SkipAgentRun: isIssueCommand(command),
Source: channel.Source{
ChannelType: TypeWecom,
ChatID: chatID,
@@ -196,6 +232,56 @@ func channelMessageFromCallback(botID string, mc aibotMsgCallback, reqID string)
}
}
+// stripLeadingMentions removes the @-mentions a message opens with, which in a
+// group chat is how the sender addresses the bot. WeCom puts them in the text
+// and sends no mention list alongside it, so there is nothing to match against
+// but the shape: an "@" at the very front, up to the next space.
+//
+// Group messages only — the caller gates it on chatType. Nobody addresses the
+// bot in a 1:1, so the same "@" at the front there is a colleague's name in the
+// sender's own sentence, and removing it would rewrite what they said.
+//
+// Only the front. A name further into the sentence is the sender talking ABOUT
+// somebody — "@Andrew ask @李雷 about yesterday" is one instruction naming one
+// colleague — and stripping that would quietly rewrite what they said.
+//
+// This feeds command classification only. The stored message keeps the text
+// exactly as it arrived, so the transcript still shows who was addressed.
+//
+// Slack does the same thing with a regex over its mention token
+// (slack/inbound.go cleanText); Feishu is handed an already-clean command body
+// by the platform. WeCom was the one adapter passing the raw text through.
+func stripLeadingMentions(s, botName string) string {
+ for {
+ trimmed := strings.TrimLeftFunc(s, unicode.IsSpace)
+ if !strings.HasPrefix(trimmed, "@") {
+ return trimmed
+ }
+ // Our own name first, matched whole. A display name may contain
+ // spaces — "Multica Bot" is the obvious one — and cutting at the
+ // first space would leave "Bot /new 重新分析", which is not a command,
+ // so every slash command in that group would still be dropped.
+ //
+ // The name is not guessed. It comes from the installation config, set
+ // when the bot was connected, because the callback carries no
+ // structured mention list to read it from. Absent, the heuristic below
+ // is what runs — correct for a one-word name, and what every
+ // installation has until somebody fills the field in.
+ if botName != "" && strings.HasPrefix(trimmed[1:], botName) {
+ s = trimmed[1+len(botName):]
+ continue
+ }
+ i := strings.IndexFunc(trimmed, unicode.IsSpace)
+ if i < 0 {
+ // The whole message is one mention and nothing else. There is no
+ // command and no words — leave it, so an empty body is decided by
+ // the caller rather than manufactured here.
+ return trimmed
+ }
+ s = trimmed[i:]
+ }
+}
+
// isIssueCommand mirrors engine.ParseIssueCommand's front-of-body detection
// without materializing the parsed struct — we only need the yes/no. A pure
// /issue command starts at the first non-empty line, "/issue" as a whole
diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.go
index 08b926484e..a352e3605e 100644
--- a/server/internal/integrations/wecom/ws_frame_test.go
+++ b/server/internal/integrations/wecom/ws_frame_test.go
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
)
func TestChannelMessageFromCallback_GroupKeepsSenderDistinctFromChat(t *testing.T) {
@@ -22,7 +23,7 @@ func TestChannelMessageFromCallback_GroupKeepsSenderDistinctFromChat(t *testing.
mc.From.UserID = "SENDER_USERID"
mc.Text.Content = "hello"
- msg := channelMessageFromCallback("bot-1", mc, "req-1")
+ msg := channelMessageFromCallback("bot-1", "", mc, "req-1")
if msg.Source.ChatType != channel.ChatTypeGroup {
t.Errorf("chat type = %v, want group", msg.Source.ChatType)
@@ -42,7 +43,7 @@ func TestChannelMessageFromCallback_P2PFallsBackChatIDToSender(t *testing.T) {
mc := aibotMsgCallback{MsgID: "m2", ChatID: "", ChatType: "single", MsgType: "text"}
mc.From.UserID = "USER_A"
- msg := channelMessageFromCallback("bot-1", mc, "req-2")
+ msg := channelMessageFromCallback("bot-1", "", mc, "req-2")
if msg.Source.ChatType != channel.ChatTypeP2P {
t.Errorf("chat type = %v, want p2p", msg.Source.ChatType)
@@ -52,6 +53,74 @@ func TestChannelMessageFromCallback_P2PFallsBackChatIDToSender(t *testing.T) {
}
}
+// TestChannelMessageFromCallback_P2PMentionIsProseNotACommand: the mention
+// strip is for groups, where the @ is the only way to reach the bot. In a 1:1
+// nobody has to address anyone, so an @ at the front is the sender naming a
+// colleague inside their own sentence.
+//
+// What a person experiences when this is not scoped: they type "@李雷 /issue
+// 帮我问问他" to the bot, meaning "ask 李雷 about the issue" — and an issue
+// titled 帮我问问他 is filed that they never asked for. SkipAgentRun is read
+// off the same line, so the bot also says nothing back. A stray issue and
+// silence, from a message that was a question.
+func TestChannelMessageFromCallback_P2PMentionIsProseNotACommand(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct{ name, content string }{
+ {"issue directive after a colleague's name", "@李雷 /issue 帮我问问他"},
+ {"fresh-session directive after a colleague's name", "@李雷 /new 的排期你问一下"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ mc := aibotMsgCallback{MsgID: "m-p2p", ChatID: "", ChatType: "single", MsgType: "text"}
+ mc.From.UserID = "USER_A"
+ mc.Text.Content = tc.content
+
+ // A configured display name must not change this either: it is the
+ // chat type that decides, not whose name is at the front.
+ msg := channelMessageFromCallback("bot-1", "Multica Bot", mc, "req-p2p")
+
+ if msg.CommandText != tc.content {
+ t.Errorf("CommandText = %q, want %q untouched — in a 1:1 the leading @ is a colleague's "+
+ "name in the sender's sentence, not addressing the bot", msg.CommandText, tc.content)
+ }
+ if cmd, ok := engine.ParseIssueCommand(msg.CommandText); ok {
+ t.Errorf("an issue titled %q would be filed from %q, which the sender never asked for",
+ cmd.Title, tc.content)
+ }
+ if _, ok := engine.ParseFreshSessionCommand(msg.CommandText); ok {
+ t.Errorf("%q would throw away the running session the sender was in the middle of", tc.content)
+ }
+ if msg.SkipAgentRun {
+ t.Errorf("SkipAgentRun = true for %q; the sender's question gets no reply at all", tc.content)
+ }
+ })
+ }
+}
+
+// TestChannelMessageFromCallback_P2PCommandStillWorks is the other side of the
+// gate: scoping the strip to groups must not stop a plain 1:1 slash command
+// from being one. This is the path that worked before the mention strip
+// existed, and it has to keep working after it.
+func TestChannelMessageFromCallback_P2PCommandStillWorks(t *testing.T) {
+ t.Parallel()
+ mc := aibotMsgCallback{MsgID: "m-p2p-cmd", ChatID: "", ChatType: "single", MsgType: "text"}
+ mc.From.UserID = "USER_A"
+ mc.Text.Content = "/issue 登录失败"
+
+ msg := channelMessageFromCallback("bot-1", "Multica Bot", mc, "req-p2p-cmd")
+
+ cmd, ok := engine.ParseIssueCommand(msg.CommandText)
+ if !ok {
+ t.Fatalf("CommandText = %q — a 1:1 /issue stopped being a command", msg.CommandText)
+ }
+ if cmd.Title != "登录失败" {
+ t.Errorf("issue title = %q, want 登录失败", cmd.Title)
+ }
+ if !msg.SkipAgentRun {
+ t.Error("SkipAgentRun = false for a pure 1:1 /issue; the agent would answer the command text too")
+ }
+}
+
func TestChannelMsgType_NonTextIsUnknown(t *testing.T) {
t.Parallel()
cases := map[string]channel.MsgType{