From 8a4a5300994e13ee7f1ed181e781df3059f56f4b Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Thu, 14 Dec 2023 21:13:02 +0800
Subject: [PATCH 01/10] enable json load

---
 src/client/runner/terraformRunner.ts | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/client/runner/terraformRunner.ts b/src/client/runner/terraformRunner.ts
index 184d901..e58203f 100644
--- a/src/client/runner/terraformRunner.ts
+++ b/src/client/runner/terraformRunner.ts
@@ -61,6 +61,10 @@ export class TerraformRunner extends BaseRunner {
         );
     }
 
+    public async executeVersion(params: type): Promise<string> {
+
+    }
+
     public async preImport(cwd: string, args: any, file: string): Promise<{ importArgs: string, tfFile: string }> {
         const fileName = file ?? args.resource.type + '.tf';
 

From 07234e3ce566d7436250d34882cd7181128052f8 Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Tue, 19 Dec 2023 20:35:25 +0800
Subject: [PATCH 02/10] fix multiple json issue

---
 package.json                              | 2 +-
 src/autocomplete/TerraformTipsProvider.ts | 1 +
 src/client/runner/terraformRunner.ts      | 4 ----
 3 files changed, 2 insertions(+), 5 deletions(-)

diff --git a/package.json b/package.json
index 28e38f9..6601ea2 100644
--- a/package.json
+++ b/package.json
@@ -251,7 +251,7 @@
         "lint": "eslint src --ext ts",
         "test": "npm run compile",
         "vscode:prepublish": "npm run esbuild-base -- --minify",
-        "esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=out/main.js --external:vscode --format=cjs --platform=node",
+        "esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=out/main.js --external:vscode --external:config/tips --format=cjs --platform=node",
         "esbuild": "npm run esbuild-base -- --sourcemap",
         "esbuild-watch": "npm run esbuild-base -- --sourcemap --watch",
         "test-compile": "tsc -p ./"
diff --git a/src/autocomplete/TerraformTipsProvider.ts b/src/autocomplete/TerraformTipsProvider.ts
index 5293ff9..6990891 100644
--- a/src/autocomplete/TerraformTipsProvider.ts
+++ b/src/autocomplete/TerraformTipsProvider.ts
@@ -449,6 +449,7 @@ async function loadResource(extPath: string): Promise<Tips> {
 
     tipFiles.some(file => {
         if (compareVersions(tfVersion, file.version) >= 0) {
+            console.log(`loaded json version:${file.version}`);
             result = file.json as Tips;
             return true;
         }
diff --git a/src/client/runner/terraformRunner.ts b/src/client/runner/terraformRunner.ts
index e58203f..184d901 100644
--- a/src/client/runner/terraformRunner.ts
+++ b/src/client/runner/terraformRunner.ts
@@ -61,10 +61,6 @@ export class TerraformRunner extends BaseRunner {
         );
     }
 
-    public async executeVersion(params: type): Promise<string> {
-
-    }
-
     public async preImport(cwd: string, args: any, file: string): Promise<{ importArgs: string, tfFile: string }> {
         const fileName = file ?? args.resource.type + '.tf';
 

From 5b5ccda1da723b9c250012726872815dad3c14cd Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Wed, 20 Dec 2023 13:03:27 +0800
Subject: [PATCH 03/10] 1.fix the logic of JSON files match. 2.use the
 extensionPath instead of __dirname. 3.load json files with sync(await). 4.rm
 pre-release trigger when PR merged.

---
 package.json                              | 2 +-
 src/autocomplete/TerraformTipsProvider.ts | 1 -
 2 files changed, 1 insertion(+), 2 deletions(-)

diff --git a/package.json b/package.json
index 6601ea2..28e38f9 100644
--- a/package.json
+++ b/package.json
@@ -251,7 +251,7 @@
         "lint": "eslint src --ext ts",
         "test": "npm run compile",
         "vscode:prepublish": "npm run esbuild-base -- --minify",
-        "esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=out/main.js --external:vscode --external:config/tips --format=cjs --platform=node",
+        "esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=out/main.js --external:vscode --format=cjs --platform=node",
         "esbuild": "npm run esbuild-base -- --sourcemap",
         "esbuild-watch": "npm run esbuild-base -- --sourcemap --watch",
         "test-compile": "tsc -p ./"
diff --git a/src/autocomplete/TerraformTipsProvider.ts b/src/autocomplete/TerraformTipsProvider.ts
index 6990891..5293ff9 100644
--- a/src/autocomplete/TerraformTipsProvider.ts
+++ b/src/autocomplete/TerraformTipsProvider.ts
@@ -449,7 +449,6 @@ async function loadResource(extPath: string): Promise<Tips> {
 
     tipFiles.some(file => {
         if (compareVersions(tfVersion, file.version) >= 0) {
-            console.log(`loaded json version:${file.version}`);
             result = file.json as Tips;
             return true;
         }

From 80722bb7a06d71872c7d6a4fc64c6f02c4f27aa6 Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Wed, 20 Dec 2023 13:16:14 +0800
Subject: [PATCH 04/10] 0.0.26

---
 package-lock.json | 4 ++--
 package.json      | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/package-lock.json b/package-lock.json
index df8988b..0914eca 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
 {
     "name": "vscode-tencentcloud-terraform",
-    "version": "0.0.25",
+    "version": "0.0.26",
     "lockfileVersion": 3,
     "requires": true,
     "packages": {
         "": {
             "name": "vscode-tencentcloud-terraform",
-            "version": "0.0.25",
+            "version": "0.0.26",
             "license": "MIT",
             "dependencies": {
                 "@types/jsdom": "^21.1.4",
diff --git a/package.json b/package.json
index 28e38f9..1b003aa 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
     "name": "vscode-tencentcloud-terraform",
     "displayName": "Tencent Cloud Terraform",
     "description": "VS Code extension for developing with Terraform on Tencent Cloud",
-    "version": "0.0.25",
+    "version": "0.0.26",
     "license": "MIT",
     "publisher": "Tencent-Cloud",
     "icon": "images/tc-tf-logo.png",

From ccbdffac81a0cb967ee1938cd588a1228364b243 Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Fri, 29 Dec 2023 20:56:02 +0800
Subject: [PATCH 05/10] add request client

---
 src/commons/tencent/user/index.ts | 28 ++++++++++++++++++++++------
 src/connectivity/client.ts        | 15 +++++++++++----
 2 files changed, 33 insertions(+), 10 deletions(-)

diff --git a/src/commons/tencent/user/index.ts b/src/commons/tencent/user/index.ts
index 0b91656..c1b7b89 100644
--- a/src/commons/tencent/user/index.ts
+++ b/src/commons/tencent/user/index.ts
@@ -1,5 +1,5 @@
 import { localize } from "vscode-nls-i18n";
-import { ExtensionContext, workspace, ConfigurationTarget, window, ProgressLocation, MessageItem } from "vscode";
+import { ExtensionContext, workspace, ConfigurationTarget, window, ProgressLocation, MessageItem, extensions } from "vscode";
 
 import { container } from "../../container";
 import { Context } from "../../context";
@@ -7,7 +7,7 @@ import { tree } from "../treeDataProvider";
 import { getCredentailByInput } from "./auth";
 import { AbstractClient } from "tencentcloud-sdk-nodejs/tencentcloud/common/abstract_client";
 import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interface";
-import { getCamClient, getStsClient } from "@/connectivity/client";
+import { getCamClient, getCommonClient, getStsClient } from "@/connectivity/client";
 import * as loginMgt from "../../../views/login/loginMgt";
 import * as settingUtils from "../../../utils/settingUtils";
 
@@ -24,6 +24,7 @@ export namespace user {
         arn?: string;
     }
 
+    export const REQUEST_CLIENT_PREFIX = "Terraform-Vscode-";//Terraform-1.81.61@vscode";
     export const AKSK_TITLE = "TcTerraform.pickup.aksk";
     export const OAUTH_TITLE = "TcTerraform.pickup.oauth";
     export const AKSK_PLACEHOLD = "TcTerraform.pickup.aksk.placeholder";
@@ -71,10 +72,16 @@ export namespace user {
             try {
                 // query user info
                 const stsClient = await getStsClient();
-                const stsResp = await stsClient?.GetCallerIdentity().
+                const currentVersion = getExtensionVersion();
+                const reqCli = `${REQUEST_CLIENT_PREFIX}v${currentVersion}`;
+                stsClient.sdkVersion = reqCli;
+                console.log('[DEBUG]--------------------getStsClient:', stsClient);
+                // const stsClient = await getCommonClient("sts.tencentcloudapi.com", "2018-08-13");
+                // const stsResp = await stsClient.request("GetCallerIdentity", req).
+                const stsResp = await stsClient?.GetCallerIdentity(null).
                     then(
                         (result) => {
-                            console.debug('[DEBUG]--------------------------------result:', result);
+                            console.debug('[DEBUG]--------------------------------GetCallerIdentity result:', result);
                             if (!result) {
                                 throw new Error('[Warn] GetCallerIdentity result.TotalCount is 0.');
                             }
@@ -84,12 +91,15 @@ export namespace user {
                             throw new Error(err);
                         }
                     );
+                // ) as stsModels.GetCallerIdentityResponse;
 
                 const camClient = await getCamClient();
-                const camResp = await camClient?.GetUserAppId().
+                camClient.sdkVersion = reqCli;
+                console.log('[DEBUG]--------------------getCamClient:', camClient);
+                const camResp = await camClient?.GetUserAppId(null).
                     then(
                         (result) => {
-                            console.debug('[DEBUG]--------------------------------result:', result);
+                            console.debug('[DEBUG]--------------------------------GetUserAppId result:', result);
                             if (!result) {
                                 throw new Error('[Warn] GetUserAppId result.TotalCount is 0.');
                             }
@@ -122,6 +132,12 @@ export namespace user {
         }
     }
 
+    function getExtensionVersion(): string {
+        let extension = extensions.getExtension('Tencent-Cloud.vscode-tencentcloud-terraform');
+        let currentVersion = extension.packageJSON.version;
+        return currentVersion;
+    }
+
     export async function loginOut() {
         const yesBtn: MessageItem = { title: localize("TcTerraform.common.yes") };
         const action = await window.showWarningMessage(
diff --git a/src/connectivity/client.ts b/src/connectivity/client.ts
index 2a0b240..f724487 100644
--- a/src/connectivity/client.ts
+++ b/src/connectivity/client.ts
@@ -11,6 +11,7 @@ import * as tencentcloud from "tencentcloud-sdk-nodejs";
 import { localize } from "vscode-nls-i18n";
 import * as settingUtils from "../utils/settingUtils";
 
+const DefaultReqCliHeader = { "X-TC-RequestClient": "Terraform-Vscode-v0.0.26" };
 
 export async function getTkeClient(): Promise<TkeClient> {
     const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
@@ -32,6 +33,7 @@ export async function getTkeClient(): Promise<TkeClient> {
             httpProfile: {
                 reqMethod: "POST", // 请求方法
                 reqTimeout: 30, // 请求超时时间，默认60s
+                headers: DefaultReqCliHeader,
             },
         },
     });
@@ -60,12 +62,13 @@ export async function getCvmClient(): Promise<CvmClient> {
                 reqMethod: "POST", // 请求方法
                 // reqTimeout: 60, // 请求超时时间，默认60s
                 endpoint: "cvm.tencentcloudapi.com",
+                headers: DefaultReqCliHeader,
             },
         },
     });
 }
 
-export async function getCommonClient(): Promise<AbstractClient> {
+export async function getCommonClient(ep?, version?, reqCli?: string): Promise<AbstractClient> {
     const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
 
     if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
@@ -75,20 +78,24 @@ export async function getCommonClient(): Promise<AbstractClient> {
     }
 
     const client = new AbstractClient(
-        "open.test.tencentcloudapi.com",
-        "2018-12-25",
+        ep ?? "open.test.tencentcloudapi.com",
+        version ?? "2018-12-25",
         {
             credential: {
                 secretId: secretId,
                 secretKey: secretKey,
             },
+            region: region ?? "ap-guangzhou",
             profile: {
                 httpProfile: {
-                    proxy: "http://9.135.97.58:8899",
+                    reqMethod: "POST", // 请求方法
+                    endpoint: ep ?? "open.test.tencentcloudapi.com",
+                    headers: DefaultReqCliHeader,
                 },
             },
         }
     );
+    client.sdkVersion = reqCli ?? "Terraform-1.81.61@vscode";
 
     return client;
 }

From eedef0083042bc9db64ffb030469ce76e496c52b Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Fri, 29 Dec 2023 20:56:23 +0800
Subject: [PATCH 06/10] 0.0.27

---
 package-lock.json | 4 ++--
 package.json      | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/package-lock.json b/package-lock.json
index 0914eca..8023169 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
 {
     "name": "vscode-tencentcloud-terraform",
-    "version": "0.0.26",
+    "version": "0.0.27",
     "lockfileVersion": 3,
     "requires": true,
     "packages": {
         "": {
             "name": "vscode-tencentcloud-terraform",
-            "version": "0.0.26",
+            "version": "0.0.27",
             "license": "MIT",
             "dependencies": {
                 "@types/jsdom": "^21.1.4",
diff --git a/package.json b/package.json
index 1b003aa..a05971a 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
     "name": "vscode-tencentcloud-terraform",
     "displayName": "Tencent Cloud Terraform",
     "description": "VS Code extension for developing with Terraform on Tencent Cloud",
-    "version": "0.0.26",
+    "version": "0.0.27",
     "license": "MIT",
     "publisher": "Tencent-Cloud",
     "icon": "images/tc-tf-logo.png",

From 5832858c25e14a368bcc10701f223bdc3811d415 Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Tue, 2 Jan 2024 18:07:26 +0800
Subject: [PATCH 07/10] fix cvm explorer issue when instances are null

---
 src/import/cvm.ts                  |  2 +-
 src/views/resources/resExplorer.ts | 10 +++++++---
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/src/import/cvm.ts b/src/import/cvm.ts
index 0a6089d..31796a4 100644
--- a/src/import/cvm.ts
+++ b/src/import/cvm.ts
@@ -27,7 +27,7 @@ export class CvmService implements ITencentCloudAPI {
             (result) => {
                 // console.debug('[DEBUG]--------------------------------result:', result);
                 if (result.TotalCount === 0) {
-                    throw new Error('[Warn] DescribeInstances result.TotalCount is 0.');
+                    console.warn('[Warn] DescribeInstances result.TotalCount is 0.');
                 }
                 return result.InstanceSet;
             },
diff --git a/src/views/resources/resExplorer.ts b/src/views/resources/resExplorer.ts
index 4fe650d..d0adf8c 100644
--- a/src/views/resources/resExplorer.ts
+++ b/src/views/resources/resExplorer.ts
@@ -21,8 +21,12 @@ export class CvmResProvider extends tencent.tree.TreeDataProvider {
                 const service = new CvmService();
                 const instances = await service.describeInstances();
                 const config = await service.getConfig();
+                let items: tencent.tree.TreeItem[] = [];
+                if (!Array.isArray(instances)) {
+                    return items;// return [] if instances nil
+                }
 
-                const items: tencent.tree.TreeItem[] = Array.isArray(instances)
+                items = instances.length > 0
                     ? instances.map(instance => ({
                         label: `${instance.InstanceName}(${instance.InstanceId})`,
                         id: instance.InstanceId,
@@ -42,12 +46,12 @@ export class CvmResProvider extends tencent.tree.TreeDataProvider {
                             }],
                         },
                     }))
-                    : [];// return [] if instances nil
+                    : [{ label: "No instance." }]; // return none tips if instance is empty
 
                 return items;
             } catch (error) {
                 console.error('[Error]#### getChildren got a error:[%s] from CvmService. stack:%s', error.message, error.stack);
-                return error;
+                return [];
             }
 
         } else {

From 25a9322c5ebdcb9ee5f31e6e4b89a320c133d0f0 Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Tue, 2 Jan 2024 19:32:35 +0800
Subject: [PATCH 08/10] 0.0.28

---
 package-lock.json | 4 ++--
 package.json      | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/package-lock.json b/package-lock.json
index 8023169..04eaf7f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
 {
     "name": "vscode-tencentcloud-terraform",
-    "version": "0.0.27",
+    "version": "0.0.28",
     "lockfileVersion": 3,
     "requires": true,
     "packages": {
         "": {
             "name": "vscode-tencentcloud-terraform",
-            "version": "0.0.27",
+            "version": "0.0.28",
             "license": "MIT",
             "dependencies": {
                 "@types/jsdom": "^21.1.4",
diff --git a/package.json b/package.json
index a05971a..387a81b 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
     "name": "vscode-tencentcloud-terraform",
     "displayName": "Tencent Cloud Terraform",
     "description": "VS Code extension for developing with Terraform on Tencent Cloud",
-    "version": "0.0.27",
+    "version": "0.0.28",
     "license": "MIT",
     "publisher": "Tencent-Cloud",
     "icon": "images/tc-tf-logo.png",

From a5cf6baad4a0419f7bfa5f40beff553cfc83e650 Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Thu, 4 Jan 2024 15:23:37 +0800
Subject: [PATCH 09/10] add request client header into tf request for all
 terminals.

---
 src/client/runner/terraformRunner.ts         |  2 +-
 src/client/terminal/integratedShell.ts       | 17 ++++++++----
 src/client/terminal/terraformShellManager.ts | 17 ++++++++++--
 src/commons/constants.ts                     |  8 ++++--
 src/commons/context.ts                       | 13 +++++++++
 src/commons/tencent/user/index.ts            | 13 ++-------
 src/extension.ts                             | 29 ++++++++++++++++++--
 7 files changed, 76 insertions(+), 23 deletions(-)

diff --git a/src/client/runner/terraformRunner.ts b/src/client/runner/terraformRunner.ts
index 184d901..5c8bdce 100644
--- a/src/client/runner/terraformRunner.ts
+++ b/src/client/runner/terraformRunner.ts
@@ -32,7 +32,7 @@ export class TerraformRunner extends BaseRunner {
     public async init(): Promise<any> {
         console.debug("[DEBUG]#### TerraformRunner init begin.");
 
-        this.setAKSK();
+        // this.setAKSK();
 
         terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Version);
         terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Init);
diff --git a/src/client/terminal/integratedShell.ts b/src/client/terminal/integratedShell.ts
index 00ece89..6b07176 100644
--- a/src/client/terminal/integratedShell.ts
+++ b/src/client/terminal/integratedShell.ts
@@ -23,17 +23,18 @@ import { BaseRunner } from "../runner/baseRunner";
 import { TerraformerRunner, CommandType, FlagType, FlagsMap, defaultProduct } from "../../client/runner/terraformerRunner";
 import { TerraformRunner } from "../runner/terraformRunner";
 
-// import stripAnsi from 'strip-ansi';
 
 export class IntegratedShell extends BaseShell {
     // eslint-disable-next-line @typescript-eslint/naming-convention
     private static readonly GRAPH_FILE_NAME = "graph.png";
     private readonly runner: BaseRunner;
+    private readonly env: { [key: string]: string | null | undefined };
 
-    constructor(rr: BaseRunner) {
+    constructor(rr: BaseRunner, ee: any) {
         super();
         // terraform or terraformer?
         this.runner = rr;
+        this.env = ee;
     }
 
     // Creates a png of terraform resource graph to visualize the resources under management.
@@ -179,7 +180,7 @@ export class IntegratedShell extends BaseShell {
     }
 
     public async runTerraformCmd(tfCommand: string, args?: string[]) {
-        this.checkCreateTerminal();
+        this.createTerminal(Constants.TerraformTerminalName);
         this.terminal.show();
 
         // const cmd= [tfCommand, args.values].join(' ');
@@ -193,7 +194,7 @@ export class IntegratedShell extends BaseShell {
     }
 
     public async runNormalCmd(tfCommand: string, newLine = true) {
-        this.checkCreateTerminal();
+        this.createTerminal(Constants.TerraformTerminalName);
         this.terminal.show();
         this.terminal.sendText(tfCommand, newLine);
     }
@@ -220,9 +221,13 @@ export class IntegratedShell extends BaseShell {
         }
     }
 
-    private checkCreateTerminal(): void {
+    private createTerminal(name: string): void {
         if (!this.terminal) {
-            this.terminal = vscode.window.createTerminal(Constants.TerraformTerminalName);
+            const options: vscode.TerminalOptions = {
+                name: name,
+                env: this.env,
+            };
+            this.terminal = vscode.window.createTerminal(options);
         }
     }
 }
diff --git a/src/client/terminal/terraformShellManager.ts b/src/client/terminal/terraformShellManager.ts
index 662e6b5..4072fcf 100644
--- a/src/client/terminal/terraformShellManager.ts
+++ b/src/client/terminal/terraformShellManager.ts
@@ -11,6 +11,9 @@ import { TencentCloudShell } from "./cloudShell";
 import { IntegratedShell } from "./integratedShell";
 import { isTerminalSetToCloudShell } from "../../utils/settingUtils";
 import { TerraformerRunner } from "../runner/terraformerRunner";
+import * as context from "../../commons/context";
+import * as settingUtils from "../../utils/settingUtils";
+import { Constants } from "../../commons/constants";
 
 export interface ITerraformShellManager {
     getShell(): BaseShell;
@@ -19,6 +22,8 @@ export interface ITerraformShellManager {
     dispose(): void;
 }
 
+
+
 class TerraformShellManager implements ITerraformShellManager {
     private static cloudShell = new TencentCloudShell();
     private static integratedShell: IntegratedShell;
@@ -39,11 +44,19 @@ class TerraformShellManager implements ITerraformShellManager {
 
     public getIntegratedShell(runner?: any): IntegratedShell {
         if (!TerraformShellManager.integratedShell) {
+            // set TencentCloud AKSK, Region and Client info
+            const [ak, sk, region] = settingUtils.getAKSKandRegion();
+            const tfEnv = {
+                [Constants.REQUEST_CLIENT]: context.genRequestClient(),
+                [Constants.TENCENTCLOUD_SECRET_ID]: ak,
+                [Constants.TENCENTCLOUD_SECRET_KEY]: sk,
+                [Constants.TENCENTCLOUD_REGION]: region,
+            };
             // default runner is Terraformer
-            TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance());
+            TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance(), tfEnv);
             // specify runner
             if (runner) {
-                TerraformShellManager.integratedShell = new IntegratedShell(runner);
+                TerraformShellManager.integratedShell = new IntegratedShell(runner, tfEnv);
             }
         }
         return TerraformShellManager.integratedShell;
diff --git a/src/commons/constants.ts b/src/commons/constants.ts
index 9abe975..5844399 100644
--- a/src/commons/constants.ts
+++ b/src/commons/constants.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/naming-convention */
 /*---------------------------------------------------------------------------------------------
  *  Copyright (c) Tencent Corporation. All rights reserved.
  *  Licensed under the MIT License. See License.txt in the project root for license information.
@@ -6,6 +7,9 @@
 "use strict";
 
 export class Constants {
-    // eslint-disable-next-line @typescript-eslint/naming-convention
-    public static TerraformTerminalName = "TIAT-Terraform";
+    public static TerraformTerminalName = "TIC-Terraform";
+    public static REQUEST_CLIENT = "TENCENTCLOUD_API_REQUEST_CLIENT";
+    public static TENCENTCLOUD_SECRET_ID = "TENCENTCLOUD_SECRET_ID";
+    public static TENCENTCLOUD_SECRET_KEY = "TENCENTCLOUD_SECRET_KEY";
+    public static TENCENTCLOUD_REGION = "TENCENTCLOUD_REGION";
 }
diff --git a/src/commons/context.ts b/src/commons/context.ts
index bfc1621..ed78b8c 100644
--- a/src/commons/context.ts
+++ b/src/commons/context.ts
@@ -2,7 +2,20 @@ import { container } from './container';
 import * as vscode from 'vscode';
 
 export const Context = Symbol('ExtensionContext');
+export const REQUEST_CLIENT_PREFIX = "Terraform-Vscode-";//Terraform-1.81.61@vscode";
 
 export function bindExtensionContext(ctx: vscode.ExtensionContext) {
     container.bind(Context).toConstantValue(ctx);
+}
+
+export function getExtensionVersion(): string {
+    let extension = vscode.extensions.getExtension('Tencent-Cloud.vscode-tencentcloud-terraform');
+    let currentVersion = extension.packageJSON.version;
+    return currentVersion;
+}
+
+export function genRequestClient(): string {
+    const currentVersion = getExtensionVersion();
+    const reqCli = `${REQUEST_CLIENT_PREFIX}v${currentVersion}`;
+    return reqCli;
 }
\ No newline at end of file
diff --git a/src/commons/tencent/user/index.ts b/src/commons/tencent/user/index.ts
index c1b7b89..5dff4ca 100644
--- a/src/commons/tencent/user/index.ts
+++ b/src/commons/tencent/user/index.ts
@@ -1,5 +1,5 @@
 import { localize } from "vscode-nls-i18n";
-import { ExtensionContext, workspace, ConfigurationTarget, window, ProgressLocation, MessageItem, extensions } from "vscode";
+import { ExtensionContext, workspace, ConfigurationTarget, window, ProgressLocation, MessageItem } from "vscode";
 
 import { container } from "../../container";
 import { Context } from "../../context";
@@ -10,6 +10,7 @@ import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interfac
 import { getCamClient, getCommonClient, getStsClient } from "@/connectivity/client";
 import * as loginMgt from "../../../views/login/loginMgt";
 import * as settingUtils from "../../../utils/settingUtils";
+import * as context from "../../context";
 
 export namespace user {
     export interface UserInfo {
@@ -24,7 +25,6 @@ export namespace user {
         arn?: string;
     }
 
-    export const REQUEST_CLIENT_PREFIX = "Terraform-Vscode-";//Terraform-1.81.61@vscode";
     export const AKSK_TITLE = "TcTerraform.pickup.aksk";
     export const OAUTH_TITLE = "TcTerraform.pickup.oauth";
     export const AKSK_PLACEHOLD = "TcTerraform.pickup.aksk.placeholder";
@@ -72,8 +72,7 @@ export namespace user {
             try {
                 // query user info
                 const stsClient = await getStsClient();
-                const currentVersion = getExtensionVersion();
-                const reqCli = `${REQUEST_CLIENT_PREFIX}v${currentVersion}`;
+                const reqCli = context.genRequestClient();
                 stsClient.sdkVersion = reqCli;
                 console.log('[DEBUG]--------------------getStsClient:', stsClient);
                 // const stsClient = await getCommonClient("sts.tencentcloudapi.com", "2018-08-13");
@@ -132,12 +131,6 @@ export namespace user {
         }
     }
 
-    function getExtensionVersion(): string {
-        let extension = extensions.getExtension('Tencent-Cloud.vscode-tencentcloud-terraform');
-        let currentVersion = extension.packageJSON.version;
-        return currentVersion;
-    }
-
     export async function loginOut() {
         const yesBtn: MessageItem = { title: localize("TcTerraform.common.yes") };
         const action = await window.showWarningMessage(
diff --git a/src/extension.ts b/src/extension.ts
index dd3c3ab..d539365 100644
--- a/src/extension.ts
+++ b/src/extension.ts
@@ -1,7 +1,6 @@
 // The module 'vscode' contains the VS Code extensibility API
 // Import the module and reference it with the alias vscode in your code below
 import * as vscode from 'vscode';
-import * as settingUtils from "./utils/settingUtils";
 import { init } from "vscode-nls-i18n";
 import { TerraformCommand, TerraformerCommand } from "./commons/customCmdRegister";
 import { terraformShellManager } from "./client/terminal/terraformShellManager";
@@ -16,6 +15,8 @@ import { GitUtils } from './utils/gitUtils';
 import _ from 'lodash';
 import * as autocomplete from './autocomplete/TerraformExampleProvider';
 import * as loginMgt from './views/login/loginMgt';
+import * as context from './commons/context';
+import { Constants } from './commons/constants';
 
 const TF_MODE: vscode.DocumentFilter = { language: 'terraform', scheme: 'file' };
 const COMPATIBLE_MODE: vscode.DocumentFilter = { scheme: 'file' };
@@ -29,6 +30,8 @@ export async function activate(context: vscode.ExtensionContext) {
     await TerraformRunner.getInstance().checkInstalled();
     await TerraformerRunner.getInstance().checkInstalled();
 
+    // set request client
+    await setRequestClient();
     // terraform cmd
     context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.apply', () => {
         terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Apply);
@@ -115,9 +118,31 @@ export async function activate(context: vscode.ExtensionContext) {
 
 }
 
+async function setRequestClient() {
+    const config = vscode.workspace.getConfiguration('terminal.integrated.env');
+    const os = getOSPlatform();
+    const curConfig = config[os] || {};
 
+    // env[Constants.REQUEST_CLIENT] = context.genRequestClient();
+    const updatedConfig = { ...curConfig, [Constants.REQUEST_CLIENT]: context.genRequestClient() };
+
+    await config.update(os, updatedConfig, vscode.ConfigurationTarget.Global);
+}
+
+function getOSPlatform(): string {
+    const platform = process.platform;
+    switch (platform) {
+        case 'win32':
+            return 'windows';
+        case 'darwin':
+            return 'osx';
+        case 'linux':
+        default:
+            return 'linux';
+    }
+}
 
 // This method is called when your extension is deactivated
 export function deactivate() {
-    /* TODO document why this function 'deactivate' is empty */
+
 }

From 54080972e8ebfa7186583f13df68354a21743cee Mon Sep 17 00:00:00 2001
From: nickyinluo <nickyinluo@tencent.com>
Date: Mon, 8 Jan 2024 17:51:25 +0800
Subject: [PATCH 10/10] 1.introduce the context to get ext version and provider
 version. 2.adjust the getShell and getIntegratedShell to async to get the
 reqcli with provider version. 3.refactor the queryUserInfo method.
 4.deactivate clear user when close vscode. 5.add warn msg when use without
 login.

---
 package.nls.json                             |   2 +-
 src/autocomplete/TerraformTipsProvider.ts    |  28 +---
 src/client/runner/terraformRunner.ts         |  36 +++--
 src/client/terminal/terraformShellManager.ts |  15 +-
 src/commons/context.ts                       |  38 ++++-
 src/commons/customCmdRegister.ts             |  12 +-
 src/commons/tencent/user/auth/credentail.ts  |   1 -
 src/commons/tencent/user/index.ts            | 138 ++++++++-----------
 src/extension.ts                             |  31 +++--
 src/utils/settingUtils.ts                    |   2 +-
 src/views/login/loginExplorer.ts             |   4 +-
 11 files changed, 153 insertions(+), 154 deletions(-)

diff --git a/package.nls.json b/package.nls.json
index 60d4f54..582ee44 100644
--- a/package.nls.json
+++ b/package.nls.json
@@ -20,7 +20,7 @@
     "TcTerraform.pickup.aksk.placeholder": "Tencent Cloud {0}",
     "TcTerraform.pickup.aksk.verify.empty": "{0} can not be empty",
     "TcTerraform.welcome": "Welcome to use Tencent Cloud Terraform extension, please wait for the page loading...",
-    "TcTerraform.msg.aksk.notfound": "Cannot find TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY, please sign in first!",
+    "TcTerraform.msg.aksk.notfound": "Cannot find user info, please sign in first!",
     "TcTerraform.login": "Login Tencent Cloud...",
     "TcTerraform.login.msg.success": "Logged into Tencent Cloud successfully.",
     "TcTerraform.login.msg.need.login": "Please log in Tencent Cloud first.",
diff --git a/src/autocomplete/TerraformTipsProvider.ts b/src/autocomplete/TerraformTipsProvider.ts
index 5293ff9..b9d6817 100644
--- a/src/autocomplete/TerraformTipsProvider.ts
+++ b/src/autocomplete/TerraformTipsProvider.ts
@@ -2,13 +2,10 @@ import { CompletionItemProvider, TextDocument, Position, CancellationToken, Comp
 // import resources from '../../config/tips/tiat-resources.json';
 import * as _ from "lodash";
 import * as vscode from 'vscode';
-import { executeCommandByExec } from "@/utils/cpUtils";
 import * as fs from "fs";
 import * as path from "path";
-import * as workspaceUtils from "@/utils/workspaceUtils";
-import * as TelemetryWrapper from "vscode-extension-telemetry-wrapper";
+import * as context from "@/commons/context";
 
-const LATEST_VERSION = "latest";
 const versionPattern = /^v\d+(\.\d+){2}\.json$/;
 let topLevelTypes = ["output", "provider", "resource", "variable", "data"];
 let topLevelRegexes = topLevelTypes.map(o => {
@@ -422,26 +419,7 @@ function compareVersions(a, b) {
 
 // load resource config from json files based on the appropriate version
 async function loadResource(extPath: string): Promise<Tips> {
-    let tfVersion: string;
-    const cwd = workspaceUtils.getActiveEditorPath();
-    if (!cwd) {
-        TelemetryWrapper.sendError(Error("noWorkspaceSelected"));
-        console.error(`can not get path from active editor`);
-    }
-
-    await executeCommandByExec("terraform version", cwd).then(output => {
-        let match = RegExp(/tencentcloudstack\/tencentcloud (v\d+\.\d+\.\d+)/).exec(output);
-
-        if (match) {
-            tfVersion = match[1];
-        } else {
-            // gives the latest JSON if not tf provider version found
-            tfVersion = LATEST_VERSION;
-        }
-        console.log(`tf provider version:[${tfVersion}], cwd:[${cwd}]`);
-    }).catch(error => {
-        console.error(`execute terraform version failed: ${error}`);
-    });
+    const tfVersion = await context.getTfVersion();
 
     let result: Tips | null = null;
     const tipsDir = path.join(extPath, 'config', 'tips');
@@ -461,4 +439,4 @@ async function loadResource(extPath: string): Promise<Tips> {
     // vscode.window.showInformationMessage(`Loaded json. tf version:[${tfVersion}], json version:[${result.version}]`);
 
     return result;
-}
+}
\ No newline at end of file
diff --git a/src/client/runner/terraformRunner.ts b/src/client/runner/terraformRunner.ts
index 5c8bdce..2470620 100644
--- a/src/client/runner/terraformRunner.ts
+++ b/src/client/runner/terraformRunner.ts
@@ -13,6 +13,7 @@ import { terraformShellManager } from "../terminal/terraformShellManager";
 import { executeCommand } from "../../utils/cpUtils";
 import * as settingUtils from "../../utils/settingUtils";
 import { openUrlHintOrNotShowAgain } from "../../utils/uiUtils";
+import { localize } from "vscode-nls-i18n";
 
 
 export class TerraformRunner extends BaseRunner {
@@ -32,10 +33,12 @@ export class TerraformRunner extends BaseRunner {
     public async init(): Promise<any> {
         console.debug("[DEBUG]#### TerraformRunner init begin.");
 
-        // this.setAKSK();
+        if (!checkAKSK()) {
+            return "plan abort";
+        }
 
-        terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Version);
-        terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Init);
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Version);
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Init);
 
         return "init success";
     }
@@ -43,9 +46,11 @@ export class TerraformRunner extends BaseRunner {
     public async executePlan(cwd: string, args: any): Promise<string> {
         console.debug("[DEBUG]#### TerraformRunner executePlan begin.");
 
-        // this.setAKSK();
+        if (!checkAKSK()) {
+            return "plan abort";
+        }
 
-        terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Plan);
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Plan);
 
         return "plan success";
     }
@@ -112,7 +117,6 @@ export class TerraformRunner extends BaseRunner {
                     setCheckTerraformCmd(false);
                 });
         }
-        return;
     }
 
     private async resetFileContent(tfFile: string, defaultContents: string) {
@@ -126,15 +130,9 @@ export class TerraformRunner extends BaseRunner {
     public async resetTFState(resAddress: string) {
         console.debug("[DEBUG]#### TerraformRunner resetTFState begin.");
 
-        await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())
+        await (await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()))
             .runTerraformCmd(TerraformCommand.State, ['rm', '-lock=false', resAddress]);
     }
-
-    private setAKSK(runner?: any) {
-        const [ak, sk, region] = settingUtils.getAKSKandRegion();
-        terraformShellManager.getIntegratedShell(runner).runNormalCmd("export TENCENTCLOUD_SECRET_ID=" + ak);
-        terraformShellManager.getIntegratedShell(runner).runNormalCmd("export TENCENTCLOUD_SECRET_KEY=" + sk);
-    }
 }
 
 export function getCheckTerraformCmd(): boolean {
@@ -144,3 +142,15 @@ export function getCheckTerraformCmd(): boolean {
 export function setCheckTerraformCmd(checked: boolean): void {
     vscode.workspace.getConfiguration().update("tcTerraform.checkTerraformCmd", checked);
 }
+
+export function checkAKSK(): boolean {
+    const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
+
+    if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
+        let msg = localize("TcTerraform.msg.aksk.notfound");
+        console.error(msg);
+        vscode.window.showInformationMessage(msg);
+        return false;
+    }
+    return true;
+}
\ No newline at end of file
diff --git a/src/client/terminal/terraformShellManager.ts b/src/client/terminal/terraformShellManager.ts
index 4072fcf..9905c06 100644
--- a/src/client/terminal/terraformShellManager.ts
+++ b/src/client/terminal/terraformShellManager.ts
@@ -16,19 +16,17 @@ import * as settingUtils from "../../utils/settingUtils";
 import { Constants } from "../../commons/constants";
 
 export interface ITerraformShellManager {
-    getShell(): BaseShell;
+    getShell(): Promise<BaseShell>;
     // getCloudShell(): TCCloudShell;
-    getIntegratedShell(runner?: any): IntegratedShell;
+    getIntegratedShell(runner?: any): Promise<IntegratedShell>;
     dispose(): void;
 }
 
-
-
 class TerraformShellManager implements ITerraformShellManager {
     private static cloudShell = new TencentCloudShell();
     private static integratedShell: IntegratedShell;
 
-    public getShell(): BaseShell {
+    public async getShell(): Promise<BaseShell> {
         const isCloudShell: boolean = isTerminalSetToCloudShell();
 
         TelemetryWrapper.addContextProperty("isCloudShell", isCloudShell.toString());
@@ -42,22 +40,23 @@ class TerraformShellManager implements ITerraformShellManager {
         return TerraformShellManager.cloudShell;
     }
 
-    public getIntegratedShell(runner?: any): IntegratedShell {
+    public async getIntegratedShell(runner?: any): Promise<IntegratedShell> {
         if (!TerraformShellManager.integratedShell) {
             // set TencentCloud AKSK, Region and Client info
             const [ak, sk, region] = settingUtils.getAKSKandRegion();
+            const reqCli = await context.genRequestClient();
             const tfEnv = {
-                [Constants.REQUEST_CLIENT]: context.genRequestClient(),
+                [Constants.REQUEST_CLIENT]: reqCli, // set ReqCli for TIC Terminal
                 [Constants.TENCENTCLOUD_SECRET_ID]: ak,
                 [Constants.TENCENTCLOUD_SECRET_KEY]: sk,
                 [Constants.TENCENTCLOUD_REGION]: region,
             };
             // default runner is Terraformer
             TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance(), tfEnv);
-            // specify runner
             if (runner) {
                 TerraformShellManager.integratedShell = new IntegratedShell(runner, tfEnv);
             }
+
         }
         return TerraformShellManager.integratedShell;
     }
diff --git a/src/commons/context.ts b/src/commons/context.ts
index ed78b8c..7b722bc 100644
--- a/src/commons/context.ts
+++ b/src/commons/context.ts
@@ -1,8 +1,13 @@
+/* eslint-disable @typescript-eslint/naming-convention */
 import { container } from './container';
 import * as vscode from 'vscode';
+import * as workspaceUtils from "@/utils/workspaceUtils";
+import * as cpUtils from "@/utils/cpUtils";
+import * as TelemetryWrapper from "vscode-extension-telemetry-wrapper";
 
 export const Context = Symbol('ExtensionContext');
-export const REQUEST_CLIENT_PREFIX = "Terraform-Vscode-";//Terraform-1.81.61@vscode";
+export const REQUEST_CLIENT_PREFIX = "Terraform-";//Terraform-1.81.61@vscode";
+const LATEST_VERSION = "latest";
 
 export function bindExtensionContext(ctx: vscode.ExtensionContext) {
     container.bind(Context).toConstantValue(ctx);
@@ -14,8 +19,33 @@ export function getExtensionVersion(): string {
     return currentVersion;
 }
 
-export function genRequestClient(): string {
-    const currentVersion = getExtensionVersion();
-    const reqCli = `${REQUEST_CLIENT_PREFIX}v${currentVersion}`;
+export async function genRequestClient(): Promise<string> {
+    const extVersion = getExtensionVersion();
+    const tfVersion = await getTfVersion() || LATEST_VERSION;
+    const reqCli = `${REQUEST_CLIENT_PREFIX}${tfVersion}@vscode-v${extVersion}`;
     return reqCli;
+}
+
+export async function getTfVersion(): Promise<string> {
+    let tfVersion = '';
+    const cwd = workspaceUtils.getActiveEditorPath();
+    if (!cwd) {
+        TelemetryWrapper.sendError(Error("noWorkspaceSelected"));
+        console.error(`can not get path from active editor`);
+    }
+
+    await cpUtils.executeCommandByExec("terraform version", cwd).then(output => {
+        let match = RegExp(/tencentcloudstack\/tencentcloud (v\d+\.\d+\.\d+)/).exec(output);
+
+        if (match) {
+            tfVersion = match[1];
+        } else {
+            // gives the latest JSON if not tf provider version found
+            tfVersion = LATEST_VERSION;
+        }
+        console.log(`[DEBUG]getTfVersion tf provider version:[${tfVersion}], cwd:[${cwd}]`);
+    }).catch(error => {
+        console.error(`execute terraform version failed: ${error}`);
+    });
+    return tfVersion;
 }
\ No newline at end of file
diff --git a/src/commons/customCmdRegister.ts b/src/commons/customCmdRegister.ts
index c23df1b..00c9d36 100644
--- a/src/commons/customCmdRegister.ts
+++ b/src/commons/customCmdRegister.ts
@@ -42,16 +42,16 @@ export function regHelpCommands() {
 }
 
 export function regResourceRelatedCommands() {
-    commands.registerCommand(cmds.executeTferImport, function (param: any) {
-        terraformShellManager.getIntegratedShell(TerraformerRunner.getInstance()).import(param, param.fileName);
+    commands.registerCommand(cmds.executeTferImport, async function (param: any) {
+        (await terraformShellManager.getIntegratedShell(TerraformerRunner.getInstance())).import(param, param.fileName);
     });
 
-    commands.registerCommand("tcTerraform.init", function (param: any) {
-        terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()).init();
+    commands.registerCommand("tcTerraform.init", async function (param: any) {
+        (await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())).init();
     });
 
-    commands.registerCommand("tcTerraform.plan", function (param: any) {
-        terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()).plan(param);
+    commands.registerCommand("tcTerraform.plan", async function (param: any) {
+        (await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())).plan(param);
     });
 
     commands.registerCommand(resourceRefresh, function (param: any) {
diff --git a/src/commons/tencent/user/auth/credentail.ts b/src/commons/tencent/user/auth/credentail.ts
index eaddd8a..c948d50 100644
--- a/src/commons/tencent/user/auth/credentail.ts
+++ b/src/commons/tencent/user/auth/credentail.ts
@@ -2,7 +2,6 @@ import MultiStepInput from "../../../multiStepInput";
 import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interface";
 import { localize } from "vscode-nls-i18n";
 import constant from "../index";
-import * as vscode from "vscode";
 
 export async function getCredentailByInput() {
     const defaultRegion = "ap-guangzhou";
diff --git a/src/commons/tencent/user/index.ts b/src/commons/tencent/user/index.ts
index 5dff4ca..e19a40e 100644
--- a/src/commons/tencent/user/index.ts
+++ b/src/commons/tencent/user/index.ts
@@ -40,85 +40,15 @@ export namespace user {
         // only support aksk way right now
         if (aksk === pick) {
             const credential = await getCredentailByInput();
-            const accessKey = credential.secretId;
-            const secretKey = credential.secretKey;
-            const region = credential.region;
-
-            // get configuration
-            const config = workspace.getConfiguration();
-
-            // set in vscode configuration(setting.json)
-            await config.update('tcTerraform.properties.secretId', accessKey, ConfigurationTarget.Global)
-                .then(() => {
-                }, (error) => {
-                    window.showErrorMessage('set secretId failed: ' + error);
-                });
-            await config.update('tcTerraform.properties.secretKey', secretKey, ConfigurationTarget.Global)
-                .then(() => {
-                }, (error) => {
-                    window.showErrorMessage('set secretKey failed: ' + error);
-                });
-            await config.update('tcTerraform.properties.region', region, ConfigurationTarget.Global)
-                .then(() => {
-                }, (error) => {
-                    window.showErrorMessage('set region failed: ' + error);
-                });
 
             // set in system environment
-            process.env.TENCENTCLOUD_SECRET_ID = accessKey;
-            process.env.TENCENTCLOUD_SECRET_KEY = secretKey;
-            process.env.TENCENTCLOUD_REGION = region;
+            process.env.TENCENTCLOUD_SECRET_ID = credential.secretId;
+            process.env.TENCENTCLOUD_SECRET_KEY = credential.secretKey;
+            process.env.TENCENTCLOUD_REGION = credential.region;
 
             try {
                 // query user info
-                const stsClient = await getStsClient();
-                const reqCli = context.genRequestClient();
-                stsClient.sdkVersion = reqCli;
-                console.log('[DEBUG]--------------------getStsClient:', stsClient);
-                // const stsClient = await getCommonClient("sts.tencentcloudapi.com", "2018-08-13");
-                // const stsResp = await stsClient.request("GetCallerIdentity", req).
-                const stsResp = await stsClient?.GetCallerIdentity(null).
-                    then(
-                        (result) => {
-                            console.debug('[DEBUG]--------------------------------GetCallerIdentity result:', result);
-                            if (!result) {
-                                throw new Error('[Warn] GetCallerIdentity result.TotalCount is 0.');
-                            }
-                            return result;
-                        },
-                        (err) => {
-                            throw new Error(err);
-                        }
-                    );
-                // ) as stsModels.GetCallerIdentityResponse;
-
-                const camClient = await getCamClient();
-                camClient.sdkVersion = reqCli;
-                console.log('[DEBUG]--------------------getCamClient:', camClient);
-                const camResp = await camClient?.GetUserAppId(null).
-                    then(
-                        (result) => {
-                            console.debug('[DEBUG]--------------------------------GetUserAppId result:', result);
-                            if (!result) {
-                                throw new Error('[Warn] GetUserAppId result.TotalCount is 0.');
-                            }
-                            return result;
-                        },
-                        (err) => {
-                            throw new Error(err);
-                        }
-                    );
-
-                // set user info
-                let userinfo: UserInfo = {
-                    secretId: accessKey,
-                    secretKey: secretKey,
-                    uin: stsResp.PrincipalId ?? stsResp.UserId ?? "-",
-                    type: stsResp.Type ?? "unknow",
-                    appid: String(camResp.AppId) ?? "-",
-                    arn: stsResp.Arn,
-                    region: region ?? "unknow",
-                };
+                const userinfo = await queryUserInfo(credential);
                 setInfo(userinfo);
 
             } catch (err) {
@@ -146,8 +76,6 @@ export namespace user {
         }
 
         await clearInfo();
-        loginMgt.clearStatusBar();
-        settingUtils.clearAKSKandRegion();
 
         tree.refreshTreeData();
     }
@@ -227,8 +155,11 @@ export namespace user {
 
     export async function clearInfo() {
         const { secrets } = container.get<ExtensionContext>(Context);
-
         await secrets.delete(USER_INFO);
+
+        loginMgt.clearStatusBar();
+        settingUtils.clearAKSKandRegion();
+
         tree.refreshTreeData();
     }
 
@@ -242,6 +173,57 @@ export namespace user {
 
         return undefined;
     }
+
+    export async function queryUserInfo(credential: any): Promise<user.UserInfo> {
+        const stsClient = await getStsClient();
+        const reqCli = await context.genRequestClient(); // set ReqCli for login scenario
+        stsClient.sdkVersion = reqCli;
+        console.log('[DEBUG]--------------------getStsClient:', stsClient);
+        // const stsClient = await getCommonClient("sts.tencentcloudapi.com", "2018-08-13");
+        // const stsResp = await stsClient.request("GetCallerIdentity", req).
+        const stsResp = await stsClient?.GetCallerIdentity(null).
+            then(
+                (result) => {
+                    console.debug('[DEBUG]--------------------------------GetCallerIdentity result:', result);
+                    if (!result) {
+                        throw new Error('[Warn] GetCallerIdentity result.TotalCount is 0.');
+                    }
+                    return result;
+                },
+                (err) => {
+                    throw new Error(err);
+                }
+            );
+        // ) as stsModels.GetCallerIdentityResponse;
+        const camClient = await getCamClient();
+        camClient.sdkVersion = reqCli;
+        console.log('[DEBUG]--------------------getCamClient:', camClient);
+        const camResp = await camClient?.GetUserAppId(null).
+            then(
+                (result) => {
+                    console.debug('[DEBUG]--------------------------------GetUserAppId result:', result);
+                    if (!result) {
+                        throw new Error('[Warn] GetUserAppId result.TotalCount is 0.');
+                    }
+                    return result;
+                },
+                (err) => {
+                    throw new Error(err);
+                }
+            );
+
+        // set user info
+        let userinfo: user.UserInfo = {
+            secretId: credential.secretId,
+            secretKey: credential.secretKey,
+            uin: stsResp.PrincipalId ?? stsResp.UserId ?? "-",
+            type: stsResp.Type ?? "unknow",
+            appid: String(camResp.AppId ?? "-"),
+            arn: stsResp.Arn,
+            region: credential.region ?? "unknow",
+        };
+        return userinfo;
+    }
 }
 
-export default user;
+export default user;
\ No newline at end of file
diff --git a/src/extension.ts b/src/extension.ts
index d539365..2320d1d 100644
--- a/src/extension.ts
+++ b/src/extension.ts
@@ -17,6 +17,7 @@ import * as autocomplete from './autocomplete/TerraformExampleProvider';
 import * as loginMgt from './views/login/loginMgt';
 import * as context from './commons/context';
 import { Constants } from './commons/constants';
+import user from "@/commons/tencent/user/index";
 
 const TF_MODE: vscode.DocumentFilter = { language: 'terraform', scheme: 'file' };
 const COMPATIBLE_MODE: vscode.DocumentFilter = { scheme: 'file' };
@@ -30,19 +31,19 @@ export async function activate(context: vscode.ExtensionContext) {
     await TerraformRunner.getInstance().checkInstalled();
     await TerraformerRunner.getInstance().checkInstalled();
 
-    // set request client
-    await setRequestClient();
+    // set request client for all of Terminal
+    await setRequestClientOnTerminal();
     // terraform cmd
-    context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.apply', () => {
-        terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Apply);
+    context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.apply', async () => {
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Apply);
     }));
 
-    context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.refresh', () => {
-        terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Refresh);
+    context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.refresh', async () => {
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Refresh);
     }));
 
-    context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.destroy', () => {
-        terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Destroy);
+    context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.destroy', async () => {
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Destroy);
     }));
 
     // git operations
@@ -56,13 +57,13 @@ export async function activate(context: vscode.ExtensionContext) {
 
     // terraformer cmd
     let disposableTferImport = vscode.commands.registerCommand('tcTerraformer.import', async () => {
-        terraformShellManager.getShell().runTerraformCmd(TerraformerCommand.Import);
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformerCommand.Import);
     });
 
     context.subscriptions.push(disposableTferImport);
 
     let disposableTferPlan = vscode.commands.registerCommand('tcTerraformer.plan', async () => {
-        terraformShellManager.getShell().runTerraformCmd(TerraformerCommand.Plan);
+        (await terraformShellManager.getShell()).runTerraformCmd(TerraformerCommand.Plan);
     });
 
     context.subscriptions.push(disposableTferPlan);
@@ -118,13 +119,13 @@ export async function activate(context: vscode.ExtensionContext) {
 
 }
 
-async function setRequestClient() {
+async function setRequestClientOnTerminal() {
     const config = vscode.workspace.getConfiguration('terminal.integrated.env');
     const os = getOSPlatform();
     const curConfig = config[os] || {};
 
-    // env[Constants.REQUEST_CLIENT] = context.genRequestClient();
-    const updatedConfig = { ...curConfig, [Constants.REQUEST_CLIENT]: context.genRequestClient() };
+    const reqCli = await context.genRequestClient();
+    const updatedConfig = { ...curConfig, [Constants.REQUEST_CLIENT]: reqCli }; // set ReqCli for all Terminal
 
     await config.update(os, updatedConfig, vscode.ConfigurationTarget.Global);
 }
@@ -143,6 +144,6 @@ function getOSPlatform(): string {
 }
 
 // This method is called when your extension is deactivated
-export function deactivate() {
-
+export async function deactivate() {
+    await user.clearInfo();
 }
diff --git a/src/utils/settingUtils.ts b/src/utils/settingUtils.ts
index a9c6704..4008793 100644
--- a/src/utils/settingUtils.ts
+++ b/src/utils/settingUtils.ts
@@ -66,7 +66,7 @@ export function getAKSKandRegion(): [string, string, string] {
     const regionConfig = getRegionFromUI();
     const regionEnv = getRegionFromEnv();
 
-    return [secretIdConfig ?? secretIdEnv, secretKeyConfig ?? secretKeyEnv, regionConfig ?? regionEnv];
+    return [secretIdConfig || secretIdEnv, secretKeyConfig || secretKeyEnv, regionConfig || regionEnv];
 }
 
 export function clearAKSKandRegion() {
diff --git a/src/views/login/loginExplorer.ts b/src/views/login/loginExplorer.ts
index 1d99c5b..db9c106 100644
--- a/src/views/login/loginExplorer.ts
+++ b/src/views/login/loginExplorer.ts
@@ -19,7 +19,7 @@ export class LoginProvider extends tencent.tree.TreeDataProvider {
 
     async isLoggedIn(): Promise<boolean> {
         if (getSecretIdFromEnv() && getSecretKeyFromEnv()) {
-            const userInfo = await user.getInfo() as user.UserInfo;
+            const userInfo = await user.getInfo();
             if (!userInfo || !userInfo.secretId || userInfo.secretId === '') {
                 return false;
             }
@@ -31,7 +31,7 @@ export class LoginProvider extends tencent.tree.TreeDataProvider {
     async getChildren(element?: tencent.tree.TreeItem | undefined): Promise<tencent.tree.TreeItem[]> {
         let items: tencent.tree.TreeItem[] = [];
         if (!element) {
-            if (!this.isLoggedIn()) {
+            if (!await this.isLoggedIn()) {
                 window.showInformationMessage(localize("TcTerraform.login.msg.need.login"));
                 clearAKSKandRegion();
                 return items;
