Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7706 feat(wecom): every notice reads the language of whoever will read it (#8831)
Xichang(Seacen) Zhaofa5d470ae40a
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 4aaf9eadba..adca0985dd 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -978,7 +978,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusBinding: wecomBinding,Senders: wecomSenders,AppURL: appURLFromEnv(),- Logger: slog.Default(),+ // Without this the replier has no way to read a reader's+ // profile language and every notice falls back to the+ // deployment's, which is the whole of what this is for.+ Languages: queries,+ Logger: slog.Default(),})// Wecom shares the engine.ChatSession (channel_type-keyed) sodiff --git a/server/cmd/server/wecom_replier_wiring_test.go b/server/cmd/server/wecom_replier_wiring_test.gonew file mode 100644index 0000000000..6a86b30520--- /dev/null+++ b/server/cmd/server/wecom_replier_wiring_test.go@@ -0,0 +1,65 @@+package main++import (+ "bytes"+ "crypto/rand"+ "encoding/base64"+ "log/slog"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The replier's language lookup is an optional field, and a missing one has no+// symptom of its own: nothing errors, nothing is empty, every notice simply+// comes out in the deployment's language whatever the reader's profile says.+// Every unit test in the wecom package sets it by hand, so the package stays+// green with the production wiring absent — which is exactly how it shipped+// absent the first time.+//+// So this asserts it off the REAL boot path: NewRouter, the same call main()+// makes. What it reads is the warning NewOutboundReplier logs when the field is+// nil, which is also what an operator would have to notice today.+//+// Two routers are built, one without the WeCom key and one with it, the same+// way wecom_bubble_wiring_test.go does: chat:done has listeners outside WeCom+// whenever another channel is configured, so only the difference between the+// two says the WeCom block ran.+func TestWecomReplierGetsItsLanguageLookupOnTheRealBootPath(t *testing.T) {+ key := make([]byte, secretbox.KeySize)+ if _, err := rand.Read(key); err != nil {+ t.Fatalf("generate a wecom secretbox key: %v", err)+ }++ var logged bytes.Buffer+ restore := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug})))+ t.Cleanup(func() { slog.SetDefault(restore) })++ t.Setenv("MULTICA_WECOM_SECRET_KEY", "")+ withoutWecom := events.New()+ NewRouter(nil, realtime.NewHub(), withoutWecom, analytics.NoopClient{}, nil)++ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))+ withWecom := events.New()+ NewRouter(nil, realtime.NewHub(), withWecom, analytics.NoopClient{}, nil)++ // Anti-vacuity: with no WeCom block entered, no replier is built and the+ // warning cannot appear for the reason this test names.+ if got, base := withWecom.SubscriberCount(protocol.EventChatDone),+ withoutWecom.SubscriberCount(protocol.EventChatDone); got <= base {+ t.Fatalf("the WeCom boot block did not run: chat:done listeners %d with the key set vs %d without, "++ "so this test proves nothing. Re-point this guard at wherever WeCom is wired now", got, base)+ }++ if got := logged.String(); strings.Contains(got, "no language lookup wired") {+ t.Errorf("the production replier was built without a language lookup, so every notice it sends "++ "uses the deployment language whatever the reader's profile says — which is the whole of "++ "what the copy pack is for. Set OutboundReplierConfig.Languages in router.go.\nlog:\n%s", got)+ }+}diff --git a/server/internal/integrations/wecom/helpers_test.go b/server/internal/integrations/wecom/helpers_test.goindex d7d0b6a610..0533b50878 100644--- a/server/internal/integrations/wecom/helpers_test.go+++ b/server/internal/integrations/wecom/helpers_test.go@@ -104,15 +104,15 @@ func TestValidateInstallationParams(t *testing.T) {func TestIssueCreatedText(t *testing.T) {t.Parallel()- withTitle := issueCreatedText(engine.Result{IssueIdentifier: "MUL-42", IssueTitle: "Fix the thing"})+ withTitle := issueCreatedText(engine.Result{IssueIdentifier: "MUL-42", IssueTitle: "Fix the thing"}, copyFor(DefaultLocale))if !strings.Contains(withTitle, "MUL-42") || !strings.Contains(withTitle, "Fix the thing") {t.Errorf("issueCreatedText = %q, want identifier + title", withTitle)}- noTitle := issueCreatedText(engine.Result{IssueIdentifier: "MUL-43"})+ noTitle := issueCreatedText(engine.Result{IssueIdentifier: "MUL-43"}, copyFor(DefaultLocale))if !strings.Contains(noTitle, "MUL-43") || strings.Contains(noTitle, "—") {t.Errorf("issueCreatedText without title = %q, want just the identifier", noTitle)}- noID := issueCreatedText(engine.Result{IssueNumber: 7})+ noID := issueCreatedText(engine.Result{IssueNumber: 7}, copyFor(DefaultLocale))if !strings.Contains(noID, "#7") {t.Errorf("issueCreatedText with no identifier = %q, want #7 fallback", noID)}diff --git a/server/internal/integrations/wecom/inbox_message.go b/server/internal/integrations/wecom/inbox_message.goindex cedbfd2459..b323b51748 100644--- a/server/internal/integrations/wecom/inbox_message.go+++ b/server/internal/integrations/wecom/inbox_message.go@@ -12,35 +12,31 @@ import ("unicode/utf8")-// aibot markdown size cap. WeCom rejects the whole frame if we-// push more than ~4096 chars, so we truncate the body on that budget. We-// use 4000 to leave headroom for the prefix + link suffix.+// inboxMarkdownMaxLen is the budget this card is written to, in RUNES.+//+// It is not the platform's cap and never was. The documented cap on one+// aibot_send_msg markdown body is 20480 utf8 bytes — sendMsgContentLimit in+// ws_frame.go, sourced to+// https://developer.work.weixin.qq.com/document/path/101138 — and a body past+// it is refused whole with errcode 45002. This constant used to be justified+// by a "~4096 chars" figure with no source behind it, which is both a+// different number and a different unit: 4000 runes of Chinese is around+// 12000 bytes, comfortably inside the real ceiling.+//+// So what this bounds is the card's length as a product choice, not as a+// protocol limit. It stays where it is because an inbox card is a pointer to+// the item and not the item, and truncating it here keeps the whole card —+// prefix, body and the "view detail" link — inside the frame with room to+// spare. Raising it would be a deliberate decision about how long a+// notification should be, and the ceiling that decision has to respect is+// sendMsgContentLimit measured in bytes, not this number.const inboxMarkdownMaxLen = 4000-// inboxTypeLabels are the Chinese display names used in the notification-// preamble. Kept locally so wecom does not reach into cmd/server for it;-// the two lists agree by convention.-var inboxTypeLabels = map[string]string{- "issue_assigned": "任务指派",- "mentioned": "提及你",- "status_changed": "状态变更",- "comment_added": "新评论",- "new_comment": "新评论",- "reaction_added": "表情反应",- "task_failed": "task 失败",- "unassigned": "取消指派",- "assignee_changed": "指派人变更",- "priority_changed": "优先级变更",- "due_date_changed": "截止日期变更",- "start_date_changed": "开始日期变更",-}--func inboxTypeLabel(t string) string {- if label, ok := inboxTypeLabels[t]; ok {- return label- }- return "新消息"-}+// The notification type labels and the deep link's anchor text live in the+// copy pack (strings.go), read through copyPack.label / InboxDetailLink. The+// pack's zh-Hans labels are the same table this file used to hold, character+// for character; the card is a 1:1 push to a named Multica member, so it is+// their own profile language that picks the pack (outbound.go).// inboxAppURL resolves the frontend URL for building the "view detail" link.// Priority: WECOM_APP_URL → MULTICA_APP_URL → FRONTEND_ORIGIN. Only HTTPS@@ -65,11 +61,12 @@ func inboxAppURL() string {//// **[{type}] {title}**// {body}-// [查看详情]({appURL}/{slug|workspaceID}/inbox?issue={issueID})+// [{detail link}]({appURL}/{slug|workspaceID}/inbox?issue={issueID})//+// The type label and the link's anchor text come from the reader's copyPack.// The link segment is omitted entirely when no appURL is configured — we// would rather send a title-only card than a broken link.-func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {+func buildInboxMarkdown(item map[string]any, workspaceID, slug string, c copyPack) string {title, _ := item["title"].(string)typeStr, _ := item["type"].(string)if title == "" && typeStr == "" {@@ -102,7 +99,7 @@ func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {var b strings.Builderb.WriteString("**[")- b.WriteString(inboxTypeLabel(typeStr))+ b.WriteString(c.label(typeStr))b.WriteString("] ")b.WriteString(title)b.WriteString("**")@@ -111,7 +108,7 @@ func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {b.WriteString(body)}if link != "" {- b.WriteString("\n[查看详情](")+ b.WriteString("\n[" + c.InboxDetailLink + "](")b.WriteString(link)b.WriteString(")")}@@ -121,10 +118,10 @@ func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {}// Truncate the body only. Prefix + link must survive intact so the// user still gets the "view detail" affordance.- prefix := "**[" + inboxTypeLabel(typeStr) + "] " + title + "**"+ prefix := "**[" + c.label(typeStr) + "] " + title + "**"suffix := ""if link != "" {- suffix = "\n[查看详情](" + link + ")"+ suffix = "\n[" + c.InboxDetailLink + "](" + link + ")"}// Neither cut below can put a "]" back next to a "(" or a ":".// truncateRunes only drops a suffix, so it cannot recreate a pair@@ -155,7 +152,7 @@ func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {// that exists can ask for it.titleRoom = 0}- return "**[" + inboxTypeLabel(typeStr) + "] " ++ return "**[" + c.label(typeStr) + "] " +truncateRunes(title, titleRoom) + "...**" + suffix}diff --git a/server/internal/integrations/wecom/inbox_message_test.go b/server/internal/integrations/wecom/inbox_message_test.goindex ec4e5f8ffa..6116bfb877 100644--- a/server/internal/integrations/wecom/inbox_message_test.go+++ b/server/internal/integrations/wecom/inbox_message_test.go@@ -15,7 +15,7 @@ func TestBuildInboxMarkdown_TitleBodyLink(t *testing.T) {"body": "from: todo\nto: in_review","issue_id": "9194c058-e8a4-4c15-9c65-86d1784ba715",}- got := buildInboxMarkdown(item, "ws-uuid", "acme")+ got := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if !strings.Contains(got, "**[状态变更] 登录页 500 错误**") {t.Fatalf("missing typed title header: %q", got)}@@ -30,7 +30,7 @@ func TestBuildInboxMarkdown_TitleBodyLink(t *testing.T) {func TestBuildInboxMarkdown_UnknownTypeFallsBackToDefault(t *testing.T) {t.Setenv("WECOM_APP_URL", "https://example.com")item := map[string]any{"type": "some_new_type", "title": "hi"}- got := buildInboxMarkdown(item, "ws-uuid", "acme")+ got := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if !strings.Contains(got, "**[新消息] hi**") {t.Fatalf("expected fallback type label 新消息, got %q", got)}@@ -39,7 +39,7 @@ func TestBuildInboxMarkdown_UnknownTypeFallsBackToDefault(t *testing.T) {func TestBuildInboxMarkdown_FallsBackToWorkspaceUUIDWhenSlugMissing(t *testing.T) {t.Setenv("WECOM_APP_URL", "https://example.com")item := map[string]any{"type": "new_comment", "title": "t", "issue_id": "iid"}- got := buildInboxMarkdown(item, "ws-uuid", "")+ got := buildInboxMarkdown(item, "ws-uuid", "", copyFor(DefaultLocale))if !strings.Contains(got, "https://example.com/ws-uuid/inbox?issue=iid") {t.Fatalf("expected workspace uuid path segment, got %q", got)}@@ -54,7 +54,7 @@ func TestBuildInboxMarkdown_NoAppURLDropsLink(t *testing.T) {os.Unsetenv(k)}item := map[string]any{"type": "new_comment", "title": "t"}- got := buildInboxMarkdown(item, "ws-uuid", "acme")+ got := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if strings.Contains(got, "查看详情") {t.Fatalf("link section must be omitted when no app url is configured: %q", got)}@@ -69,7 +69,7 @@ func TestBuildInboxMarkdown_NonHTTPSAppURLIsRejected(t *testing.T) {}t.Setenv("WECOM_APP_URL", "http://insecure.example.com")item := map[string]any{"type": "new_comment", "title": "t"}- got := buildInboxMarkdown(item, "ws-uuid", "acme")+ got := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if strings.Contains(got, "insecure.example.com") {t.Fatalf("http:// override must be dropped, got %q", got)}@@ -79,7 +79,7 @@ func TestBuildInboxMarkdown_TruncatesLongBody(t *testing.T) {t.Setenv("WECOM_APP_URL", "https://example.com")body := strings.Repeat("我", 5000) // 5000 runes, exceeds 4000 capitem := map[string]any{"type": "new_comment", "title": "hi", "body": body, "issue_id": "iid"}- got := buildInboxMarkdown(item, "ws-uuid", "acme")+ got := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if !strings.Contains(got, "...") {t.Fatalf("expected truncation marker, got tail %q", got[len(got)-50:])}@@ -98,7 +98,7 @@ func TestBuildInboxMarkdown_HandlesPointerBodyAndIssueID(t *testing.T) {"body": &bodyStr,"issue_id": &issueIDStr,}- got := buildInboxMarkdown(item, "ws-uuid", "acme")+ got := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if !strings.Contains(got, "详情") {t.Fatalf("expected pointer body to be dereferenced, got %q", got)}@@ -108,7 +108,7 @@ func TestBuildInboxMarkdown_HandlesPointerBodyAndIssueID(t *testing.T) {}func TestBuildInboxMarkdown_EmptyItemReturnsEmpty(t *testing.T) {- got := buildInboxMarkdown(map[string]any{}, "ws", "slug")+ got := buildInboxMarkdown(map[string]any{}, "ws", "slug", copyFor(DefaultLocale))if got != "" {t.Fatalf("expected empty output for empty item, got %q", got)}@@ -143,7 +143,7 @@ func TestInboxCardDoesNotRenderMemberAuthoredLinks(t *testing.T) {"title": "[click here](http://evil.example)","body": "and the body [too](http://evil.example)",}- out := buildInboxMarkdown(item, "ws-uuid", "acme")+ out := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if strings.Contains(out, "](http://evil.example)") {t.Fatalf("member-authored link syntax rendered as a link in a bot-authored card: %q", out)}@@ -159,7 +159,7 @@ func TestInboxCardFitsTheCapEvenWithAHugeTitle(t *testing.T) {huge := strings.Repeat("标题", 4000) // far past inboxMarkdownMaxLen on its ownt.Setenv("MULTICA_APP_URL", "https://multica.example")item := map[string]any{"type": "mentioned", "title": huge, "body": "body"}- out := buildInboxMarkdown(item, "ws-uuid", "acme")+ out := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {t.Fatalf("card is %d runes, cap is %d — WeCom refuses the frame and the push is lost", n, inboxMarkdownMaxLen)}@@ -185,7 +185,7 @@ func TestInboxCardKeepsAnOrdinaryBracketedTitleVerbatim(t *testing.T) {"title": "[Bug] 登录失败","body": "从 (todo) 到 (in_review)!",}- out := buildInboxMarkdown(item, "ws-uuid", "acme")+ out := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))want := "**[状态变更] [Bug] 登录失败**\n从 (todo) 到 (in_review)!"if out != want {t.Fatalf("member text did not survive verbatim:\n got %q\nwant %q", out, want)@@ -229,7 +229,7 @@ func TestInboxCardNeverPutsCloseBracketNextToOpenParen(t *testing.T) {t.Run(tc.name, func(t *testing.T) {out := buildInboxMarkdown(map[string]any{"type": "mentioned", "title": tc.title, "body": tc.body,- }, "ws-uuid", "acme")+ }, "ws-uuid", "acme", copyFor(DefaultLocale))if i := strings.Index(out, "]("); i >= 0 {t.Fatalf("\"](\" came out adjacent at byte %d — that is a working link in a card the bot signs: %q",i, window(out, i))@@ -257,7 +257,7 @@ func TestInboxCardSeamSurvivesEveryCutOffset(t *testing.T) {{"body", map[string]any{"type": "mentioned", "title": "t", "body": body}},{"title", map[string]any{"type": "mentioned", "title": title, "body": "b"}},} {- out := buildInboxMarkdown(tc.item, "ws-uuid", "acme")+ out := buildInboxMarkdown(tc.item, "ws-uuid", "acme", copyFor(DefaultLocale))if i := strings.Index(out, "]("); i >= 0 {t.Fatalf("%s cut at pad=%d fused a \"]\" onto a \"(\" at byte %d: %q", tc.name, pad, i, window(out, i))}@@ -281,7 +281,7 @@ func TestInboxCardBudgetsTheSpacesItInserts(t *testing.T) {"title": "t","body": strings.Repeat("](", 4000), // 8000 runes in, 12000 if broken}- out := buildInboxMarkdown(item, "ws-uuid", "acme")+ out := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {t.Fatalf("card is %d runes, cap is %d — the inserted spaces were not budgeted, so WeCom refuses the frame and the push is lost",n, inboxMarkdownMaxLen)@@ -322,7 +322,7 @@ func TestInboxCardDefinesNoResolvableLinkReference(t *testing.T) {out := buildInboxMarkdown(map[string]any{"type": "mentioned", "title": "t", "body": body,- }, "ws-uuid", "acme")+ }, "ws-uuid", "acme", copyFor(DefaultLocale))if dests := markdownDestinations(out); hasDestinationTo(dests, "evil.example") {t.Fatalf("body: a member-defined link survived into the card: %q resolves %v", out, dests)}@@ -331,7 +331,7 @@ func TestInboxCardDefinesNoResolvableLinkReference(t *testing.T) {// definition too, and it goes through a different length branch.out = buildInboxMarkdown(map[string]any{"type": "mentioned", "title": body, "body": "b",- }, "ws-uuid", "acme")+ }, "ws-uuid", "acme", copyFor(DefaultLocale))if dests := markdownDestinations(out); hasDestinationTo(dests, "evil.example") {t.Fatalf("title: a member-defined link survived into the card: %q resolves %v", out, dests)}@@ -354,7 +354,7 @@ func TestInboxCardKeepsAReferenceLikeTitleVerbatim(t *testing.T) {"title": "[Bug]: 登录失败","body": "[WIP]: 明天再看\n\n[复现步骤]: 见 (todo) 到 (in_review)!",}- out := buildInboxMarkdown(item, "ws-uuid", "acme")+ out := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))want := "**[状态变更] [Bug]: 登录失败**\n[WIP]: 明天再看\n\n[复现步骤]: 见 (todo) 到 (in_review)!"if out != want {t.Fatalf("member text did not survive verbatim:\n got %q\nwant %q", out, want)@@ -381,7 +381,7 @@ func TestInboxCardSeamKeepsDefinitionsBrokenAtEveryCutOffset(t *testing.T) {{"body", map[string]any{"type": "mentioned", "title": "t", "body": filler + "\n\n" + dense}},{"title", map[string]any{"type": "mentioned", "title": filler + "\n\n" + dense, "body": "b"}},} {- out := buildInboxMarkdown(tc.item, "ws-uuid", "acme")+ out := buildInboxMarkdown(tc.item, "ws-uuid", "acme", copyFor(DefaultLocale))if dests := markdownDestinations(out); hasDestinationTo(dests, "evil.example") {t.Fatalf("%s cut at pad=%d let a member-defined link through: resolves %v", tc.name, pad, dests)}@@ -405,7 +405,7 @@ func TestInboxCardBudgetsTheSpacesTheDefinitionBreakInserts(t *testing.T) {"title": "t","body": strings.Repeat("[a]: https://evil.example\n", 500),}- out := buildInboxMarkdown(item, "ws-uuid", "acme")+ out := buildInboxMarkdown(item, "ws-uuid", "acme", copyFor(DefaultLocale))if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {t.Fatalf("card is %d runes, cap is %d — the inserted spaces were not budgeted, so WeCom refuses the frame and the push is lost",n, inboxMarkdownMaxLen)diff --git a/server/internal/integrations/wecom/language_lint_test.go b/server/internal/integrations/wecom/language_lint_test.gonew file mode 100644index 0000000000..dda66d0d6c--- /dev/null+++ b/server/internal/integrations/wecom/language_lint_test.go@@ -0,0 +1,129 @@+package wecom++// language_lint_test.go — the copy rule, enforced instead of documented.+//+// strings.go already says "everything the adapter can say is a field here".+// That sentence stops nothing: a literal typed into the file that sends it+// compiles exactly as well as a pack lookup, reads fine to whoever wrote it,+// and pins that one surface to one language while every other surface follows+// the reader.+//+// This is the state the package was already in once — the binding prompt, the+// offline notices, the inbox card and the attachment notices each lived in the+// file that sent them — and nothing except this test would notice it coming+// back.++import (+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "unicode"+)++// packageGoFiles lists this package's non-test .go files, minus the ones named.+func packageGoFiles(t *testing.T, except ...string) []string {+ t.Helper()+ skip := map[string]bool{}+ for _, name := range except {+ skip[name] = true+ }+ entries, err := os.ReadDir(".")+ if err != nil {+ t.Fatalf("read package dir: %v", err)+ }+ var out []string+ for _, e := range entries {+ name := e.Name()+ if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ continue+ }+ if skip[name] {+ continue+ }+ out = append(out, name)+ }+ return out+}++// TestOnlyStringsGoHoldsUserVisibleCopy — a Chinese string literal anywhere but+// strings.go is copy that cannot be translated, because nothing outside the+// pack has a second language to offer. It compiles, it reads fine to whoever+// wrote it, and it silently pins one surface to one language while the rest of+// the adapter follows the reader — which is exactly the state this package was+// in when a colleague reading English got an English bubble and a Chinese+// everything-else.+//+// Comments are exempt by construction: this walks the AST and only ever looks+// at string literals, so the reasoning in a comment can still be written in+// whichever language explains it best.+func TestOnlyStringsGoHoldsUserVisibleCopy(t *testing.T) {+ t.Parallel()++ fset := token.NewFileSet()+ type offence struct {+ file string+ line int+ text string+ }+ var offenders []offence++ // The two files below still hold their copy as literals. They are listed+ // with an exact count rather than left out of the walk, so the lint still+ // fails on a literal added anywhere else — including a new one in either of+ // these two — and fails again if one of these loses a literal without this+ // list being updated.+ pending := map[string]int{+ "wecom_channel.go": 1,+ "media_ingest.go": 2,+ }++ for _, name := range packageGoFiles(t, "strings.go") {+ f, err := parser.ParseFile(fset, filepath.Clean(name), nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ ast.Inspect(f, func(n ast.Node) bool {+ lit, ok := n.(*ast.BasicLit)+ if !ok || lit.Kind != token.STRING {+ return true+ }+ if !hasHan(lit.Value) {+ return true+ }+ offenders = append(offenders, offence{name, fset.Position(lit.Pos()).Line, lit.Value})+ return true+ })+ }++ for _, o := range offenders {+ if n := pending[filepath.Base(o.file)]; n > 0 {+ pending[filepath.Base(o.file)] = n - 1+ continue+ }+ t.Errorf("%s:%d holds user-visible copy as a literal: %s\n"++ "Add a field to copyPack in strings.go, give it both languages, and read it through "++ "copyFor(localeFor(...)). A literal here is a surface that cannot answer an English reader.",+ o.file, o.line, o.text)+ }+ // A count that did not run out means that file lost a literal without this+ // list being updated — the follow-up landed, and the allowance outlived it.+ for file, left := range pending {+ if left > 0 {+ t.Errorf("%s has %d fewer literals than this list allows for; "++ "drop its entry now that its copy has moved", file, left)+ }+ }+}++func hasHan(s string) bool {+ for _, r := range s {+ if unicode.Is(unicode.Han, r) {+ return true+ }+ }+ return false+}diff --git a/server/internal/integrations/wecom/locale_wiring_test.go b/server/internal/integrations/wecom/locale_wiring_test.goindex 5cc6028eb3..a38411bad8 100644--- a/server/internal/integrations/wecom/locale_wiring_test.go+++ b/server/internal/integrations/wecom/locale_wiring_test.go@@ -1,27 +1,27 @@package wecom-// locale_wiring_test.go — the bubble's own copy is read off the pack for the-// reader it is addressed to, not off a literal compiled into whichever closer-// happens to seal it.+// locale_wiring_test.go — every surface the adapter speaks on reads the copy+// pack, not a literal compiled into the file that happens to send it.//-// The language is resolved when the bubble is OPENED, while who asked is still-// in hand, and carried on the handle to every closer — each of which runs-// later, from an event that names a task and nobody else. A closer that reached-// for the deployment default instead would look right in isolation and be wrong-// for every reader who set a language, so the test below drives the real-// open-then-close path and asserts on what came out of the socket.-//-// The rest of what this adapter says is still the Chinese literal at its own-// call site; those surfaces get their own test when they move to the pack.+// Localising one surface and not the rest produces the worst possible outcome:+// a colleague whose Multica profile says English gets an English notice, then+// a Chinese binding prompt and a Chinese inbox card around it. The tests below+// drive the REAL entry points — OutboundReplier.Reply, wecomChannel+// .dispatchFrame, Outbound.tryDeliverInbox — once per language and assert on+// what came out of the socket, so putting any of those literals back fails+// here rather than passing quietly.import ("context"- "reflect"+ "strings""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")@@ -53,6 +53,23 @@ func (f fakeLanguages) GetUser(_ context.Context, id pgtype.UUID) (db.User, erroreturn db.User{}, pgx.ErrNoRows}+// languagesFor builds a lookup for one asker reading in the given language.+func languagesFor(language string) fakeLanguages {+ return fakeLanguages{senderID: "T-asker", userID: localeTestUserID, language: language}+}++// sentMarkdown returns the content of the i-th aibot_send_msg frame.+func sentMarkdown(t *testing.T, conn *recordingConn, i int) string {+ t.Helper()+ body := conn.sendBody(t, i)+ md, ok := body["markdown"].(map[string]any)+ if !ok {+ t.Fatalf("frame %d has no markdown body: %#v", i, body)+ }+ content, _ := md["content"].(string)+ return content+}+// localeCases is the pair every surface below is driven with. The expected// text is read off the packs rather than spelled out again: the assertion is// that the SURFACE consults the pack, and duplicating the wording here would@@ -66,6 +83,304 @@ var localeCases = []struct {{"chinese profile", "zh-Hans", LocaleZhHans},}+// ---- surface 1: replier.go ----++func TestReplierNoticesReadTheAskersLanguage(t *testing.T) {+ t.Parallel()+ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ want := copyPacks[tc.locale]++ for _, outcome := range []struct {+ name string+ res engine.Result+ want string+ }{+ {"offline", engine.Result{Outcome: engine.OutcomeAgentOffline}, want.AgentOffline},+ {"archived", engine.Result{Outcome: engine.OutcomeAgentArchived}, want.AgentArchived},+ {"invoke denied", engine.Result{Outcome: engine.OutcomeInvokeDenied}, want.InvokeDenied},+ {+ "issue created",+ engine.Result{+ Outcome: engine.OutcomeIngested,+ IssueID: pgtype.UUID{Bytes: [16]byte{4}, Valid: true},+ IssueIdentifier: "MUL-42",+ IssueTitle: "Login is broken",+ },+ want.issueCreated("MUL-42", "Login is broken"),+ },+ {+ "issue duplicate",+ engine.Result{+ Outcome: engine.OutcomeIngested,+ IssueID: pgtype.UUID{Bytes: [16]byte{4}, Valid: true},+ IssueIdentifier: "MUL-7",+ IssueTitle: "Login is broken",+ IssueDuplicate: true,+ },+ want.issueDuplicate("MUL-7", "Login is broken"),+ },+ } {+ t.Run(outcome.name, func(t *testing.T) {+ reg := newSendersRegistry()+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}+ conn := &recordingConn{}+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))+ r := NewOutboundReplier(OutboundReplierConfig{+ Senders: reg,+ Languages: languagesFor(tc.language),+ AppURL: "https://multica.example",+ })+ // A 1:1 chat, so the destination IS the asker and their+ // own profile decides the language.+ msg := channel.InboundMessage{Source: channel.Source{+ ChatID: "T-asker",+ ChatType: channel.ChatTypeP2P,+ SenderID: "T-asker",+ }}+ r.Reply(context.Background(), inst, msg, outcome.res)++ if got := sentMarkdown(t, conn, 0); got != outcome.want {+ t.Fatalf("%s notice = %q, want the %s copy %q", outcome.name, got, tc.locale, outcome.want)+ }+ })+ }+ })+ }+}++// TestReplierGroupNoticeReadsTheRoomNotTheMember — a room has many readers and+// no shared profile, so it reads the deployment default. This is the guard on+// the fallback: it must be deploymentLocale(), not the triggering member's+// personal setting.+func TestReplierGroupNoticeReadsTheRoomNotTheMember(t *testing.T) {+ t.Parallel()+ reg := newSendersRegistry()+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}+ conn := &recordingConn{}+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))+ r := NewOutboundReplier(OutboundReplierConfig{+ Senders: reg,+ // The member who spoke reads English...+ Languages: languagesFor("en"),+ AppURL: "https://multica.example",+ })+ msg := channel.InboundMessage{Source: channel.Source{+ ChatID: "GROUP_CHAT",+ ChatType: channel.ChatTypeGroup,+ SenderID: "T-asker",+ }}+ r.Reply(context.Background(), inst, msg, engine.Result{Outcome: engine.OutcomeAgentOffline})++ // ...and the room still reads the deployment default, in front of+ // everybody else in it.+ if got, want := sentMarkdown(t, conn, 0), copyFor(deploymentLocale()).AgentOffline; got != want {+ t.Fatalf("group notice = %q, want the room's language %q", got, want)+ }+}++// TestInvokeDeniedFromAGroupReadsTheSendersLanguage — the refusal for a group+// trigger goes to the sender's own 1:1, never the room, so it is the one group+// outcome whose reader is a single person. It reads their profile, not the+// deployment default the room's notices use.+func TestInvokeDeniedFromAGroupReadsTheSendersLanguage(t *testing.T) {+ t.Parallel()+ reg := newSendersRegistry()+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}+ conn := &recordingConn{}+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))+ r := NewOutboundReplier(OutboundReplierConfig{+ Senders: reg,+ Languages: languagesFor("en"),+ AppURL: "https://multica.example",+ })+ msg := channel.InboundMessage{Source: channel.Source{+ ChatID: "GROUP_CHAT",+ ChatType: channel.ChatTypeGroup,+ SenderID: "T-asker",+ }}+ r.Reply(context.Background(), inst, msg, engine.Result{Outcome: engine.OutcomeInvokeDenied})++ if got := conn.sendBody(t, 0)["chatid"]; got != "T-asker" {+ t.Fatalf("refusal went to chatid %v, want the sender's own 1:1 T-asker", got)+ }+ if got, want := sentMarkdown(t, conn, 0), copyPacks[LocaleEn].InvokeDenied; got != want {+ t.Fatalf("refusal = %q, want the sender's language %q", got, want)+ }+}++// ---- surface 2: inbox_message.go ----++func TestInboxCardReadsTheRecipientsLanguage(t *testing.T) {+ // Not parallel: the card's deep link needs an app URL, and t.Setenv is+ // process-wide. It runs in the serial phase, before any parallel test+ // resumes.+ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ t.Setenv("WECOM_APP_URL", "https://multica.example")+ q := &fakeOutboundQueries{+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T-asker"},+ workspace: db.Workspace{Slug: "acme"},+ userLanguage: tc.language,+ userBindingID: localeTestUserID,+ }+ o, instID, conn := newOutboundWithConn(t, q)+ q.memberBinding.InstallationID = instID++ const recipient = "33333333-3333-3333-3333-333333333333"+ const workspace = "44444444-4444-4444-4444-444444444444"+ const item = "66666666-6666-6666-6666-666666666666"+ // The card is a 1:1 push to a bound member, so it goes out on this+ // installation's socket and the copy is chosen on the way. Read the+ // frame, which is what the member actually sees.+ if !o.tryDeliverInbox(context.Background(), map[string]any{+ "id": item,+ "recipient_type": "member",+ "recipient_id": recipient,+ "workspace_id": workspace,+ "type": "issue_assigned",+ "title": "New issue",+ }, recipient, workspace) {+ t.Fatal("tryDeliverInbox returned false; expected delivery to a bound member")+ }++ want := copyPacks[tc.locale]+ got := sentMarkdown(t, conn, 0)+ if !strings.HasPrefix(got, "**["+want.label("issue_assigned")+"]") {+ t.Fatalf("inbox card = %q, want the %s label %q", got, tc.locale, want.label("issue_assigned"))+ }+ if !strings.Contains(got, "["+want.InboxDetailLink+"](") {+ t.Fatalf("inbox card = %q, want the %s detail-link anchor %q", got, tc.locale, want.InboxDetailLink)+ }+ })+ }+}++// TestInboxCardUnknownTypeUsesTheSamePacksFallback — a notification kind the+// adapter has not been taught still gets a label, from the same pack as the+// rest of the card.+func TestInboxCardUnknownTypeUsesTheSamePacksFallback(t *testing.T) {+ t.Parallel()+ q := &fakeOutboundQueries{+ memberBinding: db.ChannelUserBinding{ChannelUserID: "T-asker"},+ workspace: db.Workspace{Slug: "acme"},+ userLanguage: "en",+ userBindingID: localeTestUserID,+ }+ o, instID, conn := newOutboundWithConn(t, q)+ q.memberBinding.InstallationID = instID++ const recipient = "33333333-3333-3333-3333-333333333333"+ const workspace = "44444444-4444-4444-4444-444444444444"+ const item = "66666666-6666-6666-6666-666666666666"+ if !o.tryDeliverInbox(context.Background(), map[string]any{+ "id": item,+ "recipient_type": "member",+ "recipient_id": recipient,+ "workspace_id": workspace,+ "type": "something_invented_next_year",+ "title": "New issue",+ }, recipient, workspace) {+ t.Fatal("tryDeliverInbox returned false; expected delivery to a bound member")+ }+ if got, want := sentMarkdown(t, conn, 0), "**["+copyPacks[LocaleEn].InboxTypeFallback+"]"; !strings.HasPrefix(got, want) {+ t.Fatalf("inbox card = %q, want the English fallback label %q", got, want)+ }+}++// ---- surface 3: the attachment-failure notice ----++// TestAttachmentSendFailureNoticeReadsTheDestinationsLanguage drives the whole+// chat:done path, not sendAttachments directly, because the locale is resolved+// by the caller and handed down in attachmentTarget — the delivery itself runs+// detached, with no context left to read a profile with. Constructing the+// target by hand here would test the pack and skip the wiring.+func TestAttachmentSendFailureNoticeReadsTheDestinationsLanguage(t *testing.T) {+ t.Parallel()+ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ q := oneAttachmentQueries(t, db.Attachment{+ ID: mustTestUUID(t), Filename: "big.bin", Url: "https://cdn.example/obj/bin",+ })+ // A 1:1 with the asker, so their own profile answers.+ q.sessionBinding.ChannelChatID = "T-asker"+ q.sessionBinding.ChatType = string(channel.ChatTypeP2P)+ q.userLanguage = tc.language+ q.userBindingID = localeTestUserID++ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/bin", data: []byte("DATA")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ conn.refuse[cmdUploadMediaInit] = 40058 // the server will not take the file++ if err := o.processEvent(context.Background(), chatDoneEvent("See the attached dump.")); err != nil {+ t.Fatalf("processEvent: %v", err)+ }+ // A turn that carries a file puts its answer on the socket too,+ // ahead of the file, so the notice is the LAST thing here rather+ // than the only thing.+ got := markdownSends(t, conn)+ want := copyPacks[tc.locale].MediaSendFailed+ if len(got) == 0 || got[len(got)-1] != want {+ t.Fatalf("sends = %q, want the %s failure notice %q last", got, tc.locale, want)+ }+ })+ }+}++// The relayed path builds its own attachmentTarget, so "the notice reads the+// destination's language" has to be true twice. On a multi-replica deployment+// the relayed one is the common case: chat:done lands wherever the run+// finished, and only the lease holder can write to the socket.+//+// Nothing else differs when this is wrong — the file still fails, the notice+// still goes out, it is just in the wrong language — so no other test would+// have caught it.+func TestRelayedAttachmentFailureNoticeAlsoReadsTheDestinationsLanguage(t *testing.T) {+ t.Parallel()+ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ q := oneAttachmentQueries(t, db.Attachment{+ ID: mustTestUUID(t), Filename: "big.bin", Url: "https://cdn.example/obj/bin",+ })+ // A 1:1, where the bound chatid IS the reader's userid.+ q.sessionBinding.ChannelChatID = "T-asker"+ q.sessionBinding.ChatType = string(channel.ChatTypeP2P)+ q.userLanguage = tc.language+ q.userBindingID = localeTestUserID++ o, instID, conn := newOutboundWithMedia(t, q, &fakeObjectStore{key: "obj/bin", data: []byte("DATA")})+ q.sessionBinding.InstallationID = instID+ q.installation.ID = instID+ conn.refuse[cmdUploadMediaInit] = 40058 // the server will not take the file++ if res := o.deliverRelayed(context.Background(), relayFrame{+ Kind: relayKindReply,+ InstallationID: util.UUIDToString(instID),+ ChatID: "T-asker",+ ChatType: chatTypeSingleInt,+ Content: "See the attached dump.",+ MessageID: testMessageID,+ WorkspaceID: testWorkspaceID,+ SessionID: testSessionID,+ TaskID: testTaskID,+ CarriesFiles: true,+ }); res.outcome != outcomeDone {+ t.Fatalf("outcome = %v, want outcomeDone", res.outcome)+ }++ got := markdownSends(t, conn)+ want := copyPacks[tc.locale].MediaSendFailed+ if len(got) == 0 || got[len(got)-1] != want {+ t.Fatalf("sends = %q, want the %s failure notice %q last — a relayed reply reaches the "++ "same reader as a direct one", got, tc.locale, want)+ }+ })+ }+}++// ---- surface 4: the media failure notice ----+// ---- surface 5: the streaming bubble ----// TestTheBubbleClosesInTheAskersLanguage drives the real open-then-close path.@@ -89,9 +404,6 @@ func TestTheBubbleClosesInTheAskersLanguage(t *testing.T) {if len(frames) != 2 {t.Fatalf("got %d stream frames, want 2 (open + seal)", len(frames))}- if frames[1]["finish"] != true {- t.Fatal("an empty answer did not seal the bubble; it spins until the platform ends it")- }if got, want := frames[1]["content"], copyPacks[tc.locale].StreamNoReply; got != want {t.Fatalf("closing copy = %q, want the %s copy %q", got, tc.locale, want)}@@ -99,6 +411,8 @@ func TestTheBubbleClosesInTheAskersLanguage(t *testing.T) {}}+// ---- surface 6: the read loop's own receipt ----+// ---- the deployment knob ----// restoreLocale points the deployment at l for the duration of one test and@@ -111,15 +425,25 @@ func restoreLocale(t *testing.T, l Locale) {t.Cleanup(func() { deploymentLocaleValue.Store(prev) })}+// TestSetDeploymentLocaleUnsetStaysChinese is the compatibility guard: every+// existing deployment sets nothing, and nothing must keep meaning zh-Hans.+func TestSetDeploymentLocaleUnsetStaysChinese(t *testing.T) {+ if DefaultLocale != LocaleZhHans {+ t.Fatalf("DefaultLocale = %q, want zh-Hans — WeCom is a Chinese platform", DefaultLocale)+ }+ restoreLocale(t, DefaultLocale)+ if got := SetDeploymentLocale(""); got != LocaleZhHans {+ t.Fatalf("SetDeploymentLocale(\"\") = %q, want the Chinese default left in place", got)+ }+ if got := copyFor(deploymentLocale()).AgentOffline; got != copyPacks[LocaleZhHans].AgentOffline {+ t.Fatalf("unset deployment reads %q, want the Chinese pack", got)+ }+}+// TestSetDeploymentLocaleIgnoresWhatItDoesNotRecognise — an env var is// validated by nobody. A typo must leave the language where it was rather than// quietly moving a tenant onto the other pack.func TestSetDeploymentLocaleIgnoresWhatItDoesNotRecognise(t *testing.T) {- // Every existing deployment sets nothing, and nothing must keep meaning- // zh-Hans — WeCom is a Chinese platform.- if DefaultLocale != LocaleZhHans {- t.Fatalf("DefaultLocale = %q, want zh-Hans", DefaultLocale)- }restoreLocale(t, LocaleZhHans)for _, junk := range []string{"zh_Hant", "english", "EN-US", `"en"`, " ", "fr"} {if got := SetDeploymentLocale(junk); got != LocaleZhHans {@@ -136,26 +460,40 @@ func TestSetDeploymentLocaleIgnoresWhatItDoesNotRecognise(t *testing.T) {}}-// ---- the packs ----+// TestDeploymentLocaleMovesTheCopyNobodyHasAProfileFor is the knob's whole+// justification: set it to en and the surfaces addressed to a reader nobody+// can name — a room, an unbound sender — come out in English.+func TestDeploymentLocaleMovesTheCopyNobodyHasAProfileFor(t *testing.T) {+ restoreLocale(t, LocaleEn)+ en := copyPacks[LocaleEn]-// TestEveryPackSaysSomethingVisible: each copy string is the whole content of-// a closing frame, and WeCom discards a closing frame with nothing visible in-// it — the bubble it was meant to seal then spins until the platform ends it.-// So no string in any pack may be blank. The wording itself is not pinned: the-// test above proves the closer reads the pack, and a copy edit should be a-// one-file change.-func TestEveryPackSaysSomethingVisible(t *testing.T) {- t.Parallel()- for locale, pack := range copyPacks {- v := reflect.ValueOf(pack)- for i := range v.NumField() {- if v.Field(i).Kind() != reflect.String {- continue- }- if s := v.Field(i).String(); !hasVisibleChar(s) {- t.Errorf("%s copy %s = %q has nothing visible; WeCom would discard the closing frame",- locale, v.Type().Field(i).Name, s)- }- }+ // A room: no shared profile, so the deployment answers for it.+ reg := newSendersRegistry()+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}+ conn := &recordingConn{}+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))+ r := NewOutboundReplier(OutboundReplierConfig{+ Senders: reg,+ Languages: languagesFor("zh-Hans"),+ AppURL: "https://multica.example",+ })+ r.binding = fakeBinder{raw: "RAW_TOKEN"}++ r.Reply(context.Background(), inst, channel.InboundMessage{Source: channel.Source{+ ChatID: "GROUP_CHAT",+ ChatType: channel.ChatTypeGroup,+ SenderID: "T-unbound",+ }}, engine.Result{Outcome: engine.OutcomeNeedsBinding, Sender: "T-unbound"})++ // Frame 0 is the prompt, sent privately to the sender; frame 1 is the+ // token-less line the room gets.+ prompt := sentMarkdown(t, conn, 0)+ if !strings.HasPrefix(prompt, en.BindingPromptPrefix) || !strings.HasSuffix(prompt, en.BindingPromptSuffix) {+ t.Fatalf("binding prompt = %q, want it wrapped in the English pack", prompt)+ }+ if got := sentMarkdown(t, conn, 1); got != en.BindingSentPrivately {+ t.Fatalf("group line = %q, want the English %q", got, en.BindingSentPrivately)}}++// ---- the compatibility pin ----diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex ed59123a0c..18abc03224 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -391,6 +391,11 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {ChatID: said.addr.ChatID,ChatType: said.addr.ChatType,SessionID: e.ChatSessionID,+ // Resolved here rather than at the failure, which happens on a detached+ // goroutine with no context left to read a profile with. In a 1:1 the+ // bound chatid IS the reader's userid, which is what localeFor wants; a+ // room ignores it and reads the deployment's language (language.go).+ Locale: localeFor(ctx, o.q, said.addr.InstallationID, said.addr.ChatType, said.addr.ChatID),}, !said.spoke)return nil}@@ -827,11 +832,16 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec// Resolve slug for the link. Best-effort — a missing slug just falls// back to the workspace UUID in the URL.+ // The card is a 1:1 push to a known Multica member, so their own profile+ // language decides what it says — the one surface where the reader is+ // always resolvable by construction.+ cp := copyFor(localeForUser(ctx, o.q, recipientID))+slug := ""if ws, err := o.q.GetWorkspace(ctx, workspaceID); err == nil {slug = ws.Slug}- content := buildInboxMarkdown(item, workspaceIDStr, slug)+ content := buildInboxMarkdown(item, workspaceIDStr, slug, cp)if content == "" {return false}diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.goindex 2799924ec9..b7cd47fc07 100644--- a/server/internal/integrations/wecom/outbound_media.go+++ b/server/internal/integrations/wecom/outbound_media.go@@ -55,26 +55,6 @@ type mediaObjectStore interface {// things that can be true — telling them apart is the point (see deliveryState).// Hardcoded Chinese, like every other user-facing string this adapter sends// (replier.go) — WeCom deployments are China-only.-const (- // mediaSendFailedText — we know it did not arrive. Definite, because- // claiming a definite failure that later turns out to be a delivery is how- // a user ends up ignoring the notice.- mediaSendFailedText = "⚠️ 有文件没能发出来,我这边保留着,需要的话我再试一次。"-- // mediaSendUnknownText — the frame went out and no verdict came back, so- // the file may be in the chat already. The wording has to survive both- // endings: it must not say "failed" to someone looking at the file, and it- // must not say "sent" to someone who never got it. It also explains why- // nothing is resent automatically, since that is the obvious next question- // and the answer is that a duplicate cannot be taken back.- mediaSendUnknownText = "⚠️ 有文件我没收到企业微信的送达回执,可能已经发到了、也可能没有。我不会自动重发,免得发重了;你那边没看到的话说一声,我再发一次。"-- // mediaLookupFailedText — the failure is on our side and before the- // question was even answered: we could not read what was attached to this- // reply, so we do not know whether there was a file. Saying nothing here is- // what leaves a user waiting for something that was never attempted.- mediaLookupFailedText = "⚠️ 我这边没查到这条回答带没带文件,所以要是有,这次没发出来。需要的话我再试一次。"-)// attachmentBudget bounds one answer's whole attachment delivery — reading// every object, uploading it, and sending it. Generous because a 20 MiB file@@ -143,6 +123,9 @@ type attachmentTarget struct {// SessionID is carried only so a delivery that fails minutes later can// still name the conversation it belonged to in the log and the counter.SessionID string+ // Locale is the reader's, resolved on the request path — see the call+ // site in outbound.go for why it cannot be read at the failure.+ Locale Locale}// OutboundOption configures the chat-done subscriber at construction.@@ -257,7 +240,7 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID pif err != nil {o.logger.WarnContext(ctx, "wecom outbound: attachment lookup failed","error", err, "chat_message_id", uuidStringPub(messageID))- o.tellUser(ctx, to, mediaLookupFailedText)+ o.tellUser(ctx, to, copyFor(to.Locale).MediaLookupFailed)replyFailed(dropTransport, err)return}@@ -287,7 +270,7 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID p"installation_id", uuidStringPub(to.InstallationID),"attachments", len(rows),"pending", maxPendingAttachmentDeliveries)- o.tellUser(ctx, to, mediaSendFailedText)+ o.tellUser(ctx, to, copyFor(to.Locale).MediaSendFailed)return}defer o.releaseAttachmentSlot()@@ -309,7 +292,7 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID p"installation_id", uuidStringPub(to.InstallationID), "attachments", len(rows))// Deliberately on a fresh context: the one that expired is the reason// we are here, and reusing it would drop the sentence too.- o.tellUser(context.WithoutCancel(ctx), to, mediaSendFailedText)+ o.tellUser(context.WithoutCancel(ctx), to, copyFor(to.Locale).MediaSendFailed)replyFailed(dropTransport, ctx.Err())return}@@ -392,10 +375,10 @@ func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID p// definite wording.var lines []stringif failed > 0 {- lines = append(lines, mediaSendFailedText)+ lines = append(lines, copyFor(to.Locale).MediaSendFailed)}if unknown > 0 {- lines = append(lines, mediaSendUnknownText)+ lines = append(lines, copyFor(to.Locale).MediaSendUnknown)}if len(lines) > 0 {o.tellUser(ctx, to, strings.Join(lines, "\n"))diff --git a/server/internal/integrations/wecom/outbound_media_test.go b/server/internal/integrations/wecom/outbound_media_test.goindex eef90d7fbe..2c87249e0a 100644--- a/server/internal/integrations/wecom/outbound_media_test.go+++ b/server/internal/integrations/wecom/outbound_media_test.go@@ -345,7 +345,7 @@ func TestSendAttachments_ADeliveredFileIsNotAnnounced(t *testing.T) {if len(got) != 1 || got[0] != "Here it is." {t.Errorf("text sends = %v, want the answer alone — a delivered file needs no commentary", got)}- for _, notice := range []string{mediaSendFailedText, mediaSendUnknownText, mediaLookupFailedText} {+ for _, notice := range []string{copyFor(DefaultLocale).MediaSendFailed, copyFor(DefaultLocale).MediaSendUnknown, copyFor(DefaultLocale).MediaLookupFailed} {if slices.Contains(got, notice) {t.Errorf("a delivered file was reported to the user as %q", notice)}@@ -372,10 +372,10 @@ func TestSendAttachments_ARefusedFileIsReportedAsDefinitelyFailed(t *testing.T)if len(got) != 2 {t.Fatalf("text sends = %v, want the answer and a note that the file failed", got)}- if got[1] != mediaSendFailedText {+ if got[1] != copyFor(DefaultLocale).MediaSendFailed {t.Errorf("second message = %q, want the definite failure notice — the server refused it, so there is no doubt to hedge", got[1])}- if strings.Contains(got[1], mediaSendUnknownText) {+ if strings.Contains(got[1], copyFor(DefaultLocale).MediaSendUnknown) {t.Error("a refusal was reported with the hedged wording; a definite failure the user is invited to doubt is a failure they will not act on")}if n := len(mediaSends(t, conn)); n != 0 {@@ -442,7 +442,7 @@ func TestSendAttachments_ALookupFailureIsSaidOutLoud(t *testing.T) {if len(got) != 2 {t.Fatalf("text sends = %v, want the answer and a note that the lookup failed", got)}- if got[1] != mediaLookupFailedText {+ if got[1] != copyFor(DefaultLocale).MediaLookupFailed {t.Errorf("second message = %q, want the lookup-failure notice", got[1])}}@@ -472,7 +472,7 @@ func TestSendAttachments_ADeliveryShedForBacklogIsSaidOutLoud(t *testing.T) {t.Fatalf("upload init frames = %d, want 0 — the delivery was supposed to be shed", n)}got := markdownSends(t, conn)- if len(got) != 2 || got[1] != mediaSendFailedText {+ if len(got) != 2 || got[1] != copyFor(DefaultLocale).MediaSendFailed {t.Errorf("text sends = %v, want the answer and the failure notice — a shed delivery the user is never told about is a file that silently vanishes", got)}}@@ -523,7 +523,7 @@ func TestSendAttachment_RefusesAnOversizeAttachmentWithoutReadingIt(t *testing.Tt.Errorf("upload init frames = %d, want 0", n)}got := markdownSends(t, conn)- if len(got) != 2 || got[1] != mediaSendFailedText {+ if len(got) != 2 || got[1] != copyFor(DefaultLocale).MediaSendFailed {t.Errorf("text sends = %v, want the answer and the definite failure notice", got)}}@@ -545,7 +545,7 @@ func TestSendAttachments_ReportsAnUnreadableObject(t *testing.T) {t.Errorf("upload init frames = %d, want 0 — there were no bytes to upload", n)}got := markdownSends(t, conn)- if len(got) != 2 || got[1] != mediaSendFailedText {+ if len(got) != 2 || got[1] != copyFor(DefaultLocale).MediaSendFailed {t.Errorf("text sends = %v, want the answer and the failure notice", got)}}diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.goindex 82e4a70526..c5bc2f228a 100644--- a/server/internal/integrations/wecom/relay_outbound.go+++ b/server/internal/integrations/wecom/relay_outbound.go@@ -1435,6 +1435,13 @@ func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResultChatID: f.ChatID,ChatType: f.ChatType,SessionID: f.SessionID,+ // Same reason as the direct path in outbound.go: the failure runs+ // on a detached goroutine with no context left to read a profile+ // with, so the reader's language is resolved here. A relayed reply+ // is the one a multi-replica deployment takes most of the time —+ // without this, an English reader's file-failure notice arrives in+ // the deployment's language and nothing else differs.+ Locale: localeFor(ctx, o.q, instID, f.ChatType, f.ChatID),}, !hasVisibleChar(f.Content))}return relayResult{outcome: outcomeDone, record: record}diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.goindex 93bc8557b0..9fe9c380e2 100644--- a/server/internal/integrations/wecom/replier.go+++ b/server/internal/integrations/wecom/replier.go@@ -21,19 +21,27 @@ import ("github.com/multica-ai/multica/server/internal/util")-const (- agentOfflineText = "⚠️ 智能体当前不在线,你的消息已收到,等它上线后会处理。"- agentArchivedText = "⚠️ 该智能体已归档,无法回复。请联系工作区管理员。"- freshPendingText = "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。"- chatStartedText = "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。"- issueUsageText = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"- invokeDeniedText = "⚠️ 你没有权限运行该智能体。如需使用,请联系它的所有者。"-)+// defaultBindingPath is where the web app serves the bind page.+const defaultBindingPath = "/wecom/bind"++// normalizeBindingPath applies the one default: the binding prompt is the only+// thing that builds this URL, and a deployment that configures no path still+// needs a usable link.+func normalizeBindingPath(p string) string {+ if p == "" {+ return defaultBindingPath+ }+ if !strings.HasPrefix(p, "/") {+ return "/" + p+ }+ return p+}// OutboundReplier implements engine.OutboundReplier for WeCom.type OutboundReplier struct {binding bindersenders *sendersRegistry+ languages languageLookupappURL stringbindingPath stringlogger *slog.Logger@@ -56,6 +64,13 @@ type OutboundReplierConfig struct {// with. The replier looks up the live wsSender by installation id.Senders *sendersRegistry+ // Languages resolves the notice's DESTINATION to a copy language+ // (language.go): a 1:1 reads the sender's own Multica profile, a room+ // reads the deployment default. Nil — and every unbound sender, which+ // notably includes everyone the binding prompt is FOR — gets the+ // deployment default.+ Languages languageLookup+// AppURL is the Multica web app host the user clicks into to redeem// the binding token (e.g. https://multica.example). It comes from// MULTICA_APP_URL (falling back to FRONTEND_ORIGIN) and is@@ -75,17 +90,19 @@ func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {if logger == nil {logger = slog.Default()}- bindingPath := cfg.BindingPath- if bindingPath == "" {- bindingPath = "/wecom/bind"- }- if !strings.HasPrefix(bindingPath, "/") {- bindingPath = "/" + bindingPath+ if cfg.Languages == nil {+ // Not fatal — the deployment language is a usable answer — but it is+ // the difference between this replier doing its job and quietly doing+ // main's. A missing wire produces no other symptom: nothing errors,+ // nothing is empty, every notice just comes out in one language.+ logger.Warn("wecom replier: no language lookup wired; every notice will use the deployment language " ++ "whatever the reader's profile says (set OutboundReplierConfig.Languages)")}r := &OutboundReplier{senders: cfg.Senders,+ languages: cfg.Languages,appURL: strings.TrimRight(cfg.AppURL, "/"),- bindingPath: bindingPath,+ bindingPath: normalizeBindingPath(cfg.BindingPath),logger: logger,}// Assign through the interface only when non-nil: a nil *BindingTokenService@@ -102,33 +119,43 @@ func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {// logged, not propagated: the replier runs detached from the inbound ACK// path (the engine.Router owns that goroutine).func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) {+ // These notices land in the room the message came from, so the room+ // decides the language — not whichever member happened to trigger them.+ //+ // The binding prompt is the one thing here addressed to a person rather+ // than the room, and it needs no separate resolution: its reader is+ // unbound by definition, so they have no profile to consult and get the+ // same deployment default the room does.+ c := copyFor(localeFor(ctx, r.languages, inst.ID, aibotChatTypeFromChannel(msg.Source.ChatType), msg.Source.SenderID))+switch res.Outcome {case engine.OutcomeNeedsBinding:- if err := r.sendBindingPrompt(ctx, inst, msg, res); err != nil {+ if err := r.sendBindingPrompt(ctx, inst, msg, res, c); err != nil {r.logger.WarnContext(ctx, "wecom replier: binding prompt failed","installation_id", util.UUIDToString(inst.ID), "error", err)}case engine.OutcomeAgentOffline:- if err := r.post(ctx, inst, msg, agentOfflineText); err != nil {+ if err := r.post(ctx, inst, msg, c.AgentOffline); err != nil {r.logger.WarnContext(ctx, "wecom replier: offline notice failed","installation_id", util.UUIDToString(inst.ID), "error", err)}case engine.OutcomeAgentArchived:- if err := r.post(ctx, inst, msg, agentArchivedText); err != nil {+ if err := r.post(ctx, inst, msg, c.AgentArchived); err != nil {r.logger.WarnContext(ctx, "wecom replier: archived notice failed","installation_id", util.UUIDToString(inst.ID), "error", err)}case engine.OutcomeFreshPending:- if err := r.post(ctx, inst, msg, freshPendingText); err != nil {+ if err := r.post(ctx, inst, msg, c.FreshPending); err != nil {r.logger.WarnContext(ctx, "wecom replier: fresh-start confirmation failed","installation_id", util.UUIDToString(inst.ID), "error", err)}case engine.OutcomeChatStarted:- if err := r.post(ctx, inst, msg, chatStartedText); err != nil {- r.logger.WarnContext(ctx, "wecom replier: new-chat confirmation failed", "installation_id", util.UUIDToString(inst.ID), "error", err)+ if err := r.post(ctx, inst, msg, c.ChatStarted); err != nil {+ r.logger.WarnContext(ctx, "wecom replier: new-chat confirmation failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)}case engine.OutcomeIssueUsage:- if err := r.post(ctx, inst, msg, issueUsageText); err != nil {+ if err := r.post(ctx, inst, msg, c.IssueUsage); err != nil {r.logger.WarnContext(ctx, "wecom replier: issue usage reply failed","installation_id", util.UUIDToString(inst.ID), "error", err)}@@ -149,9 +176,9 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall// never wrote — so they stopped chasing it and the report was// lost. slack/replier.go:125 and dingtalk/replier.go:125 both// branch here; WeCom was the one that did not.- text := issueCreatedText(res)+ text := issueCreatedText(res, c)if res.IssueDuplicate {- text = issueDuplicateText(res)+ text = issueDuplicateText(res, c)}if err := r.post(ctx, inst, msg, text); err != nil {r.logger.WarnContext(ctx, "wecom replier: issue confirmation failed",@@ -162,7 +189,7 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall}}-func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) error {+func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result, c copyPack) error {sender := res.Senderif sender == "" {sender = msg.Source.SenderID@@ -191,10 +218,10 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res// telling the reader to go to a chat they are already reading. Only the// group ack further down runs in the room, and it is the one that names// the 1:1.- text := "👋 绑定链接刚才已经发给你了,就在上方,请直接点击完成绑定。"+ text := c.BindingPendingif !token.Reused {bindURL := r.appURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)- text = "👋 请先绑定你的 Multica 账号,才能与我对话:\n" + bindURL + "\n(链接 15 分钟内有效)"+ text = c.BindingPromptPrefix + bindURL + c.BindingPromptSuffix}// A binding token is a bearer credential: binding.Redeem only checks that// the redeemer belongs to the token's workspace, and the bind page redeems@@ -213,7 +240,7 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res// send is accepted, so the room is never pointed at a message the wire// refused. A 1:1 trigger already received the prompt in its only room.if aibotChatTypeFromChannel(msg.Source.ChatType) == chatTypeGroupInt {- return r.post(ctx, inst, msg, "👋 已把绑定链接私发给你,请在与我的单聊里点击完成绑定。")+ return r.post(ctx, inst, msg, c.BindingSentPrivately)}return nil}@@ -226,11 +253,16 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res// sender is bound by definition at this point — the identity check is what// produced the user id this verdict was read for — so a 1:1 route to them// exists.+//+// Either way the only reader is the sender, so the sender's own profile picks+// the language — not the room's, which is what Reply resolved for everything+// else it says.func (r *OutboundReplier) sendInvokeDenied(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) error {+ text := copyFor(localeFor(ctx, r.languages, inst.ID, chatTypeSingleInt, msg.Source.SenderID)).InvokeDeniedif aibotChatTypeFromChannel(msg.Source.ChatType) != chatTypeGroupInt {- return r.post(ctx, inst, msg, invokeDeniedText)+ return r.post(ctx, inst, msg, text)}- return r.postPrivate(ctx, inst, msg.Source.SenderID, invokeDeniedText)+ return r.postPrivate(ctx, inst, msg.Source.SenderID, text)}// postPrivate delivers text to a single user's 1:1 chat (chat_type=1),@@ -283,37 +315,27 @@ func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstalla//// That title belongs to the pre-existing issue, so it is text some *other*// member wrote — not even the reporter's own, which is what makes this the-// worse of the two /issue call sites — and the reply ships as markdown. Hence-// breakMemberLinks, the same entry point issueCreatedText runs its title-// through: it breaks the inline "](" form and the link reference definition a-// multi-line title can smuggle instead. See markdown.go.-func issueDuplicateText(res engine.Result) string {- id := res.IssueIdentifier- if id == "" {- id = fmt.Sprintf("#%d", res.IssueNumber)- }- title := breakMemberLinks(strings.TrimSpace(res.IssueTitle))- if title == "" {- return "⚠️ 未创建 —— 已存在进行中的 " + id- }- return "⚠️ 未创建 —— 已存在进行中的 " + id + " — " + title+// worse of the two /issue call sites — and the reply ships as markdown. The+// pack's renderer runs it through breakMemberLinks, the same entry point+// issueCreated uses: it breaks the inline "](" form and the link reference+// definition a multi-line title can smuggle instead. See markdown.go.+func issueDuplicateText(res engine.Result, c copyPack) string {+ return c.issueDuplicate(issueRef(res), res.IssueTitle)}-func issueCreatedText(res engine.Result) string {- id := res.IssueIdentifier- if id == "" {- id = fmt.Sprintf("#%d", res.IssueNumber)- }- // The title is the reporter's own text and this confirmation goes back- // into the chat that triggered it — in a group, in front of the room. An- // issue titled "安全升级:请点击 [重置密码](https://evil.example) 完成验证"- // otherwise comes back from the bot as a working link, with the bot's- // authority behind it. A title carrying a line break can define one- // instead of writing it inline, which is why the reference-definition- // break applies here too.- title := breakMemberLinks(strings.TrimSpace(res.IssueTitle))- if title == "" {- return "✅ 已创建 " + id+// issueCreatedText answers a /issue the engine accepted. The title is the+// reporter's own text and this confirmation goes back into the chat that+// triggered it — in a group, in front of the room — so the pack breaks its+// links before it goes out. See copyPack.issueCreated.+func issueCreatedText(res engine.Result, c copyPack) string {+ return c.issueCreated(issueRef(res), res.IssueTitle)+}++// issueRef is how an issue is named in a confirmation: its identifier when the+// engine produced one, its number otherwise.+func issueRef(res engine.Result) string {+ if res.IssueIdentifier != "" {+ return res.IssueIdentifier}- return "✅ 已创建 " + id + " — " + title+ return fmt.Sprintf("#%d", res.IssueNumber)}diff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.goindex adfdf5e032..a8db91daeb 100644--- a/server/internal/integrations/wecom/replier_test.go+++ b/server/internal/integrations/wecom/replier_test.go@@ -193,8 +193,8 @@ func TestReply_CommandOutcomes_PostGuidance(t *testing.T) {outcome engine.Outcomewant string}{- {engine.OutcomeFreshPending, freshPendingText},- {engine.OutcomeIssueUsage, issueUsageText},+ {engine.OutcomeFreshPending, copyFor(DefaultLocale).FreshPending},+ {engine.OutcomeIssueUsage, copyFor(DefaultLocale).IssueUsage},} {t.Run(string(tc.outcome), func(t *testing.T) {r, inst, conn := newReplierWithConn(t)@@ -236,7 +236,7 @@ func TestSendBindingPrompt_GroupNeverLeaksToken(t *testing.T) {ChatType: channel.ChatTypeGroup,SenderID: senderID,}}- if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}); err != nil {+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}, copyFor(DefaultLocale)); err != nil {t.Fatalf("sendBindingPrompt: %v", err)}@@ -300,7 +300,7 @@ func TestSendBindingPrompt_P2PSendsOnlyPrivately(t *testing.T) {r.binding = fakeBinder{raw: rawToken}msg := channel.InboundMessage{Source: channel.Source{ChatID: "USER_A", ChatType: channel.ChatTypeP2P, SenderID: "USER_A"}}- if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: "USER_A"}); err != nil {+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: "USER_A"}, copyFor(DefaultLocale)); err != nil {t.Fatalf("sendBindingPrompt: %v", err)}conn.mu.Lock()@@ -341,7 +341,7 @@ func TestSendBindingPrompt_ThrottledSendsNoURL(t *testing.T) {ChatType: channel.ChatTypeGroup,SenderID: senderID,}}- if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}); err != nil {+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}, copyFor(DefaultLocale)); err != nil {t.Fatalf("sendBindingPrompt: %v", err)}@@ -425,7 +425,7 @@ func TestIssueConfirmationDoesNotRenderReporterLinks(t *testing.T) {IssueIdentifier: "MUL-1",IssueTitle: "安全升级:请点击 [重置密码](https://evil.example) 完成验证",}- got := issueCreatedText(res)+ got := issueCreatedText(res, copyFor(DefaultLocale))if strings.Contains(got, "](") {t.Fatalf("a reporter-authored link rendered in a bot-authored group message: %q", got)}@@ -445,7 +445,7 @@ func TestIssueConfirmationDefinesNoLinkReference(t *testing.T) {IssueIdentifier: "MUL-1",IssueTitle: "安全升级\n\n[重置密码]: https://evil.example\n\n[重置密码]",}- got := issueCreatedText(res)+ got := issueCreatedText(res, copyFor(DefaultLocale))if dests := markdownDestinations(got); hasDestinationTo(dests, "evil.example") {t.Fatalf("a reporter-defined link resolved in a bot-authored group message: %q resolves %v", got, dests)}@@ -465,7 +465,7 @@ func TestIssueConfirmationKeepsAnOrdinaryTitleVerbatim(t *testing.T) {"[Bug]: 登录失败",} {res := engine.Result{IssueIdentifier: "MUL-1", IssueTitle: title}- if got, want := issueCreatedText(res), "✅ 已创建 MUL-1 — "+title; got != want {+ if got, want := issueCreatedText(res, copyFor(DefaultLocale)), "✅ 已创建 MUL-1 — "+title; got != want {t.Fatalf("the reporter's own title came back altered:\n got %q\nwant %q", got, want)}}@@ -484,9 +484,9 @@ func TestIssueDuplicateIsNotReportedAsCreated(t *testing.T) {IssueTitle: "somebody else's title",IssueDuplicate: true,}- text := issueCreatedText(res)+ text := issueCreatedText(res, copyFor(DefaultLocale))if res.IssueDuplicate {- text = issueDuplicateText(res)+ text = issueDuplicateText(res, copyFor(DefaultLocale))}if strings.Contains(text, "已创建") {t.Errorf("a duplicate was reported as created: %q", text)diff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.goindex 8b174fd151..c85f2f0854 100644--- a/server/internal/integrations/wecom/strings.go+++ b/server/internal/integrations/wecom/strings.go@@ -1,15 +1,16 @@package wecom-// strings.go — the copy the streaming bubble writes, in one place, selected-// per READER.+// strings.go — every string a WeCom user reads, in one place, selected per+// READER.//-// IT CARRIES ONLY THE BUBBLE'S COPY. Everything else this adapter says — the-// offline and archived notices, the binding prompt, the inbox card's labels —-// is still the Chinese literal at its own call site, exactly as before. Those-// move here when they are translated; nothing about this file asks them to-// move first.+// The copy used to sit inline wherever it was sent: the offline and archived+// notices in replier.go, the binding prompt built by hand a few lines below+// them, the inbox card's type labels in inbox_message.go. All of it Chinese,+// which is right for our own tenant and wrong the moment anyone else installs+// the bot — and impossible to find, because "what does this bot say" was+// spread across three files.//-// Which pack a given bubble uses is decided by the DESTINATION, not by the+// Which pack a given message uses is decided by the DESTINATION, not by the// installation (language.go): a 1:1 gets that person's Multica profile// language, and a room — where there is no shared profile and no member list —// gets the deployment's own language.@@ -20,8 +21,9 @@ package wecom// rules. If wecom ever needs a third language with real formatting rules,// that is the moment to reach for a framework — not now.//-// The zh-Hans pack is the text a Chinese tenant reads; the English pack is for-// a reader whose Multica profile says anything else.+// The zh-Hans pack is the text this adapter was already sending, character for+// character. Nothing a Chinese tenant reads changes here; the English pack is+// new.import ("strings"@@ -109,10 +111,61 @@ func resolveLocale(s string) Locale {}}-// copyPack is the set of user-visible strings one locale's bubble is written-// in. Everything the bubble can say is a field here; nothing is built by-// concatenating fragments elsewhere.+// copyPack is the full set of user-visible strings for one locale. Everything+// the adapter can say is a field here; nothing is built by concatenating+// fragments elsewhere.type copyPack struct {+ // AgentOffline / AgentArchived answer an engine outcome.+ AgentOffline string+ AgentArchived string++ // FreshPending confirms /clear: the next chat message stays in the+ // conversation it is already in and runs without the context before it.+ // ChatStarted confirms /new, which is the other half of that split — a+ // new conversation the next message enters. Two commands, two answers:+ // telling a /clear user their conversation was replaced sends them+ // looking for a thread that never moved. IssueUsage answers a bare+ // /issue with the shape it wanted. All three are stated here rather than as+ // package constants — the lint asserts it, and a Chinese literal in+ // replier.go is a line no other locale can read.+ FreshPending string+ ChatStarted string+ IssueUsage string++ // InvokeDenied answers a member who may not run this agent (a private+ // agent belongs to its owner alone). It always goes to that member alone —+ // in place in a 1:1, in their own 1:1 for a group trigger (replier.go) — so+ // their profile picks the language even when the trigger was a room.+ InvokeDenied string++ // BindingPromptPrefix / BindingPromptSuffix wrap the bind URL.+ // BindingPending replaces the whole thing when the mint was throttled and+ // there is no URL to print. Both go to the sender alone, never to a room+ // (replier.go) — the URL carries a bearer token.+ BindingPromptPrefix string+ BindingPromptSuffix string+ BindingPending string++ // BindingSentPrivately is what the ROOM sees when an unbound member+ // triggers the bot in a group: the prompt itself went to that member's+ // 1:1 chat, and without this line the group would read the bot as broken.+ // It names no one and carries no token, so it is safe in front of an+ // audience of unknown size.+ BindingSentPrivately string++ // IssueCreatedPrefix leads the /issue confirmation; IssueTitleSeparator+ // joins the identifier to the title when there is one.+ IssueCreatedPrefix string+ IssueTitleSeparator string++ // IssueDuplicatePrefix leads the answer for an /issue the engine refused+ // because an active issue already matched. The identifier and title that+ // follow belong to THAT issue, which is why the copy has to say so rather+ // than reading like a confirmation: this case used to be answered with+ // the created copy, so the person was shown a number somebody else opened,+ // under a title they never wrote, for a report that was never filed.+ IssueDuplicatePrefix string+// The ways a streaming reply ends in something other than an answer. Each// one closes the loading bubble the question opened, so each one has to// carry visible text — WeCom discards a closing frame it considers empty@@ -124,9 +177,6 @@ type copyPack struct {// Distinct from StreamNoReply because that copy says nothing is coming,// and then something arrives: a bubble that contradicts the next message// reads as a bug even though both halves are working.- // say; the reply ahead of it already covered this message. A first- // round's empty finish keeps StreamNoReply, which has no earlier answer- // to point at.// StreamNotStarted — no run was triggered at all (agent offline or// archived, or the enqueue failed); the replier's own notice follows as// a separate message with the detail.@@ -142,6 +192,73 @@ type copyPack struct {StreamNotStarted stringStreamFailed stringStreamCancelled string++ // InboxDetailLink is the anchor text on the inbox card's deep link;+ // InboxTypeLabels names each notification kind, with InboxTypeFallback+ // covering a kind this adapter has not been taught yet.+ InboxDetailLink string+ InboxTypeLabels map[string]string+ InboxTypeFallback string+ // MediaSendFailed / MediaSendUnknown / MediaLookupFailed go the other way:+ // the agent produced a file and it did not plainly reach the chat. The+ // answer is already on screen and may well point at the file, so silence+ // would leave the user waiting for something that is not coming. One line+ // covers the whole turn however many files were affected — the reason (too+ // big, storage down, WeCom refused it) is a log line, not something the+ // reader can act on.+ //+ // Three of them because there are three things that can be true, and+ // telling them apart is the point (see deliveryState in outbound_media.go).+ // MediaSendFailed is the definite one: nothing arrived and nothing can+ // have. MediaSendUnknown is for a send whose verdict never came back — its+ // wording has to survive both endings, so it must not say "failed" to+ // someone looking at the file, and it says why nothing is resent, since a+ // duplicate cannot be taken back. MediaLookupFailed is earlier still: we+ // could not read what was attached to this reply, so we do not know whether+ // there was a file at all.+ MediaSendFailed string+ MediaSendUnknown string+ MediaLookupFailed string+}++// label returns the display name for an inbox notification type.+func (c copyPack) label(t string) string {+ if l, ok := c.InboxTypeLabels[t]; ok {+ return l+ }+ return c.InboxTypeFallback+}++// issueCreated renders the /issue confirmation.+//+// The title is whatever the reporter typed, and this goes out as a markdown+// body — so it goes through breakMemberLinks here, at the render boundary,+// exactly as buildInboxMarkdown treats a title before putting it in a card.+// Without it, "/issue 安全升级:请点击 [重置密码](https://evil.example) 完成验证"+// comes back from the Multica bot, in the group, as a working link inside a+// confirmation everyone has reason to trust. Our own copy fragments stay raw;+// only the member-authored field is broken.+func (c copyPack) issueCreated(identifier, title string) string {+ title = breakMemberLinks(strings.TrimSpace(title))+ if title == "" {+ return c.IssueCreatedPrefix + identifier+ }+ return c.IssueCreatedPrefix + identifier + c.IssueTitleSeparator + title+}++// issueDuplicate renders the answer for an /issue the engine refused because+// an active issue already matched. The identifier and title belong to THAT+// issue, not to the message being answered.+//+// The title here belongs to somebody ELSE's issue, which makes breaking its+// links more important rather than less: the reporter is being shown text they+// did not write.+func (c copyPack) issueDuplicate(identifier, title string) string {+ out := c.IssueDuplicatePrefix + identifier+ if t := breakMemberLinks(strings.TrimSpace(title)); t != "" {+ out += c.IssueTitleSeparator + t+ }+ return out}// copyFor returns the pack for a locale, falling back to the deployment's.@@ -154,17 +271,87 @@ func copyFor(l Locale) copyPack {var copyPacks = map[Locale]copyPack{LocaleZhHans: {+ AgentOffline: "⚠️ 智能体当前不在线,你的消息已收到,等它上线后会处理。",+ AgentArchived: "⚠️ 该智能体已归档,无法回复。请联系工作区管理员。",+ FreshPending: "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。",+ ChatStarted: "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。",+ IssueUsage: "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)",+ InvokeDenied: "⚠️ 你没有权限运行该智能体。如需使用,请联系它的所有者。",+ BindingPromptPrefix: "👋 请先绑定你的 Multica 账号,才能与我对话:\n",+ BindingPromptSuffix: "\n(链接 15 分钟内有效)",+ BindingPending: "👋 绑定链接刚才已经发给你了,就在上方,请直接点击完成绑定。",+ BindingSentPrivately: "👋 已把绑定链接私发给你,请在与我的单聊里点击完成绑定。",++ IssueCreatedPrefix: "✅ 已创建 ",+ IssueTitleSeparator: " — ",+ IssueDuplicatePrefix: "⚠️ 未创建 —— 已存在进行中的 ",+StreamNoReply: "(这轮没有需要回复的内容)",StreamNoReplyWithFiles: "(这轮没有文字回复,附件在下面)",StreamNotStarted: "已收到,但这条暂时没能开始处理。",StreamFailed: "⚠️ 这次没跑通,请稍后再试一次。",+ MediaSendFailed: "⚠️ 有文件没能发出来,我这边保留着,需要的话我再试一次。",+ MediaSendUnknown: "⚠️ 有文件我没收到企业微信的送达回执,可能已经发到了、也可能没有。我不会自动重发,免得发重了;你那边没看到的话说一声,我再发一次。",+ MediaLookupFailed: "⚠️ 我这边没查到这条回答带没带文件,所以要是有,这次没发出来。需要的话我再试一次。",StreamCancelled: "⏹️ 这次处理已取消。",++ InboxDetailLink: "查看详情",+ InboxTypeLabels: map[string]string{+ "issue_assigned": "任务指派",+ "mentioned": "提及你",+ "status_changed": "状态变更",+ "comment_added": "新评论",+ "new_comment": "新评论",+ "reaction_added": "表情反应",+ "task_failed": "task 失败",+ "unassigned": "取消指派",+ "assignee_changed": "指派人变更",+ "priority_changed": "优先级变更",+ "due_date_changed": "截止日期变更",+ "start_date_changed": "开始日期变更",+ },+ InboxTypeFallback: "新消息",},LocaleEn: {+ AgentOffline: "⚠️ The agent is offline right now. Your message was received and will be handled once it's back.",+ AgentArchived: "⚠️ This agent has been archived and can't reply. Please contact your workspace admin.",+ FreshPending: "✅ Fresh start ready. Your next message stays in this chat but runs without the earlier context.",+ ChatStarted: "✅ Started a new Multica chat. Your next message will enter it.",+ IssueUsage: "Please include an issue title. Use:\n\n`/issue <title>`\n`[description]` (optional)",+ InvokeDenied: "⚠️ You don't have permission to run this agent. Ask its owner if you need to use it.",+ BindingPromptPrefix: "👋 Link your Multica account before we can talk:\n",+ BindingPromptSuffix: "\n(the link is good for 15 minutes)",+ BindingPending: "👋 I already sent you a link — it is just above, tap it to finish linking.",+ BindingSentPrivately: "👋 I've sent the link to your direct chat with me — tap it there to finish linking.",++ IssueCreatedPrefix: "✅ Created ",+ IssueTitleSeparator: " — ",+ IssueDuplicatePrefix: "⚠️ Not created — an active issue already covers this: ",+StreamNoReply: "(nothing to reply with this round)",StreamNoReplyWithFiles: "(no text this round — the files follow)",StreamNotStarted: "Got it, but this one couldn't start processing.",StreamFailed: "⚠️ That run didn't go through. Please try again.",+ MediaSendFailed: "⚠️ I couldn't send one of the files. It is still here — say the word and I'll try again.",+ MediaSendUnknown: "⚠️ WeCom never confirmed one of the files, so it may or may not have arrived. I won't resend it automatically in case that shows it twice — tell me if it isn't there and I'll send it again.",+ MediaLookupFailed: "⚠️ I couldn't check whether this answer had a file with it, so if it did, it didn't go out. Say the word and I'll try again.",StreamCancelled: "⏹️ That run was cancelled.",++ InboxDetailLink: "View details",+ InboxTypeLabels: map[string]string{+ "issue_assigned": "Assigned",+ "mentioned": "Mentioned",+ "status_changed": "Status changed",+ "comment_added": "New comment",+ "new_comment": "New comment",+ "reaction_added": "Reaction",+ "task_failed": "Run failed",+ "unassigned": "Unassigned",+ "assignee_changed": "Assignee changed",+ "priority_changed": "Priority changed",+ "due_date_changed": "Due date changed",+ "start_date_changed": "Start date changed",+ },+ InboxTypeFallback: "Notification",},}diff --git a/server/internal/integrations/wecom/trace_test.go b/server/internal/integrations/wecom/trace_test.goindex 4bec5bf360..e8827ed7a3 100644--- a/server/internal/integrations/wecom/trace_test.go+++ b/server/internal/integrations/wecom/trace_test.go@@ -265,7 +265,7 @@ func TestTraceNeverLogsABindingToken(t *testing.T) {ChatType: channel.ChatTypeGroup,SenderID: senderID,}}- if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}); err != nil {+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}, copyFor(DefaultLocale)); err != nil {t.Fatalf("sendBindingPrompt: %v", err)}