Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(cli): preserve profile settings when reconnecting setup (#10290)
Danila Katalshov31416621e265
diff --git a/server/cmd/multica/cmd_setup.go b/server/cmd/multica/cmd_setup.goindex c97960b240..725b3ce9d7 100644--- a/server/cmd/multica/cmd_setup.go+++ b/server/cmd/multica/cmd_setup.go@@ -10,6 +10,7 @@ import ("net/http""net/url""os"+ "reflect""strings""time"@@ -103,13 +104,9 @@ func printConfigLocation(profile string) {// config so the user can see the passed flags/env were received rather than// silently ignored. Returns true if we should proceed, false if the user// declined.-func confirmOverwrite(profile, newServerURL, newAppURL string) (bool, error) {- cfg, err := cli.LoadCLIConfigForProfile(profile)- if err != nil {- return true, nil // can't load → treat as no config- }+func confirmOverwrite(cfg cli.CLIConfig, newServerURL, newAppURL string) bool {if cfg.ServerURL == "" {- return true, nil // no server configured → fresh config+ return true // no server configured → fresh config}fmt.Fprintln(os.Stderr, "Current configuration:")@@ -119,16 +116,20 @@ func confirmOverwrite(profile, newServerURL, newAppURL string) (bool, error) {fmt.Fprintf(os.Stderr, " workspace: %s\n", cfg.WorkspaceID)}fmt.Fprintln(os.Stderr, "")- fmt.Fprint(os.Stderr, "This will reset your configuration. Continue? [y/N] ")+ if sameSetupBackend(cfg.ServerURL, newServerURL) {+ fmt.Fprint(os.Stderr, "Keep the existing local settings and sign in again? [y/N] ")+ } else {+ fmt.Fprint(os.Stderr, "This will reset your configuration. Continue? [y/N] ")+ }reader := bufio.NewReader(os.Stdin)answer, _ := reader.ReadString('\n')answer = strings.TrimSpace(strings.ToLower(answer))if answer != "y" && answer != "yes" {fmt.Fprintln(os.Stderr, "Aborted.")- return false, nil+ return false}- return true, nil+ return true}// formatURLChange renders "old -> new" when setup is about to change the value,@@ -151,15 +152,15 @@ func runSetupCloud(cmd *cobra.Command, args []string) error {AppURL: defaultCloudAppURL,}- ok, err := confirmOverwrite(profile, cfg.ServerURL, cfg.AppURL)+ existing, err := cli.LoadCLIConfigForProfile(profile)if err != nil {- return err+ return fmt.Errorf("read existing profile: %w", err)}- if !ok {+ if !confirmOverwrite(existing, cfg.ServerURL, cfg.AppURL) {return nil}- if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {+ if err := saveSetupTarget(profile, cfg.ServerURL, cfg.AppURL, existing); err != nil {return fmt.Errorf("save config: %w", err)}@@ -198,7 +199,10 @@ func runSetupSelfHost(cmd *cobra.Command, args []string) error {// Before this, setup self-host read only the flags, so a self-hoster who set// MULTICA_SERVER_URL still got the localhost default and an "unreachable"// error (GitHub #3912).- existing, _ := cli.LoadCLIConfigForProfile(profile)+ existing, err := cli.LoadCLIConfigForProfile(profile)+ if err != nil {+ return fmt.Errorf("read existing profile: %w", err)+ }serverURL, userProvidedServerURL := resolveSelfHostServerURL(cmd, existing)appURL := resolveSelfHostAppURL(cmd, existing)frontendPort, _ := cmd.Flags().GetInt("frontend-port")@@ -221,16 +225,12 @@ func runSetupSelfHost(cmd *cobra.Command, args []string) error {}}- ok, err := confirmOverwrite(profile, serverURL, appURL)- if err != nil {- return err- }- if !ok {+ if !confirmOverwrite(existing, serverURL, appURL) {return nil}// Verify backend health before writing so a failed setup preserves the profile.- probeResult, err := persistSelfHostConfigIfReachable(serverURL, appURL, profile, probeServer)+ probeResult, err := persistSelfHostConfigIfReachable(serverURL, appURL, profile, existing, probeServer)if err != nil {return fmt.Errorf("save config: %w", err)}@@ -339,21 +339,45 @@ func daemonActiveTaskCount(health map[string]any) int64 {// persistSelfHostConfigIfReachable writes the self-host URLs only after a// healthy Multica response, preserving the existing profile on probe failure.-func persistSelfHostConfigIfReachable(serverURL, appURL, profile string, probe func(string) serverProbeResult) (serverProbeResult, error) {+func persistSelfHostConfigIfReachable(serverURL, appURL, profile string, expected cli.CLIConfig, probe func(string) serverProbeResult) (serverProbeResult, error) {result := probe(serverURL)if !result.healthy {return result, nil}- cfg := cli.CLIConfig{- ServerURL: serverURL,- AppURL: appURL,- }- if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {+ if err := saveSetupTarget(profile, serverURL, appURL, expected); err != nil {return result, err}return result, nil}+// Only trailing slashes are cosmetic when deciding whether local settings+// belong to the same backend.+func sameSetupBackend(old, next string) bool {+ return old != "" && strings.TrimRight(old, "/") == strings.TrimRight(next, "/")+}++func saveSetupTarget(profile, serverURL, appURL string, expected cli.CLIConfig) error {+ cfg, err := cli.LoadCLIConfigForProfile(profile)+ if err != nil {+ return err+ }+ // The prompt and health request can both outlive another writer. Never+ // apply an overwrite approved for an earlier version of the profile.+ if !reflect.DeepEqual(cfg, expected) {+ return fmt.Errorf("profile changed during setup; rerun setup")+ }+ if sameSetupBackend(cfg.ServerURL, serverURL) {+ if strings.TrimRight(cfg.AppURL, "/") == strings.TrimRight(appURL, "/") && cfg.Token == "" && cfg.WorkspaceID == "" {+ return nil+ }+ } else {+ cfg = cli.CLIConfig{}+ }+ cfg.Token, cfg.WorkspaceID = "", ""+ cfg.ServerURL, cfg.AppURL = serverURL, appURL+ return cli.SaveCLIConfigForProfile(cfg, profile)+}+// resolveSelfHostServerURL picks the backend URL for `setup self-host`: the// --server-url flag wins, then the MULTICA_SERVER_URL env var (consistent with// the rest of the CLI and the env var documented on the root flag), then andiff --git a/server/cmd/multica/cmd_setup_test.go b/server/cmd/multica/cmd_setup_test.goindex 335f0db23a..23e2ca464d 100644--- a/server/cmd/multica/cmd_setup_test.go+++ b/server/cmd/multica/cmd_setup_test.go@@ -76,7 +76,7 @@ func TestSelfHostSetupHealthResponses(t *testing.T) {}))defer server.Close()- result, err := persistSelfHostConfigIfReachable(server.URL, "https://new.example", profile, probeServer)+ result, err := persistSelfHostConfigIfReachable(server.URL, "https://new.example", profile, existing, probeServer)if err != nil {t.Fatal(err)}@@ -203,7 +203,7 @@ func TestPersistSelfHostConfigIfReachable(t *testing.T) {}proceed, err := persistSelfHostConfigIfReachable(- "https://api.new.example", "https://new.example", "",+ "https://api.new.example", "https://new.example", "", existing,func(string) serverProbeResult { return serverProbeResult{} },)if err != nil {@@ -229,7 +229,7 @@ func TestPersistSelfHostConfigIfReachable(t *testing.T) {redirectTestHome(t, t.TempDir())proceed, err := persistSelfHostConfigIfReachable(- "https://api.new.example", "https://new.example", "",+ "https://api.new.example", "https://new.example", "", cli.CLIConfig{},func(string) serverProbeResult { return serverProbeResult{statusCode: http.StatusOK, healthy: true} },)if err != nil {@@ -608,3 +608,160 @@ func TestSetupCommandsFailClosedInTaskContext(t *testing.T) {t.Fatalf("owner config content changed: got %q", after)}}++func TestSetupKeepsProfileOnlyForTheSameBackend(t *testing.T) {+ for _, tc := range []struct {+ target string+ keep bool+ }{+ {"https://example.invalid/team/", true},+ {"https://example.invalid/another", false},+ {"https://example.invalid:8443/team", false},+ {"http://example.invalid/team", false},+ {"https://other.invalid/team", false},+ {"https://EXAMPLE.invalid/team", false},+ {"https://[email protected]/team", false},+ {"https://example.invalid:443/team", false},+ } {+ t.Run(tc.target, func(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ old := cli.CLIConfig{ServerURL: "https://example.invalid/team", Token: "test-only", WorkspaceID: "w", DeviceName: "workstation", PollInterval: "1m"}+ if err := cli.SaveCLIConfigForProfile(old, "dev"); err != nil {+ t.Fatal(err)+ }+ if _, err := persistSelfHostConfigIfReachable(tc.target, "https://app.invalid", "dev", old, func(string) serverProbeResult { return serverProbeResult{statusCode: http.StatusOK, healthy: true} }); err != nil {+ t.Fatal(err)+ }+ got, err := cli.LoadCLIConfigForProfile("dev")+ if err != nil {+ t.Fatal(err)+ }+ if tc.keep && (got.DeviceName != old.DeviceName || got.PollInterval != old.PollInterval) {+ t.Fatal("same backend lost profile settings")+ }+ if got.Token != "" || got.WorkspaceID != "" {+ t.Fatal("setup retained login credentials")+ }+ if !tc.keep && got.DeviceName != "" {+ t.Fatal("different backend inherited profile")+ }+ })+ }+}++func TestSetupRejectsProfileChangedDuringConfirmationOrProbe(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ const profile = "setup-change"+ old := cli.CLIConfig{ServerURL: "https://a.invalid", AppURL: "https://a.invalid", Token: "old-fixture"}+ newLogin := cli.CLIConfig{ServerURL: "https://b.invalid", AppURL: "https://b.invalid", Token: "new-fixture", DeviceName: "new-device"}+ for _, stage := range []string{"while confirming", "during health check"} {+ t.Run(stage, func(t *testing.T) {+ if err := cli.SaveCLIConfigForProfile(old, profile); err != nil {+ t.Fatal(err)+ }+ if stage == "while confirming" {+ if err := cli.SaveCLIConfigForProfile(newLogin, profile); err != nil {+ t.Fatal(err)+ }+ }+ ok, err := persistSelfHostConfigIfReachable(old.ServerURL, old.AppURL, profile, old, func(string) serverProbeResult {+ if stage == "during health check" {+ if err := cli.SaveCLIConfigForProfile(newLogin, profile); err != nil {+ t.Fatal(err)+ }+ }+ return serverProbeResult{statusCode: http.StatusOK, healthy: true}+ })+ if err == nil || !strings.Contains(err.Error(), "profile changed") {+ t.Fatalf("setup accepted stale confirmation: %v, %v", ok, err)+ }+ got, err := cli.LoadCLIConfigForProfile(profile)+ if err != nil || got.ServerURL != newLogin.ServerURL || got.Token != newLogin.Token || got.DeviceName != newLogin.DeviceName {+ t.Fatal("setup replaced a concurrently changed login")+ }+ })+ }+}++func TestSetupDoesNotRewriteAnUnchangedTarget(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ cfg := cli.CLIConfig{ServerURL: "https://example.test", AppURL: "https://app.example.test"}+ if err := cli.SaveCLIConfigForProfile(cfg, "dev"); err != nil {+ t.Fatal(err)+ }+ path, err := cli.CLIConfigPathForProfile("dev")+ if err != nil {+ t.Fatal(err)+ }+ before, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ ok, err := persistSelfHostConfigIfReachable(cfg.ServerURL+"/", cfg.AppURL+"/", "dev", cfg, func(string) serverProbeResult { return serverProbeResult{statusCode: http.StatusOK, healthy: true} })+ if err != nil || !ok.healthy {+ t.Fatalf("setup = %v, %v", ok, err)+ }+ after, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ if !os.SameFile(before, after) {+ t.Fatal("unchanged profile was rewritten")+ }+}++func TestSetupUnreadableProfileIsNotOverwritten(t *testing.T) {+ for _, setup := range []struct {+ name string+ run func(*cobra.Command, []string) error+ }{+ {"cloud", runSetupCloud},+ {"self-host", runSetupSelfHost},+ } {+ for _, invalid := range []string{"invalid JSON", "permission denied"} {+ t.Run(setup.name+"/"+invalid, func(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ const profile = "unreadable-setup"+ path, err := cli.CLIConfigPathForProfile(profile)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ before := []byte(`{"device_name":"preserve me",`)+ if invalid == "permission denied" {+ before = []byte(`{"device_name":"preserve me"}`)+ }+ if err := os.WriteFile(path, before, 0o600); err != nil {+ t.Fatal(err)+ }+ if invalid == "permission denied" {+ if err := os.Chmod(path, 0); err != nil {+ t.Skipf("cannot make profile unreadable: %v", err)+ }+ defer os.Chmod(path, 0o600)+ if _, err := os.ReadFile(path); err == nil {+ t.Skip("platform allows reading a mode-000 profile")+ }+ }+ cmd := testCmd()+ cmd.Flags().String("profile", profile, "")+ err = setup.run(cmd, nil)+ if err == nil || !strings.Contains(err.Error(), "read existing profile") {+ t.Fatalf("setup error = %v, want read existing profile", err)+ }+ if err := os.Chmod(path, 0o600); err != nil {+ t.Fatal(err)+ }+ after, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(before, after) {+ t.Fatal("setup replaced an unreadable profile")+ }+ })+ }+ }+}