Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(cli): preserve literal issue attachment paths (#9787)
沙雕的小鱼儿 boyfeiyu82918d30fc25
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex d6a1cf4cda..a8a58fcaea 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -366,6 +366,12 @@ CLI configuration files contain tokens that can access Multica as you. Don't comThe tables below cover every current top-level command, grouped the way the CLI itself groups them. All commands accept the global flags `--server-url`, `--workspace-id`, `--profile`, and `--debug`. `--output` is registered per command, and the default format varies: `list` commands default to a table, while `get` and `create` commands mostly default to JSON. Full flags are defined by `multica <command> --help`.+### Issue attachments++For `issue create`, `issue update`, and `issue comment add`, each `--attachment` takes one literal file path, including any commas or double quotes in the filename. Repeat the flag for multiple files: `--attachment 'report,final.csv' --attachment notes.txt`. Omitting the flag attaches no files; an explicitly empty path is an error. All local paths are checked before any file is uploaded.++Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --attachment b` to attach two files. The former now selects a single file named `a,b`. Remove extra CSV quotes from the old workaround `--attachment '"report,final.csv"'`; use `--attachment 'report,final.csv'` unless the filename itself contains those double quotes.+### Core| Command | Subcommand | Purpose | Key flags |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex eeb1b32081..e691925b80 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -343,6 +343,12 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓下表覆盖当前全部顶层命令,按 CLI 自身的分组排列。所有命令都接受全局 flag `--server-url`、`--workspace-id`、`--profile` 和 `--debug`。`--output` 是逐命令注册的 flag,默认格式因命令而异:`list` 类默认表格,`get`、`create` 类多默认 JSON。完整参数以 `multica <command> --help` 为准。+### 任务附件++`issue create`、`issue update` 和 `issue comment add` 的每个 `--attachment` 接受一个完整文件路径,保留文件名中的逗号和双引号。多个文件须重复 flag,例如 `--attachment 'report,final.csv' --attachment notes.txt`。省略 flag 时不添加附件;显式传入空路径会报错。所有本地路径都通过检查后才开始上传。++从旧 CSV 解析方式迁移:要添加两个文件,将 `--attachment a,b` 改为 `--attachment a --attachment b`。前一种写法现在只选择名为 `a,b` 的单个文件。旧用法 `--attachment '"report,final.csv"'` 中额外的 CSV 双引号也须移除,改用 `--attachment 'report,final.csv'`;只有文件名本身包含双引号时才保留。+### Core| 命令 | 子命令 | 用途 | 关键 flag |diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 512a89dda7..04d156f5b3 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -19,6 +19,7 @@ import ("unicode/utf8""github.com/spf13/cobra"+ "github.com/spf13/pflag""github.com/multica-ai/multica/server/internal/cli""github.com/multica-ai/multica/server/internal/util"@@ -674,7 +675,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). 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")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.`)@@ -684,7 +685,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().StringSlice("attachment", nil, "Local file path(s) to attach to the issue description (repeatable); 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")issueUpdateCmd.Flags().String("status", "", "New status")issueUpdateCmd.Flags().String("priority", "", "New priority")issueUpdateCmd.Flags().String("assignee", "", "New assignee name (member, agent, or squad; fuzzy match)")@@ -756,7 +757,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().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times). 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). 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")@@ -1392,6 +1393,20 @@ func collectLocalAttachments(cmd *cobra.Command, attachments []string) ([]pendinreturn pending, nil}+func issueAttachmentPaths(cmd *cobra.Command) ([]string, error) {+ flag := cmd.Flags().Lookup("attachment")+ if flag == nil {+ return nil, errors.New("--attachment flag is not registered")+ }+ paths, ok := flag.Value.(pflag.SliceValue)+ if !ok {+ return nil, errors.New("--attachment flag does not contain a path array")+ }+ // GetStringArray round-trips through CSV and loses a single empty string.+ // Read the stored values so an explicit empty path reaches file validation.+ return paths.GetSlice(), 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@@ -1489,7 +1504,10 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {// Use a longer timeout when attachments are present (file uploads can be slow).timeout := cli.APITimeout()- attachments, _ := cmd.Flags().GetStringSlice("attachment")+ attachments, err := issueAttachmentPaths(cmd)+ if err != nil {+ return err+ }if len(attachments) > 0 {timeout = cli.AtLeastAPITimeout(60 * time.Second)}@@ -1696,7 +1714,10 @@ func activeDuplicateIssueCreateMessage(err error) (string, bool) {}func runIssueUpdate(cmd *cobra.Command, args []string) error {- attachmentPaths, _ := cmd.Flags().GetStringSlice("attachment")+ attachmentPaths, err := issueAttachmentPaths(cmd)+ if err != nil {+ return err+ }noStart, _ := cmd.Flags().GetBool("no-start")statusChanged := cmd.Flags().Changed("status")statusFlag, _ := cmd.Flags().GetString("status")@@ -2564,7 +2585,10 @@ 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, _ := cmd.Flags().GetStringSlice("attachment")+ 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 {diff --git a/server/cmd/multica/cmd_issue_attachment_test.go b/server/cmd/multica/cmd_issue_attachment_test.gonew file mode 100644index 0000000000..abe958f854--- /dev/null+++ b/server/cmd/multica/cmd_issue_attachment_test.go@@ -0,0 +1,199 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "reflect"+ "runtime"+ "slices"+ "strings"+ "sync"+ "testing"+ "time"+)++// Run the production command tree in a fresh process so each argv uses the real+// flag registrations without leaking Cobra's global flag state between tests.+func TestIssueAttachmentArgvProcess(t *testing.T) {+ if os.Getenv("MULTICA_TEST_ATTACHMENT_ARGV") != "1" {+ return+ }+ separator := slices.Index(os.Args, "--")+ if separator < 0 {+ t.Fatal("missing CLI argv")+ }+ // TestMain clears task credentials before tests run. Set only synthetic+ // credentials here, after that isolation, and let TestMain clean up normally.+ t.Setenv("MULTICA_SERVER_URL", os.Getenv("MULTICA_TEST_ATTACHMENT_SERVER"))+ t.Setenv("MULTICA_TOKEN", "mat_SYNTHETIC_ONLY")+ t.Setenv("MULTICA_WORKSPACE_ID", "11111111-1111-4111-8111-111111111111")+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", filepath.Join(t.TempDir(), "config"))+ rootCmd.SetArgs(os.Args[separator+1:])+ if err := rootCmd.Execute(); err != nil {+ t.Fatal(err)+ }+}++func TestIssueAttachmentLiteralArgv(t *testing.T) {+ const issueID = "11111111-1111-4111-8111-111111111111"+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ for _, command := range []string{"create", "update", "comment"} {+ t.Run(command, func(t *testing.T) {+ for _, tc := range []struct {+ name string+ flags []string+ want []string+ wantError bool+ fragments bool+ }{+ {name: "comma", flags: []string{"--attachment", "report,final.csv"}, want: []string{"report,final.csv"}},+ {name: "comma with fragments", flags: []string{"--attachment", "report,final.csv"}, want: []string{"report,final.csv"}, fragments: true},+ {name: "missing literal with fragments", flags: []string{"--attachment", "absent,ghost.txt"}, wantError: true, fragments: true},+ {name: "valid then missing", flags: []string{"--attachment", "first.txt", "--attachment", "missing.txt"}, wantError: true},+ {name: "repeated", flags: []string{"--attachment", "first.txt", "--attachment", "second.txt"}, want: []string{"first.txt", "second.txt"}},+ {name: "mixed repeated", flags: []string{"--attachment", "first.txt", "--attachment", "report,final.csv"}, want: []string{"first.txt", "report,final.csv"}},+ {name: "equals", flags: []string{"--attachment=report,final.csv", "--attachment=first.txt"}, want: []string{"report,final.csv", "first.txt"}},+ {name: "space", flags: []string{"--attachment", "with space.txt"}, want: []string{"with space.txt"}},+ {name: "literal quote", flags: []string{"--attachment", `say"hi.txt`}, want: []string{`say"hi.txt`}},+ {name: "unicode", flags: []string{"--attachment", "报告.txt"}, want: []string{"报告.txt"}},+ {name: "empty", flags: []string{"--attachment", ""}, wantError: true},+ {name: "empty equals", flags: []string{"--attachment="}, wantError: true},+ {name: "valid then empty", flags: []string{"--attachment", "first.txt", "--attachment="}, wantError: true},+ {name: "none"},+ {name: "old CSV quotes are literal", flags: []string{"--attachment", `"report,final.csv"`}, wantError: true},+ {name: "quoted filename exists", flags: []string{"--attachment", `"report,final.csv"`}, want: []string{`"report,final.csv"`}},+ {name: "external", flags: []string{"--attachment", "../outside.txt"}, wantError: true},+ {name: "external symlink", flags: []string{"--attachment", "link.txt"}, wantError: true},+ {name: "external allowed", flags: []string{"--attachment", "../outside.txt", "--allow-external-file"}, want: []string{"outside.txt"}},+ {name: "URL skipped", flags: []string{"--attachment", "https://example.invalid/a,b", "--attachment", "first.txt"}, want: []string{"first.txt"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if runtime.GOOS == "windows" && strings.Contains(strings.Join(tc.flags, ""), `"`) {+ t.Skip("Windows filenames cannot contain double quotes")+ }+ parent := t.TempDir()+ dir := filepath.Join(parent, "workdir")+ if err := os.Mkdir(dir, 0o700); err != nil {+ t.Fatal(err)+ }+ payload := func(name string) string { return "synthetic payload: " + name + "\n" }+ files := []string{"report,final.csv", "first.txt", "second.txt", "with space.txt", "报告.txt", "body.md"}+ if runtime.GOOS != "windows" {+ files = append(files, `say"hi.txt`)+ }+ if tc.name == "quoted filename exists" {+ files = append(files, `"report,final.csv"`)+ }+ if tc.fragments {+ files = append(files, "report", "final.csv", "absent", "ghost.txt")+ }+ for _, name := range files {+ if err := os.WriteFile(filepath.Join(dir, name), []byte(payload(name)), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ outside := filepath.Join(parent, "outside.txt")+ if err := os.WriteFile(outside, []byte(payload("outside.txt")), 0o600); err != nil {+ t.Fatal(err)+ }+ if tc.name == "external symlink" {+ if err := os.Symlink(outside, filepath.Join(dir, "link.txt")); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ }++ type upload struct{ name, content string }+ var mu sync.Mutex+ var uploads []upload+ mutations := 0+ issuePath := "/api/issues/" + issueID+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ defer mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/api/upload-file":+ file, header, err := r.FormFile("file")+ if err != nil {+ t.Errorf("multipart file: %v", err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ defer file.Close()+ data, err := io.ReadAll(file)+ if err != nil {+ t.Errorf("read multipart file: %v", err)+ }+ uploads = append(uploads, upload{header.Filename, string(data)})+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": fmt.Sprintf("attachment-%d", len(uploads)), "filename": header.Filename,+ "content_type": "text/plain", "markdown_url": "https://example.invalid/attachment",+ })+ case r.Method == http.MethodGet && r.URL.Path == issuePath:+ _ = json.NewEncoder(w).Encode(map[string]any{"id": issueID, "identifier": "TEST-1", "description": "existing body", "revision": 1})+ case (r.Method == http.MethodPost && (r.URL.Path == "/api/issues" || r.URL.Path == issuePath+"/comments")) ||+ (r.Method == http.MethodPut && r.URL.Path == issuePath):+ mutations+++ _ = json.NewEncoder(w).Encode(map[string]any{"id": issueID, "identifier": "TEST-1"})+ default:+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ defer server.Close()+ argv := []string{"issue", "create", "--title", "fixture"}+ if command == "update" {+ argv = []string{"issue", "update", issueID, "--title", "fixture"}+ } else if command == "comment" {+ argv = []string{"issue", "comment", "add", issueID, "--content-file", "body.md"}+ }+ argv = append(argv, tc.flags...)+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ child := exec.CommandContext(ctx, executable, append([]string{"-test.run=^TestIssueAttachmentArgvProcess$", "--"}, argv...)...)+ child.Dir = dir+ for _, entry := range os.Environ() {+ if !strings.HasPrefix(entry, "MULTICA_") {+ child.Env = append(child.Env, entry)+ }+ }+ child.Env = append(child.Env,+ "MULTICA_TEST_ATTACHMENT_ARGV=1", "MULTICA_TEST_ATTACHMENT_SERVER="+server.URL)+ output, err := child.CombinedOutput()+ if ctx.Err() != nil {+ t.Fatalf("CLI timed out: %s", output)+ }+ if (err != nil) != tc.wantError {+ t.Errorf("argv %q: err=%v, wantError=%v; output: %s", argv, err, tc.wantError, output)+ }+ mu.Lock()+ defer mu.Unlock()+ var want []upload+ for _, name := range tc.want {+ want = append(want, upload{name, payload(name)})+ }+ if !reflect.DeepEqual(uploads, want) {+ t.Errorf("uploads = %#v, want %#v", uploads, want)+ }+ wantMutations := 1+ if tc.wantError {+ wantMutations = 0+ }+ if mutations != wantMutations {+ t.Errorf("issue/comment mutations = %d, want %d", mutations, wantMutations)+ }+ })+ }+ })+ }+}diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 359dbe7aef..cc6691bd84 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -559,7 +559,7 @@ func newIssueCommentAddTestCmd() *cobra.Command {cmd.Flags().Bool("content-stdin", false, "")cmd.Flags().String("content-file", "", "")cmd.Flags().Bool("allow-external-file", false, "")- cmd.Flags().StringSlice("attachment", nil, "")+ cmd.Flags().StringArray("attachment", nil, "")cmd.Flags().String("parent", "", "")cmd.Flags().StringSlice("steer", nil, "")cmd.Flags().Bool("steer-active", false, "")@@ -924,7 +924,7 @@ func newIssueCreateTestCmd() *cobra.Command {cmd.Flags().String("due-date", "", "")cmd.Flags().Bool("allow-duplicate", false, "")cmd.Flags().String("output", "json", "")- cmd.Flags().StringSlice("attachment", nil, "")+ cmd.Flags().StringArray("attachment", nil, "")cmd.Flags().StringSlice("attachment-id", nil, "")cmd.Flags().StringArray("property", nil, "")return cmd@@ -3783,9 +3783,7 @@ func TestRunIssueCreateRejectsInvalidPriorityBeforeRequest(t *testing.T) {}func TestRunIssueUpdateRejectsInvalidStatusBeforeRequest(t *testing.T) {- cmd := &cobra.Command{Use: "update"}- cmd.Flags().String("status", "", "")- cmd.Flags().String("priority", "", "")+ cmd := newIssueUpdateTestCmd()_ = cmd.Flags().Set("status", "not a status")err := runIssueUpdate(cmd, []string{"MUL-1"})if err == nil {@@ -3797,9 +3795,7 @@ func TestRunIssueUpdateRejectsInvalidStatusBeforeRequest(t *testing.T) {}func TestRunIssueUpdateRejectsInvalidPriorityBeforeRequest(t *testing.T) {- cmd := &cobra.Command{Use: "update"}- cmd.Flags().String("status", "", "")- cmd.Flags().String("priority", "", "")+ cmd := newIssueUpdateTestCmd()_ = cmd.Flags().Set("priority", "P1")err := runIssueUpdate(cmd, []string{"MUL-1"})if err == nil {@@ -3817,7 +3813,7 @@ func newIssueUpdateTestCmd() *cobra.Command {cmd.Flags().Bool("description-stdin", false, "")cmd.Flags().String("description-file", "", "")cmd.Flags().Bool("allow-external-file", false, "")- cmd.Flags().StringSlice("attachment", nil, "")+ cmd.Flags().StringArray("attachment", nil, "")cmd.Flags().String("status", "", "")cmd.Flags().String("priority", "", "")cmd.Flags().String("assignee", "", "")