Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
[MUL-8300] fix(lark): resolve outbound references to workspace links (#9604)
Frezca8e75614212a
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 7d344db5aa..6e86b6990c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -617,7 +617,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// backfills) take it directly; the constructor-based services// wrap *db.Queries internally, so they keep taking queries.cs := lark.NewChannelStore(queries)- patcher := lark.NewPatcher(cs, installSvc, larkClient, lark.PatcherConfig{})+ patcher := lark.NewPatcher(cs, installSvc, larkClient, lark.PatcherConfig{AppURL: appURLFromEnv()})if store != nil && patcher.SetAttachments(store) {h.DeclareChannelFileDelivery(string(channel.TypeFeishu))}diff --git a/server/internal/integrations/channel/issue_link.go b/server/internal/integrations/channel/issue_link.goindex afec7438d7..1902f1dcd8 100644--- a/server/internal/integrations/channel/issue_link.go+++ b/server/internal/integrations/channel/issue_link.go@@ -13,9 +13,19 @@ import (// that forgets to plumb the slug through loses its link loudly, instead of// silently shipping the unroutable legacy /issues/{identifier} form again.func IssueWebLink(appURL, workspaceSlug, identifier string) string {- if appURL == "" || workspaceSlug == "" || identifier == "" {+ return ReferenceWebLink(appURL, workspaceSlug, "issue", identifier)+}++// ReferenceWebLink builds detail links for the navigable mention types.+// Member references address users, not workspace membership rows.+func ReferenceWebLink(appURL, workspaceSlug, kind, id string) string {+ route := map[string]string{+ "issue": "issues", "project": "projects", "agent": "agents",+ "squad": "squads", "member": "members",+ }[kind]+ if appURL == "" || workspaceSlug == "" || id == "" || route == "" {return ""}return strings.TrimRight(appURL, "/") + "/" + url.PathEscape(workspaceSlug) +- "/issues/" + url.PathEscape(identifier)+ "/" + route + "/" + url.PathEscape(id)}diff --git a/server/internal/integrations/channel/reference_links.go b/server/internal/integrations/channel/reference_links.gonew file mode 100644index 0000000000..796dbfe3de--- /dev/null+++ b/server/internal/integrations/channel/reference_links.go@@ -0,0 +1,262 @@+package channel++import (+ "bufio"+ "bytes"+ "regexp"+ "sort"+ "strings"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/ast"+ "github.com/yuin/goldmark/extension"+ extast "github.com/yuin/goldmark/extension/ast"+ "github.com/yuin/goldmark/parser"+ htmlrenderer "github.com/yuin/goldmark/renderer/html"+ "github.com/yuin/goldmark/text"+ "github.com/yuin/goldmark/util"+)++var replyIssueIdentifier = regexp.MustCompile(`[A-Z0-9]{1,10}-[0-9]+`)+var replyIssueProtectedURL = regexp.MustCompile(+ `(?i)(?:[a-z][a-z0-9+.-]*://|www\.|mailto:|[/\\])[^\s\p{Z}\x{0085}\x0b<>]+` ++ "|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9.-]+")++type referenceEdit struct {+ start, end int+ kind, reference string+ prefix, suffix string+}++// LinkReferences rewrites outbound Multica references using a caller-owned+// resolver. Code, existing URLs and unresolved references retain their source.+// Broadcast mentions have no detail route and become inert display text.+func LinkReferences(content string, resolve func(kind, reference string) string) string {+ if resolve == nil || (!strings.Contains(content, "[") && !replyIssueIdentifier.MatchString(content)) {+ return content+ }+ var out strings.Builder+ last := 0+ for _, edit := range referenceEdits(content) {+ replacement := edit.prefix+ if edit.kind != "all" || edit.reference != "all" {+ link := resolve(edit.kind, edit.reference)+ if link == "" {+ continue+ }+ replacement = edit.prefix + link + edit.suffix+ }+ out.WriteString(content[last:edit.start])+ out.WriteString(replacement)+ last = edit.end+ }+ if last == 0 {+ return content+ }+ out.WriteString(content[last:])+ return out.String()+}++func referenceEdits(content string) []referenceEdit {+ inlines := parser.DefaultInlineParsers()+ for i := range inlines {+ inlines[i].Value = referenceSourceParser{inlines[i].Value.(parser.InlineParser)}+ }+ p := parser.NewParser(parser.WithBlockParsers(parser.DefaultBlockParsers()...), parser.WithInlineParsers(inlines...), parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...))+ source := []byte(content)+ md := goldmark.New(goldmark.WithParser(p), goldmark.WithExtensions(extension.Table))+ doc := md.Parser().Parse(text.NewReader(source))+ urls := referenceURLRanges(source, doc)+ var edits []referenceEdit+ _ = ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {+ if !entering {+ return ast.WalkContinue, nil+ }+ switch n := node.(type) {+ case *ast.Link:+ if target, ok := strings.CutPrefix(string(util.URLEscape(n.Destination, true)), "mention://"); ok {+ kind, reference, valid := strings.Cut(target, "/")+ if !valid || kind == "" || reference == "" {+ return ast.WalkSkipChildren, nil+ }+ edit := referenceEdit{kind: kind, reference: reference}+ labelEnd, _ := n.AttributeString("reference_label_end")+ end, _ := n.AttributeString("source_end")+ if labelEnd, ok := labelEnd.(int); ok {+ if kind == "all" && reference == "all" {+ if end, ok := end.(int); ok && n.Pos() >= 0 && n.Pos() < labelEnd {+ edit.start, edit.end, edit.prefix = n.Pos(), end, string(source[n.Pos()+1:labelEnd])+ edits = append(edits, edit)+ }+ return ast.WalkSkipChildren, nil+ }+ if end, ok := end.(int); ok && n.Reference != nil {+ edit.start, edit.end, edit.prefix, edit.suffix = labelEnd+1, end, "(", inlineReferenceTitle(n.Title)+")"+ edits = append(edits, edit)+ } else {+ start, _ := n.AttributeString("reference_destination_start")+ stop, _ := n.AttributeString("reference_destination_end")+ if start, ok := start.(int); ok {+ if stop, ok := stop.(int); ok && start >= 0 && start < stop && stop <= len(source) {+ edit.start, edit.end = start, stop+ edits = append(edits, edit)+ }+ }+ }+ }+ }+ return ast.WalkSkipChildren, nil+ case *ast.CodeSpan, *ast.CodeBlock, *ast.FencedCodeBlock, *ast.Image, *ast.AutoLink, *ast.RawHTML, *ast.HTMLBlock:+ return ast.WalkSkipChildren, nil+ case *ast.Text:+ for _, match := range replyIssueIdentifier.FindAllIndex(source[n.Segment.Start:n.Segment.Stop], -1) {+ start, end := n.Segment.Start+match[0], n.Segment.Start+match[1]+ urlIndex := sort.Search(len(urls), func(i int) bool { return urls[i].Stop > start })+ if urlIndex < len(urls) && urls[urlIndex].Start < end {+ continue+ }+ if bareIssueInProse(source, n, start, end) {+ reference := string(source[start:end])+ edits = append(edits, referenceEdit{start: start, end: end, kind: "issue", reference: reference, prefix: "[" + reference + "](", suffix: ")"})+ }+ }+ }+ return ast.WalkContinue, nil+ })+ sort.Slice(edits, func(i, j int) bool { return edits[i].start < edits[j].start })+ return edits+}++// Match raw URLs across text/emphasis nodes, but never through a complete+// Markdown construct. A URL in a link destination must not protect later prose.+func referenceURLRanges(source []byte, doc ast.Node) []text.Segment {+ var markup []text.Segment+ _ = ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {+ if !entering {+ return ast.WalkContinue, nil+ }+ switch node.(type) {+ case *extast.TableCell:+ // A raw URL may span emphasis nodes, but cannot cross into the+ // next GFM cell. Escaped pipes inside a cell remain URL content.+ for i := 0; i < node.Lines().Len(); i++ {+ line := node.Lines().At(i)+ markup = append(markup, text.NewSegment(line.Start, line.Start), text.NewSegment(line.Stop, line.Stop))+ }+ case *ast.Link, *ast.Image, *ast.CodeSpan, *ast.AutoLink, *ast.RawHTML:+ start, _ := node.AttributeString("source_start")+ end, _ := node.AttributeString("source_end")+ if start, ok := start.(int); ok {+ if end, ok := end.(int); ok && start >= 0 && start < end && end <= len(source) {+ markup = append(markup, text.NewSegment(start, end))+ }+ }+ return ast.WalkSkipChildren, nil+ }+ return ast.WalkContinue, nil+ })+ sort.Slice(markup, func(i, j int) bool { return markup[i].Start < markup[j].Start })+ var urls []text.Segment+ add := func(start, end int) {+ for _, match := range replyIssueProtectedURL.FindAllIndex(source[start:end], -1) {+ urls = append(urls, text.NewSegment(start+match[0], start+match[1]))+ }+ }+ last := 0+ for _, span := range markup {+ if span.Start > last {+ add(last, span.Start)+ }+ if span.Stop > last {+ last = span.Stop+ }+ }+ add(last, len(source))+ return urls+}++// Capture source boundaries through Goldmark so nested and reference labels+// retain their original Markdown rather than being reconstructed.+type referenceSourceParser struct{ parser.InlineParser }++func (p referenceSourceParser) Parse(parent ast.Node, reader text.Reader, pc parser.Context) ast.Node {+ beforeLine, before := reader.Position()+ n := p.InlineParser.Parse(parent, reader, pc)+ switch n.(type) {+ case *ast.Link, *ast.Image, *ast.CodeSpan, *ast.AutoLink, *ast.RawHTML:+ endLine, end := reader.Position()+ start := before.Start+ switch n.(type) {+ case *ast.Link:+ n.SetAttributeString("reference_label_end", before.Start)+ start = n.Pos()+ link := n.(*ast.Link)+ if link.Reference == nil {+ // Reuse the block reader's container-aware whitespace handling;+ // raw source scanning would stop at a continuation line's '>'.+ reader.SetPosition(beforeLine, before)+ reader.Advance(1) // closing label bracket+ if reader.Peek() == '(' {+ reader.Advance(1)+ reader.SkipSpaces()+ if reader.Peek() == '<' {+ reader.Advance(1)+ }+ _, destination := reader.Position()+ stop := destination.Start + len(link.Destination)+ if destination.Start >= 0 && stop <= end.Start && bytes.HasPrefix(reader.Source()[destination.Start:], link.Destination) {+ n.SetAttributeString("reference_destination_start", destination.Start)+ n.SetAttributeString("reference_destination_end", stop)+ }+ }+ reader.SetPosition(endLine, end)+ }+ case *ast.Image:+ start = n.Pos()+ }+ n.SetAttributeString("source_start", start)+ n.SetAttributeString("source_end", end.Start)+ }+ return n+}++func (p referenceSourceParser) CloseBlock(parent ast.Node, reader text.Reader, pc parser.Context) {+ if closer, ok := p.InlineParser.(parser.CloseBlocker); ok {+ closer.CloseBlock(parent, reader, pc)+ }+}++func inlineReferenceTitle(title []byte) string {+ if title == nil {+ return ""+ }+ // Use Goldmark's own title decoding, then keep the expanded title on one+ // source line so reference links in quotes/lists retain their containers.+ var escaped bytes.Buffer+ w := bufio.NewWriter(&escaped)+ htmlrenderer.DefaultWriter.Write(w, title)+ _ = w.Flush()+ value := strings.NewReplacer("\\", "\", "\r", " ", "\n", " ").Replace(escaped.String())+ return ` "` + value + `"`+}++func bareIssueInProse(source []byte, node *ast.Text, start, end int) bool {+ isToken := func(c byte) bool {+ return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("_-./\\@", rune(c))+ }+ // Only parsed emphasis delimiters are exempt from the underscore token+ // guard. Underscores inside words and URL ranges remain protected.+ _, emphasis := node.Parent().(*ast.Emphasis)+ leadingEmphasis := emphasis && start == node.Segment.Start && node.PreviousSibling() == nil && start > 0 && source[start-1] == '_'+ trailingEmphasis := emphasis && end == node.Segment.Stop && node.NextSibling() == nil && end < len(source) && source[end] == '_'+ if start > 0 && isToken(source[start-1]) && !leadingEmphasis || end < len(source) && isToken(source[end]) && source[end] != '.' && !trailingEmphasis {+ return false+ }+ if end+1 < len(source) && source[end] == '.' && isToken(source[end+1]) {+ return false+ }+ if start >= 2 && source[start-1] == '[' && source[start-2] == '\\' {+ return false+ }+ return true+}diff --git a/server/internal/integrations/channel/reference_links_test.go b/server/internal/integrations/channel/reference_links_test.gonew file mode 100644index 0000000000..b483928e9d--- /dev/null+++ b/server/internal/integrations/channel/reference_links_test.go@@ -0,0 +1,216 @@+package channel++import (+ "bytes"+ "strings"+ "testing"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/extension"+)++func TestLinkReferencesContainerDestinations(t *testing.T) {+ const target = "mention://project/real-id"+ const destination = "https://deployment.example/team/projects/real-id"+ for _, body := range []string{+ "> [Project](\n> " + target + "\n> )",+ "> [Project](\n> <" + target + "> \"Title\"\n> )",+ "> > [Project](\n> > " + target + "\n> > )",+ "> - [Project](\n> " + target + "\n> )",+ "> [Project](\r\n> " + target + "\r\n> )",+ "- [Project](\n " + target + "\n )",+ } {+ t.Run(body, func(t *testing.T) {+ got := LinkReferences(body, func(kind, id string) string { return destination })+ if want := strings.Replace(body, target, destination, 1); got != want {+ t.Fatalf("rewrite=%q, want=%q", got, want)+ }+ })+ }+}++func TestLinkReferencesEscapedDestinations(t *testing.T) {+ const destination = "https://deployment.example/team/projects/real-id"+ for _, target := range []string{+ `mention\://project/real-id`,+ `mention:\/\/project/real-id`,+ `mention://project/real-id`,+ `mention://project/real-id`,+ `mention://project/real-id`,+ } {+ t.Run(target, func(t *testing.T) {+ body := "[Project](" + target + " \"mention://project/real-id\")"+ got := LinkReferences(body, func(kind, id string) string {+ if kind != "project" || id != "real-id" {+ t.Fatalf("unexpected target: %s/%s", kind, id)+ }+ return destination+ })+ if want := "[Project](" + destination + " \"mention://project/real-id\")"; got != want {+ t.Fatalf("rewrite=%q, want=%q", got, want)+ }+ if unresolved := LinkReferences(body, func(string, string) string { return "" }); unresolved != body {+ t.Fatalf("unresolved destination changed: %q", unresolved)+ }+ })+ }+}++func TestLinkReferencesTableBoundaries(t *testing.T) {+ const issue = "[FEED-193](https://deployment.example/team/issues/FEED-193)"+ for _, tc := range []struct{ name, body, want string }{+ {"adjacent cells", "|docs|task|\n|---|---|\n|https://docs.example|FEED-193|", "|docs|task|\n|---|---|\n|https://docs.example|" + issue + "|"},+ {"URL query", "|docs|task|\n|---|---|\n|https://docs.example/?q=FEED-193|FEED-193|", "|docs|task|\n|---|---|\n|https://docs.example/?q=FEED-193|" + issue + "|"},+ {"emphasis in URL", "|docs|task|\n|---|---|\n|https://docs.example/?q=**FEED-193**|FEED-193|", "|docs|task|\n|---|---|\n|https://docs.example/?q=**FEED-193**|" + issue + "|"},+ {"escaped pipe in URL", "|docs|task|\n|---|---|\n|https://docs.example/?q=FEED-193\\|part|FEED-193|", "|docs|task|\n|---|---|\n|https://docs.example/?q=FEED-193\\|part|" + issue + "|"},+ {"quoted table", "> |docs|task|\n> |---|---|\n> |https://docs.example|FEED-193|", "> |docs|task|\n> |---|---|\n> |https://docs.example|" + issue + "|"},+ {"code with pipe", "|docs|task|\n|---|---|\n|`https://docs.example/FEED-193\\|FEED-193`|FEED-193|", "|docs|task|\n|---|---|\n|`https://docs.example/FEED-193\\|FEED-193`|" + issue + "|"},+ {"pipe outside table", "https://docs.example/?q=FEED-193|FEED-193", "https://docs.example/?q=FEED-193|FEED-193"},+ {"inline code", "`|docs|task|\n|---|---|\n|https://docs.example|FEED-193|`", "`|docs|task|\n|---|---|\n|https://docs.example|FEED-193|`"},+ {"without outer pipes", "docs|task\n---|---\nhttps://docs.example|FEED-193", "docs|task\n---|---\nhttps://docs.example|" + issue},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := LinkReferences(tc.body, func(kind, id string) string { return "https://deployment.example/team/issues/FEED-193" })+ if got != tc.want {+ t.Fatalf("rewrite=%q, want=%q", got, tc.want)+ }+ })+ }+}++func TestLinkReferencesReferenceTitles(t *testing.T) {+ const target = "mention://project/real-id"+ const destination = "https://deployment.example/team/projects/real-id"+ for _, form := range []string{"[Project][ref]", "[Project][]", "[Project]"} {+ for _, title := range []string{`"Title"`, `'A "quote" & value'`, `"escaped \& and \\path"`, "\"multi\nline\""} {+ t.Run(form+title, func(t *testing.T) {+ label := "ref"+ if form != "[Project][ref]" {+ label = "Project"+ }+ body := form + "\n\n[" + label + "]: " + target + " " + title+ for _, body := range []string{body, "> " + strings.ReplaceAll(body, "\n", "\n> ")} {+ converted := LinkReferences(body, func(string, string) string { return destination })+ var originalHTML, convertedHTML bytes.Buffer+ md := goldmark.New(goldmark.WithExtensions(extension.Table))+ if err := md.Convert([]byte(body), &originalHTML); err != nil {+ t.Fatal(err)+ }+ if err := md.Convert([]byte(converted), &convertedHTML); err != nil {+ t.Fatal(err)+ }+ if want := strings.Replace(originalHTML.String(), target, destination, 1); convertedHTML.String() != want {+ t.Fatalf("rendered=%q, want=%q; source=%q", convertedHTML.String(), want, converted)+ }+ }+ })+ }+ }+}++func TestLinkReferences(t *testing.T) {+ const destination = "https://deployment.example/team/projects/real-id"+ for _, tc := range []struct{ name, body, want string }{+ {"inline", "[Project](mention://project/real-id)", "[Project](" + destination + ")"},+ {"angle and title", "[Project](<mention://project/real-id> \"Title\")", "[Project](<" + destination + "> \"Title\")"},+ {"nested label", "[A [B]](mention://project/real-id)", "[A [B]](" + destination + ")"},+ {"full reference", "[Project][p]\n\n[p]: mention://project/real-id", "[Project](" + destination + ")\n\n[p]: mention://project/real-id"},+ {"collapsed reference", "[Project][]\n\n[Project]: mention://project/real-id", "[Project](" + destination + ")\n\n[Project]: mention://project/real-id"},+ {"shortcut reference", "[Project]\n\n[Project]: mention://project/real-id", "[Project](" + destination + ")\n\n[Project]: mention://project/real-id"},+ {"unresolved", "[Unknown](mention://future/real-id)", ""},+ {"code", "`[Project](mention://project/real-id)`", ""},+ {"image", "", ""},+ {"external label", "[FEED-193](https://external.example)", ""},+ {"broadcast", "[@all](mention://all/all)", "@all"},+ {"broadcast escaped label", `[@All \[members\]](mention://all/all)`, `@All \[members\]`},+ {"broadcast reference", "[@all][everyone]\n\n[everyone]: mention://all/all", "@all\n\n[everyone]: mention://all/all"},+ {"broadcast code", "`[@all](mention://all/all)`", ""},+ {"invalid broadcast", "[@all](mention://all/not-all)", ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ want := tc.want+ if want == "" {+ want = tc.body+ }+ got := LinkReferences(tc.body, func(kind, id string) string {+ if kind == "all" && id == "all" {+ t.Fatal("broadcast reached resolver")+ }+ if kind == "project" && id == "real-id" {+ return destination+ }+ return ""+ })+ if got != want {+ t.Fatalf("rewrite=%q, want=%q", got, want)+ }+ })+ }+}++func TestReferenceWebLink(t *testing.T) {+ for kind, route := range map[string]string{"issue": "issues", "project": "projects", "agent": "agents", "member": "members", "squad": "squads"} {+ t.Run(kind, func(t *testing.T) {+ if got := ReferenceWebLink("https://deployment.example/", "team", ""+kind, "id"); got != "https://deployment.example/team/"+route+"/id" {+ t.Fatal(got)+ }+ })+ }+ if got := ReferenceWebLink("https://deployment.example", "team", "all", "all"); got != "" {+ t.Fatalf("invented broadcast route: %q", got)+ }+ if got := ReferenceWebLink("https://deployment.example", "team space", "project", "id/with space"); !strings.Contains(got, "team%20space/projects/id%2Fwith%20space") {+ t.Fatalf("unsafe route escaping: %q", got)+ }+}++func TestLinkReferencesMarkdownBoundaries(t *testing.T) {+ const (+ docs = "[docs](https://external.example)"+ issue = "[FEED-193](https://deployment.example/team/issues/FEED-193)"+ project = "https://deployment.example/team/projects/real-id"+ )+ for _, tc := range []struct{ name, body, want string }{+ {"after link", docs + "FEED-193", docs + issue},+ {"after link with prose", docs + "后续任务:FEED-193", docs + "后续任务:" + issue},+ {"after parenthesized destination", "[docs](https://external.example/a_(b))FEED-193", "[docs](https://external.example/a_(b))" + issue},+ {"after image", "FEED-193", "" + issue},+ {"after inline code", "`https://external.example`FEED-193", "`https://external.example`" + issue},+ {"after autolink", "<https://external.example>FEED-193", "<https://external.example>" + issue},+ {"after reference", "[docs][d]FEED-193\n\n[d]: https://external.example", "[docs][d]" + issue + "\n\n[d]: https://external.example"},+ {"successive links", docs + "FEED-193" + docs + "FEED-193", docs + issue + docs + issue},+ {"next raw URL", docs + "https://next.example/?q=中文:FEED-193", ""},+ {"next email URL", docs + "mailto:[email protected]?subject=中文:FEED-193", ""},+ {"internal reference", "[Project](mention://project/real-id)FEED-193", "[Project](" + project + ")" + issue},+ {"broadcast", "[@all](mention://all/all)FEED-193", "@all" + issue},+ {"list", "- " + docs + "FEED-193", "- " + docs + issue},+ {"blockquote", "> " + docs + "FEED-193", "> " + docs + issue},+ {"raw URL spanning emphasis", "https://external.example/?q=中文:(**FEED-193**)", ""},+ {"underscore emphasis", "_FEED-193_", "_" + issue + "_"},+ {"underscore strong emphasis", "__FEED-193__", "__" + issue + "__"},+ {"nested emphasis", "**_FEED-193_**", "**_" + issue + "_**"},+ {"emphasis with prose", "_任务 FEED-193_ 和 _FEED-193 任务_", "_任务 " + issue + "_ 和 _" + issue + " 任务_"},+ {"emphasis after link", docs + "_FEED-193_", docs + "_" + issue + "_"},+ {"underscore word tokens", "some_FEED-193 FEED-193_suffix _some_FEED-193_ _FEED-193_suffix_", ""},+ {"raw URL spanning underscore emphasis", "https://external.example/?q=中文:(_FEED-193_)", ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ want := tc.want+ if want == "" {+ want = tc.body+ }+ got := LinkReferences(tc.body, func(kind, id string) string {+ if kind == "issue" && id == "FEED-193" {+ return "https://deployment.example/team/issues/FEED-193"+ }+ if kind == "project" && id == "real-id" {+ return project+ }+ return ""+ })+ if got != want {+ t.Fatalf("rewrite=%q, want=%q", got, want)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.goindex 78b4fbd368..b2e1d61da6 100644--- a/server/internal/integrations/lark/outbound.go+++ b/server/internal/integrations/lark/outbound.go@@ -144,6 +144,7 @@ func (defaultRenderer) Render(in RenderInput) (CardRender, error) {// without a real Postgres connection.type PatcherQueries interface {mediaDeliveryQueries+ referenceLinkQueriesGetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)@@ -173,10 +174,11 @@ type CredentialsResolver interface {// PatcherConfig tunes the outbound Patcher. Defaults via withDefaults;// tests typically override Renderer / Now / Logger.type PatcherConfig struct {+ // AppURL is the deployment's web URL for verified outbound reference links.+ AppURL string// Renderer drives the error card template used on the EventTaskFailed// path. The success path (EventChatDone) bypasses the renderer- // entirely — it sends the raw assistant reply as a plain text IM- // message — so this only matters for the failure branch.+ // and sends a text message or Markdown card.Renderer RendererNow func() time.TimeLogger *slog.Logger@@ -543,6 +545,7 @@ func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentiahandedOff = p.deliverAttachmentsAsync(ctx, creds, binding, target, workspaceID, payload)return nil}+ content = p.linkReplyReferences(ctx, workspaceID, content)// A plain answer with bound images also needs an updatable card. The// bounded metadata probe does not read bytes or wait for an upload.markdown := containsMarkdown(content) || p.replyNeedsMediaCard(ctx, workspaceID, payload)diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.goindex 481d150fc6..e25e409744 100644--- a/server/internal/integrations/lark/outbound_test.go+++ b/server/internal/integrations/lark/outbound_test.go@@ -100,6 +100,9 @@ func (f *fakePatcherQueries) GetChatSession(ctx context.Context, id pgtype.UUID)func (f *fakePatcherQueries) GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error) {return f.agent, f.agentErr}+func (f *fakePatcherQueries) GetWorkspace(context.Context, pgtype.UUID) (db.Workspace, error) {+ return db.Workspace{}, pgx.ErrNoRows+}func (f *fakePatcherQueries) GetLarkInstallation(ctx context.Context, id pgtype.UUID) (Installation, error) {return f.installation, f.installationErr}diff --git a/server/internal/integrations/lark/reference_links.go b/server/internal/integrations/lark/reference_links.gonew file mode 100644index 0000000000..994fba1c9a--- /dev/null+++ b/server/internal/integrations/lark/reference_links.go@@ -0,0 +1,59 @@+package lark++import (+ "context"+ "fmt"+ "net/url"+ "strconv"+ "strings"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type referenceLinkQueries interface {+ GetWorkspace(context.Context, pgtype.UUID) (db.Workspace, error)+}++// linkReplyReferences formats the outbound copy using workspace metadata.+// Target existence is handled by the destination pages.+func (p *Patcher) linkReplyReferences(ctx context.Context, workspaceID pgtype.UUID, content string) string {+ appURL, err := url.Parse(p.cfg.AppURL)+ if err != nil || (appURL.Scheme != "http" && appURL.Scheme != "https") || appURL.Host == "" || !workspaceID.Valid {+ return content+ }+ var ws db.Workspace+ var workspaceErr error+ loaded := false+ return channel.LinkReferences(content, func(kind, reference string) string {+ switch kind {+ case "issue", "project", "agent", "squad", "member":+ default:+ return ""+ }+ prefix := ""+ if id, err := util.ParseUUID(reference); err == nil {+ reference = util.UUIDToString(id)+ } else {+ if kind != "issue" {+ return ""+ }+ var numberText string+ prefix, numberText, _ = strings.Cut(reference, "-")+ number, err := strconv.ParseInt(numberText, 10, 32)+ if prefix == "" || err != nil || number <= 0 || fmt.Sprintf("%s-%d", prefix, number) != reference {+ return ""+ }+ }+ if !loaded {+ loaded = true+ ws, workspaceErr = p.queries.GetWorkspace(ctx, workspaceID)+ }+ if workspaceErr != nil || ws.ID != workspaceID || ws.Slug == "" || (prefix != "" && prefix != ws.IssuePrefix) {+ return ""+ }+ return channel.ReferenceWebLink(p.cfg.AppURL, ws.Slug, kind, reference)+ })+}diff --git a/server/internal/integrations/lark/reference_links_test.go b/server/internal/integrations/lark/reference_links_test.gonew file mode 100644index 0000000000..ab64077a49--- /dev/null+++ b/server/internal/integrations/lark/reference_links_test.go@@ -0,0 +1,509 @@+package lark++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++const referenceUUID = "11111111-1111-4111-8111-111111111111"+const issueUUID = "44444444-4444-4444-8444-444444444444"++type referenceLinkQueryFake struct {+ *fakePatcherQueries+ workspace db.Workspace+ workspaceErr error+ workspaceReads int+ workspaceReadID pgtype.UUID+}++func (f *referenceLinkQueryFake) GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error) {+ f.workspaceReads+++ f.workspaceReadID = id+ if ctx.Err() != nil {+ return db.Workspace{}, ctx.Err()+ }+ return f.workspace, f.workspaceErr+}++func referenceLinkFixture(t *testing.T) (*Patcher, *referenceLinkQueryFake) {+ t.Helper()+ p, base, _ := newTestPatcher(t)+ q := &referenceLinkQueryFake{fakePatcherQueries: base, workspace: db.Workspace{ID: uuidFromString(t, "ffffffff-ffff-ffff-ffff-ffffffffffff"), Slug: "feedback", IssuePrefix: "FEED"}}+ p.queries = q+ p.cfg.AppURL = "https://deployment.example/"+ return p, q+}++func TestLinkReplyReferencesEntities(t *testing.T) {+ for kind, route := range map[string]string{"issue": "issues", "project": "projects", "member": "members", "agent": "agents", "squad": "squads"} {+ t.Run(kind, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ q.workspace.IssuePrefix = "" // UUID references do not need an issue prefix.+ id := referenceUUID+ body := "[@Label](mention://" + kind + "/" + id + ")"+ want := "[@Label](https://deployment.example/feedback/" + route + "/" + id + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body+" "+body); got != want+" "+want {+ t.Fatalf("reply=%q, want=%q", got, want+" "+want)+ }+ if q.workspaceReads != 1 || q.workspaceReadID != q.workspace.ID {+ t.Fatalf("workspace reads=%d, id=%v", q.workspaceReads, q.workspaceReadID)+ }+ })+ }+}++func TestLinkReplyReferencesMarkdownForms(t *testing.T) {+ for kind, route := range map[string]string{"issue": "issues", "project": "projects", "member": "members", "agent": "agents", "squad": "squads"} {+ for _, tc := range []struct {+ name, body, want string+ protected bool+ }{+ {"formatted label", `[**Label [inner]**](%s)`, `[**Label [inner]**](%s)`, false},+ {"escaped label and title", `[Label \[inner\]](<%s> "Title")`, `[Label \[inner\]](<%s> "Title")`, false},+ {"full reference", "[Label][ref]\n\n[ref]: %s", "[Label](%s)\n\n[ref]: %s", false},+ {"collapsed reference", "[Label][]\n\n[Label]: %s", "[Label](%s)\n\n[Label]: %s", false},+ {"shortcut reference", "[Label]\n\n[Label]: %s", "[Label](%s)\n\n[Label]: %s", false},+ {"multiline quote", "> [Label](\n> %s\n> )", "> [Label](\n> %s\n> )", false},+ {"quoted angle and title", "> [Label](\n> <%s> \"Title\"\n> )", "> [Label](\n> <%s> \"Title\"\n> )", false},+ {"nested quoted list", "> - [Label](\n> %s\n> )", "> - [Label](\n> %s\n> )", false},+ {"full reference with title", "[Label][ref]\n\n[ref]: %s \"Title\"", "[Label](%s \"Title\")\n\n[ref]: %s \"Title\"", false},+ {"collapsed reference with title", "[Label][]\n\n[Label]: %s \"Title\"", "[Label](%s \"Title\")\n\n[Label]: %s \"Title\"", false},+ {"shortcut reference with title", "[Label]\n\n[Label]: %s \"Title\"", "[Label](%s \"Title\")\n\n[Label]: %s \"Title\"", false},+ {"code", "`[Label](%s)`", "", true},+ {"image", "", "", true},+ } {+ t.Run(kind+"/"+tc.name, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ id, resolved := referenceUUID, referenceUUID+ if kind == "issue" {+ id, resolved = issueUUID, issueUUID+ }+ target := "mention://" + kind + "/" + id+ body := fmt.Sprintf(tc.body, target)+ want := body+ if !tc.protected {+ link := "https://deployment.example/feedback/" + route + "/" + resolved+ if strings.Contains(tc.body, "\n\n") {+ want = fmt.Sprintf(tc.want, link, target)+ } else {+ want = fmt.Sprintf(tc.want, link)+ }+ }+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply=%q, want=%q", got, want)+ }+ if tc.protected && q.workspaceReads != 0 {+ t.Fatal("protected Markdown caused a lookup")+ }+ })+ }+ }+}++func TestLinkReplyReferencesEncodedTargets(t *testing.T) {+ for kind, route := range map[string]string{"issue": "issues", "project": "projects", "member": "members", "agent": "agents", "squad": "squads"} {+ t.Run(kind, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ id, resolved := referenceUUID, referenceUUID+ if kind == "issue" {+ id, resolved = issueUUID, issueUUID+ }+ var body, want []string+ link := "https://deployment.example/feedback/" + route + "/" + resolved+ for _, scheme := range []string{`mention\://`, `mention:\/\/`, "mention://", "mention://", "mention://"} {+ body = append(body, "[@Label]("+scheme+kind+"/"+id+")")+ want = append(want, "[@Label]("+link+")")+ }+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, strings.Join(body, " ")); got != strings.Join(want, " ") {+ t.Fatalf("reply=%q, want=%q", got, strings.Join(want, " "))+ }+ if q.workspaceReads != 1 {+ t.Fatalf("encoded targets queried workspace %d times", q.workspaceReads)+ }+ })+ }+}++func TestLinkReplyReferencesPreservesUnresolved(t *testing.T) {+ for _, kind := range []string{"issue", "project", "member", "agent", "squad"} {+ for _, failure := range []string{"malformed UUID", "workspace error", "missing slug", "wrong workspace metadata"} {+ t.Run(kind+"/"+failure, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ workspaceID := q.workspace.ID+ id := referenceUUID+ switch failure {+ case "malformed UUID":+ id = "not-an-id"+ case "workspace error":+ q.workspaceErr = errors.New("unavailable")+ case "missing slug":+ q.workspace.Slug = ""+ case "wrong workspace metadata":+ q.workspace.ID = uuidFromString(t, "55555555-5555-4555-8555-555555555555")+ }+ body := "[@Label](mention://" + kind + "/" + id + ")"+ if got := p.linkReplyReferences(context.Background(), workspaceID, body); got != body {+ t.Fatalf("unresolved reference changed: %q", got)+ }+ })+ }+ }+}++func TestLinkReplyReferencesLoadsWorkspaceOnceOnFailure(t *testing.T) {+ p, q := referenceLinkFixture(t)+ q.workspaceErr = errors.New("unavailable")+ body := "FEED-193 [Project](mention://project/" + referenceUUID + ") [Member](mention://member/" + referenceUUID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, strings.Repeat(body, 30)); got != strings.Repeat(body, 30) {+ t.Fatalf("failed workspace lookup changed reply: %q", got)+ }+ if q.workspaceReads != 1 {+ t.Fatalf("failed workspace lookup retried %d times", q.workspaceReads)+ }+}++func TestLinkReplyReferencesBroadcastIsDisplayOnly(t *testing.T) {+ p, q := referenceLinkFixture(t)+ q.workspaceErr = errors.New("no lookup needed")+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, "FYI [@all](mention://all/all)"); got != "FYI @all" || q.workspaceReads != 0 {+ t.Fatalf("broadcast conversion=%q, reads=%d", got, q.workspaceReads)+ }+}++func TestPatcherLinksAllReferencesForFeishu(t *testing.T) {+ p, base, api := groupPatcherWithSender(t, "ou_sender")+ _, q := referenceLinkFixture(t)+ q.fakePatcherQueries = base+ base.installation.WorkspaceID = q.workspace.ID+ p.queries = q+ p.cfg.AppURL = "https://deployment.example"+ id := referenceUUID+ body := "[Issue](mention://issue/" + issueUUID + ")"+ want := "[Issue](https://deployment.example/feedback/issues/" + issueUUID + ")"+ for _, entry := range []struct{ kind, route string }{{"project", "projects"}, {"member", "members"}, {"agent", "agents"}, {"squad", "squads"}} {+ body += " [@Label](mention://" + entry.kind + "/" + id + ")"+ want += " [@Label](https://deployment.example/feedback/" + entry.route + "/" + id + ")"+ }+ body += " [@all](mention://all/all)"+ want += " @all"+ p.handleEvent(events.Event{Type: protocol.EventChatDone, TaskID: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee", ChatSessionID: uuidString(base.binding.ChatSessionID), Payload: protocol.ChatDonePayload{Content: body}})+ if len(api.mdCardSent) != 1 || len(api.textSent) != 0 {+ t.Fatalf("expected one reference card: cards=%d, texts=%d", len(api.mdCardSent), len(api.textSent))+ }+ if got := api.mdCardSent[0]; got.Markdown != prependMarkdownMention("ou_sender", want) || got.ReplyTarget != threadReplyTarget(base.binding) {+ t.Fatalf("outbound reference conversion or routing changed: %+v", got)+ }+}++func TestLinkReplyIssues(t *testing.T) {+ const (+ internal = "mention://issue/44444444-4444-4444-8444-444444444444"+ uuidWeb = "https://deployment.example/feedback/issues/44444444-4444-4444-8444-444444444444"+ web = "https://deployment.example/feedback/issues/FEED-193"+ )+ for _, tc := range []struct{ name, body, want string }{+ {"UUID link", "已记录:[FEED-193](" + internal + ")。", "已记录:[FEED-193](" + uuidWeb + ")。"},+ {"identifier link", "[反馈](mention://issue/FEED-193)", "[反馈](" + web + ")"},+ {"nested label", "[反馈 [详情]](" + internal + ")", "[反馈 [详情]](" + uuidWeb + ")"},+ {"escaped label", `[反馈 \[详情\]](` + internal + `)`, `[反馈 \[详情\]](` + uuidWeb + `)`},+ {"code in label", "[详情 `]` FEED-193](" + internal + ")", "[详情 `]` FEED-193](" + uuidWeb + ")"},+ {"title and angle destination", "[反馈](<" + internal + "> \"详情\")", "[反馈](<" + uuidWeb + "> \"详情\")"},+ {"internal full reference", "[反馈][task]\n\n[task]: " + internal, "[反馈](" + uuidWeb + ")\n\n[task]: " + internal},+ {"internal collapsed reference", "[FEED-193][]\n\n[FEED-193]: " + internal, "[FEED-193](" + uuidWeb + ")\n\n[FEED-193]: " + internal},+ {"internal shortcut reference", "[FEED-193]\n\n[FEED-193]: " + internal, "[FEED-193](" + uuidWeb + ")\n\n[FEED-193]: " + internal},+ {"bare and punctuation", "已记录:FEED-193。 FEED-193.", "已记录:[FEED-193](" + web + ")。 [FEED-193](" + web + ")."},+ {"emphasis", "**FEED-193**", "**[FEED-193](" + web + ")**"},+ {"inline code", "`FEED-193` `[反馈](" + internal + ")`", ""},+ {"fenced code", "```md\nFEED-193\n[反馈](" + internal + ")\n```", ""},+ {"indented code", " FEED-193\n [反馈](" + internal + ")\n", ""},+ {"existing link", "[FEED-193](https://elsewhere.example)", ""},+ {"existing image", "", ""},+ {"reference link", "[FEED-193][docs]\n\n[docs]: https://elsewhere.example", ""},+ {"raw URL query", "https://elsewhere.example?q=FEED-193#FEED-193", ""},+ {"URL parentheses", "https://elsewhere.example?q=(FEED-193)", ""},+ {"URL angle brackets", "<https://elsewhere.example/FEED-193>", ""},+ {"email", "[email protected]", ""},+ {"relative path", "/path?q=FEED-193", ""},+ {"file and path tokens", "FEED-193.ts path/FEED-193 FEED-193/file", ""},+ {"escaped example", `\[FEED-193](` + internal + `)`, ""},+ {"other prefix", "OTHER-193", ""},+ {"embedded identifier", "xFEED-193 FEED-193x FEED-193-2", ""},+ {"unknown issue", "FEED-194", "[FEED-194](https://deployment.example/feedback/issues/FEED-194)"},+ {"noncanonical number", "FEED-0193 FEED-0 FEED-99999999999999999999", ""},+ {"plain reply", "已记录。", ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ want := tc.want+ if want == "" {+ want = tc.body+ }+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, tc.body); got != want {+ t.Fatalf("reply = %q, want %q", got, want)+ }+ })+ }+}++func TestLinkReplyIssuesAcceptsNumericPrefixes(t *testing.T) {+ for _, prefix := range []string{"1", "123", "1A", "A1", "1234567890"} {+ t.Run(prefix, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ q.workspace.IssuePrefix = prefix+ identifier := prefix + "-193"+ link := "https://deployment.example/feedback/issues/" + identifier+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, identifier); got != "["+identifier+"]("+link+")" {+ t.Fatalf("bare identifier did not link: %q", got)+ }+ q.workspaceReads = 0+ body := identifier + " [编号](mention://issue/" + identifier + ") [UUID](mention://issue/44444444-4444-4444-8444-444444444444)"+ want := "[" + identifier + "](" + link + ") [编号](" + link + ") [UUID](https://deployment.example/feedback/issues/" + issueUUID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply = %q, want %q", got, want)+ }+ if q.workspaceReads != 1 || q.workspaceReadID != q.workspace.ID {+ t.Fatalf("workspace reads=%d, id=%v", q.workspaceReads, q.workspaceReadID)+ }+ })+ }+}++func TestLinkReplyIssuesPreservesURLs(t *testing.T) {+ for _, rawURL := range []string{+ "https://example.test/path:FEED-193",+ "https://example.test/?q=中文,FEED-193",+ "https://example.test/#上下文;FEED-193",+ "https://example.test/?q=中文。FEED-193",+ "https://example.test/?q=中文:(**FEED-193**)",+ "https://example.test/?q=中文:FEED-193&other=FEED-193",+ "HTTP://localhost/?q=中文:FEED-193",+ "ftp://example.test/中文:FEED-193",+ "www.example.test/?q=中文:FEED-193",+ "//example.test/?q=中文:FEED-193",+ "/path?q=中文:FEED-193",+ `C:\path\中文:FEED-193`,+ "mailto:[email protected]?subject=中文:FEED-193",+ "[email protected]",+ "[email protected]",+ "https://example.test/?q=" + strings.Repeat("中文;FEED-193", 30),+ } {+ t.Run(rawURL, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, rawURL); got != rawURL || q.workspaceReads != 0 {+ t.Fatalf("URL-only reply changed or queried workspace: reply=%q, reads=%d", got, q.workspaceReads)+ }+ body := rawURL + "\u00a0正文:FEED-193。"+ want := rawURL + "\u00a0正文:[FEED-193](https://deployment.example/feedback/issues/FEED-193)。"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply = %q, want %q", got, want)+ }+ if q.workspaceReads != 1 {+ t.Fatalf("workspace reads=%d", q.workspaceReads)+ }+ })+ }+}++func TestLinkReplyIssuesPreservesReplyWhenLookupUnavailable(t *testing.T) {+ for _, tc := range []struct {+ name string+ setup func(*Patcher, *referenceLinkQueryFake)+ }{+ {"workspace error", func(_ *Patcher, q *referenceLinkQueryFake) { q.workspaceErr = errors.New("unavailable") }},+ {"missing slug", func(_ *Patcher, q *referenceLinkQueryFake) { q.workspace.Slug = "" }},+ {"missing app URL", func(p *Patcher, _ *referenceLinkQueryFake) { p.cfg.AppURL = "" }},+ {"non HTTP app URL", func(p *Patcher, _ *referenceLinkQueryFake) { p.cfg.AppURL = "mention://app" }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ tc.setup(p, q)+ body := "FEED-193 [Issue](mention://issue/" + issueUUID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != body {+ t.Fatalf("reply changed without workspace metadata: %q", got)+ }+ })+ }+}++func TestLinkReplyReferencesWorkspaceReadIsPerReply(t *testing.T) {+ p, q := referenceLinkFixture(t)+ body := "[Project](mention://project/" + referenceUUID + ")"+ want := "[Project](https://deployment.example/feedback/projects/" + referenceUUID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("first reply=%q", got)+ }+ q.workspace.Slug = "renamed"+ want = "[Project](https://deployment.example/renamed/projects/" + referenceUUID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("second reply=%q", got)+ }+ if q.workspaceReads != 2 || q.workspaceReadID != q.workspace.ID {+ t.Fatalf("workspace reads=%d", q.workspaceReads)+ }+}++func TestPatcherLinksIssueReferencesForFeishu(t *testing.T) {+ for _, tc := range []struct{ body, target string }{+ {"已记录:[DEMO-193](mention://issue/" + issueUUID + ")。", issueUUID},+ {"已记录:DEMO-193。", "DEMO-193"},+ } {+ t.Run(tc.body, func(t *testing.T) {+ p, base, api := groupPatcherWithSender(t, "ou_sender")+ wsID := uuidFromString(t, "ffffffff-ffff-ffff-ffff-ffffffffffff")+ base.installation.WorkspaceID = wsID+ q := &referenceLinkQueryFake{fakePatcherQueries: base, workspace: db.Workspace{ID: wsID, Slug: "demo", IssuePrefix: "DEMO"}}+ p.queries = q+ p.cfg.AppURL = "https://multica.example"+ p.handleEvent(events.Event{Type: protocol.EventChatDone, TaskID: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee", ChatSessionID: uuidString(base.binding.ChatSessionID), Payload: protocol.ChatDonePayload{Content: tc.body}})+ if len(api.mdCardSent) != 1 || len(api.textSent) != 0 {+ t.Fatalf("cards=%d, texts=%d", len(api.mdCardSent), len(api.textSent))+ }+ got := api.mdCardSent[0]+ want := prependMarkdownMention("ou_sender", "已记录:[DEMO-193](https://multica.example/demo/issues/"+tc.target+")。")+ if got.Markdown != want || got.ReplyTarget != threadReplyTarget(base.binding) {+ t.Fatalf("outbound=%+v, want=%q", got, want)+ }+ if q.workspaceReads != 1 {+ t.Fatalf("workspace reads=%d", q.workspaceReads)+ }+ })+ }+}++func TestLinkReplyReferencesNonexistentTargets(t *testing.T) {+ const id = "99999999-9999-4999-8999-999999999999"+ for kind, route := range map[string]string{"issue": "issues", "project": "projects", "member": "members", "agent": "agents", "squad": "squads"} {+ t.Run(kind, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ body := "[Missing](mention://" + kind + "/" + id + ")"+ want := "[Missing](https://deployment.example/feedback/" + route + "/" + id + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply=%q, want=%q", got, want)+ }+ if q.workspaceReads != 1 {+ t.Fatalf("workspace reads=%d", q.workspaceReads)+ }+ })+ }+ t.Run("matching issue identifier", func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ body := "FEED-194 [Missing](mention://issue/FEED-194)"+ link := "https://deployment.example/feedback/issues/FEED-194"+ want := "[FEED-194](" + link + ") [Missing](" + link + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply=%q, want=%q", got, want)+ }+ if q.workspaceReads != 1 {+ t.Fatalf("workspace reads=%d", q.workspaceReads)+ }+ })+}++func TestLinkReplyReferencesManyTargetsUseOneWorkspaceRead(t *testing.T) {+ for _, count := range []int{1, 32, 80} {+ t.Run(fmt.Sprint(count), func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ var body, want strings.Builder+ for i := 1; i <= count; i++ {+ id := fmt.Sprintf("%08x-9999-4999-8999-999999999999", i)+ for _, entry := range []struct{ kind, route string }{{"issue", "issues"}, {"project", "projects"}, {"member", "members"}, {"agent", "agents"}, {"squad", "squads"}} {+ fmt.Fprintf(&body, "[Label](mention://%s/%s) ", entry.kind, id)+ fmt.Fprintf(&want, "[Label](https://deployment.example/feedback/%s/%s) ", entry.route, id)+ }+ fmt.Fprintf(&body, "FEED-%d ", i)+ fmt.Fprintf(&want, "[FEED-%d](https://deployment.example/feedback/issues/FEED-%d) ", i, i)+ }+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body.String()); got != want.String() {+ t.Fatal("distinct nonexistent targets were not all linked")+ }+ if q.workspaceReads != 1 {+ t.Fatalf("workspace reads=%d for %d targets", q.workspaceReads, count*6)+ }+ })+ }+}++func TestLinkReplyReferencesNoCandidatesAvoidWorkspaceRead(t *testing.T) {+ for _, body := range []string{+ "Plain reply.",+ "`FEED-193 [Project](mention://project/11111111-1111-4111-8111-111111111111)`",+ "```md\nFEED-193\n[Project](mention://project/11111111-1111-4111-8111-111111111111)\n```",+ "",+ "[FEED-193](https://docs.example/FEED-193)",+ "https://docs.example/?q=FEED-193",+ "[Label](mention://unknown/11111111-1111-4111-8111-111111111111)",+ "[Label](mention://project/not-a-uuid)",+ "[Label](mention://issue/not-a-uuid)",+ "FEED-0 FEED-0193 FEED-999999999999999999999",+ } {+ t.Run(body, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != body {+ t.Fatalf("reply changed: %q", got)+ }+ if q.workspaceReads != 0 {+ t.Fatalf("nonconvertible content queried workspace %d times", q.workspaceReads)+ }+ })+ }+}++func TestLinkReplyReferencesUnrelatedPrefixes(t *testing.T) {+ for _, tc := range []struct{ prefix, body, want string }{+ {"FEED", "UTF-8 SHA-256 OTHER-193", "UTF-8 SHA-256 OTHER-193"},+ {"FEED", "UTF-8 FEED-194 SHA-256", "UTF-8 [FEED-194](https://deployment.example/feedback/issues/FEED-194) SHA-256"},+ {"UTF", "UTF-8 SHA-256", "[UTF-8](https://deployment.example/feedback/issues/UTF-8) SHA-256"},+ } {+ t.Run(tc.prefix+"/"+tc.body, func(t *testing.T) {+ p, q := referenceLinkFixture(t)+ q.workspace.IssuePrefix = tc.prefix+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, tc.body); got != tc.want {+ t.Fatalf("reply=%q, want=%q", got, tc.want)+ }+ if q.workspaceReads != 1 || q.workspaceReadID != q.workspace.ID {+ t.Fatalf("workspace reads=%d, id=%v", q.workspaceReads, q.workspaceReadID)+ }+ })+ }+}++func TestLinkReplyReferencesUUIDsWithoutIssuePrefix(t *testing.T) {+ p, q := referenceLinkFixture(t)+ q.workspace.IssuePrefix = ""+ body := "FEED-193 [Issue](mention://issue/" + issueUUID + ")"+ want := "FEED-193 [Issue](https://deployment.example/feedback/issues/" + issueUUID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply=%q, want=%q", got, want)+ }+ if q.workspaceReads != 1 {+ t.Fatalf("workspace reads=%d", q.workspaceReads)+ }+}++func TestLinkReplyReferencesMemberUsesMentionUserID(t *testing.T) {+ p, q := referenceLinkFixture(t)+ const userID = "22222222-2222-4222-8222-222222222222"+ body := "[@User](mention://member/" + userID + ")"+ want := "[@User](https://deployment.example/feedback/members/" + userID + ")"+ if got := p.linkReplyReferences(context.Background(), q.workspace.ID, body); got != want {+ t.Fatalf("reply=%q, want=%q", got, want)+ }+}++func TestLinkReplyReferencesCanceledContext(t *testing.T) {+ p, q := referenceLinkFixture(t)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ body := "FEED-193 [Project](mention://project/" + referenceUUID + ")"+ if got := p.linkReplyReferences(ctx, q.workspace.ID, body); got != body || q.workspaceReads != 1 {+ t.Fatalf("reply=%q, reads=%d", got, q.workspaceReads)+ }+}diff --git a/server/internal/integrations/wecom/relay_publish_state_test.go b/server/internal/integrations/wecom/relay_publish_state_test.goindex 22b7fa98b2..eb37425738 100644--- a/server/internal/integrations/wecom/relay_publish_state_test.go+++ b/server/internal/integrations/wecom/relay_publish_state_test.go@@ -36,8 +36,10 @@ func TestRelayPublish_InboxWithNoHolderIsNoHolder(t *testing.T) {t.Parallel()relay, dedupe := &fanoutRelay{}, newSharedDedupe()// A handler that owns no socket at all.+ // Keep the normal acceptance budget: this tests the verdict and fence,+ // not scheduler latency on a loaded race runner.router := inboxPublishRouter(t, relay, dedupe,- RelayConfig{AcceptanceWindow: 40 * time.Millisecond},+ RelayConfig{},&Outbound{senders: newSendersRegistry(), logger: slog.Default()})instID := util.UUIDToString(mustTestUUID(t))