Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(cli): reference issue create attachments in the description (#8736)
Bohan Jiang6ee01c33aad8
diff --git a/server/cmd/multica/cmd_attachment.go b/server/cmd/multica/cmd_attachment.goindex ffc453330d..30c66c9f8e 100644--- a/server/cmd/multica/cmd_attachment.go+++ b/server/cmd/multica/cmd_attachment.go@@ -92,15 +92,7 @@ func runAttachmentUpload(cmd *cobra.Command, args []string) error {}filename := filepath.Base(path)- // Escape markdown label metacharacters in the filename so a name like- // `report[v2].pdf` does not truncate the snippet's label. Files render as a- // block-level attachment card via `!file[...]( )`; images render inline via- // ``.- label := escapeMarkdownLabel(filename)- markdown := fmt.Sprintf("!file[%s](%s)", label, att.MarkdownURL)- if strings.HasPrefix(att.ContentType, "image/") {- markdown = fmt.Sprintf("", label, att.MarkdownURL)- }+ markdown := attachmentMarkdown(filename, att.ContentType, att.MarkdownURL)fmt.Fprintln(os.Stderr, "Uploaded:", filename)return cli.PrintJSON(os.Stdout, map[string]any{@@ -111,6 +103,20 @@ func runAttachmentUpload(cmd *cobra.Command, args []string) error {})}+// attachmentMarkdown renders the markdown snippet that makes an uploaded file+// visible in a body: images inline via ``, every other file as a+// block-level attachment card via `!file[...]( )`. The label is escaped so a+// name like `report[v2].pdf` stays one label instead of truncating the+// snippet. Shared by `attachment upload` (prints it for the agent to paste)+// and `issue create --attachment` (appends it to the description).+func attachmentMarkdown(filename, contentType, markdownURL string) string {+ label := escapeMarkdownLabel(filename)+ if strings.HasPrefix(contentType, "image/") {+ return fmt.Sprintf("", label, markdownURL)+ }+ return fmt.Sprintf("!file[%s](%s)", label, markdownURL)+}+// escapeMarkdownLabel escapes the metacharacters a markdown link/image label// may not contain unescaped ([ ] ( ) and backslash), so a filename like// `report[v2].pdf` stays a single valid label instead of truncating thediff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex b0448241f3..c762006363 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -626,7 +626,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().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times)")+ issueCreateCmd.Flags().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times). 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().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 inside one flag. Property and option/member names are case-insensitive; UUIDs are accepted. Filter-only __none__, >=, <=, and != forms are rejected.`)@@ -1336,6 +1336,49 @@ func collectLocalAttachments(cmd *cobra.Command, attachments []string) ([]pendinreturn pending, nil}+// appendAttachmentReferences appends the markdown snippet of every uploaded+// attachment to an issue description, so the file renders on the issue page+// instead of only existing as a stored row. Each snippet goes in its own+// paragraph because file cards are block-level. An attachment the description+// already references is skipped — a caller may have composed the markdown+// itself (quick-create keeps the user's pasted image inline), and appending it+// again would render the same file twice.+func appendAttachmentReferences(description string, attachments []cli.AttachmentResponse) string {+ snippets := make([]string, 0, len(attachments))+ for _, att := range attachments {+ if descriptionReferencesAttachment(description, att) {+ continue+ }+ snippets = append(snippets, attachmentMarkdown(filepath.Base(att.Filename), att.ContentType, att.MarkdownURL))+ }+ if len(snippets) == 0 {+ return description+ }+ appended := strings.Join(snippets, "\n\n")+ if strings.TrimSpace(description) == "" {+ return appended+ }+ return strings.TrimRight(description, "\n") + "\n\n" + appended+}++// descriptionReferencesAttachment reports whether a description body already+// points at this attachment. It matches the durable `markdown_url` and the+// `/api/attachments/<id>` path it is built from rather than the raw storage+// `url`, which bodies never carry — the same rule the web composers use+// (`contentReferencesAttachment`).+func descriptionReferencesAttachment(description string, att cli.AttachmentResponse) bool {+ if description == "" {+ return false+ }+ if att.MarkdownURL != "" && strings.Contains(description, att.MarkdownURL) {+ return true+ }+ if att.ID != "" && strings.Contains(description, "/api/attachments/"+att.ID) {+ return true+ }+ return false+}+func appendUniqueStrings(dst []string, values ...string) []string {seen := make(map[string]struct{}, len(dst)+len(values))out := make([]string, 0, len(dst)+len(values))@@ -1425,7 +1468,6 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {"Deliver the file itself with `multica issue create --attachment <path>` (repeatable) and drop the link."); err != nil {return err}- body["description"] = desc}if statusFlag != "" {body["status"] = statusFlag@@ -1489,9 +1531,6 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {return err}attachmentIDs = appendUniqueStrings(attachmentIDs, envAttachmentIDs...)- if len(attachmentIDs) > 0 {- body["attachment_ids"] = attachmentIDs- }// Pre-validate attachments BEFORE creating the issue so a bad path can// never produce a half-created issue (which would otherwise trigger@@ -1504,6 +1543,33 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {return err}+ // Upload BEFORE creating the issue, and append each file's markdown to the+ // description. A file is visible on an issue only when the description+ // references it — every other writer honors that (the web create dialog and+ // the description editor bind exactly what the body references). Uploading+ // after the create, as this used to, stored the file with an `issue_id` and+ // left the description untouched, so it rendered nowhere on web, desktop or+ // mobile (MUL-7600 / #8692). Uploading first also removes the old+ // partial-success state: a failure here means no issue was created, so the+ // retry is safe and cannot duplicate.+ uploaded := make([]cli.AttachmentResponse, 0, len(pending))+ for _, att := range pending {+ result, uploadErr := client.UploadIssueAttachment(ctx, att.data, att.path, "")+ if uploadErr != nil {+ return fmt.Errorf("upload attachment %s (no issue created): %w", att.path, uploadErr)+ }+ uploaded = append(uploaded, result)+ attachmentIDs = appendUniqueStrings(attachmentIDs, result.ID)+ fmt.Fprintf(os.Stderr, "Uploaded %s\n", att.path)+ }+ desc = appendAttachmentReferences(desc, uploaded)+ if hasDesc || len(uploaded) > 0 {+ body["description"] = desc+ }+ if len(attachmentIDs) > 0 {+ body["attachment_ids"] = attachmentIDs+ }+var result map[string]anyif err := client.PostJSON(ctx, "/api/issues", body, &result); err != nil {if msg, ok := activeDuplicateIssueCreateMessage(err); ok {@@ -1515,20 +1581,6 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {return fmt.Errorf("issue %s was created, but the server did not confirm its custom properties; review it before retrying: %w", issueDisplayKey(result), err)}- // Upload attachments and link them to the newly created issue.- // Failures here are partial-success: the issue exists already, so- // turning a non-zero exit on the caller would invite a retry that- // duplicates the issue. Warn on stderr and continue.- issueID := strVal(result, "id")- for _, att := range pending {- if _, uploadErr := client.UploadFile(ctx, att.data, att.path, issueID); uploadErr != nil {- fmt.Fprintf(os.Stderr, "warning: upload attachment %s failed (issue already created, %s): %v\n",- att.path, strVal(result, "identifier"), uploadErr)- continue- }- fmt.Fprintf(os.Stderr, "Uploaded %s\n", att.path)- }-output, _ := cmd.Flags().GetString("output")if output == "table" {headers := []string{"KEY", "TITLE", "STATUS", "PRIORITY"}diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 80d2ad4b9c..1606126547 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -1075,6 +1075,196 @@ func TestRunIssueCreateSendsExistingAttachmentIDs(t *testing.T) {}}+// issueCreateAttachmentServer serves the upload + create pair `issue create+// --attachment` walks, recording the request order so a test can assert the+// upload happens BEFORE the issue exists. uploadStatus != 200 fails every+// upload.+type issueCreateAttachmentServer struct {+ srv *httptest.Server+ uploadStatus int+ calls []string+ createBody map[string]any+ uploadNames []string+}++func newIssueCreateAttachmentServer(t *testing.T) *issueCreateAttachmentServer {+ t.Helper()+ s := &issueCreateAttachmentServer{uploadStatus: http.StatusOK}+ s.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/api/upload-file":+ s.calls = append(s.calls, "upload")+ if s.uploadStatus != http.StatusOK {+ w.WriteHeader(s.uploadStatus)+ _, _ = w.Write([]byte(`{"error":"storage unavailable"}`))+ return+ }+ file, header, err := r.FormFile("file")+ if err != nil {+ t.Errorf("upload without file part: %v", err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ defer file.Close()+ if issueID := r.FormValue("issue_id"); issueID != "" {+ t.Errorf("upload carried issue_id %q; issue create must upload unbound and bind via attachment_ids", issueID)+ }+ name := header.Filename+ s.uploadNames = append(s.uploadNames, name)+ id := fmt.Sprintf("att-%d", len(s.uploadNames))+ contentType := "application/octet-stream"+ if strings.HasSuffix(name, ".png") {+ contentType = "image/png"+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": id,+ "filename": name,+ "content_type": contentType,+ "url": "https://storage.example/" + id,+ "download_url": "/api/attachments/" + id + "/download",+ "markdown_url": "https://api.example/api/attachments/" + id + "/download",+ })+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues":+ s.calls = append(s.calls, "create")+ if err := json.NewDecoder(r.Body).Decode(&s.createBody); err != nil {+ t.Errorf("decode create body: %v", err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": "issue-1",+ "identifier": "MUL-1",+ "title": "With attachments",+ "status": "todo",+ "priority": "none",+ })+ default:+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ t.Cleanup(s.srv.Close)+ setCLITestServerEnv(t, s.srv.URL)+ return s+}++// writeIssueCreateAttachment writes a file in the current working directory so+// it passes the MUL-4252 workdir guard.+func writeIssueCreateAttachment(t *testing.T, name string) string {+ t.Helper()+ if err := os.WriteFile(name, []byte("payload"), 0o600); err != nil {+ t.Fatalf("write %s: %v", name, err)+ }+ return name+}++// TestRunIssueCreateAppendsAttachmentReferencesToDescription is the MUL-7600 /+// #8692 regression: a file passed to `issue create --attachment` was uploaded+// with an issue_id but never referenced from the description, and an issue+// renders only the files its description references — so the file existed+// server-side and appeared nowhere on web, desktop or mobile. The upload must+// now precede the create and its markdown must land in the description.+func TestRunIssueCreateAppendsAttachmentReferencesToDescription(t *testing.T) {+ t.Chdir(t.TempDir())+ srv := newIssueCreateAttachmentServer(t)++ cmd := newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "With attachments")+ _ = cmd.Flags().Set("description", "Repro steps below.")+ _ = cmd.Flags().Set("attachment", writeIssueCreateAttachment(t, "shot.png"))+ _ = cmd.Flags().Set("attachment", writeIssueCreateAttachment(t, "server.log"))+ if err := runIssueCreate(cmd, nil); err != nil {+ t.Fatalf("runIssueCreate: %v", err)+ }++ if want := []string{"upload", "upload", "create"}; !slices.Equal(srv.calls, want) {+ t.Fatalf("request order = %v, want %v (uploads must precede the create so a failure leaves no issue)", srv.calls, want)+ }+ desc, _ := srv.createBody["description"].(string)+ wantImage := ""+ wantFile := "!file[server.log](https://api.example/api/attachments/att-2/download)"+ if !strings.Contains(desc, wantImage) {+ t.Errorf("description missing image reference %q; got %q", wantImage, desc)+ }+ if !strings.Contains(desc, wantFile) {+ t.Errorf("description missing file card reference %q; got %q", wantFile, desc)+ }+ if !strings.HasPrefix(desc, "Repro steps below.\n\n") {+ t.Errorf("description dropped the author's body; got %q", desc)+ }+ ids, ok := srv.createBody["attachment_ids"].([]any)+ if !ok || len(ids) != 2 || ids[0] != "att-1" || ids[1] != "att-2" {+ t.Fatalf("attachment_ids = %#v, want [att-1 att-2]", srv.createBody["attachment_ids"])+ }+}++// TestRunIssueCreateKeepsDescriptionWhenAttachmentIsOnlyFile covers a create+// with no --description: the snippet alone becomes the description, otherwise+// the file still has nothing referencing it.+func TestRunIssueCreateKeepsDescriptionWhenAttachmentIsOnlyFile(t *testing.T) {+ t.Chdir(t.TempDir())+ srv := newIssueCreateAttachmentServer(t)++ cmd := newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "Screenshot only")+ _ = cmd.Flags().Set("attachment", writeIssueCreateAttachment(t, "shot.png"))+ if err := runIssueCreate(cmd, nil); err != nil {+ t.Fatalf("runIssueCreate: %v", err)+ }++ if got, want := srv.createBody["description"], ""; got != want {+ t.Fatalf("description = %#v, want %q", got, want)+ }+}++// TestRunIssueCreateDoesNotDuplicateReferencedAttachment guards the+// quick-create path: the agent keeps the user's pasted markdown in the+// description, so appending the same reference again would render one file+// twice.+func TestRunIssueCreateDoesNotDuplicateReferencedAttachment(t *testing.T) {+ t.Chdir(t.TempDir())+ srv := newIssueCreateAttachmentServer(t)++ cmd := newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "Already referenced")+ _ = cmd.Flags().Set("description", "Before\n\n\n\nAfter")+ _ = cmd.Flags().Set("attachment", writeIssueCreateAttachment(t, "shot.png"))+ if err := runIssueCreate(cmd, nil); err != nil {+ t.Fatalf("runIssueCreate: %v", err)+ }++ desc, _ := srv.createBody["description"].(string)+ if got := strings.Count(desc, "/api/attachments/att-1/download"); got != 1 {+ t.Fatalf("attachment referenced %d times, want 1; got %q", got, desc)+ }+ ids, ok := srv.createBody["attachment_ids"].([]any)+ if !ok || len(ids) != 1 || ids[0] != "att-1" {+ t.Fatalf("attachment_ids = %#v, want [att-1] so the referenced file still binds", srv.createBody["attachment_ids"])+ }+}++// TestRunIssueCreateFailsBeforeCreateWhenUploadFails pins the new failure+// shape: the upload runs first, so a storage failure means no issue was+// created and the caller can retry without duplicating one. The old order+// created the issue, warned on stderr, and silently lost the file.+func TestRunIssueCreateFailsBeforeCreateWhenUploadFails(t *testing.T) {+ t.Chdir(t.TempDir())+ srv := newIssueCreateAttachmentServer(t)+ srv.uploadStatus = http.StatusInternalServerError++ cmd := newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "Upload fails")+ _ = cmd.Flags().Set("attachment", writeIssueCreateAttachment(t, "shot.png"))+ err := runIssueCreate(cmd, nil)+ if err == nil {+ t.Fatal("expected upload failure to abort the create")+ }+ if !strings.Contains(err.Error(), "no issue created") {+ t.Errorf("error should tell the caller no issue exists; got %v", err)+ }+ if slices.Contains(srv.calls, "create") {+ t.Fatalf("issue was created despite the failed upload: %v", srv.calls)+ }+}+func TestRunIssueCreateShowsDuplicateMessage(t *testing.T) {want := "Active duplicate issue exists: YUA-36 SH-PM-SYNTH-01 Synthesize recommendation-to-shortlist planning outputs (status: in_progress). Set allow_duplicate=true or use --allow-duplicate to create another."srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex 941e0d9f9c..5b2b74a05b 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -472,55 +472,79 @@ type AttachmentResponse struct {// UploadFile uploads a file via multipart form to /api/upload-file.// It returns the attachment ID from the server response.func (c *APIClient) UploadFile(ctx context.Context, fileData []byte, filename string, issueID string) (string, error) {+ att, err := c.UploadIssueAttachment(ctx, fileData, filename, issueID)+ if err != nil {+ return "", err+ }+ return att.ID, nil+}++// UploadIssueAttachment uploads a file via multipart form to /api/upload-file+// and returns the full AttachmentResponse. An empty issueID leaves the row+// unbound, which is what `issue create` needs: the file is uploaded before the+// issue exists, its `markdown_url` goes into the description, and the create+// call binds it via `attachment_ids`.+func (c *APIClient) UploadIssueAttachment(ctx context.Context, fileData []byte, filename string, issueID string) (AttachmentResponse, error) {var body bytes.Bufferwriter := multipart.NewWriter(&body)part, err := writer.CreateFormFile("file", filepath.Base(filename))if err != nil {- return "", fmt.Errorf("create form file: %w", err)+ return AttachmentResponse{}, fmt.Errorf("create form file: %w", err)}if _, err := part.Write(fileData); err != nil {- return "", fmt.Errorf("write file data: %w", err)+ return AttachmentResponse{}, fmt.Errorf("write file data: %w", err)}if issueID != "" {if err := writer.WriteField("issue_id", issueID); err != nil {- return "", fmt.Errorf("write issue_id field: %w", err)+ return AttachmentResponse{}, fmt.Errorf("write issue_id field: %w", err)}}if err := writer.Close(); err != nil {- return "", fmt.Errorf("close multipart writer: %w", err)+ return AttachmentResponse{}, fmt.Errorf("close multipart writer: %w", err)}req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/api/upload-file", &body)if err != nil {- return "", err+ return AttachmentResponse{}, err}req.Header.Set("Content-Type", writer.FormDataContentType())c.setHeaders(req)- resp, err := c.HTTPClient.Do(req)+ // Honor a longer context deadline for large files: callers widen the+ // context for uploads, which the default client timeout would shadow.+ // Same shape as UploadChatAttachment / UploadFileWithURL.+ httpClient := c.HTTPClient+ if deadline, ok := ctx.Deadline(); ok {+ remaining := time.Until(deadline)+ if remaining > httpClient.Timeout {+ clientCopy := *httpClient+ clientCopy.Timeout = remaining+ httpClient = &clientCopy+ }+ }++ resp, err := httpClient.Do(req)err = wrapTransport(req, err)if err != nil {- return "", err+ return AttachmentResponse{}, err}defer resp.Body.Close()if resp.StatusCode >= 400 {- return "", newHTTPError(http.MethodPost, "/api/upload-file", resp)+ return AttachmentResponse{}, newHTTPError(http.MethodPost, "/api/upload-file", resp)}- var result map[string]any+ var result AttachmentResponseif err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return "", fmt.Errorf("decode upload response: %w", err)+ return AttachmentResponse{}, fmt.Errorf("decode upload response: %w", err)}-- id, _ := result["id"].(string)- if id == "" {- return "", fmt.Errorf("upload response missing attachment id")+ if result.ID == "" {+ return AttachmentResponse{}, fmt.Errorf("upload response missing attachment id")}- return id, nil+ return result, nil}// UploadChatAttachment uploads a file via multipart form to /api/upload-file