diff --git a/eslint-rules/index.js b/eslint-rules/index.js index 843b55be..a7c8e72b 100644 --- a/eslint-rules/index.js +++ b/eslint-rules/index.js @@ -1,14 +1,13 @@ // eslint-rules/index.js const noProtobufObjectLiterals = require("./no-protobuf-object-literals") const noGrpcClientObjectLiterals = require("./no-grpc-client-object-literals") -// const noVscodePostmessage = require("./no-vscode-postmessage") -const { off } = require("process") +const noVscodePostmessage = require("./no-vscode-postmessage") module.exports = { rules: { "no-protobuf-object-literals": noProtobufObjectLiterals, "no-grpc-client-object-literals": noGrpcClientObjectLiterals, - // "no-vscode-postmessage": noVscodePostmessage, + "no-vscode-postmessage": noVscodePostmessage, }, configs: { recommended: { @@ -16,7 +15,7 @@ module.exports = { rules: { "local/no-protobuf-object-literals": "error", "local/no-grpc-client-object-literals": "error", - "local/no-vscode-postmessage": "off", //"error", + "local/no-vscode-postmessage": "error", }, }, }, diff --git a/proto/account.proto b/proto/account.proto index e715731c..5c5eff6f 100644 --- a/proto/account.proto +++ b/proto/account.proto @@ -26,6 +26,11 @@ service AccountService { // Fetches all user credits data (balance, usage transactions, payment transactions) rpc fetchUserCreditsData(EmptyRequest) returns (UserCreditsData); + + rpc shengSuanYunLoginClicked(EmptyRequest) returns (String); + rpc shengSuanYunLogoutClicked(EmptyRequest) returns (Empty); + rpc shengSuanYunUserData(EmptyRequest) returns (UserCreditsData); + rpc subscribeSSYAuthCallback(EmptyRequest) returns (stream String); } message AuthStateChangedRequest { diff --git a/src/core/controller/account/shengSuanYunLoginClicked.ts b/src/core/controller/account/shengSuanYunLoginClicked.ts new file mode 100644 index 00000000..b66691e1 --- /dev/null +++ b/src/core/controller/account/shengSuanYunLoginClicked.ts @@ -0,0 +1,15 @@ +import * as vscode from "vscode" +import { EmptyRequest, String } from "../../../shared/proto/common" +import { Controller } from ".." + +export async function shengSuanYunLoginClicked(controller: Controller, _: EmptyRequest): Promise { + const uriScheme = vscode.env.uriScheme + const id = "cline-shengsuan" + const authUrl = vscode.Uri.parse( + `https://router.shengsuanyun.com/auth?from=${id}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://shengsuan-cloud.${id}/ssy`)}`, + ) + await vscode.env.openExternal(authUrl) + return String.create({ + value: authUrl.toString(), + }) +} diff --git a/src/core/controller/account/shengSuanYunLogoutClicked.ts b/src/core/controller/account/shengSuanYunLogoutClicked.ts new file mode 100644 index 00000000..77990fd0 --- /dev/null +++ b/src/core/controller/account/shengSuanYunLogoutClicked.ts @@ -0,0 +1,8 @@ +import { Empty } from "../../../shared/proto/common" +import type { EmptyRequest } from "../../../shared/proto/common" +import type { Controller } from "../index" + +export async function shengSuanYunLogoutClicked(controller: Controller, _request: EmptyRequest): Promise { + await controller.handleSignOut() + return Empty.create({}) +} diff --git a/src/core/controller/account/shengSuanYunUserData.ts b/src/core/controller/account/shengSuanYunUserData.ts new file mode 100644 index 00000000..2f2e4517 --- /dev/null +++ b/src/core/controller/account/shengSuanYunUserData.ts @@ -0,0 +1,15 @@ +import type { Controller } from "../index" +import type { EmptyRequest } from "@shared/proto/common" +import { UserCreditsData } from "@shared/proto/account" + +export async function shengSuanYunUserData(controller: Controller, request: EmptyRequest): Promise { + try { + if (!controller.accountServiceSSY) { + throw new Error("Account service not available") + } + return await controller.accountServiceSSY.fetchUserDataRPC() + } catch (error) { + console.error(`Failed to fetch user credits data: ${error}`) + throw error + } +} diff --git a/src/core/controller/account/subscribeSSYAuthCallback.ts b/src/core/controller/account/subscribeSSYAuthCallback.ts new file mode 100644 index 00000000..8979e5f6 --- /dev/null +++ b/src/core/controller/account/subscribeSSYAuthCallback.ts @@ -0,0 +1,51 @@ +import { Controller } from "../index" +import { EmptyRequest } from "../../../shared/proto/common" +import { String as ProtoString } from "../../../shared/proto/common" +import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" + +const activeAuthCallbackSubscriptions = new Set() + +export async function subscribeSSYAuthCallback( + controller: Controller, + request: EmptyRequest, + responseStream: StreamingResponseHandler, + requestId?: string, +): Promise { + // Add this subscription to the active subscriptions + activeAuthCallbackSubscriptions.add(responseStream) + + // Register cleanup when the connection is closed + const cleanup = () => { + activeAuthCallbackSubscriptions.delete(responseStream) + } + + // Register the cleanup function with the request registry if we have a requestId + if (requestId) { + getRequestRegistry().registerRequest(requestId, cleanup, { type: "authCallback_subscription" }, responseStream) + } +} + +/** + * Send an authCallback event to all active subscribers + * @param customToken The custom token for authentication + */ +export async function sendSSYAuthCallbackEvent(customToken: string): Promise { + // Send the event to all active subscribers + const promises = Array.from(activeAuthCallbackSubscriptions).map(async (responseStream) => { + try { + const event: ProtoString = { + value: customToken, + } + await responseStream( + event, + false, // Not the last message + ) + } catch (error) { + console.error("Error sending authCallback event:", error) + // Remove the subscription if there was an error + activeAuthCallbackSubscriptions.delete(responseStream) + } + }) + + await Promise.all(promises) +} diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 49ff2f67..75d15461 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -47,6 +47,7 @@ import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceC import { sendRelinquishControlEvent } from "./ui/subscribeToRelinquishControl" import { handleTaskServiceRequest } from "./task" import { BooleanRequest } from "@shared/proto/common" +import { sendSSYAuthCallbackEvent } from "./account/subscribeSSYAuthCallback" /* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts @@ -91,13 +92,10 @@ export class Controller { return apiConfiguration?.clineApiKey }, ) - this.accountServiceSSY = new SSYAccountService( - (msg) => this.postMessageToWebview(msg), - async () => { - const { apiConfiguration } = await this.getStateToPostToWebview() - return apiConfiguration?.shengSuanYunToken - }, - ) + this.accountServiceSSY = new SSYAccountService(async () => { + const { apiConfiguration } = await this.getStateToPostToWebview() + return apiConfiguration?.shengSuanYunToken + }) // Clean up legacy checkpoints cleanupLegacyCheckpoints(this.context.globalStorageUri.fsPath, this.outputChannel).catch((error) => { console.error("Failed to cleanup legacy checkpoints:", error) @@ -222,15 +220,6 @@ export class Controller { */ async handleWebviewMessage(message: WebviewMessage) { switch (message.type) { - case "authStateChanged": - await this.setUserInfo(message.user || message.userSSY || undefined) - await this.postStateToWebview() - break - - case "fetchUserCreditsData": { - await this.fetchUserCreditsData() - break - } case "fetchMcpMarketplace": { await this.fetchMcpMarketplace(message.bool) break @@ -247,23 +236,6 @@ export class Controller { } break } - case "accountLoginClickedSSY": { - const id = "cline-shengsuan" - const authUrl = vscode.Uri.parse( - `https://router.shengsuanyun.com/auth?from=${id}&callback_url=${encodeURIComponent(`${this.uriScheme || "vscode"}://shengsuan-cloud.${id}/ssy`)}`, - ) - vscode.env.openExternal(authUrl) - break - } - case "accountLogoutClickedSSY": { - await this.handleSignOut() - break - } - case "fetchUserCreditsData": { - await this.fetchUserCreditsData() - break - } - // Add more switch case statements here as more webview message commands // are created within the webview context (i.e. inside media/main.js) } @@ -518,11 +490,7 @@ export class Controller { async fetchUserCreditsData() { try { - await Promise.all([ - this.accountServiceSSY?.fetchRate(), - this.accountServiceSSY?.fetchUsageTransactions(), - this.accountServiceSSY?.fetchPaymentTransactions(), - ]) + await this.accountServiceSSY?.fetchUserDataRPC() } catch (error) { console.error("Failed to fetch user credits data:", error) } @@ -731,10 +699,7 @@ export class Controller { if (response.data && response.data.data && response.data.data.api_key) { apiKey = response.data.data.api_key customToken = response.data.data.jwt_token - await this.postMessageToWebview({ - type: "authCallback", - customToken, - }) + await sendSSYAuthCallbackEvent(customToken) } else { throw new Error("Invalid response from Shengsuanyun API", { cause: response }) } diff --git a/src/core/controller/models/refreshRequestyModels.ts b/src/core/controller/models/refreshRequestyModels.ts index 69d8459c..2be16439 100644 --- a/src/core/controller/models/refreshRequestyModels.ts +++ b/src/core/controller/models/refreshRequestyModels.ts @@ -48,9 +48,5 @@ export async function refreshRequestyModels(controller: Controller, _: EmptyRequ console.error("Error fetching Requesty models:", error) } - controller.postMessageToWebview({ - type: "requestyModels", - shengSuanYunModels: models, - }) return OpenRouterCompatibleModelInfo.create({ models }) } diff --git a/src/core/controller/models/refreshShengSuanYunModels.ts b/src/core/controller/models/refreshShengSuanYunModels.ts index 85c35005..a7848e36 100644 --- a/src/core/controller/models/refreshShengSuanYunModels.ts +++ b/src/core/controller/models/refreshShengSuanYunModels.ts @@ -73,12 +73,6 @@ export async function refreshShengSuanYunModels( description: model.description ?? "", } } - - controller.postMessageToWebview({ - type: "shengSuanYunModels", - shengSuanYunModels: typedModels, - }) - return OpenRouterCompatibleModelInfo.create({ models: typedModels }) } diff --git a/src/services/account/SSYAccountService.ts b/src/services/account/SSYAccountService.ts index 1d5ac8d4..d624b8e1 100644 --- a/src/services/account/SSYAccountService.ts +++ b/src/services/account/SSYAccountService.ts @@ -1,17 +1,13 @@ -import type { PaymentTransaction, UsageTransaction } from "../../shared/ClineAccount" +import type { BalanceResponse, PaymentTransaction, UsageTransaction } from "../../shared/ClineAccount" import { ExtensionMessage } from "../../shared/ExtensionMessage" import axios, { AxiosRequestConfig } from "axios" +import { UserCreditsData } from "@shared/proto/account" export class SSYAccountService { private readonly baseUrl = "https://api.shengsuanyun.com" - private postMessageToWebview: (message: ExtensionMessage) => Promise private getSSYApiKey: () => Promise - constructor( - postMessageToWebview: (message: ExtensionMessage) => Promise, - getSSYApiKey: () => Promise, - ) { - this.postMessageToWebview = postMessageToWebview + constructor(getSSYApiKey: () => Promise) { this.getSSYApiKey = getSSYApiKey } private async authenticatedRequest(endpoint: string, config: AxiosRequestConfig = {}): Promise { @@ -34,67 +30,52 @@ export class SSYAccountService { return response.data.data } - async fetchRate(): Promise { - try { - const rate = await this.authenticatedRequest("/base/rate") - if (!rate) { - return undefined - } - await this.postMessageToWebview({ - type: "fetchUSDRate", - fetchUSDRate: rate, - }) - return rate - } catch (error) { - console.error("Failed to fetch USD rate:", error) - return undefined - } - } - async fetchUsageTransactions(): Promise { + async fetchUserDataRPC(): Promise { try { const dqs = this.dateQueryString() - const res: any = await this.authenticatedRequest(`/modelrouter/userlog?page=1&pageSize=1000&${dqs}`) - if (!res || !Array.isArray(res.logs)) { - return undefined - } - const utl = res.logs.map((it: any) => ({ - spentAt: it.request_time, - modelProvider: "", - model: `${it.model?.company}/${it.model?.name}`, - credits: it.total_amount / 10000000, - totalTokens: it.total_amount, - promptTokens: it.input_tokens, - completionTokens: it.output_tokens, - })) + let [rate, usage, payment, user] = await Promise.all([ + this.authenticatedRequest("/base/rate"), + this.authenticatedRequest(`/modelrouter/userlog?page=1&pageSize=1000&${dqs}`), + this.authenticatedRequest("/modelrouter/listrecharge?page=1&pageSize=10000"), + this.authenticatedRequest("/user/info"), + ]) - await this.postMessageToWebview({ - type: "userCreditsUsage", - userCreditsUsage: utl, - }) - return utl - } catch (error) { - console.error("Failed to fetch usage transactions:", error) - return undefined - } - } - async fetchPaymentTransactions(): Promise { - try { - const res = await this.authenticatedRequest("/modelrouter/listrecharge?page=1&pageSize=10000") - if (!res || !Array.isArray(res.records)) { - return undefined + if (!usage || !Array.isArray(usage?.logs)) { + usage = [] + } else { + usage = usage.logs.map((it: any) => ({ + spentAt: it.request_time, + modelProvider: "", + model: `${it.model?.company}/${it.model?.name}`, + credits: it.total_amount / 10000000, + totalTokens: it.total_amount, + promptTokens: it.input_tokens, + completionTokens: it.output_tokens, + })) } - const cpl = res.records.map((it: any) => ({ - paidAt: it.create_at, - amountCents: (it.price / 10000).toString(), - })) - await this.postMessageToWebview({ - type: "userCreditsPayments", - userCreditsPayments: cpl, + + if (!payment || !Array.isArray(payment.records)) { + payment = [] + } else { + payment = payment.records.map((it: any) => ({ + paidAt: it.create_at, + amountCents: (it.price / 10000).toString(), + })) + } + + let balance = { currentBalance: 0 } + if (user && user.Wallet && user.Wallet.Assets && rate) { + balance = { currentBalance: (rate * user.Wallet.Assets) / 10000 } + } + + return UserCreditsData.create({ + balance: balance, + usageTransactions: usage, + paymentTransactions: payment, }) - return cpl } catch (error) { - console.error("Failed to fetch payment transactions:", error) - return undefined + console.error("Failed fetchUserDataRPC:", error) + throw error } } diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 38588079..7f23fcd0 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -1,33 +1,18 @@ // type that represents json data that is sent from extension to webview, called ExtensionMessage and has 'type' enum which can be 'plusButtonClicked' or 'settingsButtonClicked' or 'hello' import { GitCommit } from "../utils/git" -import { ApiConfiguration, ModelInfo } from "./api" +import { ApiConfiguration } from "./api" import { AutoApprovalSettings } from "./AutoApprovalSettings" import { BrowserSettings } from "./BrowserSettings" import { ChatSettings } from "./ChatSettings" import { HistoryItem } from "./HistoryItem" import { McpServer, McpMarketplaceCatalog, McpDownloadResponse, McpViewTab } from "./mcp" import { TelemetrySetting } from "./TelemetrySetting" -import type { BalanceResponse, UsageTransaction, PaymentTransaction } from "../shared/ClineAccount" import { ClineRulesToggles } from "./cline-rules" -import { UserInfo } from "./UserInfo" -import { ShengSuanYunModelInfo } from "./proto/models" // webview will hold state export interface ExtensionMessage { - type: - | "action" - | "state" - | "selectedImages" - | "mcpDownloadDetails" - | "grpc_response" - | "fetchUSDRate" - | "userCreditsBalance" - | "userCreditsUsage" - | "userCreditsPayments" - | "shengSuanYunModels" - | "authCallback" - | "requestyModels" + type: "action" | "state" | "selectedImages" | "mcpDownloadDetails" | "grpc_response" text?: string action?: "accountLogoutClicked" state?: ExtensionState @@ -45,10 +30,6 @@ export interface ExtensionMessage { commits?: GitCommit[] url?: string isImage?: boolean - fetchUSDRate?: number - userCreditsBalance?: BalanceResponse - userCreditsUsage?: UsageTransaction[] - userCreditsPayments?: PaymentTransaction[] success?: boolean endpoint?: string isBundled?: boolean @@ -69,7 +50,6 @@ export interface ExtensionMessage { is_streaming?: boolean // Whether this is part of a streaming response sequence_number?: number // For ordering chunks in streaming responses } - shengSuanYunModels?: Record } export type Platform = "aix" | "darwin" | "freebsd" | "linux" | "openbsd" | "sunos" | "win32" | "unknown" diff --git a/src/shared/WebviewMessage.ts b/src/shared/WebviewMessage.ts index 977f5611..08904f69 100644 --- a/src/shared/WebviewMessage.ts +++ b/src/shared/WebviewMessage.ts @@ -14,12 +14,6 @@ export interface WebviewMessage { | "telemetrySetting" | "grpc_request" | "grpc_request_cancel" - | "fetchUSDRate" - | "accountLoginClickedSSY" - | "accountLogoutClickedSSY" - | "authStateChanged" - | "fetchUserCreditsData" - | "authCallback" text?: string disabled?: boolean diff --git a/src/shared/api.ts b/src/shared/api.ts index 64f069a7..a1553273 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -2512,9 +2512,9 @@ export const requestyDefaultModelInfo: ModelInfo = { // ShengSuanYun // https://router.shengsuanyun.com/model -export const shengSuanYunDefaultModelId: string = "anthropic/claude-3.7-sonnet" +export const shengSuanYunDefaultModelId: string = "anthropic/claude-sonnet-4" export const shengSuanYunDefaultModelInfo: ModelInfo = { - maxTokens: 128_000, + maxTokens: 64_000, contextWindow: 200_000, supportsImages: true, supportsPromptCache: true, diff --git a/src/shared/proto/account.ts b/src/shared/proto/account.ts index 874e3edb..529b3c71 100644 --- a/src/shared/proto/account.ts +++ b/src/shared/proto/account.ts @@ -789,6 +789,38 @@ export const AccountServiceDefinition = { responseStream: false, options: {}, }, + shengSuanYunLoginClicked: { + name: "shengSuanYunLoginClicked", + requestType: EmptyRequest, + requestStream: false, + responseType: String, + responseStream: false, + options: {}, + }, + shengSuanYunLogoutClicked: { + name: "shengSuanYunLogoutClicked", + requestType: EmptyRequest, + requestStream: false, + responseType: Empty, + responseStream: false, + options: {}, + }, + shengSuanYunUserData: { + name: "shengSuanYunUserData", + requestType: EmptyRequest, + requestStream: false, + responseType: UserCreditsData, + responseStream: false, + options: {}, + }, + subscribeSSYAuthCallback: { + name: "subscribeSSYAuthCallback", + requestType: EmptyRequest, + requestStream: false, + responseType: String, + responseStream: true, + options: {}, + }, }, } as const; diff --git a/webview-ui/src/components/account/AccountView.tsx b/webview-ui/src/components/account/AccountView.tsx index 5bd48773..d115f904 100644 --- a/webview-ui/src/components/account/AccountView.tsx +++ b/webview-ui/src/components/account/AccountView.tsx @@ -1,7 +1,6 @@ import { VSCodeButton, VSCodeDivider, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import { memo, useEffect, useState } from "react" import { useFirebaseAuth } from "@/context/FirebaseAuthContext" -import { vscode } from "@/utils/vscode" import VSCodeButtonLink from "../common/VSCodeButtonLink" import ClineLogoWhite from "../../assets/ClineLogoWhite" import CountUp from "react-countup" @@ -43,30 +42,20 @@ export const ClineAccountView = () => { const [usageData, setUsageData] = useState([]) const [paymentsData, setPaymentsData] = useState([]) - // Listen for balance and transaction data updates from the extension useEffect(() => { - const handleMessage = (event: MessageEvent) => { - const message = event.data - if (message.type === "userCreditsBalance" && message.userCreditsBalance) { - setBalance(message.userCreditsBalance.currentBalance) - } else if (message.type === "userCreditsUsage" && message.userCreditsUsage) { - setUsageData(message.userCreditsUsage) - } else if (message.type === "userCreditsPayments" && message.userCreditsPayments) { - setPaymentsData(message.userCreditsPayments) - } - setIsLoading(false) - } - - window.addEventListener("message", handleMessage) - - // Fetch all account data when component mounts if (user) { setIsLoading(true) - vscode.postMessage({ type: "fetchUserCreditsData" }) - } - - return () => { - window.removeEventListener("message", handleMessage) + AccountServiceClient.fetchUserCreditsData(EmptyRequest.create()) + .then((response) => { + setBalance(response.balance?.currentBalance || 0) + setUsageData(response.usageTransactions) + setPaymentsData(response.paymentTransactions) + setIsLoading(false) + }) + .catch((error) => { + console.error("Failed to fetch user credits data:", error) + setIsLoading(false) + }) } }, [user]) @@ -139,7 +128,20 @@ export const ClineAccountView = () => { vscode.postMessage({ type: "fetchUserCreditsData" })}> + onClick={() => { + setIsLoading(true) + AccountServiceClient.fetchUserCreditsData(EmptyRequest.create()) + .then((response) => { + setBalance(response.balance?.currentBalance || 0) + setUsageData(response.usageTransactions) + setPaymentsData(response.paymentTransactions) + setIsLoading(false) + }) + .catch((error) => { + console.error("Failed to refresh user credits data:", error) + setIsLoading(false) + }) + }}> @@ -182,72 +184,66 @@ export const ClineAccountView = () => { export const SSYAccountView = () => { const { userSSY: ssyUser, handleSignOutSSY } = useShengSuanYunAuth() const { userInfo, apiConfiguration } = useExtensionState() - let user = apiConfiguration?.shengSuanYunToken ? ssyUser || userInfo : undefined - const [rate, setRate] = useState(0) + + const [balance, setBalance] = useState(0) const [isLoading, setIsLoading] = useState(true) const [usageData, setUsageData] = useState([]) const [paymentsData, setPaymentsData] = useState([]) - // Listen for balance and transaction data updates from the extension + // Fetch all account data when component mounts using gRPC useEffect(() => { - const handleMessage = (event: MessageEvent) => { - const message = event.data - if (message.type === "fetchUSDRate" && message.fetchUSDRate) { - setRate(message.fetchUSDRate) - } else if (message.type === "userCreditsUsage" && message.userCreditsUsage) { - setUsageData(message.userCreditsUsage) - } else if (message.type === "userCreditsPayments" && message.userCreditsPayments) { - setPaymentsData(message.userCreditsPayments) - } - setIsLoading(false) - } - - window.addEventListener("message", handleMessage) - // Fetch all account data when component mounts if (user) { setIsLoading(true) - vscode.postMessage({ type: "fetchUserCreditsData" }) - } - - return () => { - window.removeEventListener("message", handleMessage) + AccountServiceClient.shengSuanYunUserData(EmptyRequest.create()) + .then((response) => { + setBalance(response.balance?.currentBalance || 0) + setUsageData(response.usageTransactions) + setPaymentsData(response.paymentTransactions) + setIsLoading(false) + }) + .catch((error) => { + console.error("Failed to fetch user credits data:", error) + setIsLoading(false) + }) } }, [user]) const handleLogin = () => { - vscode.postMessage({ type: "accountLoginClickedSSY" }) + AccountServiceClient.shengSuanYunLoginClicked(EmptyRequest.create()).catch((err) => + console.error("Failed to get login URL:", err), + ) } const handleLogout = () => { - // First notify extension to clear API keys and state - vscode.postMessage({ type: "accountLogoutClickedSSY" }) - // Then sign out of Firebase + AccountServiceClient.shengSuanYunLogoutClicked(EmptyRequest.create()).catch((err) => + console.error("Failed to logout:", err), + ) handleSignOutSSY() } return (
- {user && user.Wallet ? ( + {user ? (
- {user.HeadImg ? ( - Profile + {user.photoURL ? ( + Profile ) : (
- {user.Nickname?.[0] || user.Email?.[0] || "?"} + {user.displayName?.[0] || user.email?.[0] || "?"}
)}
- {user.Nickname && ( + {user.displayName && (

- {user.Nickname} + {user.displayName}

)} - {user.Email && ( -
{user.Email}
+ {user.email && ( +
{user.email}
)}
@@ -257,31 +253,44 @@ export const SSYAccountView = () => {
+ appearance="primary" + className="w-full"> 个人中心
- + 退出登录
-
余额
- {isLoading && rate ? ( -
加载...
+ {isLoading ? ( +
加载中...
) : ( <> $ - + vscode.postMessage({ type: "fetchUserCreditsData" })}> + onClick={() => { + setIsLoading(true) + AccountServiceClient.shengSuanYunUserData(EmptyRequest.create()) + .then((response) => { + setBalance(response.balance?.currentBalance || 0) + setUsageData(response.usageTransactions) + setPaymentsData(response.paymentTransactions) + setIsLoading(false) + }) + .catch((error) => { + console.error("Failed to refresh user credits data:", error) + setIsLoading(false) + }) + }}> @@ -298,26 +307,19 @@ export const SSYAccountView = () => {
- +
) : (
- -

注册一个帐户以访问最新型号,注册账单仪表板以查看使用情况和积分, 以及更多即将推出的功能。

- +

注册帐户访问最新模型,进群联系客服,获得100万Tokens免费额度,以及更多即将推出的功能。

- 注册 / 登录 Cline 胜算云 + 注册 Cline 胜算云Router

继续即表示您同意 服务条款 和{" "} - 隐私政策 + 隐私政策.

)} diff --git a/webview-ui/src/components/account/CreditsHistoryTable.tsx b/webview-ui/src/components/account/CreditsHistoryTable.tsx index c8a20691..a6a321c8 100644 --- a/webview-ui/src/components/account/CreditsHistoryTable.tsx +++ b/webview-ui/src/components/account/CreditsHistoryTable.tsx @@ -8,10 +8,9 @@ interface CreditsHistoryTableProps { isLoading: boolean usageData: UsageTransaction[] paymentsData: PaymentTransaction[] - rateUSD?: number } -const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 }: CreditsHistoryTableProps) => { +const CreditsHistoryTable = ({ isLoading, usageData, paymentsData }: CreditsHistoryTableProps) => { const [activeTab, setActiveTab] = useState<"usage" | "payments">("usage") return (
@@ -27,7 +26,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 } {/* Content container */}
- {isLoading && !rateUSD ? ( + {isLoading ? (
加载中...
@@ -65,7 +64,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 } {model} {/* {`${row.promptTokens} → ${row.completionTokens}`} */} - {`$${(rateUSD * Number(row.credits || "0")).toFixed(7)}`} + {`$${Number(row.credits || "0").toFixed(7)}`} ) })} @@ -80,7 +79,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 } {activeTab === "payments" && ( <> - {paymentsData.length > 0 ? ( + {paymentsData && paymentsData.length > 0 ? ( @@ -99,7 +98,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 } {formatTimestamp(row.paidAt, "zh-CN")} - {`$${(rateUSD * Number(row.amountCents || "0")).toFixed(2)}`} + {`$${Number(row.amountCents || "0").toFixed(2)}`} {`${row.credits || ""}`} ))} diff --git a/webview-ui/src/components/common/AlertDialog.tsx b/webview-ui/src/components/common/AlertDialog.tsx index 072f63b2..f835a1a8 100644 --- a/webview-ui/src/components/common/AlertDialog.tsx +++ b/webview-ui/src/components/common/AlertDialog.tsx @@ -105,7 +105,7 @@ export function UnsavedChangesDialog({ {description} - Cancel + 取消 {showSaveOption && onSave && {saveText}} {confirmText} diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index a23d1c1a..652b36a0 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -17,9 +17,6 @@ import { vertexGlobalModels, vertexModels, xaiModels, - shengSuanYunDefaultModelId, - shengSuanYunDefaultModelInfo, - sapAiCoreDefaultModelId, sapAiCoreModels, } from "@shared/api" import { EmptyRequest, StringRequest } from "@shared/proto/common" @@ -667,7 +664,7 @@ const ApiOptions = ({ )}

- Select a model... + 选择模型... {Object.keys(bedrockModels).map((modelId) => ( ))} - Custom + 自定义 {apiConfiguration?.awsBedrockCustomSelected && ( @@ -868,7 +865,7 @@ const ApiOptions = ({ marginTop: 3, color: "var(--vscode-descriptionForeground)", }}> - This key is stored locally and only used to make API requests from this extension. + 此密钥存储在本地,仅用于从此扩展发出 API 请求。 {!apiConfiguration?.fireworksApiKey && ( - You can get a Fireworks API key by signing up here. + 您可以通过在此处注册来获取 Fireworks API 密钥。 )}

@@ -894,8 +891,8 @@ const ApiOptions = ({ color: "var(--vscode-descriptionForeground)", }}> - (Note: Cline uses complex prompts and works best with Claude - models. Less capable models may not work as expected.) + (注意: Cline 使用复杂的提示,与 Claude + 模型配合使用效果最佳。性能较差的模型可能无法达到预期效果。)

- Max Completion Tokens + 最大输出 Tokens - Max Context Tokens + 上下文窗口
)} @@ -1077,7 +1074,7 @@ const ApiOptions = ({ type="url" onInput={handleInputChange("liteLlmBaseUrl")} placeholder={"Default: http://localhost:4000"}> - Base URL (optional) + Base URL (可选) - Use prompt caching (GA) + 使用提示词缓存 (GA)

提示缓存需要受支持的提供程序和模型 @@ -1129,7 +1126,7 @@ const ApiOptions = ({ - Thinking Mode 配置 + 推理配置

@@ -1210,7 +1207,7 @@ const ApiOptions = ({ liteLlmModelInfo: modelInfo, }) }}> - Max Output Tokens + 最大输出 Tokens
@@ -1275,7 +1272,7 @@ const ApiOptions = ({ {/* Model selection - use filterable picker */} 0 ? "Search and select a model..." : "e.g. llama3.1"} + placeholder={ollamaModels.length > 0 ? "搜索和选择模型..." : "e.g. llama3.1"} /> {/* Show status message based on model availability */} @@ -1298,8 +1295,7 @@ const ApiOptions = ({ color: "var(--vscode-descriptionForeground)", fontStyle: "italic", }}> - Unable to fetch models from Ollama server. Please ensure Ollama is running and accessible, or enter - the model ID manually above. + 无法从 Ollama 服务器获取模型。请确保 Ollama 正在运行且可访问,或者在上方手动输入模型 ID。

)} @@ -1346,7 +1342,7 @@ const ApiOptions = ({ marginTop: 3, color: "var(--vscode-descriptionForeground)", }}> - This key is stored locally and only used to make API requests from this extension.{" "} + 此密钥存储在本地,仅用于从此扩展发出 API 请求.{" "} {!apiConfiguration?.nebiusApiKey && ( - This key is stored locally and only used to make API requests from this extension. + 此密钥存储在本地,仅用于从此扩展发出 API 请求 {!apiConfiguration?.cerebrasApiKey && ( {apiConfiguration?.sapAiCoreClientId && (

- Client Id is set. To change it, please re-enter the value. + 客户端 ID 已设置。如需更改,请重新输入该值。

)} - These credentials are stored locally and only used to make API requests from this extension. + 这些凭证存储在本地,仅用于从此扩展发出 API 请求。 - You can find more information about SAP AI Core API access here. + 您可以在此处找到有关 SAP AI Core API 访问的更多信息。

diff --git a/webview-ui/src/components/settings/ShengSuanYunAccountInfoCard.tsx b/webview-ui/src/components/settings/ShengSuanYunAccountInfoCard.tsx index 04730b5a..68efaa06 100644 --- a/webview-ui/src/components/settings/ShengSuanYunAccountInfoCard.tsx +++ b/webview-ui/src/components/settings/ShengSuanYunAccountInfoCard.tsx @@ -1,7 +1,7 @@ -import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" -import { useShengSuanYunAuth } from "@/context/ShengSuanYunAuthContext" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { useExtensionState } from "@/context/ExtensionStateContext" -import { vscode } from "@/utils/vscode" +import { AccountServiceClient } from "@/services/grpc-client" +import { EmptyRequest } from "@shared/proto/common" export const ShengSuanYunAccountInfoCard = () => { const { apiConfiguration, navigateToAccount } = useExtensionState() @@ -9,18 +9,16 @@ export const ShengSuanYunAccountInfoCard = () => { return (
{key ? ( - { - navigateToAccount() - }}> + navigateToAccount()}> 查看账单与使用记录 ) : ( { - vscode.postMessage({ type: "accountLoginClickedSSY" }) + AccountServiceClient.shengSuanYunLoginClicked(EmptyRequest.create()).catch((err) => + console.error("shengSuanYunLoginClicked Failed to get login URL:", err), + ) }}> 登录胜算云 diff --git a/webview-ui/src/components/settings/ShengSuanYunModelPicker.tsx b/webview-ui/src/components/settings/ShengSuanYunModelPicker.tsx index 9b423caf..50423a81 100644 --- a/webview-ui/src/components/settings/ShengSuanYunModelPicker.tsx +++ b/webview-ui/src/components/settings/ShengSuanYunModelPicker.tsx @@ -63,7 +63,6 @@ const ShengSuanYunModelPicker: React.FC = ({ isPop useMount(() => { ModelsServiceClient.refreshShengSuanYunModels(EmptyRequest.create({})) .then((res) => { - console.log(res, "==============================") setShengSuanYunModels({ [shengSuanYunDefaultModelId]: shengSuanYunDefaultModelInfo, ...res.models, diff --git a/webview-ui/src/components/welcome/WelcomeView.tsx b/webview-ui/src/components/welcome/WelcomeView.tsx index 023f9a8c..c437f3e5 100644 --- a/webview-ui/src/components/welcome/WelcomeView.tsx +++ b/webview-ui/src/components/welcome/WelcomeView.tsx @@ -2,7 +2,6 @@ import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import { useEffect, useState, memo } from "react" import { useExtensionState } from "@/context/ExtensionStateContext" import { validateApiConfiguration } from "@/utils/validate" -import { vscode } from "@/utils/vscode" import ApiOptions from "@/components/settings/ApiOptions" import ClineLogoWhite from "@/assets/ClineLogoWhite" import { AccountServiceClient, ModelsServiceClient } from "@/services/grpc-client" @@ -18,7 +17,9 @@ const WelcomeView = memo(() => { const disableLetsGoButton = apiErrorMessage != null const handleLogin = () => { - vscode.postMessage({ type: "accountLoginClickedSSY" }) + AccountServiceClient.shengSuanYunLoginClicked(EmptyRequest.create()).catch((err) => + console.error("shengSuanYunLoginClicked Failed to get login URL:", err), + ) } const handleSubmit = async () => { @@ -47,10 +48,10 @@ const WelcomeView = memo(() => {
-
+
Cline中文版,由中国胜算云Router赞助开发,一分钟注册,国内就能调用,Claude / GPT 等全球100个大模型
-
限时新用户,注册限时赠送 Claude 4 Sonnet 免费额度!
+
限时新用户,注册限时赠送 Claude 4 Sonnet 免费额度!
diff --git a/webview-ui/src/context/FirebaseAuthContext.tsx b/webview-ui/src/context/FirebaseAuthContext.tsx index e28a4f68..b5e003f7 100644 --- a/webview-ui/src/context/FirebaseAuthContext.tsx +++ b/webview-ui/src/context/FirebaseAuthContext.tsx @@ -1,5 +1,4 @@ import { AccountServiceClient } from "@/services/grpc-client" -import { vscode } from "@/utils/vscode" import { EmptyRequest } from "@shared/proto/common" import { initializeApp } from "firebase/app" import { User, getAuth, signInWithCustomToken, signOut } from "firebase/auth" diff --git a/webview-ui/src/context/ShengSuanYunAuthContext.tsx b/webview-ui/src/context/ShengSuanYunAuthContext.tsx index 4f4b6335..7fd71b93 100644 --- a/webview-ui/src/context/ShengSuanYunAuthContext.tsx +++ b/webview-ui/src/context/ShengSuanYunAuthContext.tsx @@ -1,7 +1,9 @@ import React, { createContext, useCallback, useContext, useEffect, useState } from "react" import { useExtensionState } from "./ExtensionStateContext" import axios, { AxiosRequestConfig } from "axios" -import { vscode } from "@/utils/vscode" +import { AccountServiceClient } from "@/services/grpc-client" +import { AuthStateChanged, AuthStateChangedRequest } from "@shared/proto/account" +import { EmptyRequest } from "@shared/proto/common" interface ShengSuanYunAuthContextType { userSSY: any | null @@ -14,7 +16,8 @@ const ShengSuanYunAuthContext = createContext = ({ children }) => { const [userSSY, setUser] = useState(null) const [isInitSSY, setIsInitialized] = useState(false) - const { apiConfiguration } = useExtensionState() + const { apiConfiguration, setUserInfo } = useExtensionState() + useEffect(() => { if (apiConfiguration?.shengSuanYunToken) signInWithTokenSSY(apiConfiguration?.shengSuanYunToken) }, [apiConfiguration?.shengSuanYunToken]) @@ -32,43 +35,46 @@ export const ShengSuanYunAuthProvider: React.FC<{ children: React.ReactNode }> = if (!res.data || !res.data.data || res.data.code != 0) { throw new Error(`Invalid response from ${uri} API`) } - const usi = { - Email: res.data.data.Email, - Nickname: res.data.data.Nickname, - HeadImg: res.data.data.HeadImg, - Username: res.data.data.Username, - Wallet: res.data.data.Wallet, - Phone: res.data.data.Phone, + const user: any = { + displayName: res.data.data.Nickname || res.data.data.Username || undefined, + email: res.data.data.Email ?? undefined, + photoURL: res.data.data.HeadImg ?? undefined, } - setUser(usi) + setUser(user) setIsInitialized(true) - console.log("ShengSuanYunAuthProvider onAuthStateChanged user", usi) - vscode.postMessage({ - type: "authStateChanged", - userSSY: usi, - }) + AccountServiceClient.authStateChanged(AuthStateChangedRequest.create({ user })) + .then((res: AuthStateChanged) => { + setUserInfo(res.user) + }) + .catch((error) => { + console.error("Error updating auth state via gRPC:", error) + }) } catch (error) { console.error("Error signing in with custom token:", error) throw error } } - // Listen for auth callback from extension useEffect(() => { - const handleMessage = (event: MessageEvent) => { - const message = event.data - if (message.type === "authCallback" && message.customToken) { - signInWithTokenSSY(message.customToken) - } - } - - window.addEventListener("message", handleMessage) - return () => window.removeEventListener("message", handleMessage) + const cleanup = AccountServiceClient.subscribeSSYAuthCallback(EmptyRequest.create({}), { + onResponse: (event) => { + if (event.value) { + signInWithTokenSSY(event.value) + } + }, + onError: (error) => { + console.error("Error in signInWithTokenSSY subscription:", error) + }, + onComplete: () => {}, + }) + return cleanup }, [signInWithTokenSSY]) const handleSignOutSSY = useCallback(async () => { try { - vscode.postMessage({ type: "accountLogoutClickedSSY" }) + AccountServiceClient.shengSuanYunLogoutClicked(EmptyRequest.create()).catch((err) => + console.error("shengSuanYunLogoutClicked Failed to logout:", err), + ) console.log("Successfully signed out of ssy") } catch (error) { console.error("Error signing out of ssy:", error)