enable no-vscode-postmessage eslint rule.

This commit is contained in:
shengsuan-cloud committed 2025-07-01 17:24:13 +08:00
1 parent 4f0e97d62a
commit 205b6c06b2
23 files changed
+331 -296

No files matched your search

+3 -4
View File
@@ -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",
},
},
},
+5
View File
@@ -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 {
@@ -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<String> {
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(),
})
}
@@ -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<Empty> {
await controller.handleSignOut()
return Empty.create({})
}
@@ -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<UserCreditsData> {
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
}
}
@@ -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<StreamingResponseHandler>()
export async function subscribeSSYAuthCallback(
controller: Controller,
request: EmptyRequest,
responseStream: StreamingResponseHandler,
requestId?: string,
): Promise<void> {
// 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<void> {
// 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)
}
+7 -42
View File
@@ -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 })
}
@@ -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 })
}
@@ -73,12 +73,6 @@ export async function refreshShengSuanYunModels(
description: model.description ?? "",
}
}
controller.postMessageToWebview({
type: "shengSuanYunModels",
shengSuanYunModels: typedModels,
})
return OpenRouterCompatibleModelInfo.create({ models: typedModels })
}
+43 -62
View File
@@ -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<void>
private getSSYApiKey: () => Promise<string | undefined>
constructor(
postMessageToWebview: (message: ExtensionMessage) => Promise<void>,
getSSYApiKey: () => Promise<string | undefined>,
) {
this.postMessageToWebview = postMessageToWebview
constructor(getSSYApiKey: () => Promise<string | undefined>) {
this.getSSYApiKey = getSSYApiKey
}
private async authenticatedRequest<T>(endpoint: string, config: AxiosRequestConfig = {}): Promise<T> {
@@ -34,67 +30,52 @@ export class SSYAccountService {
return response.data.data
}
async fetchRate(): Promise<number | undefined> {
try {
const rate = await this.authenticatedRequest<any>("/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<UsageTransaction[] | undefined> {
async fetchUserDataRPC(): Promise<UserCreditsData> {
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<any>("/base/rate"),
this.authenticatedRequest<any>(`/modelrouter/userlog?page=1&pageSize=1000&${dqs}`),
this.authenticatedRequest<any>("/modelrouter/listrecharge?page=1&pageSize=10000"),
this.authenticatedRequest<any>("/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<PaymentTransaction[] | undefined> {
try {
const res = await this.authenticatedRequest<any>("/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
}
}
+2 -22
View File
@@ -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<string, ShengSuanYunModelInfo>
}
export type Platform = "aix" | "darwin" | "freebsd" | "linux" | "openbsd" | "sunos" | "win32" | "unknown"
-6
View File
@@ -14,12 +14,6 @@ export interface WebviewMessage {
| "telemetrySetting"
| "grpc_request"
| "grpc_request_cancel"
| "fetchUSDRate"
| "accountLoginClickedSSY"
| "accountLogoutClickedSSY"
| "authStateChanged"
| "fetchUserCreditsData"
| "authCallback"
text?: string
disabled?: boolean
+2 -2
View File
@@ -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,
+32
View File
@@ -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;
@@ -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<UsageTransaction[]>([])
const [paymentsData, setPaymentsData] = useState<PaymentTransaction[]>([])
// 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 = () => {
<VSCodeButton
appearance="icon"
className="mt-1"
onClick={() => 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)
})
}}>
<span className="codicon codicon-refresh"></span>
</VSCodeButton>
</>
@@ -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<UsageTransaction[]>([])
const [paymentsData, setPaymentsData] = useState<PaymentTransaction[]>([])
// 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 (
<div className="h-full flex flex-col">
{user && user.Wallet ? (
{user ? (
<div className="flex flex-col pr-3 h-full">
<div className="flex flex-col w-full">
<div className="flex items-center mb-6 flex-wrap gap-y-4">
{user.HeadImg ? (
<img src={user.HeadImg} alt="Profile" className="size-16 rounded-full mr-4" />
{user.photoURL ? (
<img src={user.photoURL} alt="Profile" className="size-16 rounded-full mr-4" />
) : (
<div className="size-16 rounded-full bg-[var(--vscode-button-background)] flex items-center justify-center text-2xl text-[var(--vscode-button-foreground)] mr-4">
{user.Nickname?.[0] || user.Email?.[0] || "?"}
{user.displayName?.[0] || user.email?.[0] || "?"}
</div>
)}
<div className="flex flex-col">
{user.Nickname && (
{user.displayName && (
<h2 className="text-[var(--vscode-foreground)] m-0 mb-1 text-lg font-medium">
{user.Nickname}
{user.displayName}
</h2>
)}
{user.Email && (
<div className="text-sm text-[var(--vscode-descriptionForeground)]">{user.Email}</div>
{user.email && (
<div className="text-sm text-[var(--vscode-descriptionForeground)]">{user.email}</div>
)}
</div>
</div>
@@ -257,31 +253,44 @@ export const SSYAccountView = () => {
<div className="w-full min-[225px]:w-1/2">
<VSCodeButtonLink
href="https://router.shengsuanyun.com/user/bill"
className="w-full bg-white text-gray-800">
appearance="primary"
className="w-full">
个人中心
</VSCodeButtonLink>
</div>
<VSCodeButton onClick={handleLogout} className="w-full min-[225px]:w-1/2 bg-white text-gray-800">
<VSCodeButton appearance="secondary" onClick={handleLogout} className="w-full min-[225px]:w-1/2">
退出登录
</VSCodeButton>
</div>
<VSCodeDivider className="w-full my-6" />
<div className="w-full flex flex-col items-center">
<div className="text-sm text-[var(--vscode-descriptionForeground)] mb-3">余额</div>
<div className="text-4xl font-bold text-[var(--vscode-foreground)] mb-6 flex items-center gap-2">
{isLoading && rate ? (
<div className="text-[var(--vscode-descriptionForeground)]">加载...</div>
{isLoading ? (
<div className="text-[var(--vscode-descriptionForeground)]">加载中...</div>
) : (
<>
<span>$</span>
<CountUp end={(rate * user.Wallet?.Assets) / 10000} duration={0.66} decimals={2} />
<CountUp end={balance} duration={0.66} decimals={2} />
<VSCodeButton
appearance="icon"
className="mt-1"
onClick={() => 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)
})
}}>
<span className="codicon codicon-refresh"></span>
</VSCodeButton>
</>
@@ -298,26 +307,19 @@ export const SSYAccountView = () => {
<VSCodeDivider className="mt-6 mb-3 w-full" />
<div className="flex-grow flex flex-col min-h-0 pb-[0px]">
<CreditsHistoryTable
isLoading={isLoading}
usageData={usageData}
paymentsData={paymentsData}
rateUSD={rate}
/>
<CreditsHistoryTable isLoading={isLoading} usageData={usageData} paymentsData={paymentsData} />
</div>
</div>
) : (
<div className="flex flex-col items-center pr-3">
<ClineLogoWhite className="size-16 mb-4" />
<p style={{}}>注册一个帐户以访问最新型号,注册账单仪表板以查看使用情况和积分, 以及更多即将推出的功能。</p>
<p style={{}}>注册帐户访问最新模型,进群联系客服,获得100万Tokens免费额度,以及更多即将推出的功能。</p>
<VSCodeButton onClick={handleLogin} className="w-full mb-4">
注册 / 登录 Cline 胜算云
注册 Cline 胜算云Router
</VSCodeButton>
<p className="text-[var(--vscode-descriptionForeground)] text-xs text-center m-0">
继续即表示您同意 <VSCodeLink href="https://cline.bot/tos">服务条款</VSCodeLink> 和{" "}
<VSCodeLink href="https://cline.bot/privacy">隐私政策</VSCodeLink>
<VSCodeLink href="https://cline.bot/privacy">隐私政策.</VSCodeLink>
</p>
</div>
)}
@@ -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 (
<div className="flex flex-col flex-grow h-full">
@@ -27,7 +26,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 }
{/* Content container */}
<div className="mt-[15px] mb-[0px] rounded-md overflow-auto flex-grow">
{isLoading && !rateUSD ? (
{isLoading ? (
<div className="flex justify-center items-center p-4">
<div className="text-[var(--vscode-descriptionForeground)]">加载中...</div>
</div>
@@ -65,7 +64,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 }
</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="2">{model}</VSCodeDataGridCell>
{/* <VSCodeDataGridCell grid-column="3">{`${row.promptTokens} → ${row.completionTokens}`}</VSCodeDataGridCell> */}
<VSCodeDataGridCell grid-column="3">{`$${(rateUSD * Number(row.credits || "0")).toFixed(7)}`}</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="3">{`$${Number(row.credits || "0").toFixed(7)}`}</VSCodeDataGridCell>
</VSCodeDataGridRow>
)
})}
@@ -80,7 +79,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 }
{activeTab === "payments" && (
<>
{paymentsData.length > 0 ? (
{paymentsData && paymentsData.length > 0 ? (
<VSCodeDataGrid>
<VSCodeDataGridRow row-type="header">
<VSCodeDataGridCell cell-type="columnheader" grid-column="1">
@@ -99,7 +98,7 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, rateUSD = 0 }
<VSCodeDataGridCell grid-column="1">
{formatTimestamp(row.paidAt, "zh-CN")}
</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="2">{`$${(rateUSD * Number(row.amountCents || "0")).toFixed(2)}`}</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="2">{`$${Number(row.amountCents || "0").toFixed(2)}`}</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="3">{`${row.credits || ""}`}</VSCodeDataGridCell>
</VSCodeDataGridRow>
))}
@@ -105,7 +105,7 @@ export function UnsavedChangesDialog({
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel}>Cancel</AlertDialogCancel>
<AlertDialogCancel onClick={onCancel}>取消</AlertDialogCancel>
{showSaveOption && onSave && <AlertDialogAction onClick={onSave}>{saveText}</AlertDialogAction>}
<AlertDialogAction onClick={onConfirm} appearance={showSaveOption ? "secondary" : "primary"}>
{confirmText}
@@ -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 = ({
)}
</p>
<label htmlFor="bedrock-model-dropdown">
<span style={{ fontWeight: 500 }}>Model</span>
<span style={{ fontWeight: 500 }}>模型</span>
</label>
<DropdownContainer zIndex={DROPDOWN_Z_INDEX - 2} className="dropdown-container">
<VSCodeDropdown
@@ -683,7 +680,7 @@ const ApiOptions = ({
})
}}
style={{ width: "100%" }}>
<VSCodeOption value="">Select a model...</VSCodeOption>
<VSCodeOption value="">选择模型...</VSCodeOption>
{Object.keys(bedrockModels).map((modelId) => (
<VSCodeOption
key={modelId}
@@ -696,7 +693,7 @@ const ApiOptions = ({
{modelId}
</VSCodeOption>
))}
<VSCodeOption value="custom">Custom</VSCodeOption>
<VSCodeOption value="custom">自定义</VSCodeOption>
</VSCodeDropdown>
</DropdownContainer>
{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 && (
<VSCodeLink
href="https://fireworks.ai/settings/users/api-keys"
@@ -876,7 +873,7 @@ const ApiOptions = ({
display: "inline",
fontSize: "inherit",
}}>
You can get a Fireworks API key by signing up here.
您可以通过在此处注册来获取 Fireworks API 密钥。
</VSCodeLink>
)}
</p>
@@ -894,8 +891,8 @@ const ApiOptions = ({
color: "var(--vscode-descriptionForeground)",
}}>
<span style={{ color: "var(--vscode-errorForeground)" }}>
(<span style={{ fontWeight: 500 }}>Note:</span> Cline uses complex prompts and works best with Claude
models. Less capable models may not work as expected.)
(<span style={{ fontWeight: 500 }}>注意:</span> Cline 使用复杂的提示,与 Claude
模型配合使用效果最佳。性能较差的模型可能无法达到预期效果。)
</span>
</p>
<VSCodeTextField
@@ -917,7 +914,7 @@ const ApiOptions = ({
})
}}
placeholder={"2000"}>
<span style={{ fontWeight: 500 }}>Max Completion Tokens</span>
<span style={{ fontWeight: 500 }}>最大输出 Tokens</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.fireworksModelMaxTokens?.toString() || ""}
@@ -938,7 +935,7 @@ const ApiOptions = ({
})
}}
placeholder={"4000"}>
<span style={{ fontWeight: 500 }}>Max Context Tokens</span>
<span style={{ fontWeight: 500 }}>上下文窗口</span>
</VSCodeTextField>
</div>
)}
@@ -1077,7 +1074,7 @@ const ApiOptions = ({
type="url"
onInput={handleInputChange("liteLlmBaseUrl")}
placeholder={"Default: http://localhost:4000"}>
<span style={{ fontWeight: 500 }}>Base URL (optional)</span>
<span style={{ fontWeight: 500 }}>Base URL (可选)</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.liteLlmApiKey || ""}
@@ -1108,7 +1105,7 @@ const ApiOptions = ({
})
}}
style={{ fontWeight: 500, color: "var(--vscode-charts-green)" }}>
Use prompt caching (GA)
使用提示词缓存 (GA)
</VSCodeCheckbox>
<p style={{ fontSize: "12px", marginTop: 3, color: "var(--vscode-charts-green)" }}>
提示缓存需要受支持的提供程序和模型
@@ -1129,7 +1126,7 @@ const ApiOptions = ({
<VSCodeLink
href="https://docs.litellm.ai/docs/reasoning_content"
style={{ display: "inline", fontSize: "inherit" }}>
Thinking Mode 配置
推理配置
</VSCodeLink>
</p>
</>
@@ -1210,7 +1207,7 @@ const ApiOptions = ({
liteLlmModelInfo: modelInfo,
})
}}>
<span style={{ fontWeight: 500 }}>Max Output Tokens</span>
<span style={{ fontWeight: 500 }}>最大输出 Tokens</span>
</VSCodeTextField>
</div>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
@@ -1275,7 +1272,7 @@ const ApiOptions = ({
{/* Model selection - use filterable picker */}
<label htmlFor="ollama-model-selection">
<span style={{ fontWeight: 500 }}>Model</span>
<span style={{ fontWeight: 500 }}>模型</span>
</label>
<OllamaModelPicker
ollamaModels={ollamaModels}
@@ -1286,7 +1283,7 @@ const ApiOptions = ({
ollamaModelId: modelId,
})
}}
placeholder={ollamaModels.length > 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。
</p>
)}
@@ -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 && (
<VSCodeLink
href="https://studio.nebius.com/settings/api-keys"
@@ -1437,7 +1433,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?.cerebrasApiKey && (
<VSCodeLink
href="https://cloud.cerebras.ai/"
@@ -1464,7 +1460,7 @@ const ApiOptions = ({
</VSCodeTextField>
{apiConfiguration?.sapAiCoreClientId && (
<p style={{ fontSize: "12px", color: "var(--vscode-descriptionForeground)" }}>
Client Id is set. To change it, please re-enter the value.
客户端 ID 已设置。如需更改,请重新输入该值。
</p>
)}
<VSCodeTextField
@@ -1507,11 +1503,11 @@ const ApiOptions = ({
marginTop: "5px",
color: "var(--vscode-descriptionForeground)",
}}>
These credentials are stored locally and only used to make API requests from this extension.
这些凭证存储在本地,仅用于从此扩展发出 API 请求。
<VSCodeLink
href="https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/access-sap-ai-core-via-api"
style={{ display: "inline" }}>
You can find more information about SAP AI Core API access here.
您可以在此处找到有关 SAP AI Core API 访问的更多信息。
</VSCodeLink>
</p>
</div>
@@ -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 (
<div className="max-w-[600px]">
{key ? (
<VSCodeButton
appearance="secondary"
onClick={() => {
navigateToAccount()
}}>
<VSCodeButton appearance="secondary" onClick={() => navigateToAccount()}>
查看账单与使用记录
</VSCodeButton>
) : (
<VSCodeButton
appearance="primary"
onClick={() => {
vscode.postMessage({ type: "accountLoginClickedSSY" })
AccountServiceClient.shengSuanYunLoginClicked(EmptyRequest.create()).catch((err) =>
console.error("shengSuanYunLoginClicked Failed to get login URL:", err),
)
}}>
登录胜算云
</VSCodeButton>
@@ -63,7 +63,6 @@ const ShengSuanYunModelPicker: React.FC<ShengSuanYunModelPickerProps> = ({ isPop
useMount(() => {
ModelsServiceClient.refreshShengSuanYunModels(EmptyRequest.create({}))
.then((res) => {
console.log(res, "==============================")
setShengSuanYunModels({
[shengSuanYunDefaultModelId]: shengSuanYunDefaultModelInfo,
...res.models,
@@ -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(() => {
<ClineLogoWhite className="size-16" />
</div>
<div className="flex flex-col gap-3">
<div className="bg-white p-3 text-gray-800">
<div className="">
Cline中文版,由中国胜算云Router赞助开发,一分钟注册,国内就能调用,Claude / GPT 等全球100个大模型
</div>
<div className="bg-white p-3 text-gray-800">限时新用户,注册限时赠送 Claude 4 Sonnet 免费额度!</div>
<div className="">限时新用户,注册限时赠送 Claude 4 Sonnet 免费额度!</div>
</div>
<VSCodeButton appearance="primary" onClick={handleLogin} className="w-full mt-1">
@@ -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"
@@ -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<ShengSuanYunAuthContextType | unde
export const ShengSuanYunAuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [userSSY, setUser] = useState<any | null>(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)