Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(cli): add agent avatar upload command (#1760)
Bright Zhengc2f199650aaf
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 298ce55fd7..1d588bfef8 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -7,6 +7,7 @@ import ("io""net/url""os"+ "path/filepath""strings""time"@@ -68,6 +69,13 @@ var agentTasksCmd = &cobra.Command{RunE: runAgentTasks,}+var agentAvatarCmd = &cobra.Command{+ Use: "avatar <id>",+ Short: "Upload an avatar image for an agent",+ Args: exactArgs(1),+ RunE: runAgentAvatar,+}+// Agent skills subcommands.var agentSkillsCmd = &cobra.Command{@@ -97,6 +105,7 @@ func init() {agentCmd.AddCommand(agentArchiveCmd)agentCmd.AddCommand(agentRestoreCmd)agentCmd.AddCommand(agentTasksCmd)+ agentCmd.AddCommand(agentAvatarCmd)agentCmd.AddCommand(agentSkillsCmd)agentSkillsCmd.AddCommand(agentSkillsListCmd)@@ -149,6 +158,10 @@ func init() {// agent tasksagentTasksCmd.Flags().String("output", "table", "Output format: table or json")+ // agent avatar+ agentAvatarCmd.Flags().String("file", "", "Path to the avatar image file (required)")+ agentAvatarCmd.Flags().String("output", "json", "Output format: table or json")+// agent skills listagentSkillsListCmd.Flags().String("output", "table", "Output format: table or json")@@ -321,13 +334,14 @@ func runAgentGet(cmd *cobra.Command, args []string) error {return cli.PrintJSON(os.Stdout, agent)}- headers := []string{"ID", "NAME", "STATUS", "RUNTIME", "VISIBILITY", "DESCRIPTION"}+ headers := []string{"ID", "NAME", "STATUS", "RUNTIME", "VISIBILITY", "AVATAR_URL", "DESCRIPTION"}rows := [][]string{{strVal(agent, "id"),strVal(agent, "name"),strVal(agent, "status"),strVal(agent, "runtime_mode"),strVal(agent, "visibility"),+ strVal(agent, "avatar_url"),strVal(agent, "description"),}}cli.PrintTable(os.Stdout, headers, rows)@@ -571,6 +585,86 @@ func runAgentTasks(cmd *cobra.Command, args []string) error {return nil}+func runAgentAvatar(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ filePath, _ := cmd.Flags().GetString("file")+ if filePath == "" {+ return fmt.Errorf("--file is required")+ }++ // Validate file exists.+ info, err := os.Stat(filePath)+ if err != nil {+ return fmt.Errorf("file not found: %w", err)+ }++ // Validate extension.+ ext := strings.ToLower(filepath.Ext(filePath))+ validExts := map[string]bool{".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true}+ if !validExts[ext] {+ return fmt.Errorf("unsupported file format %q: must be .png, .jpg, .jpeg, .gif, or .webp", ext)+ }++ // Client-side size guard: reject files > 5MB.+ const maxSize = 5 << 20 // 5 MB+ if info.Size() > maxSize {+ return fmt.Errorf("file too large: %d bytes (max 5MB)", info.Size())+ }++ fileData, err := os.ReadFile(filePath)+ if err != nil {+ return fmt.Errorf("read file: %w", err)+ }++ // Defensive re-check: guard against TOCTOU race where the file+ // was swapped between stat and read.+ if len(fileData) > maxSize {+ return fmt.Errorf("file too large: %d bytes (max 5MB)", len(fileData))+ }++ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ // Agent existence pre-check.+ var agent map[string]any+ if err := client.GetJSON(ctx, "/api/agents/"+args[0], &agent); err != nil {+ return fmt.Errorf("get agent: %w", err)+ }++ id, url, err := client.UploadFileWithURL(ctx, fileData, filePath)+ if err != nil {+ return fmt.Errorf("upload avatar: %w", err)+ }++ body := map[string]any{"avatar_url": url}+ var result map[string]any+ if err := client.PutJSON(ctx, "/api/agents/"+args[0], body, &result); err != nil {+ return fmt.Errorf("update agent avatar: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, map[string]any{+ "id": id,+ "agent_id": args[0],+ "avatar_url": url,+ })+ }++ headers := []string{"ID", "AGENT_ID", "AVATAR_URL"}+ rows := [][]string{{+ id,+ args[0],+ url,+ }}+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}+// ---------------------------------------------------------------------------// Agent skills subcommands// ---------------------------------------------------------------------------diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.goindex 95459d47a9..f92c00c484 100644--- a/server/cmd/multica/cmd_agent_test.go+++ b/server/cmd/multica/cmd_agent_test.go@@ -2,6 +2,10 @@ package mainimport ("bytes"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest""os""path/filepath""reflect"@@ -490,3 +494,438 @@ func TestResolveCustomEnv(t *testing.T) {}})}++// TestAgentAvatarHappyPath verifies the full flow: agent pre-check, file upload,+// and avatar update all succeed.+func TestAgentAvatarHappyPath(t *testing.T) {+ dir := t.TempDir()+ pngPath := filepath.Join(dir, "avatar.png")+ if err := os.WriteFile(pngPath, []byte("fake-png-data"), 0o644); err != nil {+ t.Fatalf("write test png: %v", err)+ }++ var gotPaths []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPaths = append(gotPaths, r.URL.Path)+ switch r.URL.Path {+ case "/api/agents/agent-123":+ if r.Method == http.MethodGet {+ json.NewEncoder(w).Encode(map[string]any{+ "id": "agent-123",+ "name": "TestAgent",+ })+ } else if r.Method == http.MethodPut {+ var body map[string]any+ json.NewDecoder(r.Body).Decode(&body)+ if body["avatar_url"] != "https://cdn.example.com/avatars/agent-123.png" {+ t.Errorf("unexpected avatar_url: %v", body["avatar_url"])+ }+ json.NewEncoder(w).Encode(map[string]any{+ "id": "agent-123",+ "name": "TestAgent",+ "avatar_url": "https://cdn.example.com/avatars/agent-123.png",+ })+ } else {+ t.Errorf("unexpected method: %s", r.Method)+ }+ case "/api/upload-file":+ if r.Method != http.MethodPost {+ t.Errorf("expected POST, got %s", r.Method)+ }+ json.NewEncoder(w).Encode(map[string]any{+ "id": "att-456",+ "url": "https://cdn.example.com/avatars/agent-123.png",+ })+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", pngPath); err != nil {+ t.Fatal(err)+ }++ if err := runAgentAvatar(cmd, []string{"agent-123"}); err != nil {+ t.Fatalf("runAgentAvatar: %v", err)+ }++ if len(gotPaths) != 3 {+ t.Fatalf("expected 3 API calls, got %d: %v", len(gotPaths), gotPaths)+ }+}++// TestAgentAvatarUnsupportedFormat rejects files with unsupported extensions.+func TestAgentAvatarUnsupportedFormat(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ dir := t.TempDir()+ txtPath := filepath.Join(dir, "avatar.txt")+ if err := os.WriteFile(txtPath, []byte("not an image"), 0o644); err != nil {+ t.Fatalf("write test txt: %v", err)+ }++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", txtPath); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error for unsupported format, got nil")+ }+ if !strings.Contains(err.Error(), "unsupported file format") {+ t.Fatalf("expected 'unsupported file format' error, got: %v", err)+ }+}++// TestAgentAvatarOversizedFile rejects files larger than 5MB.+func TestAgentAvatarOversizedFile(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ dir := t.TempDir()+ bigPath := filepath.Join(dir, "big.png")+ // Write slightly more than 5MB.+ if err := os.WriteFile(bigPath, make([]byte, 5<<20+1), 0o644); err != nil {+ t.Fatalf("write test file: %v", err)+ }++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", bigPath); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error for oversized file, got nil")+ }+ if !strings.Contains(err.Error(), "file too large") {+ t.Fatalf("expected 'file too large' error, got: %v", err)+ }+}++// TestAgentAvatarMissingAgent returns 404 when the agent does not exist.+func TestAgentAvatarMissingAgent(t *testing.T) {+ dir := t.TempDir()+ pngPath := filepath.Join(dir, "avatar.png")+ if err := os.WriteFile(pngPath, []byte("fake-png-data"), 0o644); err != nil {+ t.Fatalf("write test png: %v", err)+ }++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/api/agents/missing-agent" {+ w.WriteHeader(http.StatusNotFound)+ io.WriteString(w, "agent not found")+ return+ }+ http.NotFound(w, r)+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", pngPath); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"missing-agent"})+ if err == nil {+ t.Fatal("expected error for missing agent, got nil")+ }+ if !strings.Contains(err.Error(), "get agent") {+ t.Fatalf("expected 'get agent' error, got: %v", err)+ }+}++// TestAgentAvatarUploadFailure handles upload endpoint returning an error.+func TestAgentAvatarUploadFailure(t *testing.T) {+ dir := t.TempDir()+ pngPath := filepath.Join(dir, "avatar.png")+ if err := os.WriteFile(pngPath, []byte("fake-png-data"), 0o644); err != nil {+ t.Fatalf("write test png: %v", err)+ }++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/agents/agent-123":+ json.NewEncoder(w).Encode(map[string]any{"id": "agent-123", "name": "TestAgent"})+ case "/api/upload-file":+ w.WriteHeader(http.StatusInternalServerError)+ io.WriteString(w, "upload failed")+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", pngPath); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error for upload failure, got nil")+ }+ if !strings.Contains(err.Error(), "upload avatar") {+ t.Fatalf("expected 'upload avatar' error, got: %v", err)+ }+}++// TestAgentAvatarUpdateFailure handles the PUT update endpoint returning an error.+func TestAgentAvatarUpdateFailure(t *testing.T) {+ dir := t.TempDir()+ pngPath := filepath.Join(dir, "avatar.png")+ if err := os.WriteFile(pngPath, []byte("fake-png-data"), 0o644); err != nil {+ t.Fatalf("write test png: %v", err)+ }++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/agents/agent-123":+ if r.Method == http.MethodPut {+ w.WriteHeader(http.StatusForbidden)+ io.WriteString(w, "forbidden")+ return+ }+ json.NewEncoder(w).Encode(map[string]any{"id": "agent-123", "name": "TestAgent"})+ case "/api/upload-file":+ json.NewEncoder(w).Encode(map[string]any{+ "id": "att-456",+ "url": "https://cdn.example.com/avatars/agent-123.png",+ })+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", pngPath); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error for update failure, got nil")+ }+ if !strings.Contains(err.Error(), "update agent avatar") {+ t.Fatalf("expected 'update agent avatar' error, got: %v", err)+ }+}+++// TestAgentAvatarMissingFileFlag rejects when --file is not provided.+func TestAgentAvatarMissingFileFlag(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error when --file is missing, got nil")+ }+ if !strings.Contains(err.Error(), "--file is required") {+ t.Fatalf("expected '--file is required' error, got: %v", err)+ }+}++// TestAgentAvatarNonexistentFile rejects when the file path does not exist.+func TestAgentAvatarNonexistentFile(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", filepath.Join(t.TempDir(), "does-not-exist.png")); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error for non-existent file, got nil")+ }+ if !strings.Contains(err.Error(), "file not found") {+ t.Fatalf("expected 'file not found' error, got: %v", err)+ }+}++// TestAgentAvatarSizeBoundary verifies that exactly 5MB passes and 5MB+1 fails.+func TestAgentAvatarSizeBoundary(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ t.Run("exactly 5MB passes", func(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "ok.png")+ if err := os.WriteFile(path, make([]byte, 5<<20), 0o644); err != nil {+ t.Fatalf("write test file: %v", err)+ }++ // The command will fail later because no server is running, but+ // the size validation itself should pass.+ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", path); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ // We expect an error from the network call, not from size validation.+ if err != nil && strings.Contains(err.Error(), "file too large") {+ t.Fatalf("size validation should pass for exactly-5MB file, got: %v", err)+ }+ })++ t.Run("5MB plus one byte is rejected", func(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "big.png")+ if err := os.WriteFile(path, make([]byte, 5<<20+1), 0o644); err != nil {+ t.Fatalf("write test file: %v", err)+ }++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", path); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ if err == nil {+ t.Fatal("expected error for 5MB+1 file, got nil")+ }+ if !strings.Contains(err.Error(), "file too large") {+ t.Fatalf("expected 'file too large' error, got: %v", err)+ }+ })+}++// TestAgentAvatarCaseInsensitiveExtension verifies uppercase extensions are accepted.+func TestAgentAvatarCaseInsensitiveExtension(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ for _, ext := range []string{"avatar.PNG", "avatar.JPG", "avatar.JPEG", "avatar.GIF", "avatar.WEBP"} {+ t.Run(ext, func(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, ext)+ if err := os.WriteFile(path, []byte("fake"), 0o644); err != nil {+ t.Fatalf("write test file: %v", err)+ }++ cmd := &cobra.Command{Use: "avatar"}+ cmd.Flags().String("file", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("file", path); err != nil {+ t.Fatal(err)+ }++ err := runAgentAvatar(cmd, []string{"agent-123"})+ // We expect an error from the network call, not from extension validation.+ if err != nil && strings.Contains(err.Error(), "unsupported file format") {+ t.Fatalf("extension validation should pass for %s, got: %v", ext, err)+ }+ })+ }+}++// TestAgentGetTableIncludesAvatarURL verifies the table output includes AVATAR_URL.+func TestAgentGetTableIncludesAvatarURL(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/agents/agent-123" {+ t.Errorf("unexpected path: %s", r.URL.Path)+ }+ json.NewEncoder(w).Encode(map[string]any{+ "id": "agent-123",+ "name": "TestAgent",+ "status": "active",+ "runtime_mode": "cloud",+ "visibility": "workspace",+ "avatar_url": "https://cdn.example.com/avatar.png",+ "description": "A test agent",+ })+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := &cobra.Command{Use: "get"}+ cmd.Flags().String("output", "table", "")+ cmd.Flags().String("profile", "", "")++ // Capture stdout.+ old := os.Stdout+ r, w, _ := os.Pipe()+ os.Stdout = w++ err := runAgentGet(cmd, []string{"agent-123"})++ w.Close()+ os.Stdout = old+ out, _ := io.ReadAll(r)++ if err != nil {+ t.Fatalf("runAgentGet: %v", err)+ }+ if !strings.Contains(string(out), "AVATAR_URL") {+ t.Fatalf("table output missing AVATAR_URL header: %s", string(out))+ }+ if !strings.Contains(string(out), "https://cdn.example.com/avatar.png") {+ t.Fatalf("table output missing avatar_url value: %s", string(out))+ }+}diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex fd39acf2eb..0091ecd3e9 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -269,6 +269,17 @@ func (c *APIClient) PatchJSON(ctx context.Context, path string, body any, out anreturn json.NewDecoder(resp.Body).Decode(out)}+// AttachmentResponse mirrors the server's upload-file response.+type AttachmentResponse struct {+ ID string `json:"id"`+ URL string `json:"url"`+ DownloadURL string `json:"download_url"`+ Filename string `json:"filename"`+ ContentType string `json:"content_type"`+ SizeBytes int64 `json:"size_bytes"`+ CreatedAt string `json:"created_at"`+}+// 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) {@@ -323,6 +334,69 @@ func (c *APIClient) UploadFile(ctx context.Context, fileData []byte, filename streturn id, nil}+// UploadFileWithURL uploads a file via multipart form to /api/upload-file+// without associating it with an issue or comment. It decodes the full+// AttachmentResponse and returns the attachment ID and URL.+func (c *APIClient) UploadFileWithURL(ctx context.Context, fileData []byte, filename string) (string, string, error) {+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)++ part, err := writer.CreateFormFile("file", filepath.Base(filename))+ if err != nil {+ return "", "", fmt.Errorf("create form file: %w", err)+ }+ if _, err := part.Write(fileData); err != nil {+ return "", "", fmt.Errorf("write file data: %w", err)+ }++ if err := writer.Close(); err != nil {+ return "", "", 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+ }+ req.Header.Set("Content-Type", writer.FormDataContentType())+ c.setHeaders(req)++ // Use a client that respects the context deadline for slow uploads+ // (e.g. avatar uploads with 5MB files). The default 15s HTTP client+ // timeout shadows any longer context deadline.+ 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)+ if err != nil {+ return "", "", err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ respData, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ return "", "", fmt.Errorf("upload file returned %d: %s", resp.StatusCode, strings.TrimSpace(string(respData)))+ }++ var result AttachmentResponse+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return "", "", fmt.Errorf("decode upload response: %w", err)+ }+ if result.URL == "" {+ return "", "", fmt.Errorf("upload response missing attachment url")+ }+ // Allow empty ID: the server returns id="" in the fallback path where+ // S3 upload succeeded but the attachment DB record failed. The file+ // is still usable via its URL.+ return result.ID, result.URL, nil+}+// DownloadFile downloads a file from the given URL and returns the response body.// This is used for downloading attachments via their signed download_url.// Downloads are limited to 100 MB to match the upload size limit.diff --git a/server/internal/cli/client_test.go b/server/internal/cli/client_test.goindex 6248f44559..5e96efccf4 100644--- a/server/internal/cli/client_test.go+++ b/server/internal/cli/client_test.go@@ -6,6 +6,7 @@ import ("io""net/http""net/http/httptest"+ "strings""testing")@@ -234,6 +235,135 @@ func TestDownloadFile(t *testing.T) {})}+func TestUploadFileWithURL(t *testing.T) {+ t.Run("success", func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("expected POST, got %s", r.Method)+ }+ if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "multipart/form-data") {+ t.Errorf("expected multipart content-type, got %s", ct)+ }++ file, header, err := r.FormFile("file")+ if err != nil {+ t.Fatalf("missing file field: %v", err)+ }+ defer file.Close()++ data, _ := io.ReadAll(file)+ if string(data) != "hello" {+ t.Errorf("unexpected file data: %q", string(data))+ }+ if header.Filename != "test.txt" {+ t.Errorf("unexpected filename: %q", header.Filename)+ }++ // Verify no issue_id or comment_id fields are sent.+ if r.FormValue("issue_id") != "" {+ t.Errorf("unexpected issue_id field")+ }+ if r.FormValue("comment_id") != "" {+ t.Errorf("unexpected comment_id field")+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(AttachmentResponse{+ ID: "att-123",+ URL: "https://cdn.example.com/file.txt",+ Filename: "test.txt",+ SizeBytes: 5,+ })+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "ws-1", "test-token")+ id, url, err := client.UploadFileWithURL(context.Background(), []byte("hello"), "test.txt")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if id != "att-123" {+ t.Errorf("expected id att-123, got %s", id)+ }+ if url != "https://cdn.example.com/file.txt" {+ t.Errorf("expected url https://cdn.example.com/file.txt, got %s", url)+ }+ })++ t.Run("error status", func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusBadRequest)+ io.WriteString(w, "bad request")+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "", "")+ _, _, err := client.UploadFileWithURL(context.Background(), []byte("x"), "x.txt")+ if err == nil {+ t.Fatal("expected error, got nil")+ }+ if !strings.Contains(err.Error(), "upload file returned 400") {+ t.Errorf("unexpected error message: %s", err.Error())+ }+ })++ t.Run("missing id in response succeeds (fallback path)", func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]string{"url": "https://example.com"})+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "", "")+ id, url, err := client.UploadFileWithURL(context.Background(), []byte("x"), "x.txt")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if id != "" {+ t.Errorf("expected empty id, got %s", id)+ }+ if url != "https://example.com" {+ t.Errorf("expected url https://example.com, got %s", url)+ }+ })++ t.Run("workspace header sent", func(t *testing.T) {+ var gotWorkspace string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotWorkspace = r.Header.Get("X-Workspace-ID")+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(AttachmentResponse{ID: "att-1", URL: "https://example.com"})+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "ws-abc", "test-token")+ _, _, err := client.UploadFileWithURL(context.Background(), []byte("x"), "x.txt")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if gotWorkspace != "ws-abc" {+ t.Errorf("expected X-Workspace-ID ws-abc, got %s", gotWorkspace)+ }+ })++ t.Run("missing url in response", func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(AttachmentResponse{ID: "att-123"})+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "", "")+ _, _, err := client.UploadFileWithURL(context.Background(), []byte("x"), "x.txt")+ if err == nil {+ t.Fatal("expected error, got nil")+ }+ if !strings.Contains(err.Error(), "missing attachment url") {+ t.Errorf("unexpected error message: %s", err.Error())+ }+ })+}+func TestNormalizeGOOS(t *testing.T) {cases := map[string]string{"darwin": "macos",diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 06c4ad2f71..6220b7a1f6 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -234,8 +234,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {}writeJSON(w, http.StatusOK, map[string]string{+ "id": "",+ "url": link,"filename": header.Filename,- "link": link,})return}@@ -248,8 +249,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {return}writeJSON(w, http.StatusOK, map[string]string{+ "id": id.String(),+ "url": link,"filename": header.Filename,- "link": link,})}