Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(cli): central error translation layer (PR1, MUL-3104) (#3892)
LinYushen28de8b8bdead
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex e9b5a2fb7d..87e6d63edc 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -337,7 +337,7 @@ func runAgentList(cmd *cobra.Command, _ []string) error {}}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var agents []map[string]any@@ -384,7 +384,7 @@ func runAgentGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var agent map[string]any@@ -475,7 +475,7 @@ func runAgentCreate(cmd *cobra.Command, _ []string) error {body["max_concurrent_tasks"] = v}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -557,7 +557,7 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {return fmt.Errorf("no fields to update; use --name, --description, --instructions, --runtime-id, --runtime-config, --model, --custom-args, --mcp-config, --visibility, --status, or --max-concurrent-tasks (env vars now live behind `multica agent env set <id>`)")}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -580,7 +580,7 @@ func runAgentArchive(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -603,7 +603,7 @@ func runAgentRestore(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -626,7 +626,7 @@ func runAgentTasks(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var tasks []map[string]any@@ -694,7 +694,7 @@ func runAgentAvatar(cmd *cobra.Command, args []string) error {return fmt.Errorf("file too large: %d bytes (max 5MB)", len(fileData))}- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))defer cancel()// Agent existence pre-check.@@ -743,7 +743,7 @@ func runAgentSkillsList(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var skills []map[string]any@@ -783,7 +783,7 @@ func runAgentSkillsSet(cmd *cobra.Command, args []string) error {"skill_ids": cleanIDs,}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result json.RawMessage@@ -811,7 +811,7 @@ func runAgentSkillsAdd(cmd *cobra.Command, args []string) error {"skill_ids": cleanIDs,}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result json.RawMessage@@ -877,7 +877,7 @@ func runAgentEnvGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var resp map[string]any@@ -922,7 +922,7 @@ func runAgentEnvSet(cmd *cobra.Command, args []string) error {body := map[string]any{"custom_env": ce}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]anydiff --git a/server/cmd/multica/cmd_attachment.go b/server/cmd/multica/cmd_attachment.goindex 0280d729c4..8466880af3 100644--- a/server/cmd/multica/cmd_attachment.go+++ b/server/cmd/multica/cmd_attachment.go@@ -26,8 +26,8 @@ var attachmentDownloadCmd = &cobra.Command{# Download to a specific directory$ multica attachment download abc123 -o /tmp/images`,- Args: exactArgs(1),- RunE: runAttachmentDownload,+ Args: exactArgs(1),+ RunE: runAttachmentDownload,}func init() {@@ -42,7 +42,7 @@ func runAttachmentDownload(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))defer cancel()// Fetch attachment metadata (includes signed download_url).diff --git a/server/cmd/multica/cmd_auth.go b/server/cmd/multica/cmd_auth.goindex d0cf1390a0..1681934902 100644--- a/server/cmd/multica/cmd_auth.go+++ b/server/cmd/multica/cmd_auth.go@@ -300,7 +300,7 @@ func runAuthLoginBrowser(cmd *cobra.Command) error {// Use the JWT to create a PAT via the existing API.client := cli.NewAPIClient(serverURL, "", jwtToken)- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()hostname, _ := os.Hostname()@@ -373,7 +373,7 @@ func runAuthLoginToken(cmd *cobra.Command, providedToken string) error {serverURL := resolveServerURL(cmd)client := cli.NewAPIClient(serverURL, "", token)- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var me struct {@@ -408,7 +408,7 @@ func runAuthStatus(cmd *cobra.Command, _ []string) error {client := cli.NewAPIClient(serverURL, "", token)- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var me struct {diff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.goindex 5950d3a4ec..671ebec95f 100644--- a/server/cmd/multica/cmd_autopilot.go+++ b/server/cmd/multica/cmd_autopilot.go@@ -180,7 +180,7 @@ func runAutopilotList(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()path := "/api/autopilots"@@ -225,7 +225,7 @@ func runAutopilotGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -283,7 +283,7 @@ func runAutopilotCreate(cmd *cobra.Command, _ []string) error {return fmt.Errorf("--mode must be create_issue or run_only")}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()agentID, err := resolveAgent(ctx, client, agent)@@ -333,7 +333,7 @@ func runAutopilotUpdate(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -413,7 +413,7 @@ func runAutopilotDelete(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -434,7 +434,7 @@ func runAutopilotTrigger(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(30*time.Second))defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -461,7 +461,7 @@ func runAutopilotRuns(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -547,7 +547,7 @@ func runAutopilotTriggerAdd(cmd *cobra.Command, args []string) error {body["label"] = v}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -591,7 +591,7 @@ func runAutopilotTriggerRotateURL(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -661,7 +661,7 @@ func runAutopilotTriggerUpdate(cmd *cobra.Command, args []string) error {return fmt.Errorf("no fields to update; use --enabled, --cron, --timezone, or --label")}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])@@ -693,7 +693,7 @@ func runAutopilotTriggerDelete(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()autopilotRef, err := resolveAutopilotID(ctx, client, args[0])diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 8bba66852b..5062e54079 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -383,7 +383,7 @@ func runIssueList(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()if client.WorkspaceID == "" {@@ -510,7 +510,7 @@ func runIssuePullRequests(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -572,7 +572,7 @@ func runIssueGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -636,10 +636,10 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {}// Use a longer timeout when attachments are present (file uploads can be slow).- timeout := 15 * time.Second+ timeout := cli.APITimeout()attachments, _ := cmd.Flags().GetStringSlice("attachment")if len(attachments) > 0 {- timeout = 60 * time.Second+ timeout = cli.AtLeastAPITimeout(60 * time.Second)}ctx, cancel := context.WithTimeout(context.Background(), timeout)defer cancel()@@ -794,7 +794,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -908,7 +908,7 @@ func runIssueAssign(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -971,7 +971,7 @@ func runIssueStatus(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, id)@@ -1004,7 +1004,7 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -1164,10 +1164,10 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {}// Use a longer timeout when attachments are present (file uploads can be slow).- timeout := 15 * time.Second+ timeout := cli.APITimeout()attachments, _ := cmd.Flags().GetStringSlice("attachment")if len(attachments) > 0 {- timeout = 60 * time.Second+ timeout = cli.AtLeastAPITimeout(60 * time.Second)}ctx, cancel := context.WithTimeout(context.Background(), timeout)defer cancel()@@ -1229,7 +1229,7 @@ func runIssueCommentDelete(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()if err := client.DeleteJSON(ctx, "/api/comments/"+args[0]); err != nil {@@ -1250,7 +1250,7 @@ func runIssueRuns(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -1305,7 +1305,7 @@ func runIssueRunMessages(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueID := ""@@ -1372,7 +1372,7 @@ func runIssueRerun(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -1405,7 +1405,7 @@ func runIssueCancelTask(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueScope := ""@@ -1445,7 +1445,7 @@ func runIssueSearch(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()params := url.Values{}@@ -1507,7 +1507,7 @@ func runIssueSubscriberList(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -1559,7 +1559,7 @@ func runIssueSubscriberMutation(cmd *cobra.Command, issueID, action string) erroreturn err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, issueID)diff --git a/server/cmd/multica/cmd_issue_label.go b/server/cmd/multica/cmd_issue_label.goindex 8d989a7206..edad673bc9 100644--- a/server/cmd/multica/cmd_issue_label.go+++ b/server/cmd/multica/cmd_issue_label.go@@ -4,7 +4,6 @@ import ("context""fmt""os"- "time""github.com/spf13/cobra"@@ -61,7 +60,7 @@ func runIssueLabelList(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -89,7 +88,7 @@ func runIssueLabelAdd(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -122,7 +121,7 @@ func runIssueLabelRemove(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])diff --git a/server/cmd/multica/cmd_issue_metadata.go b/server/cmd/multica/cmd_issue_metadata.goindex 467c80b78e..e97acaeb10 100644--- a/server/cmd/multica/cmd_issue_metadata.go+++ b/server/cmd/multica/cmd_issue_metadata.go@@ -10,7 +10,6 @@ import ("sort""strconv""strings"- "time""github.com/spf13/cobra"@@ -170,7 +169,7 @@ func runIssueMetadataList(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -221,7 +220,7 @@ func runIssueMetadataGet(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -268,7 +267,7 @@ func runIssueMetadataSet(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])@@ -302,7 +301,7 @@ func runIssueMetadataDelete(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, args[0])diff --git a/server/cmd/multica/cmd_label.go b/server/cmd/multica/cmd_label.goindex 34c710b9f5..a6dcb69a4e 100644--- a/server/cmd/multica/cmd_label.go+++ b/server/cmd/multica/cmd_label.go@@ -5,7 +5,6 @@ import ("fmt""net/url""os"- "time""github.com/spf13/cobra"@@ -81,7 +80,7 @@ func runLabelList(cmd *cobra.Command, _ []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()params := url.Values{}@@ -132,7 +131,7 @@ func runLabelGet(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()labelRef, err := resolveLabelID(ctx, client, args[0])@@ -178,7 +177,7 @@ func runLabelCreate(cmd *cobra.Command, _ []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()body := map[string]any{"name": name, "color": color}@@ -206,7 +205,7 @@ func runLabelUpdate(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()labelRef, err := resolveLabelID(ctx, client, args[0])@@ -249,7 +248,7 @@ func runLabelDelete(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()labelRef, err := resolveLabelID(ctx, client, args[0])diff --git a/server/cmd/multica/cmd_login.go b/server/cmd/multica/cmd_login.goindex db26c46f5c..ad02de2571 100644--- a/server/cmd/multica/cmd_login.go+++ b/server/cmd/multica/cmd_login.go@@ -80,7 +80,7 @@ func autoWatchWorkspaces(cmd *cobra.Command) error {}client := cli.NewAPIClient(serverURL, "", token)- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var workspaces []struct {@@ -162,10 +162,17 @@ func waitForWorkspaceCreation(cmd *cobra.Command, client *cli.APIClient) ([]struconst pollTimeout = 5 * time.Minutedeadline := time.Now().Add(pollTimeout)+ // Per-poll request budget. We keep a short 10s floor so the loop stays+ // responsive (a hung request shouldn't block a single iteration for long),+ // but it still honors MULTICA_HTTP_TIMEOUT via AtLeastAPITimeout so a user+ // who raised the timeout for a slow network isn't capped below it. The+ // overall wait is bounded by pollTimeout regardless.+ pollRequestTimeout := cli.AtLeastAPITimeout(10 * time.Second)+for time.Now().Before(deadline) {time.Sleep(pollInterval)- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), pollRequestTimeout)var workspaces []struct {ID string `json:"id"`Name string `json:"name"`diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.goindex 94b113ec5b..47ac456004 100644--- a/server/cmd/multica/cmd_project.go+++ b/server/cmd/multica/cmd_project.go@@ -7,7 +7,6 @@ import ("net/url""os""strings"- "time""github.com/spf13/cobra"@@ -185,7 +184,7 @@ func runProjectList(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()params := url.Values{}@@ -245,7 +244,7 @@ func runProjectGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])@@ -296,7 +295,7 @@ func runProjectCreate(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()body := map[string]any{"title": title}@@ -365,7 +364,7 @@ func runProjectUpdate(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])@@ -430,7 +429,7 @@ func runProjectDelete(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])@@ -466,7 +465,7 @@ func runProjectStatus(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, id)@@ -499,7 +498,7 @@ func runProjectResourceList(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])@@ -595,7 +594,7 @@ func runProjectResourceAdd(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])@@ -628,7 +627,7 @@ func runProjectResourceUpdate(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])@@ -839,7 +838,7 @@ func runProjectResourceRemove(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()projectRef, err := resolveProjectID(ctx, client, args[0])diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.goindex 0bfb951803..baa27d0734 100644--- a/server/cmd/multica/cmd_runtime.go+++ b/server/cmd/multica/cmd_runtime.go@@ -75,7 +75,7 @@ func runRuntimeList(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var runtimes []map[string]any@@ -115,7 +115,7 @@ func runRuntimeUsage(cmd *cobra.Command, args []string) error {return fmt.Errorf("--days must be between 1 and 365")}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var usage []map[string]any@@ -152,7 +152,7 @@ func runRuntimeActivity(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var activity []map[string]any@@ -188,7 +188,7 @@ func runRuntimeUpdate(cmd *cobra.Command, args []string) error {return fmt.Errorf("--target-version is required")}- ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(150*time.Second))defer cancel()body := map[string]any{diff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.goindex 0c17123e13..c6b08fcf50 100644--- a/server/cmd/multica/cmd_skill.go+++ b/server/cmd/multica/cmd_skill.go@@ -221,7 +221,7 @@ func runSkillList(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var skills []map[string]any@@ -254,7 +254,7 @@ func runSkillGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var skill map[string]any@@ -311,7 +311,7 @@ func runSkillCreate(cmd *cobra.Command, _ []string) error {body["config"] = config}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -363,7 +363,7 @@ func runSkillUpdate(cmd *cobra.Command, args []string) error {return fmt.Errorf("no fields to update; use --name, --description, --content, or --config")}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -398,7 +398,7 @@ func runSkillDelete(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()if err := client.DeleteJSON(ctx, "/api/skills/"+args[0]); err != nil {@@ -424,7 +424,7 @@ func runSkillImport(cmd *cobra.Command, _ []string) error {"url": importURL,}- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))defer cancel()var result map[string]any@@ -480,7 +480,7 @@ func runSkillSearch(cmd *cobra.Command, args []string) error {return fmt.Errorf("query is required")}- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))defer cancel()var results []map[string]any@@ -519,7 +519,7 @@ func runSkillFilesList(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var files []map[string]any@@ -569,7 +569,7 @@ func runSkillFilesUpsert(cmd *cobra.Command, args []string) error {"content": content,}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var result map[string]any@@ -592,7 +592,7 @@ func runSkillFilesDelete(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()if err := client.DeleteJSON(ctx, "/api/skills/"+args[0]+"/files/"+args[1]); err != nil {diff --git a/server/cmd/multica/cmd_squad.go b/server/cmd/multica/cmd_squad.goindex e081ccf50e..1be625b0f5 100644--- a/server/cmd/multica/cmd_squad.go+++ b/server/cmd/multica/cmd_squad.go@@ -6,7 +6,6 @@ import ("os""strconv""text/tabwriter"- "time""github.com/spf13/cobra"@@ -32,7 +31,7 @@ func runSquadList(cmd *cobra.Command, _ []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var squads []map[string]any@@ -86,7 +85,7 @@ func runSquadGet(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var squad map[string]any@@ -133,7 +132,7 @@ func runSquadCreate(cmd *cobra.Command, _ []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()leaderID, err := resolveAgent(ctx, client, leader)@@ -176,7 +175,7 @@ func runSquadUpdate(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()body := map[string]any{}@@ -236,7 +235,7 @@ func runSquadDelete(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()if err := client.DeleteJSON(ctx, "/api/squads/"+args[0]); err != nil {@@ -270,7 +269,7 @@ func runSquadMemberList(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var members []map[string]any@@ -322,7 +321,7 @@ func runSquadMemberAdd(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()body := map[string]any{@@ -372,7 +371,7 @@ func runSquadMemberSetRole(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()body := map[string]any{@@ -418,7 +417,7 @@ func runSquadMemberRemove(cmd *cobra.Command, args []string) error {if err != nil {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()body := map[string]any{@@ -471,7 +470,7 @@ func runSquadActivity(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()issueRef, err := resolveIssueRef(ctx, client, issueID)diff --git a/server/cmd/multica/cmd_user.go b/server/cmd/multica/cmd_user.goindex 16fb3fb4f2..efd0ca3f15 100644--- a/server/cmd/multica/cmd_user.go+++ b/server/cmd/multica/cmd_user.go@@ -5,7 +5,6 @@ import ("fmt""os""text/tabwriter"- "time""github.com/spf13/cobra"@@ -70,7 +69,7 @@ func runUserProfileGet(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var me map[string]any@@ -116,7 +115,7 @@ func runUserProfileUpdate(cmd *cobra.Command, _ []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var me map[string]anydiff --git a/server/cmd/multica/cmd_workspace.go b/server/cmd/multica/cmd_workspace.goindex faf9991ee0..573844a774 100644--- a/server/cmd/multica/cmd_workspace.go+++ b/server/cmd/multica/cmd_workspace.go@@ -6,7 +6,6 @@ import ("os""strings""text/tabwriter"- "time""unicode/utf8""github.com/spf13/cobra"@@ -120,7 +119,7 @@ func fetchWorkspaces(ctx context.Context, cmd *cobra.Command) ([]workspaceSummar}func runWorkspaceList(cmd *cobra.Command, _ []string) error {- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()workspaces, err := fetchWorkspaces(ctx, cmd)@@ -242,7 +241,7 @@ func resolveWorkspaceRef(ctx context.Context, cmd *cobra.Command, input string)}func runWorkspaceSwitch(cmd *cobra.Command, args []string) error {- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()ws, err := resolveWorkspaceRef(ctx, cmd, args[0])@@ -277,7 +276,7 @@ func resolveWorkspaceArg(cmd *cobra.Command, args []string) (string, error) {if uuidRegexp.MatchString(trimmed) {return trimmed, nil}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()ws, err := resolveWorkspaceRef(ctx, cmd, trimmed)if err != nil {@@ -302,7 +301,7 @@ func runWorkspaceGet(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var ws map[string]any@@ -396,7 +395,7 @@ func runWorkspaceUpdate(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var ws map[string]any@@ -445,7 +444,7 @@ func runWorkspaceMembers(cmd *cobra.Command, args []string) error {return err}- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ ctx, cancel := cli.APIContext(context.Background())defer cancel()var members []map[string]anydiff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 4297503a20..6d4169ce96 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -16,10 +16,15 @@ var (date = "unknown")+// debugFlag is bound to the persistent --debug flag and, when set, makes+// FormatError emit the full original error chain instead of just the+// user-facing message.+var debugFlag bool+var rootCmd = &cobra.Command{- Use: "multica",- Short: "Multica CLI — local agent runtime and management tool",- Long: "Work seamlessly with Multica from the command line.",+ Use: "multica",+ Short: "Multica CLI — local agent runtime and management tool",+ Long: "Work seamlessly with Multica from the command line.",SilenceUsage: true,SilenceErrors: true,}@@ -35,6 +40,7 @@ func init() {rootCmd.PersistentFlags().String("server-url", "", "Multica server URL (env: MULTICA_SERVER_URL)")rootCmd.PersistentFlags().String("workspace-id", "", "Workspace ID (env: MULTICA_WORKSPACE_ID)")rootCmd.PersistentFlags().String("profile", "", "Configuration profile name (e.g. dev) — isolates config, daemon state, and workspaces")+ rootCmd.PersistentFlags().BoolVar(&debugFlag, "debug", false, "Print full error details on failure (env: MULTICA_DEBUG)")// Core commandsissueCmd.GroupID = groupCore@@ -88,8 +94,8 @@ func main() {cli.CleanupStaleUpdateArtifacts()if err := rootCmd.Execute(); err != nil {if err != errSilent {- fmt.Fprintln(os.Stderr, "Error:", err)+ fmt.Fprintln(os.Stderr, cli.FormatError(err, debugFlag))}- os.Exit(1)+ os.Exit(cli.ExitCodeFor(err))}}diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex 923921d765..07450882d2 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -8,8 +8,10 @@ import ("io""mime/multipart""net/http"+ "os""path/filepath""runtime"+ "strconv""strings""time")@@ -70,13 +72,92 @@ func (e *HTTPError) Error() string {return fmt.Sprintf("%s %s returned %d: %s", e.Method, e.Path, e.StatusCode, strings.TrimSpace(e.Body))}+// newHTTPError builds a *HTTPError from an error response (status >= 400),+// reading a capped slice of the body. Every Multica API helper funnels its+// >= 400 responses through this so the top-level FormatError / ExitCodeFor can+// classify the failure via errors.As(err, **HTTPError) regardless of which+// HTTP verb the command used.+func newHTTPError(method, path string, resp *http.Response) *HTTPError {+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ return &HTTPError{+ Method: method,+ Path: path,+ StatusCode: resp.StatusCode,+ Body: strings.TrimSpace(string(data)),+ }+}++// defaultHTTPTimeout is the per-request timeout for the CLI's HTTP client.+// It can be overridden with the MULTICA_HTTP_TIMEOUT environment variable+// (see httpTimeout). 30s is chosen over the historical 15s because complex+// networks (notably in mainland China) routinely need more than 15s to+// complete the TLS handshake plus request round-trip, which surfaced as an+// opaque "context deadline exceeded" to users.+const defaultHTTPTimeout = 30 * time.Second++// httpTimeout returns the HTTP client timeout, honoring MULTICA_HTTP_TIMEOUT.+// The value may be a Go duration string ("45s", "2m") or a plain integer+// number of seconds ("45"). Invalid or non-positive values fall back to the+// default.+func httpTimeout() time.Duration {+ v := strings.TrimSpace(os.Getenv("MULTICA_HTTP_TIMEOUT"))+ if v == "" {+ return defaultHTTPTimeout+ }+ if d, err := time.ParseDuration(v); err == nil && d > 0 {+ return d+ }+ if secs, err := strconv.Atoi(v); err == nil && secs > 0 {+ return time.Duration(secs) * time.Second+ }+ return defaultHTTPTimeout+}++// apiContextGrace is added on top of the HTTP transport timeout when deriving+// a command-level context deadline, so the transport timeout (which produces a+// clean, classifiable "request timed out" error) is the one that fires rather+// than the outer context being canceled first.+const apiContextGrace = 5 * time.Second++// APITimeout returns the deadline budget for a single CLI API command. It is+// always at least the configured HTTP transport timeout (see httpTimeout,+// which honors MULTICA_HTTP_TIMEOUT) plus a small grace margin, so a+// command-level context never truncates an in-flight request below the timeout+// the user configured. This is the fix for command contexts that previously+// hardcoded a 15s deadline shorter than the 30s/env transport timeout.+func APITimeout() time.Duration {+ return AtLeastAPITimeout(0)+}++// AtLeastAPITimeout returns max(min, APITimeout()). Use it for commands that+// need a larger floor than usual (for example file uploads, which historically+// used a 60s budget).+func AtLeastAPITimeout(min time.Duration) time.Duration {+ budget := httpTimeout() + apiContextGrace+ if min > budget {+ return min+ }+ return budget+}++// APIContext derives a command-scoped context whose deadline is APITimeout().+// The returned cancel func must be called (typically via defer) to release+// resources. Commands should use this instead of context.WithTimeout with a+// hardcoded duration so the deadline always respects MULTICA_HTTP_TIMEOUT.+func APIContext(parent context.Context) (context.Context, context.CancelFunc) {+ if parent == nil {+ parent = context.Background()+ }+ return context.WithTimeout(parent, APITimeout())+}+// NewAPIClient creates a new API client for ctrl commands.func NewAPIClient(baseURL, workspaceID, token string) *APIClient {return &APIClient{BaseURL: strings.TrimRight(baseURL, "/"),WorkspaceID: workspaceID,Token: token,- HTTPClient: &http.Client{Timeout: 15 * time.Second},+ HTTPClient: &http.Client{Timeout: httpTimeout()},}}@@ -132,19 +213,14 @@ func (c *APIClient) GetJSON(ctx context.Context, path string, out any) error {c.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return err}defer resp.Body.Close()if resp.StatusCode >= 400 {- data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return &HTTPError{- Method: http.MethodGet,- Path: path,- StatusCode: resp.StatusCode,- Body: strings.TrimSpace(string(data)),- }+ return newHTTPError(http.MethodGet, path, resp)}if out == nil {return nil@@ -163,14 +239,14 @@ func (c *APIClient) GetJSONWithHeaders(ctx context.Context, path string, out anyc.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return nil, err}defer resp.Body.Close()if resp.StatusCode >= 400 {- data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return nil, fmt.Errorf("GET %s returned %d: %s", path, resp.StatusCode, strings.TrimSpace(string(data)))+ return nil, newHTTPError(http.MethodGet, path, resp)}if out != nil {if err := json.NewDecoder(resp.Body).Decode(out); err != nil {@@ -189,14 +265,14 @@ func (c *APIClient) DeleteJSON(ctx context.Context, path string) error {c.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return err}defer resp.Body.Close()if resp.StatusCode >= 400 {- data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("DELETE %s returned %d: %s", path, resp.StatusCode, strings.TrimSpace(string(data)))+ return newHTTPError(http.MethodDelete, path, resp)}return nil}@@ -215,14 +291,14 @@ func (c *APIClient) DeleteJSONWithBody(ctx context.Context, path string, body anc.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return err}defer resp.Body.Close()if resp.StatusCode >= 400 {- respData, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("DELETE %s returned %d: %s", path, resp.StatusCode, strings.TrimSpace(string(respData)))+ return newHTTPError(http.MethodDelete, path, resp)}return nil}@@ -242,19 +318,14 @@ func (c *APIClient) PostJSON(ctx context.Context, path string, body any, out anyc.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return err}defer resp.Body.Close()if resp.StatusCode >= 400 {- respData, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return &HTTPError{- Method: http.MethodPost,- Path: path,- StatusCode: resp.StatusCode,- Body: strings.TrimSpace(string(respData)),- }+ return newHTTPError(http.MethodPost, path, resp)}if out == nil {return nil@@ -277,14 +348,14 @@ func (c *APIClient) PutJSON(ctx context.Context, path string, body any, out any)c.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return err}defer resp.Body.Close()if resp.StatusCode >= 400 {- respData, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("PUT %s returned %d: %s", path, resp.StatusCode, strings.TrimSpace(string(respData)))+ return newHTTPError(http.MethodPut, path, resp)}if out == nil {return nil@@ -307,14 +378,14 @@ func (c *APIClient) PatchJSON(ctx context.Context, path string, body any, out anc.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return err}defer resp.Body.Close()if resp.StatusCode >= 400 {- respData, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("PATCH %s returned %d: %s", path, resp.StatusCode, strings.TrimSpace(string(respData)))+ return newHTTPError(http.MethodPatch, path, resp)}if out == nil {return nil@@ -365,14 +436,14 @@ func (c *APIClient) UploadFile(ctx context.Context, fileData []byte, filename stc.setHeaders(req)resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)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)))+ return "", newHTTPError(http.MethodPost, "/api/upload-file", resp)}var result map[string]any@@ -414,8 +485,8 @@ func (c *APIClient) UploadFileWithURL(ctx context.Context, fileData []byte, filec.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.+ // (e.g. avatar uploads with 5MB files). The default HTTP client timeout+ // shadows any longer context deadline.httpClient := c.HTTPClientif deadline, ok := ctx.Deadline(); ok {remaining := time.Until(deadline)@@ -427,14 +498,14 @@ func (c *APIClient) UploadFileWithURL(ctx context.Context, fileData []byte, file}resp, err := httpClient.Do(req)+ err = wrapTransport(req, err)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)))+ return "", "", newHTTPError(http.MethodPost, "/api/upload-file", resp)}var result AttachmentResponse@@ -478,14 +549,14 @@ func (c *APIClient) DownloadFile(ctx context.Context, downloadURL string) ([]byt}resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return nil, err}defer resp.Body.Close()if resp.StatusCode >= 400 {- body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return nil, fmt.Errorf("download returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))+ return nil, newHTTPError(http.MethodGet, downloadURL, resp)}const maxDownloadSize = 100 << 20 // 100 MB@@ -499,6 +570,7 @@ func (c *APIClient) HealthCheck(ctx context.Context) (string, error) {return "", err}resp, err := c.HTTPClient.Do(req)+ err = wrapTransport(req, err)if err != nil {return "", err}@@ -506,7 +578,12 @@ func (c *APIClient) HealthCheck(ctx context.Context) (string, error) {data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))if resp.StatusCode >= 400 {- return "", fmt.Errorf("health check returned %d: %s", resp.StatusCode, strings.TrimSpace(string(data)))+ return "", &HTTPError{+ Method: http.MethodGet,+ Path: "/health",+ StatusCode: resp.StatusCode,+ Body: strings.TrimSpace(string(data)),+ }}return strings.TrimSpace(string(data)), nil}diff --git a/server/internal/cli/client_test.go b/server/internal/cli/client_test.goindex 5e96efccf4..a5675b7044 100644--- a/server/internal/cli/client_test.go+++ b/server/internal/cli/client_test.go@@ -3,6 +3,7 @@ package cliimport ("context""encoding/json"+ "errors""io""net/http""net/http/httptest"@@ -302,8 +303,12 @@ func TestUploadFileWithURL(t *testing.T) {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())+ var httpErr *HTTPError+ if !errors.As(err, &httpErr) {+ t.Fatalf("expected *HTTPError, got %T: %v", err, err)+ }+ if httpErr.StatusCode != 400 {+ t.Errorf("expected status 400, got %d", httpErr.StatusCode)}})diff --git a/server/internal/cli/errors.go b/server/internal/cli/errors.gonew file mode 100644index 0000000000..edcf31f46a--- /dev/null+++ b/server/internal/cli/errors.go@@ -0,0 +1,414 @@+package cli++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "encoding/json"+ "errors"+ "fmt"+ "net"+ "net/http"+ "os"+ "strings"+ "syscall"+)++// ErrorKind is a coarse, user-facing classification of an error. The CLI's+// many internal error strings ("resolve issue: ...", raw net/http messages,+// JSON bodies) are not meaningful to end users; FormatError collapses them+// into one of these kinds and renders a friendly, localized message.+//+// The zero value is intentionally KindNetworkTimeout-adjacent only by index;+// always classify explicitly rather than relying on the zero value.+type ErrorKind int++const (+ // Network / transport layer (errors returned by http.Client.Do).+ KindNetworkTimeout ErrorKind = iota // context deadline exceeded / i/o timeout+ KindNetworkDNS // no such host+ KindNetworkRefused // connection refused+ KindNetworkTLS // x509 / tls handshake failures+ KindNetworkOffline // catch-all: host unreachable, reset, etc.++ // HTTP status layer.+ KindAuthRequired // 401+ KindForbidden // 403+ KindNotFound // 404+ KindConflict // 409+ KindValidation // 400 / 422+ KindRateLimited // 429+ KindServerError // 5xx++ // Anything we could not classify.+ KindUnknown+)++// Tiered process exit codes. Stable so users can branch on them in scripts.+const (+ ExitGeneric = 1 // anything not covered below+ ExitNetwork = 2 // any KindNetwork*+ ExitAuth = 3 // 401 / 403+ ExitNotFound = 4 // 404+ ExitValidation = 5 // 400 / 422+)++// IsNetwork reports whether the kind is a transport-layer failure.+func (k ErrorKind) IsNetwork() bool {+ switch k {+ case KindNetworkTimeout, KindNetworkDNS, KindNetworkRefused, KindNetworkTLS, KindNetworkOffline:+ return true+ default:+ return false+ }+}++// NetworkError wraps a transport-layer error (the error returned by+// http.Client.Do, before any HTTP status is available). It strips the raw+// URL out of the user-facing message while preserving the original error for+// --debug output and errors.Is/As inspection.+type NetworkError struct {+ Kind ErrorKind+ Op string // e.g. "GET /api/issues/abc" — shown only in --debug+ Err error // the original net/http error+}++func (e *NetworkError) Error() string {+ if e.Op != "" {+ return fmt.Sprintf("%s: %s", e.Op, e.Err.Error())+ }+ return e.Err.Error()+}++func (e *NetworkError) Unwrap() error { return e.Err }++// Kind maps an HTTPError's status code onto an ErrorKind.+func (e *HTTPError) Kind() ErrorKind {+ switch e.StatusCode {+ case 401:+ return KindAuthRequired+ case 403:+ return KindForbidden+ case 404:+ return KindNotFound+ case 409:+ return KindConflict+ case 400, 422:+ return KindValidation+ case 429:+ return KindRateLimited+ default:+ if e.StatusCode >= 500 {+ return KindServerError+ }+ return KindUnknown+ }+}++// classifyNetworkError inspects a transport-layer error and returns the+// matching network ErrorKind. It prefers typed inspection (errors.As /+// errors.Is) and falls back to string matching for cases the standard library+// does not expose as distinct types.+func classifyNetworkError(err error) ErrorKind {+ if err == nil {+ return KindUnknown+ }++ // Timeouts (context deadline or socket i/o timeout).+ if errors.Is(err, context.DeadlineExceeded) {+ return KindNetworkTimeout+ }+ var netErr net.Error+ if errors.As(err, &netErr) && netErr.Timeout() {+ return KindNetworkTimeout+ }++ // DNS resolution failures.+ var dnsErr *net.DNSError+ if errors.As(err, &dnsErr) {+ return KindNetworkDNS+ }++ // TLS / certificate failures.+ var certVerifyErr *tls.CertificateVerificationError+ if errors.As(err, &certVerifyErr) {+ return KindNetworkTLS+ }+ var unknownAuthorityErr x509.UnknownAuthorityError+ if errors.As(err, &unknownAuthorityErr) {+ return KindNetworkTLS+ }+ var hostnameErr x509.HostnameError+ if errors.As(err, &hostnameErr) {+ return KindNetworkTLS+ }+ var certInvalidErr x509.CertificateInvalidError+ if errors.As(err, &certInvalidErr) {+ return KindNetworkTLS+ }++ // Connection refused.+ if errors.Is(err, syscall.ECONNREFUSED) {+ return KindNetworkRefused+ }++ // String fallbacks for anything not surfaced as a typed error.+ msg := strings.ToLower(err.Error())+ switch {+ case strings.Contains(msg, "context deadline exceeded"), strings.Contains(msg, "timeout"), strings.Contains(msg, "timed out"):+ return KindNetworkTimeout+ case strings.Contains(msg, "no such host"), strings.Contains(msg, "server misbehaving"), strings.Contains(msg, "name resolution"):+ return KindNetworkDNS+ case strings.Contains(msg, "connection refused"):+ return KindNetworkRefused+ case strings.Contains(msg, "x509"), strings.Contains(msg, "certificate"), strings.Contains(msg, "tls"):+ return KindNetworkTLS+ }+ return KindNetworkOffline+}++// wrapTransport converts a raw transport error returned by http.Client.Do+// into a *NetworkError. It returns nil when err is nil so call sites can+// reassign unconditionally:+//+// resp, err := c.HTTPClient.Do(req)+// err = wrapTransport(req, err)+// if err != nil { return err }+func wrapTransport(req *http.Request, err error) error {+ if err == nil {+ return nil+ }+ op := ""+ if req != nil && req.URL != nil {+ op = req.Method + " " + req.URL.Path+ }+ return &NetworkError{Kind: classifyNetworkError(err), Op: op, Err: err}+}++// Language is the language FormatError renders messages in.+type Language int++const (+ LangEN Language = iota+ LangZH+)++// DetectLanguage chooses the output language from the environment. English is+// the default (matching the CLI's help output); a Chinese locale in LC_ALL,+// LC_MESSAGES, or LANG (in that precedence order) switches to Chinese.+func DetectLanguage() Language {+ for _, key := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {+ v := strings.ToLower(strings.TrimSpace(os.Getenv(key)))+ if v == "" {+ continue+ }+ if strings.HasPrefix(v, "zh") {+ return LangZH+ }+ // First locale variable that is set wins; if it is not Chinese we+ // fall through to English without consulting lower-precedence vars.+ return LangEN+ }+ return LangEN+}++// kindMessages holds the {English, Chinese} user-facing message for each kind.+var kindMessages = map[ErrorKind][2]string{+ KindNetworkTimeout: {+ "Request timed out: the server did not respond in time. Check your network connection or try again later. You can raise the limit with MULTICA_HTTP_TIMEOUT.",+ "请求超时:服务器未在规定时间内响应。请检查网络连接或稍后重试。可通过 MULTICA_HTTP_TIMEOUT 调高超时时间。",+ },+ KindNetworkDNS: {+ "Could not resolve the Multica server address. Check your network connection or the --server-url setting.",+ "无法解析 Multica 服务器地址。请检查网络连接或 --server-url 配置。",+ },+ KindNetworkRefused: {+ "Could not connect to the Multica server. Make sure the server address is correct and reachable.",+ "无法连接到 Multica 服务器。请确认服务器地址正确且网络可达。",+ },+ KindNetworkTLS: {+ "Could not establish a secure connection to the Multica server (TLS/certificate error). Check your system clock and CA certificates.",+ "无法与 Multica 服务器建立安全连接(TLS/证书错误)。请检查系统时间和 CA 证书。",+ },+ KindNetworkOffline: {+ "Could not reach the Multica server. Check your network connection.",+ "无法访问 Multica 服务器。请检查网络连接。",+ },+ KindAuthRequired: {+ "Your session has expired or you are not signed in. Run `multica login` to sign in again.",+ "登录已过期或尚未登录。请运行 `multica login` 重新登录。",+ },+ KindForbidden: {+ "You do not have permission to access this resource.",+ "无权访问该资源。",+ },+ KindNotFound: {+ "The requested resource was not found. The ID may not exist or may belong to a different workspace.",+ "未找到请求的资源。该 ID 可能不存在,或不属于当前 workspace。",+ },+ KindConflict: {+ "The request conflicts with the current state of the resource.",+ "请求与资源的当前状态冲突。",+ },+ KindValidation: {+ "The request was invalid.",+ "请求无效。",+ },+ KindRateLimited: {+ "Too many requests. Please wait a moment and try again.",+ "请求过于频繁。请稍后重试。",+ },+ KindServerError: {+ "The Multica service is temporarily unavailable. Please try again later; contact support if the problem persists.",+ "Multica 服务暂时不可用。请稍后重试,如持续出现请联系支持。",+ },+ KindUnknown: {+ "An unexpected error occurred.",+ "发生未知错误。",+ },+}++// messageFor returns the localized message for a kind.+func messageFor(kind ErrorKind, lang Language) string {+ m, ok := kindMessages[kind]+ if !ok {+ m = kindMessages[KindUnknown]+ }+ if lang == LangZH {+ return m[1]+ }+ return m[0]+}++// FormatError translates an error into a single user-facing line (or a+// detailed multi-line block when debug is set). It is the only user-facing+// translation entry point and is meant to be called once, at the top level+// (main.go), on the error bubbling up from a command.+//+// When debug is false it skips the internal verb chain ("resolve issue: ...")+// and the raw URL/JSON body, showing only the friendly message. When debug is+// true (or MULTICA_DEBUG is set) it additionally prints the full original+// error chain for troubleshooting.+func FormatError(err error, debug bool) string {+ if err == nil {+ return ""+ }+ lang := DetectLanguage()+ base := userMessage(err, lang)+ if debug || debugEnabled() {+ return base + "\n\n" + debugDetail(err)+ }+ return base+}++// userMessage produces the friendly message for the root cause of err.+func userMessage(err error, lang Language) string {+ // Transport-layer failure.+ var netErr *NetworkError+ if errors.As(err, &netErr) {+ return messageFor(netErr.Kind, lang)+ }++ // HTTP status failure.+ var httpErr *HTTPError+ if errors.As(err, &httpErr) {+ kind := httpErr.Kind()+ // Validation errors usually carry a useful server-provided message;+ // surface it instead of the generic line.+ if kind == KindValidation {+ if serverMsg := extractServerMessage(httpErr.Body); serverMsg != "" {+ if lang == LangZH {+ return "请求无效:" + serverMsg+ }+ return "Invalid request: " + serverMsg+ }+ }+ return messageFor(kind, lang)+ }++ // Not a recognized typed error: this is typically a local/business error+ // whose message is already meant for the user (e.g. a missing argument or+ // a validation message constructed in a command). Show it as-is.+ return strings.TrimSpace(err.Error())+}++// extractServerMessage tries to pull a human-readable message out of a JSON+// error body like {"error":"..."} or {"message":"..."}. Returns "" if the+// body is not JSON or has no recognizable message field.+func extractServerMessage(body string) string {+ body = strings.TrimSpace(body)+ if body == "" || body[0] != '{' {+ return ""+ }+ var parsed map[string]any+ if err := json.Unmarshal([]byte(body), &parsed); err != nil {+ return ""+ }+ for _, key := range []string{"error", "message", "detail", "title"} {+ if v, ok := parsed[key]; ok {+ if s, ok := v.(string); ok && strings.TrimSpace(s) != "" {+ return strings.TrimSpace(s)+ }+ }+ }+ return ""+}++// debugDetail renders the full original error chain plus any structured+// details from typed errors, for --debug / MULTICA_DEBUG output.+func debugDetail(err error) string {+ var sb strings.Builder+ sb.WriteString("[debug] ")+ sb.WriteString(err.Error())++ var netErr *NetworkError+ if errors.As(err, &netErr) {+ fmt.Fprintf(&sb, "\n[debug] network: op=%q kind=%d cause=%v", netErr.Op, netErr.Kind, netErr.Err)+ }+ var httpErr *HTTPError+ if errors.As(err, &httpErr) {+ fmt.Fprintf(&sb, "\n[debug] http: %s %s status=%d body=%s",+ httpErr.Method, httpErr.Path, httpErr.StatusCode, strings.TrimSpace(httpErr.Body))+ }+ return sb.String()+}++// debugEnabled reports whether MULTICA_DEBUG requests debug output.+func debugEnabled() bool {+ switch strings.ToLower(strings.TrimSpace(os.Getenv("MULTICA_DEBUG"))) {+ case "", "0", "false", "no", "off":+ return false+ default:+ return true+ }+}++// ExitCodeFor maps an error onto a tiered process exit code so callers can+// branch in scripts: network=2, auth(401/403)=3, not-found(404)=4,+// validation(400/422)=5, everything else=1.+func ExitCodeFor(err error) int {+ if err == nil {+ return 0+ }++ var netErr *NetworkError+ if errors.As(err, &netErr) {+ return ExitNetwork+ }++ var httpErr *HTTPError+ if errors.As(err, &httpErr) {+ switch httpErr.Kind() {+ case KindAuthRequired, KindForbidden:+ return ExitAuth+ case KindNotFound:+ return ExitNotFound+ case KindValidation:+ return ExitValidation+ default:+ return ExitGeneric+ }+ }++ return ExitGeneric+}diff --git a/server/internal/cli/errors_integration_test.go b/server/internal/cli/errors_integration_test.gonew file mode 100644index 0000000000..960e9c0313--- /dev/null+++ b/server/internal/cli/errors_integration_test.go@@ -0,0 +1,232 @@+package cli++import (+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++// TestHelperStatusErrorsAreClassified is an integration test that drives the+// real client helpers against a fake server and asserts the error they return+// flows correctly through the top-level FormatError / ExitCodeFor. This is the+// coverage the unit tests were missing: it proves that the actual command+// paths (issue update -> PutJSON, comment list -> GetJSONWithHeaders, project+// delete -> DeleteJSON, agent update -> PatchJSON, upload, download) all get+// the friendly copy and the tiered exit code, not the old raw string + exit 1.+func TestHelperStatusErrorsAreClassified(t *testing.T) {+ withLang(t, "en_US.UTF-8")++ // Each helper wraps a real client call onto a fixed path. The server+ // returns whatever status the current case dictates.+ helpers := []struct {+ name string+ call func(c *APIClient, ctx context.Context) error+ }{+ {"GetJSON (issue get)", func(c *APIClient, ctx context.Context) error {+ var out map[string]any+ return c.GetJSON(ctx, "/api/issues/abc", &out)+ }},+ {"GetJSONWithHeaders (comment list)", func(c *APIClient, ctx context.Context) error {+ var out []any+ _, err := c.GetJSONWithHeaders(ctx, "/api/issues/abc/comments", &out)+ return err+ }},+ {"PostJSON (issue create)", func(c *APIClient, ctx context.Context) error {+ return c.PostJSON(ctx, "/api/issues", map[string]any{"title": "t"}, nil)+ }},+ {"PutJSON (issue update)", func(c *APIClient, ctx context.Context) error {+ return c.PutJSON(ctx, "/api/issues/abc", map[string]any{"title": "t"}, nil)+ }},+ {"PatchJSON (agent update)", func(c *APIClient, ctx context.Context) error {+ return c.PatchJSON(ctx, "/api/agents/abc", map[string]any{"name": "n"}, nil)+ }},+ {"DeleteJSON (project delete)", func(c *APIClient, ctx context.Context) error {+ return c.DeleteJSON(ctx, "/api/projects/abc")+ }},+ {"DeleteJSONWithBody (squad member remove)", func(c *APIClient, ctx context.Context) error {+ return c.DeleteJSONWithBody(ctx, "/api/squads/abc/members", map[string]any{"member_id": "x"})+ }},+ {"UploadFile (issue attachment)", func(c *APIClient, ctx context.Context) error {+ _, err := c.UploadFile(ctx, []byte("x"), "x.txt", "abc")+ return err+ }},+ {"UploadFileWithURL (avatar)", func(c *APIClient, ctx context.Context) error {+ _, _, err := c.UploadFileWithURL(ctx, []byte("x"), "x.txt")+ return err+ }},+ {"DownloadFile (attachment)", func(c *APIClient, ctx context.Context) error {+ _, err := c.DownloadFile(ctx, "/uploads/abc")+ return err+ }},+ }++ statusCases := []struct {+ status int+ wantExit int+ wantCopy string+ }{+ {http.StatusUnauthorized, ExitAuth, "multica login"},+ {http.StatusForbidden, ExitAuth, "permission"},+ {http.StatusNotFound, ExitNotFound, "not found"},+ {http.StatusUnprocessableEntity, ExitValidation, "title is required"},+ {http.StatusInternalServerError, ExitGeneric, "temporarily unavailable"},+ }++ for _, sc := range statusCases {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(sc.status)+ // Validation responses carry a server message that FormatError+ // should surface verbatim; other statuses ignore the body.+ io.WriteString(w, `{"error":"title is required"}`)+ }))++ for _, h := range helpers {+ t.Run(http.StatusText(sc.status)+"/"+h.name, func(t *testing.T) {+ client := NewAPIClient(srv.URL, "ws", "token")+ err := h.call(client, context.Background())+ if err == nil {+ t.Fatalf("expected error, got nil")+ }++ // 1. The helper must return a *HTTPError (possibly wrapped).+ var httpErr *HTTPError+ if !errors.As(err, &httpErr) {+ t.Fatalf("expected *HTTPError, got %T: %v", err, err)+ }+ if httpErr.StatusCode != sc.status {+ t.Errorf("status = %d, want %d", httpErr.StatusCode, sc.status)+ }++ // 2. Tiered exit code.+ if got := ExitCodeFor(err); got != sc.wantExit {+ t.Errorf("ExitCodeFor = %d, want %d", got, sc.wantExit)+ }++ // 3. Friendly, localized copy — and no raw path/verb leak.+ msg := FormatError(err, false)+ if !strings.Contains(msg, sc.wantCopy) {+ t.Errorf("FormatError = %q, want it to contain %q", msg, sc.wantCopy)+ }+ if strings.Contains(msg, "/api/") || strings.Contains(msg, "returned") {+ t.Errorf("FormatError leaked raw detail: %q", msg)+ }+ })+ }++ srv.Close()+ }+}++// TestCommandContextNotTruncatedBelowHTTPTimeout proves the must-fix: a+// command-level context derived from APIContext never cancels a request before+// the configured transport timeout. Previously commands hardcoded a 15s+// context that truncated a longer MULTICA_HTTP_TIMEOUT.+func TestCommandContextNotTruncatedBelowHTTPTimeout(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ // Use a short transport timeout so the test runs fast; the command budget+ // (transport + grace) is what we assert is NOT the limiting factor.+ t.Setenv("MULTICA_HTTP_TIMEOUT", "400ms")++ if APITimeout() <= httpTimeout() {+ t.Fatalf("APITimeout (%v) must be strictly greater than httpTimeout (%v)", APITimeout(), httpTimeout())+ }++ t.Run("request within transport budget completes (context does not fire first)", func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ time.Sleep(120 * time.Millisecond) // < 400ms transport timeout+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]string{"ok": "true"})+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "", "")+ ctx, cancel := APIContext(context.Background())+ defer cancel()++ var out map[string]string+ if err := client.GetJSON(ctx, "/x", &out); err != nil {+ t.Fatalf("expected success within transport budget, got %v", err)+ }+ })++ t.Run("transport timeout governs and yields a friendly timeout error", func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ time.Sleep(900 * time.Millisecond) // > 400ms transport timeout+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "", "")+ ctx, cancel := APIContext(context.Background())+ defer cancel()++ start := time.Now()+ err := client.GetJSON(ctx, "/x", nil)+ elapsed := time.Since(start)++ if err == nil {+ t.Fatal("expected a timeout error")+ }+ // Must fail near the 400ms transport timeout, not the ~5.4s command+ // context deadline. A generous 3s ceiling keeps the test non-flaky+ // while still proving the context did not govern.+ if elapsed > 3*time.Second {+ t.Errorf("request took %v; the command context likely truncated/governed instead of the transport timeout", elapsed)+ }+ if msg := FormatError(err, false); !strings.Contains(msg, "timed out") {+ t.Errorf("expected friendly timeout copy, got %q", msg)+ }+ if got := ExitCodeFor(err); got != ExitNetwork {+ t.Errorf("ExitCodeFor = %d, want ExitNetwork(%d)", got, ExitNetwork)+ }+ })+}++// TestAPITimeoutRespectsEnv verifies the command budget tracks+// MULTICA_HTTP_TIMEOUT and the AtLeast floor.+func TestAPITimeoutRespectsEnv(t *testing.T) {+ t.Run("default", func(t *testing.T) {+ t.Setenv("MULTICA_HTTP_TIMEOUT", "")+ if got, want := APITimeout(), defaultHTTPTimeout+apiContextGrace; got != want {+ t.Errorf("APITimeout = %v, want %v", got, want)+ }+ })+ t.Run("env override raises both transport and command budget", func(t *testing.T) {+ t.Setenv("MULTICA_HTTP_TIMEOUT", "90s")+ if got, want := APITimeout(), 90*time.Second+apiContextGrace; got != want {+ t.Errorf("APITimeout = %v, want %v", got, want)+ }+ })+ t.Run("AtLeast floor wins when larger", func(t *testing.T) {+ t.Setenv("MULTICA_HTTP_TIMEOUT", "10s")+ if got, want := AtLeastAPITimeout(60*time.Second), 60*time.Second; got != want {+ t.Errorf("AtLeastAPITimeout = %v, want %v", got, want)+ }+ })+ t.Run("AtLeast budget wins when larger than floor", func(t *testing.T) {+ t.Setenv("MULTICA_HTTP_TIMEOUT", "120s")+ if got, want := AtLeastAPITimeout(60*time.Second), 120*time.Second+apiContextGrace; got != want {+ t.Errorf("AtLeastAPITimeout = %v, want %v", got, want)+ }+ })+ // The login workspace-creation poll uses a short 10s floor to stay+ // responsive, but it must still honor MULTICA_HTTP_TIMEOUT (it is not a+ // silent exception to the env-override promise). With the env unset the+ // budget is at least the 10s floor; with the env raised it scales up.+ t.Run("login poll 10s floor honors env override", func(t *testing.T) {+ t.Setenv("MULTICA_HTTP_TIMEOUT", "")+ if got := AtLeastAPITimeout(10 * time.Second); got < 10*time.Second {+ t.Errorf("AtLeastAPITimeout(10s) = %v, want >= 10s floor", got)+ }+ t.Setenv("MULTICA_HTTP_TIMEOUT", "90s")+ if got, want := AtLeastAPITimeout(10*time.Second), 90*time.Second+apiContextGrace; got != want {+ t.Errorf("AtLeastAPITimeout(10s) with env=90s = %v, want %v", got, want)+ }+ })+}diff --git a/server/internal/cli/errors_test.go b/server/internal/cli/errors_test.gonew file mode 100644index 0000000000..b4e8cee9fa--- /dev/null+++ b/server/internal/cli/errors_test.go@@ -0,0 +1,273 @@+package cli++import (+ "context"+ "crypto/x509"+ "errors"+ "fmt"+ "net"+ "strings"+ "syscall"+ "testing"+)++// timeoutErr is a net.Error whose Timeout() reports true, used to exercise the+// net.Error timeout branch without a real socket.+type timeoutErr struct{}++func (timeoutErr) Error() string { return "i/o timeout" }+func (timeoutErr) Timeout() bool { return true }+func (timeoutErr) Temporary() bool { return true }++func TestClassifyNetworkError(t *testing.T) {+ cases := []struct {+ name string+ err error+ want ErrorKind+ }{+ {"context deadline", context.DeadlineExceeded, KindNetworkTimeout},+ {"wrapped deadline", fmt.Errorf("resolve issue: %w", context.DeadlineExceeded), KindNetworkTimeout},+ {"net timeout", timeoutErr{}, KindNetworkTimeout},+ {"dns", &net.DNSError{Err: "no such host", Name: "api.multica.ai", IsNotFound: true}, KindNetworkDNS},+ {"connection refused", syscall.ECONNREFUSED, KindNetworkRefused},+ {"x509 unknown authority", x509.UnknownAuthorityError{}, KindNetworkTLS},+ {"x509 hostname", x509.HostnameError{Host: "api.multica.ai"}, KindNetworkTLS},+ {"timeout string fallback", errors.New("Get \"https://x\": net/http: request canceled (Client.Timeout exceeded)"), KindNetworkTimeout},+ {"dns string fallback", errors.New("dial tcp: lookup api.multica.ai: no such host"), KindNetworkDNS},+ {"refused string fallback", errors.New("dial tcp 127.0.0.1:443: connect: connection refused"), KindNetworkRefused},+ {"tls string fallback", errors.New("x509: certificate signed by unknown authority"), KindNetworkTLS},+ {"offline catch-all", errors.New("write: connection reset by peer"), KindNetworkOffline},+ {"nil", nil, KindUnknown},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := classifyNetworkError(tc.err); got != tc.want {+ t.Errorf("classifyNetworkError(%v) = %d, want %d", tc.err, got, tc.want)+ }+ })+ }+}++func TestHTTPErrorKind(t *testing.T) {+ cases := []struct {+ status int+ want ErrorKind+ }{+ {401, KindAuthRequired},+ {403, KindForbidden},+ {404, KindNotFound},+ {409, KindConflict},+ {400, KindValidation},+ {422, KindValidation},+ {429, KindRateLimited},+ {500, KindServerError},+ {502, KindServerError},+ {418, KindUnknown},+ }+ for _, tc := range cases {+ t.Run(fmt.Sprintf("status_%d", tc.status), func(t *testing.T) {+ e := &HTTPError{StatusCode: tc.status}+ if got := e.Kind(); got != tc.want {+ t.Errorf("HTTPError{%d}.Kind() = %d, want %d", tc.status, got, tc.want)+ }+ })+ }+}++// TestFormatErrorAllKinds asserts that every ErrorKind produces a non-empty,+// localized, user-facing message in both languages, and that none of them leak+// the raw internal error string when debug is off.+func TestFormatErrorAllKinds(t *testing.T) {+ withLang(t, "") // default English+ allKinds := []ErrorKind{+ KindNetworkTimeout, KindNetworkDNS, KindNetworkRefused, KindNetworkTLS, KindNetworkOffline,+ KindAuthRequired, KindForbidden, KindNotFound, KindConflict, KindValidation,+ KindRateLimited, KindServerError, KindUnknown,+ }+ for _, lang := range []Language{LangEN, LangZH} {+ for _, k := range allKinds {+ msg := messageFor(k, lang)+ if strings.TrimSpace(msg) == "" {+ t.Errorf("messageFor(kind=%d, lang=%d) is empty", k, lang)+ }+ }+ }+}++func TestFormatErrorNetwork(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ raw := errors.New("Get \"https://api.multica.ai/api/issues/abc\": context deadline exceeded")+ netErr := &NetworkError{Kind: KindNetworkTimeout, Op: "GET /api/issues/abc", Err: raw}+ wrapped := fmt.Errorf("resolve issue: %w", netErr)++ got := FormatError(wrapped, false)+ if !strings.Contains(got, "timed out") {+ t.Errorf("expected friendly timeout message, got %q", got)+ }+ // Must not leak the URL or internal verb chain when debug is off.+ if strings.Contains(got, "api.multica.ai") || strings.Contains(got, "resolve issue") {+ t.Errorf("user message leaked internal detail: %q", got)+ }+}++func TestFormatErrorChineseLocale(t *testing.T) {+ withLang(t, "zh_CN.UTF-8")+ netErr := &NetworkError{Kind: KindNetworkDNS, Err: errors.New("no such host")}+ got := FormatError(netErr, false)+ if !strings.Contains(got, "无法解析") {+ t.Errorf("expected Chinese DNS message, got %q", got)+ }+}++func TestFormatErrorValidationUsesServerMessage(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ httpErr := &HTTPError{+ Method: "POST",+ Path: "/api/issues",+ StatusCode: 422,+ Body: `{"error":"title is required"}`,+ }+ got := FormatError(httpErr, false)+ if !strings.Contains(got, "title is required") {+ t.Errorf("expected server validation message surfaced, got %q", got)+ }+}++func TestFormatErrorDebugIncludesRawChain(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ httpErr := &HTTPError{Method: "GET", Path: "/api/issues/abc", StatusCode: 404, Body: `{"error":"not found"}`}+ wrapped := fmt.Errorf("resolve issue: %w", httpErr)++ off := FormatError(wrapped, false)+ if strings.Contains(off, "/api/issues/abc") {+ t.Errorf("debug-off output should not contain raw path: %q", off)+ }++ on := FormatError(wrapped, true)+ if !strings.Contains(on, "[debug]") || !strings.Contains(on, "/api/issues/abc") {+ t.Errorf("debug-on output should include raw chain: %q", on)+ }+}++func TestFormatErrorPlainError(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ got := FormatError(errors.New("title is required"), false)+ if got != "title is required" {+ t.Errorf("plain error should pass through, got %q", got)+ }+ if FormatError(nil, false) != "" {+ t.Errorf("nil error should format to empty string")+ }+}++func TestExitCodeFor(t *testing.T) {+ cases := []struct {+ name string+ err error+ want int+ }{+ {"nil", nil, 0},+ {"network", &NetworkError{Kind: KindNetworkTimeout, Err: errors.New("x")}, ExitNetwork},+ {"wrapped network", fmt.Errorf("resolve: %w", &NetworkError{Kind: KindNetworkDNS, Err: errors.New("x")}), ExitNetwork},+ {"auth 401", &HTTPError{StatusCode: 401}, ExitAuth},+ {"forbidden 403", &HTTPError{StatusCode: 403}, ExitAuth},+ {"not found 404", &HTTPError{StatusCode: 404}, ExitNotFound},+ {"validation 400", &HTTPError{StatusCode: 400}, ExitValidation},+ {"validation 422", &HTTPError{StatusCode: 422}, ExitValidation},+ {"conflict 409", &HTTPError{StatusCode: 409}, ExitGeneric},+ {"rate limited 429", &HTTPError{StatusCode: 429}, ExitGeneric},+ {"server 500", &HTTPError{StatusCode: 500}, ExitGeneric},+ {"plain", errors.New("boom"), ExitGeneric},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := ExitCodeFor(tc.err); got != tc.want {+ t.Errorf("ExitCodeFor(%v) = %d, want %d", tc.err, got, tc.want)+ }+ })+ }+}++func TestDetectLanguage(t *testing.T) {+ cases := []struct {+ name string+ env map[string]string+ want Language+ }{+ {"default english", map[string]string{}, LangEN},+ {"lang zh", map[string]string{"LANG": "zh_CN.UTF-8"}, LangZH},+ {"lang en", map[string]string{"LANG": "en_US.UTF-8"}, LangEN},+ {"lc_all wins over lang", map[string]string{"LC_ALL": "en_US.UTF-8", "LANG": "zh_CN.UTF-8"}, LangEN},+ {"lc_all zh", map[string]string{"LC_ALL": "zh_CN.UTF-8", "LANG": "en_US.UTF-8"}, LangZH},+ {"lc_messages zh", map[string]string{"LC_MESSAGES": "zh_TW.UTF-8"}, LangZH},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ for _, k := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {+ t.Setenv(k, "")+ }+ for k, v := range tc.env {+ t.Setenv(k, v)+ }+ if got := DetectLanguage(); got != tc.want {+ t.Errorf("DetectLanguage() = %d, want %d", got, tc.want)+ }+ })+ }+}++func TestExtractServerMessage(t *testing.T) {+ cases := []struct {+ body string+ want string+ }{+ {`{"error":"title is required"}`, "title is required"},+ {`{"message":"invalid priority"}`, "invalid priority"},+ {`{"detail":"bad due date"}`, "bad due date"},+ {`not json`, ""},+ {`{}`, ""},+ {``, ""},+ {`{"error":""}`, ""},+ }+ for _, tc := range cases {+ t.Run(tc.body, func(t *testing.T) {+ if got := extractServerMessage(tc.body); got != tc.want {+ t.Errorf("extractServerMessage(%q) = %q, want %q", tc.body, got, tc.want)+ }+ })+ }+}++func TestHTTPTimeout(t *testing.T) {+ cases := []struct {+ name string+ val string+ want string // human description of expected duration+ }{+ {"unset", "", "30s"},+ {"duration", "45s", "45s"},+ {"minutes", "2m", "2m0s"},+ {"plain seconds", "10", "10s"},+ {"invalid falls back", "garbage", "30s"},+ {"zero falls back", "0", "30s"},+ {"negative falls back", "-5", "30s"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Setenv("MULTICA_HTTP_TIMEOUT", tc.val)+ if got := httpTimeout().String(); got != tc.want {+ t.Errorf("httpTimeout() with %q = %s, want %s", tc.val, got, tc.want)+ }+ })+ }+}++// withLang clears the locale env vars and sets LANG to the given value for the+// duration of the test, so language-dependent assertions are deterministic+// regardless of the host environment.+func withLang(t *testing.T, lang string) {+ t.Helper()+ t.Setenv("LC_ALL", "")+ t.Setenv("LC_MESSAGES", "")+ t.Setenv("LANG", lang)+}