Skip to content

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

Go

MUL-9028: feat(cli): rewrite body links to same-call attachments (#10362)

Jiayuan Zhangac2ac4013ddf
diff --git a/server/cmd/multica/attachment_link_rewrite.go b/server/cmd/multica/attachment_link_rewrite.go
new file mode 100644
index 0000000000..305de02277
--- /dev/null
+++ b/server/cmd/multica/attachment_link_rewrite.go
@@ -0,0 +1,325 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net/url"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/yuin/goldmark"
+ "github.com/yuin/goldmark/ast"
+ "github.com/yuin/goldmark/text"
+ "github.com/yuin/goldmark/util"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// An agent places a screenshot under the paragraph it illustrates by writing
+// `![](./a.png)` in the body and passing `--attachment ./a.png` in the same
+// call (MUL-9028). That relative path means nothing to any reader, so before
+// the body is published every link/image destination naming one of this
+// call's attachments is replaced with that attachment's durable URL — the
+// first published revision is already the correct one.
+//
+// The rules mirror the local-path lint (local_path_link_lint.go):
+//
+// - Only real inline Link / Image destinations are rewritten. A path quoted
+// in a code span or fenced block is not a destination and stays verbatim.
+// - Only targets that resolve to exactly one attachment are rewritten. A
+// target that names no attachment is left alone for the lint to judge.
+
+// attachmentLinkRewrite is one destination that was swapped for an uploaded
+// attachment's URL, reported on stderr so the agent can check the result.
+type attachmentLinkRewrite struct {
+ Target string
+ URL string
+}
+
+// attachmentLinkMatcher resolves a markdown destination to the --attachment
+// it names.
+type attachmentLinkMatcher struct {
+ byPath map[string]int
+ byName map[string][]int
+}
+
+func newAttachmentLinkMatcher(paths []string) *attachmentLinkMatcher {
+ m := &attachmentLinkMatcher{byPath: map[string]int{}, byName: map[string][]int{}}
+ for i, p := range paths {
+ if strings.TrimSpace(p) == "" || isHTTPURL(p) {
+ continue
+ }
+ keys := attachmentPathKeys(p)
+ if len(keys) == 0 {
+ continue
+ }
+ if _, dup := m.byPath[keys[0]]; dup {
+ // The same file attached twice; the first upload wins and the
+ // duplicate must not make its bare name ambiguous.
+ continue
+ }
+ for _, key := range keys {
+ m.byPath[key] = i
+ }
+ base := filepath.Base(p)
+ m.byName[base] = append(m.byName[base], i)
+ }
+ return m
+}
+
+// attachmentPathKeys returns the absolute path of p plus, when it differs, its
+// symlink-resolved form, so `/var/...` and `/private/var/...` (macOS) match.
+func attachmentPathKeys(p string) []string {
+ abs, err := filepath.Abs(p)
+ if err != nil {
+ return nil
+ }
+ keys := []string{abs}
+ if real, err := filepath.EvalSymlinks(abs); err == nil && real != abs {
+ keys = append(keys, real)
+ }
+ return keys
+}
+
+// match returns the index of the attachment target names. A target matches
+// when it resolves to the same file as an attachment path, or — for a bare
+// file name such as `a.png` or `./a.png` — when exactly one attachment has
+// that name.
+func (m *attachmentLinkMatcher) match(target string) (int, bool) {
+ raw := strings.TrimSpace(target)
+ if raw == "" {
+ return -1, false
+ }
+ candidates := []string{raw}
+ if unescaped := string(util.UnescapePunctuations([]byte(raw))); unescaped != raw {
+ candidates = append(candidates, unescaped)
+ }
+ for _, c := range append([]string(nil), candidates...) {
+ if decoded, err := url.PathUnescape(c); err == nil && decoded != c {
+ candidates = append(candidates, decoded)
+ }
+ }
+ for _, c := range candidates {
+ if i, ok := m.matchPath(c); ok {
+ return i, true
+ }
+ }
+ return -1, false
+}
+
+func (m *attachmentLinkMatcher) matchPath(target string) (int, bool) {
+ // A Windows drive path parses as a URL with scheme "c", so test for an
+ // absolute path before sniffing schemes — same order as the lint.
+ if !filepath.IsAbs(target) {
+ parsed, err := url.Parse(target)
+ if err == nil && strings.EqualFold(parsed.Scheme, "file") {
+ target = parsed.Path
+ if len(target) > 2 && target[0] == '/' && target[2] == ':' {
+ target = target[1:] // file:///C:/x → C:/x
+ }
+ } else if err == nil && parsed.Scheme != "" {
+ return -1, false
+ }
+ }
+ local := filepath.FromSlash(target)
+ for _, key := range attachmentPathKeys(local) {
+ if i, ok := m.byPath[key]; ok {
+ return i, true
+ }
+ }
+ cleaned := filepath.Clean(local)
+ if !filepath.IsAbs(cleaned) && !strings.ContainsRune(cleaned, filepath.Separator) {
+ if idx := m.byName[cleaned]; len(idx) == 1 {
+ return idx[0], true
+ }
+ }
+ return -1, false
+}
+
+// rewriteAttachmentLinks replaces every inline link/image destination in body
+// that names one of paths with the URL at the same index in urls. Bodies with
+// nothing to rewrite are returned unchanged byte for byte.
+func rewriteAttachmentLinks(body string, paths, urls []string) (string, []attachmentLinkRewrite) {
+ if body == "" || len(paths) == 0 {
+ return body, nil
+ }
+ matcher := newAttachmentLinkMatcher(paths)
+ if len(matcher.byPath) == 0 {
+ return body, nil
+ }
+
+ source := []byte(body)
+ doc := goldmark.New().Parser().Parse(text.NewReader(source))
+
+ var codeSpans []text.Segment
+ _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
+ if entering && n.Kind() == ast.KindCodeSpan {
+ for c := n.FirstChild(); c != nil; c = c.NextSibling() {
+ if t, ok := c.(*ast.Text); ok {
+ codeSpans = append(codeSpans, t.Segment)
+ }
+ }
+ }
+ return ast.WalkContinue, nil
+ })
+
+ type edit struct {
+ start, stop int
+ url string
+ }
+ var edits []edit
+ claimed := map[int]bool{}
+ var rewrites []attachmentLinkRewrite
+ reported := map[string]bool{}
+ // Post-order: an image nested in a link label claims its own destination
+ // before the enclosing link searches past it for the outer one.
+ _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
+ if entering {
+ return ast.WalkContinue, nil
+ }
+ var link *ast.Link
+ switch node := n.(type) {
+ case *ast.Link:
+ link = node
+ case *ast.Image:
+ link = &ast.Link{}
+ link.Destination, link.Reference = node.Destination, node.Reference
+ default:
+ return ast.WalkContinue, nil
+ }
+ // Reference-style links keep their destination in a definition
+ // elsewhere in the body; they are left for the lint.
+ if link.Reference != nil || len(link.Destination) == 0 || n.Pos() < 0 {
+ return ast.WalkContinue, nil
+ }
+ target := string(link.Destination)
+ idx, ok := matcher.match(target)
+ if !ok || idx >= len(urls) || urls[idx] == "" {
+ return ast.WalkContinue, nil
+ }
+ start := locateLinkDestination(source, n.Pos(), link.Destination, claimed, codeSpans)
+ if start < 0 {
+ return ast.WalkContinue, nil
+ }
+ claimed[start] = true
+ edits = append(edits, edit{start: start, stop: start + len(link.Destination), url: urls[idx]})
+ if !reported[target] {
+ reported[target] = true
+ rewrites = append(rewrites, attachmentLinkRewrite{Target: target, URL: urls[idx]})
+ }
+ return ast.WalkContinue, nil
+ })
+ if len(edits) == 0 {
+ return body, nil
+ }
+
+ sort.Slice(edits, func(i, j int) bool { return edits[i].start < edits[j].start })
+ var b strings.Builder
+ last := 0
+ for _, e := range edits {
+ b.Write(source[last:e.start])
+ b.WriteString(e.url)
+ last = e.stop
+ }
+ b.Write(source[last:])
+ return b.String(), rewrites
+}
+
+// locateLinkDestination returns the byte offset of a link's destination,
+// searching from the link's start for the first unclaimed occurrence that is a
+// whole destination directly after the `](` closing a label. The parser does
+// not record the destination's own position, and the same text may also
+// appear in the label or as a prefix of a nested link's destination.
+func locateLinkDestination(source []byte, from int, dest []byte, claimed map[int]bool, codeSpans []text.Segment) int {
+ for from < len(source) {
+ i := bytes.Index(source[from:], dest)
+ if i < 0 {
+ return -1
+ }
+ start := from + i
+ if !claimed[start] && !insideSegments(start, codeSpans) && isWholeLinkDestination(source, start, start+len(dest)) {
+ return start
+ }
+ from = start + 1
+ }
+ return -1
+}
+
+// isWholeLinkDestination reports whether source[start:stop] is an entire
+// inline link destination: opened by `](` (optionally `<`), and closed by the
+// matching `>` or by the whitespace / `)` that ends a bare destination.
+func isWholeLinkDestination(source []byte, start, stop int) bool {
+ j := start - 1
+ angle := j >= 0 && source[j] == '<'
+ if angle {
+ j--
+ if stop >= len(source) || source[stop] != '>' {
+ return false
+ }
+ } else if stop < len(source) && !isLinkSpace(source[stop]) && source[stop] != ')' {
+ return false
+ }
+ for j >= 0 && isLinkSpace(source[j]) {
+ j--
+ }
+ return j >= 1 && source[j] == '(' && source[j-1] == ']'
+}
+
+func isLinkSpace(c byte) bool {
+ return c == ' ' || c == '\t' || c == '\n' || c == '\r'
+}
+
+func insideSegments(pos int, segments []text.Segment) bool {
+ for _, s := range segments {
+ if pos >= s.Start && pos < s.Stop {
+ return true
+ }
+ }
+ return false
+}
+
+// previewAttachmentLinks rewrites body against placeholder URLs, before
+// anything is uploaded, so the local-path lint judges the body that will
+// actually be published: a link to a file attached in the same call is not a
+// dead local link, and rejecting it after the upload would orphan the file.
+func previewAttachmentLinks(body string, paths []string) string {
+ placeholders := make([]string, len(paths))
+ for i := range paths {
+ placeholders[i] = fmt.Sprintf("https://attachment.invalid/%d", i)
+ }
+ rewritten, _ := rewriteAttachmentLinks(body, paths, placeholders)
+ return rewritten
+}
+
+// applyAttachmentLinks rewrites body against the uploaded attachments (aligned
+// with pending) and reports each rewritten target on w.
+func applyAttachmentLinks(w io.Writer, body, field string, pending []pendingAttachment, uploaded []cli.AttachmentResponse) string {
+ paths := make([]string, len(pending))
+ urls := make([]string, len(pending))
+ for i, att := range pending {
+ paths[i] = att.path
+ if i < len(uploaded) {
+ urls[i] = attachmentBodyURL(uploaded[i])
+ }
+ }
+ rewritten, rewrites := rewriteAttachmentLinks(body, paths, urls)
+ for _, r := range rewrites {
+ fmt.Fprintf(w, "Linked %s in the %s to the uploaded attachment %s\n", r.Target, field, r.URL)
+ }
+ return rewritten
+}
+
+// attachmentBodyURL is the URL a body embeds for an uploaded attachment: the
+// server's durable markdown_url, or the per-attachment download path an older
+// server would have built it from.
+func attachmentBodyURL(att cli.AttachmentResponse) string {
+ if att.MarkdownURL != "" {
+ return att.MarkdownURL
+ }
+ if att.ID != "" {
+ return "/api/attachments/" + att.ID + "/download"
+ }
+ return ""
+}
diff --git a/server/cmd/multica/attachment_link_rewrite_test.go b/server/cmd/multica/attachment_link_rewrite_test.go
new file mode 100644
index 0000000000..f5e1335e11
--- /dev/null
+++ b/server/cmd/multica/attachment_link_rewrite_test.go
@@ -0,0 +1,305 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+const rewriteURL = "https://cdn.example/a"
+
+func TestRewriteAttachmentLinks(t *testing.T) {
+ workdir := withWorkdir(t)
+ for _, name := range []string{"a.png", "b.png", "my shot.png", "shots/a.png"} {
+ if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(name, []byte("png"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ for _, tc := range []struct {
+ name string
+ paths []string
+ body string
+ want string
+ }{
+ {
+ name: "dot-relative image",
+ paths: []string{"./a.png"},
+ body: "Option A\n\n![Option A](./a.png)\n\nOption B",
+ want: "Option A\n\n![Option A](" + rewriteURL + ")\n\nOption B",
+ },
+ {
+ name: "bare name matches a dot-relative attachment",
+ paths: []string{"./a.png"},
+ body: "![](a.png)",
+ want: "![](" + rewriteURL + ")",
+ },
+ {
+ name: "bare name matches an attachment in a subdirectory",
+ paths: []string{"shots/a.png"},
+ body: "![](./a.png)",
+ want: "![](" + rewriteURL + ")",
+ },
+ {
+ name: "relative path",
+ paths: []string{"./shots/a.png"},
+ body: "![](shots/a.png)",
+ want: "![](" + rewriteURL + ")",
+ },
+ {
+ name: "absolute path in the workdir",
+ paths: []string{"a.png"},
+ body: "![](" + filepath.ToSlash(filepath.Join(workdir, "a.png")) + ")",
+ want: "![](" + rewriteURL + ")",
+ },
+ {
+ name: "plain link, angle brackets and title",
+ paths: []string{"my shot.png"},
+ body: "[open](<./my shot.png> \"title\")",
+ want: "[open](<" + rewriteURL + "> \"title\")",
+ },
+ {
+ name: "percent-encoded name",
+ paths: []string{"my shot.png"},
+ body: "![](./my%20shot.png)",
+ want: "![](" + rewriteURL + ")",
+ },
+ {
+ name: "every occurrence",
+ paths: []string{"a.png"},
+ body: "![1](./a.png) and ![2](a.png)",
+ want: "![1](" + rewriteURL + ") and ![2](" + rewriteURL + ")",
+ },
+ {
+ name: "label text naming the same path is untouched",
+ paths: []string{"a.png"},
+ body: "[see ./a.png](./a.png)",
+ want: "[see ./a.png](" + rewriteURL + ")",
+ },
+ {
+ name: "image nested in a link to the same file",
+ paths: []string{"a.png"},
+ body: "[![](./a.png)](./a.png)",
+ want: "[![](" + rewriteURL + ")](" + rewriteURL + ")",
+ },
+ {
+ name: "nested destination sharing the attachment path as a prefix is untouched",
+ paths: []string{"a.png"},
+ body: "[![preview](./a.png.thumb.png)](./a.png)",
+ want: "[![preview](./a.png.thumb.png)](" + rewriteURL + ")",
+ },
+ {
+ name: "nested angle destination sharing a prefix is untouched",
+ paths: []string{"a.png"},
+ body: "[![preview](<./a.png thumb.png>)](<./a.png>)",
+ want: "[![preview](<./a.png thumb.png>)](<" + rewriteURL + ">)",
+ },
+ {
+ name: "code span is untouched",
+ paths: []string{"a.png"},
+ body: "write `![](./a.png)` like this: ![](./a.png)",
+ want: "write `![](./a.png)` like this: ![](" + rewriteURL + ")",
+ },
+ {
+ name: "fenced block is untouched",
+ paths: []string{"a.png"},
+ body: "```md\n![](./a.png)\n```\n",
+ want: "```md\n![](./a.png)\n```\n",
+ },
+ {
+ name: "indented block is untouched",
+ paths: []string{"a.png"},
+ body: "text\n\n ![](./a.png)\n",
+ want: "text\n\n ![](./a.png)\n",
+ },
+ {
+ name: "unmatched local path is untouched",
+ paths: []string{"a.png"},
+ body: "![](./b.png)",
+ want: "![](./b.png)",
+ },
+ {
+ name: "different directory is not a bare-name match",
+ paths: []string{"a.png"},
+ body: "![](other/a.png)",
+ want: "![](other/a.png)",
+ },
+ {
+ name: "ambiguous bare name is untouched",
+ paths: []string{"shots/a.png", "other/a.png"},
+ body: "![](./a.png)",
+ want: "![](./a.png)",
+ },
+ {
+ name: "URL with the same name is untouched",
+ paths: []string{"a.png"},
+ body: "![](https://example.com/a.png)",
+ want: "![](https://example.com/a.png)",
+ },
+ {
+ name: "reference-style link is untouched",
+ paths: []string{"a.png"},
+ body: "![shot][s]\n\n[s]: ./a.png\n",
+ want: "![shot][s]\n\n[s]: ./a.png\n",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ urls := make([]string, len(tc.paths))
+ for i := range urls {
+ urls[i] = rewriteURL
+ }
+ got, _ := rewriteAttachmentLinks(tc.body, tc.paths, urls)
+ if got != tc.want {
+ t.Errorf("rewrite =\n%q\nwant\n%q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestRewriteAttachmentLinksMapsEachAttachment(t *testing.T) {
+ withWorkdir(t)
+ got, rewrites := rewriteAttachmentLinks(
+ "A\n\n![A](./a.png)\n\nB\n\n![B](./b.png)\n\nagain ![A](a.png)",
+ []string{"a.png", "b.png"},
+ []string{"/api/attachments/1/download", "/api/attachments/2/download"},
+ )
+ want := "A\n\n![A](/api/attachments/1/download)\n\nB\n\n![B](/api/attachments/2/download)\n\nagain ![A](/api/attachments/1/download)"
+ if got != want {
+ t.Fatalf("rewrite =\n%q\nwant\n%q", got, want)
+ }
+ if len(rewrites) != 3 || rewrites[0].Target != "./a.png" || rewrites[1].Target != "./b.png" || rewrites[2].Target != "a.png" {
+ t.Errorf("rewrites = %#v", rewrites)
+ }
+}
+
+// A link to a file attached in the same call is not a dead local link, so the
+// lint must not reject it — the preview body it checks has it rewritten.
+func TestPreviewAttachmentLinksSatisfiesLocalPathLint(t *testing.T) {
+ workdir := withWorkdir(t)
+ withAgentContext(t)
+ shot := filepath.Join(workdir, "shot.png")
+ if err := os.WriteFile(shot, []byte("x"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ body := "![shot](" + shot + ")"
+ if err := guardLocalPathLinks(previewAttachmentLinks(body, []string{"shot.png"}), "comment body", "hint"); err != nil {
+ t.Errorf("attached path should pass the lint, got: %v", err)
+ }
+ if err := guardLocalPathLinks(previewAttachmentLinks(body, nil), "comment body", "hint"); err == nil {
+ t.Error("unattached workdir path should still fail the lint")
+ }
+}
+
+func TestRunIssueCommentAddRewritesInlineAttachmentLinks(t *testing.T) {
+ withWorkdir(t)
+ withAgentContext(t)
+ if err := os.WriteFile("a.png", []byte("png"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ content := "Option A\n\n![Option A](./a.png)\n\n```\n![](./a.png)\n```\n\nOption B ![](./b.png)\n"
+ if err := os.WriteFile("reply.md", []byte(content), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ const markdownURL = "https://app.example/api/attachments/att-1/download"
+ var posted map[string]any
+ posts := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1"})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/upload-file":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": "att-1", "filename": "a.png", "content_type": "image/png", "markdown_url": markdownURL,
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues/issue-1/comments":
+ posts++
+ if err := json.NewDecoder(r.Body).Decode(&posted); err != nil {
+ t.Fatalf("decode comment: %v", err)
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "comment-1", "revision": 1})
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ cmd := newIssueCommentAddTestCmd()
+ _ = cmd.Flags().Set("content-file", "reply.md")
+ _ = cmd.Flags().Set("attachment", "./a.png")
+ _ = cmd.Flags().Set("output", "table")
+ stderr := captureStderr(t)
+ err := runIssueCommentAdd(cmd, []string{"MUL-1"})
+ report := stderr.read()
+ if err != nil {
+ t.Fatalf("runIssueCommentAdd: %v", err)
+ }
+
+ if posts != 1 {
+ t.Fatalf("comment posts = %d, want exactly 1", posts)
+ }
+ want := "Option A\n\n![Option A](" + markdownURL + ")\n\n```\n![](./a.png)\n```\n\nOption B ![](./b.png)"
+ if posted["content"] != want {
+ t.Errorf("content =\n%q\nwant\n%q", posted["content"], want)
+ }
+ if ids, _ := posted["attachment_ids"].([]any); len(ids) != 1 || ids[0] != "att-1" {
+ t.Errorf("attachment_ids = %#v, want [att-1]", posted["attachment_ids"])
+ }
+ if !strings.Contains(report, "Linked ./a.png in the comment body to the uploaded attachment "+markdownURL) {
+ t.Errorf("stderr should report the rewrite, got %q", report)
+ }
+}
+
+func TestRunIssueCreateKeepsInlineAttachmentInPlace(t *testing.T) {
+ withWorkdir(t)
+ if err := os.WriteFile("a.png", []byte("png"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ var posted map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodPost && r.URL.Path == "/api/upload-file":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "att-1", "filename": "a.png", "content_type": "image/png"})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues":
+ if err := json.NewDecoder(r.Body).Decode(&posted); err != nil {
+ t.Fatalf("decode issue: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1"})
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+
+ cmd := newIssueCreateTestCmd()
+ _ = cmd.Flags().Set("title", "inline")
+ _ = cmd.Flags().Set("description", "Before\n\n![shot](a.png)\n\nAfter")
+ _ = cmd.Flags().Set("attachment", "a.png")
+ _ = cmd.Flags().Set("output", "json")
+ stderr := captureStderr(t)
+ err := runIssueCreate(cmd, nil)
+ stderr.read()
+ if err != nil {
+ t.Fatalf("runIssueCreate: %v", err)
+ }
+ // No markdown_url from this server: the download path is the fallback, and
+ // the inline reference means nothing is appended at the end.
+ want := "Before\n\n![shot](/api/attachments/att-1/download)\n\nAfter"
+ if posted["description"] != want {
+ t.Errorf("description =\n%q\nwant\n%q", posted["description"], want)
+ }
+}
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 2671819156..22dcc8c52e 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -680,7 +680,7 @@ func init() {
issueCreateCmd.Flags().String("due-date", "", "Due date (calendar day, YYYY-MM-DD)")
issueCreateCmd.Flags().Bool("allow-duplicate", false, "Allow creating an issue even when an active duplicate exists")
issueCreateCmd.Flags().String("output", "json", "Output format: table or json")
- issueCreateCmd.Flags().StringArray("attachment", nil, "File path to attach (one literal path per flag; repeat --attachment for multiple files). Each file is uploaded and its markdown reference is appended to the description, which is what makes it render on the issue page")
+ issueCreateCmd.Flags().StringArray("attachment", nil, "File path to attach (one literal path per flag; repeat --attachment for multiple files). Each file is uploaded and its markdown reference is appended to the description, which is what makes it render on the issue page. To place it inline instead, reference the same path in the description (e.g. ![shot](./a.png)); that link is rewritten to the uploaded file")
issueCreateCmd.Flags().StringSlice("attachment-id", nil, "Existing attachment UUID(s) to bind to the created issue (can be specified multiple times)")
issueCreateCmd.Flags().StringArray("property", nil, `Set a custom property atomically with creation as "Name=Value" (repeatable, one distinct property per flag). Multi-value properties use comma-separated values; multi_text/multi_url also accept JSON arrays (required for commas in entries or values starting with "["). Property and option/member names are case-insensitive; UUIDs are accepted. Filter-only __none__, >=, <=, and != forms are rejected.`)
@@ -690,7 +690,7 @@ func init() {
issueUpdateCmd.Flags().Bool("description-stdin", false, "Read new description from stdin (preserves multi-line content verbatim)")
issueUpdateCmd.Flags().String("description-file", "", "Read new description from a UTF-8 file (preserves multi-line content verbatim; use this on Windows when stdin piping mangles non-ASCII bytes). The path must be inside the current working directory unless --allow-external-file is set.")
issueUpdateCmd.Flags().Bool("allow-external-file", false, "Allow --description-file / --attachment to read a path outside the current working directory. Off by default so a stale temp file from another run/environment can't be picked up (MUL-4252).")
- issueUpdateCmd.Flags().StringArray("attachment", nil, "Local file path to attach (one literal path per flag; repeat --attachment for multiple files); references are appended to the end of the description")
+ issueUpdateCmd.Flags().StringArray("attachment", nil, "Local file path to attach (one literal path per flag; repeat --attachment for multiple files); references are appended to the end of the description, except where the description already links the same path (e.g. ![shot](./a.png)), which is rewritten to the uploaded file in place")
issueUpdateCmd.Flags().String("status", "", "New status")
issueUpdateCmd.Flags().String("priority", "", "New priority")
issueUpdateCmd.Flags().String("pr-auto-complete", "", "Change status when linked PRs merge: on or off (on takes effect at the next PR event)")
@@ -763,7 +763,7 @@ func init() {
issueCommentAddCmd.Flags().String("content-file", "", "Read comment content from a UTF-8 file (preserves multi-line content verbatim; use this on Windows when stdin piping mangles non-ASCII bytes). The path must be inside the current working directory unless --allow-external-file is set.")
issueCommentAddCmd.Flags().Bool("allow-external-file", false, "Allow --content-file / --attachment to read a path outside the current working directory. Off by default so a stale file from another run/environment can't be picked up (MUL-4252).")
issueCommentAddCmd.Flags().String("parent", "", "Parent comment ID to reply under. A comment-triggered agent run must reply under its trigger comment; omitting --parent to post a top-level comment is rejected")
- issueCommentAddCmd.Flags().StringArray("attachment", nil, "File path to attach (one literal path per flag; repeat --attachment for multiple files). Non-image files, HTML included, show as file cards that open in the viewer; to render a chart inside the comment, put a ```html or ```mermaid block in the content instead")
+ issueCommentAddCmd.Flags().StringArray("attachment", nil, "File path to attach (one literal path per flag; repeat --attachment for multiple files). To show an image at a specific spot, reference the same path in the content (e.g. ![shot](./a.png)); that link is rewritten to the uploaded file before posting. Non-image files, HTML included, show as file cards that open in the viewer; to render a chart inside the comment, put a ```html or ```mermaid block in the content instead")
issueCommentAddCmd.Flags().StringSlice("steer", nil, "Run ID (full UUID or short prefix) whose in-progress turn should receive this comment instead of a follow-up run (repeatable)")
issueCommentAddCmd.Flags().Bool("steer-active", false, "Add this comment to the running turn of every agent on this issue you may steer, and of any other recipient that is running")
issueCommentAddCmd.Flags().String("output", "json", "Output format: table or json")
@@ -1594,8 +1594,8 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {
return err
}
if hasDesc {
- if err := guardLocalPathLinks(desc, "issue description",
- "Deliver the file itself with `multica issue create --attachment <path>` (repeatable) and drop the link."); err != nil {
+ if err := guardLocalPathLinks(previewAttachmentLinks(desc, attachments), "issue description",
+ "Deliver the file itself with `multica issue create --attachment <path>` (repeatable); a link or image whose target is that same path is rewritten to the uploaded file and renders in place. Otherwise drop the link."); err != nil {
return err
}
}
@@ -1692,6 +1692,7 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {
attachmentIDs = appendUniqueStrings(attachmentIDs, result.ID)
fmt.Fprintf(os.Stderr, "Uploaded %s\n", att.path)
}
+ desc = applyAttachmentLinks(os.Stderr, desc, "issue description", pending, uploaded)
desc = appendAttachmentReferences(desc, uploaded)
if hasDesc || len(uploaded) > 0 {
body["description"] = desc
@@ -1837,8 +1838,8 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
- if err := guardLocalPathLinks(desc, "issue description",
- "Attach the file with `multica issue update <issue-id> --attachment <path>` and drop the local-path link."); err != nil {
+ if err := guardLocalPathLinks(previewAttachmentLinks(desc, attachmentPaths), "issue description",
+ "Attach the file with `multica issue update <issue-id> --attachment <path>`; a link or image whose target is that same path is rewritten to the uploaded file and renders in place. Otherwise drop the local-path link."); err != nil {
return err
}
body["description"] = desc
@@ -1946,6 +1947,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
fmt.Fprintf(os.Stderr, "Uploaded %s\n", att.path)
}
if len(attachmentRefs) > 0 {
+ desc = applyAttachmentLinks(os.Stderr, desc, "issue description", pending, attachmentRefs)
body["description"] = appendAttachmentReferences(desc, attachmentRefs)
body["attachment_ids"] = attachmentIDs
}
@@ -2655,8 +2657,12 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
if !hasContent {
return fmt.Errorf("--content, --content-stdin, or --content-file is required")
}
- if err := guardLocalPathLinks(content, "comment body",
- "Deliver the file itself with `multica issue comment add <issue-id> --attachment <path>` (repeatable) and drop the link."); err != nil {
+ attachments, err := issueAttachmentPaths(cmd)
+ if err != nil {
+ return err
+ }
+ if err := guardLocalPathLinks(previewAttachmentLinks(content, attachments), "comment body",
+ "Deliver the file itself with `multica issue comment add <issue-id> --attachment <path>` (repeatable); a link or image whose target is that same path is rewritten to the uploaded file and renders in place. Otherwise drop the link."); err != nil {
return err
}
@@ -2667,10 +2673,6 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
// Use a longer timeout when attachments are present (file uploads can be slow).
timeout := cli.APITimeout()
- attachments, err := issueAttachmentPaths(cmd)
- if err != nil {
- return err
- }
steerInputs, _ := cmd.Flags().GetStringSlice("steer")
steerActive, _ := cmd.Flags().GetBool("steer-active")
if (len(steerInputs) > 0 || steerActive) && len(attachments) > 0 {
@@ -2704,15 +2706,18 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
return err
}
var attachmentIDs []string
+ uploaded := make([]cli.AttachmentResponse, 0, len(pending))
for _, att := range pending {
// Comment attachments are linked by the comment request; upload them unbound first.
- id, uploadErr := client.UploadFile(ctx, att.data, att.path, "")
+ result, uploadErr := client.UploadIssueAttachment(ctx, att.data, att.path, "")
if uploadErr != nil {
return fmt.Errorf("upload attachment %s: %w", att.path, uploadErr)
}
- attachmentIDs = append(attachmentIDs, id)
+ attachmentIDs = append(attachmentIDs, result.ID)
+ uploaded = append(uploaded, result)
fmt.Fprintf(os.Stderr, "Uploaded %s\n", att.path)
}
+ content = applyAttachmentLinks(os.Stderr, content, "comment body", pending, uploaded)
body := map[string]any{"content": content}
if len(steerTargets) > 0 {
diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.md
index 280096fc3b..b45e550467 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md
@@ -371,6 +371,11 @@ Where content goes decides how it shows:
a file card that opens in the viewer, **HTML included**: an uploaded
`report.html` is a deliverable to open, not an inline chart. Use it for
something the reader keeps or downloads.
+- **An attached image at a specific spot** — reference the attached path in
+ the body, e.g. `![Option A](./a.png)` with `--attachment ./a.png` in the same
+ call. The CLI rewrites that link to the uploaded file before posting, so the
+ image shows right there instead of at the end. Code spans and blocks are left
+ alone.
For HTML that follows light / dark mode, style it with `var(--background)`,
`var(--foreground)`, `var(--muted)`, `var(--muted-foreground)`, `var(--border)`,