feat: add configurable Cursor TAB routing

This commit is contained in:
leookun
2026-08-24 04:35:28 +08:00
parent 8a4fc5076a
commit 0f23a9a9c3
23 changed files with 649 additions and 73 deletions
Generated
+1 -1
View File
@@ -1128,7 +1128,7 @@ checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
[[package]]
name = "cursor-byok-desktop"
version = "0.1.0-beta.1"
version = "0.1.0-beta.2"
dependencies = [
"axum",
"cursor-server",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "cursor-byok-desktop",
"version": "0.1.0-beta.1",
"version": "0.1.0-beta.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cursor-byok-desktop",
"version": "0.1.0-beta.1",
"version": "0.1.0-beta.2",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.8.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cursor-byok-desktop",
"version": "0.1.0-beta.1",
"version": "0.1.0-beta.2",
"description": "Cursor BYOK desktop management application",
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cursor-byok-desktop"
version = "0.1.0-beta.1"
version = "0.1.0-beta.2"
edition = "2021"
publish = false
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Cursor BYOK",
"version": "0.1.0-beta.1",
"version": "0.1.0-beta.2",
"identifier": "dev.cursorbyok.desktop",
"build": {
"beforeDevCommand": "npm run dev",
+9
View File
@@ -97,6 +97,13 @@ export interface ProxySettingsInput {
password?: string;
}
export type TabMode = "public" | "direct" | "custom";
export interface TabSettings {
mode: TabMode;
address: string;
}
export interface OverviewMetrics {
llm_calls: number;
successful_calls: number;
@@ -283,4 +290,6 @@ export const api = {
clearStatisticsStorage: () => request<StatisticsStorage>("/settings/storage/statistics", { method: "DELETE" }),
proxySettings: () => request<ProxySettings>("/settings/proxy"),
setProxySettings: (settings: ProxySettingsInput) => request<ProxySettings>("/settings/proxy", { method: "PUT", body: JSON.stringify(settings) }),
tabSettings: () => request<TabSettings>("/settings/tab"),
setTabSettings: (settings: TabSettings) => request<TabSettings>("/settings/tab", { method: "PUT", body: JSON.stringify(settings) }),
};
@@ -1,5 +1,10 @@
@use "../../styles/typography" as type;
.page {
display: grid;
gap: 16px;
}
.gate {
min-height: 250px;
display: flex;
@@ -0,0 +1,51 @@
@use "../../styles/typography" as type;
.title {
min-width: 0;
display: flex;
align-items: center;
gap: 5px;
}
.row {
min-height: 62px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 12px 16px;
& + & {
border-top: 1px solid var(--vscode-sideBar-border);
}
}
.description {
min-width: 0;
display: grid;
gap: 5px;
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.selectControl,
.addressInput {
width: min(300px, 44%);
flex: 0 0 auto;
}
@media (max-width: 620px) {
.row {
align-items: stretch;
flex-direction: column;
gap: 10px;
}
.selectControl,
.addressInput {
width: 100%;
}
}
@@ -0,0 +1,53 @@
import cursorIconUrl from "../../assets/icons/cursor.svg";
import type { TabMode, TabSettings } from "../../api";
import { Button } from "../ui/Button";
import { TextInput } from "../ui/FormControls";
import { Icon } from "../ui/Icon";
import { Select } from "../ui/Select";
import { TitledCard } from "../ui/TitledCard";
import styles from "./TabSettingsCard.module.scss";
export function TabSettingsCard({ settings, saving, onChange, onSave }: {
settings: TabSettings;
saving: boolean;
onChange: (settings: TabSettings) => void;
onSave: () => void;
}) {
return <TitledCard
title={<div className={styles.title}><Icon src={cursorIconUrl} size="1.1em" /><span>{t("TAB 设置")}</span></div>}
action={<Button size="small" variant="primary" disabled={saving} onClick={onSave}>{saving ? t("保存中…") : t("保存")}</Button>}
>
<div className={styles.row}>
<div className={styles.description}>
<strong>{t("TAB 选择")}</strong>
<small>{t("控制 Cursor TAB 相关接口的连接方式。")}</small>
</div>
<div className={styles.selectControl}>
<Select
value={settings.mode}
ariaLabel={t("TAB 选择")}
options={[
{ value: "public", label: t("使用公益服务") },
{ value: "direct", label: t("直连") },
{ value: "custom", label: t("自定义") },
]}
onChange={(mode) => onChange({ ...settings, mode: mode as TabMode })}
/>
</div>
</div>
{settings.mode === "custom" && <div className={styles.row}>
<div className={styles.description}>
<strong>{t("TAB 服务地址")}</strong>
<small>{t("原接口路径会追加到此服务地址。")}</small>
</div>
<TextInput
className={styles.addressInput}
value={settings.address}
placeholder="https://tab.leokun.cn"
aria-label={t("TAB 服务地址")}
onChange={(event) => onChange({ ...settings, address: event.target.value })}
onKeyDown={(event) => { if (event.key === "Enter") onSave(); }}
/>
</div>}
</TitledCard>;
}
+185 -52
View File
@@ -175,7 +175,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 156,
"line": 180,
"column": 89
}
]
@@ -278,12 +278,12 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 108,
"line": 109,
"column": 47
},
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 172,
"line": 173,
"column": 15
}
]
@@ -353,7 +353,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 155,
"line": 179,
"column": 36
},
{
@@ -440,17 +440,17 @@
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 120,
"line": 144,
"column": 40
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 120,
"line": 144,
"column": 119
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 123,
"line": 147,
"column": 63
}
]
@@ -515,7 +515,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 79,
"line": 87,
"column": 86
}
]
@@ -573,17 +573,17 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 98,
"line": 106,
"column": 32
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 98,
"line": 106,
"column": 119
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 133,
"line": 157,
"column": 44
}
]
@@ -766,7 +766,7 @@
"refs": [
{
"file": "layouts/AppLayout.tsx",
"line": 216,
"line": 220,
"column": 14
}
]
@@ -805,12 +805,12 @@
},
{
"file": "layouts/AppLayout.tsx",
"line": 217,
"line": 221,
"column": 19
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 133,
"line": 157,
"column": 67
},
{
@@ -877,7 +877,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 141,
"line": 165,
"column": 70
},
{
@@ -887,6 +887,18 @@
}
]
},
"2f4a9609285d8f49": {
"source": "TAB 设置已保存",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 128,
"column": 15
}
]
},
"2f5f1d6fbfb061ed": {
"source": "未设置",
"kind": "text",
@@ -932,7 +944,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 133,
"line": 157,
"column": 89
}
]
@@ -944,7 +956,7 @@
"refs": [
{
"file": "layouts/AppLayout.tsx",
"line": 218,
"line": 222,
"column": 20
}
]
@@ -1024,12 +1036,12 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 106,
"line": 107,
"column": 50
},
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 154,
"line": 155,
"column": 15
}
]
@@ -1137,6 +1149,18 @@
}
]
},
"3f6c25aa329163a4": {
"source": "原接口路径会追加到此服务地址。",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 41,
"column": 17
}
]
},
"3fd47edce45b3603": {
"source": "关闭",
"kind": "text",
@@ -1144,7 +1168,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 126,
"line": 150,
"column": 71
}
]
@@ -1168,12 +1192,12 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 105,
"line": 106,
"column": 46
},
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 145,
"line": 146,
"column": 15
}
]
@@ -1338,8 +1362,8 @@
},
{
"file": "layouts/AppLayout.tsx",
"line": 197,
"column": 84
"line": 194,
"column": 67
}
]
},
@@ -1348,6 +1372,11 @@
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 32,
"column": 39
},
{
"file": "components/overview/OverviewTimeRangeFilter.tsx",
"line": 89,
@@ -1389,6 +1418,18 @@
}
]
},
"5401344227e49e2f": {
"source": "TAB 设置",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 17,
"column": 90
}
]
},
"54644705e9c61009": {
"source": "端口设置",
"kind": "text",
@@ -1449,11 +1490,40 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 120,
"line": 144,
"column": 52
}
]
},
"59346e82b3dd2998": {
"source": "TAB 服务地址",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 40,
"column": 18
},
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 47,
"column": 21
}
]
},
"5a3bd99fa69a40c1": {
"source": "使用公益服务",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 30,
"column": 39
}
]
},
"5ae715656ffbc35d": {
"source": "合并到该上游所有模型的请求体。",
"kind": "text",
@@ -1502,7 +1572,7 @@
"refs": [
{
"file": "layouts/AppLayout.tsx",
"line": 222,
"line": 226,
"column": 11
}
]
@@ -1528,12 +1598,12 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 107,
"line": 108,
"column": 51
},
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 163,
"line": 164,
"column": 15
}
]
@@ -1614,7 +1684,7 @@
"refs": [
{
"file": "api.ts",
"line": 265,
"line": 272,
"column": 43
}
]
@@ -1876,7 +1946,7 @@
"refs": [
{
"file": "api.ts",
"line": 260,
"line": 267,
"column": 43
}
]
@@ -1919,6 +1989,18 @@
}
]
},
"7e0891860c9e6374": {
"source": "TAB 服务地址不能为空",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 125,
"column": 83
}
]
},
"7e1845870b528392": {
"source": "启用模型",
"kind": "text",
@@ -2003,7 +2085,7 @@
"refs": [
{
"file": "api.ts",
"line": 214,
"line": 221,
"column": 21
}
]
@@ -2049,7 +2131,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 150,
"line": 174,
"column": 21
}
]
@@ -2158,11 +2240,23 @@
"refs": [
{
"file": "layouts/AppLayout.tsx",
"line": 224,
"line": 228,
"column": 16
}
]
},
"8f9b0d6cc477d334": {
"source": "控制 Cursor TAB 相关接口的连接方式。",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 23,
"column": 17
}
]
},
"90800c48a1dd0655": {
"source": "{label} 必须是 JSON 对象",
"kind": "template",
@@ -2172,7 +2266,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 142,
"line": 166,
"column": 87
},
{
@@ -2237,7 +2331,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 134,
"line": 158,
"column": 11
}
]
@@ -2278,6 +2372,23 @@
}
]
},
"966498853d801a52": {
"source": "TAB 选择",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 22,
"column": 18
},
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 28,
"column": 22
}
]
},
"9850ed41a5bfbb0c": {
"source": "已选 {count} 项",
"kind": "template",
@@ -2434,6 +2545,11 @@
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 18,
"column": 109
},
{
"file": "components/settings/ProxySettingsCard.tsx",
"line": 33,
@@ -2482,7 +2598,7 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 186,
"line": 187,
"column": 24
}
]
@@ -2680,16 +2796,28 @@
},
{
"file": "layouts/AppLayout.tsx",
"line": 237,
"line": 241,
"column": 64
},
{
"file": "layouts/AppLayout.tsx",
"line": 237,
"line": 241,
"column": 125
}
]
},
"b06325c5660f0c29": {
"source": "直连",
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 31,
"column": 39
}
]
},
"b4411558b932266f": {
"source": "上游类型",
"kind": "text",
@@ -2788,7 +2916,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 126,
"line": 150,
"column": 93
}
]
@@ -2892,7 +3020,7 @@
"refs": [
{
"file": "layouts/AppLayout.tsx",
"line": 229,
"line": 233,
"column": 24
}
]
@@ -3000,17 +3128,17 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 97,
"line": 105,
"column": 32
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 97,
"line": 105,
"column": 95
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 123,
"line": 147,
"column": 51
}
]
@@ -3198,7 +3326,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 77,
"line": 85,
"column": 45
}
]
@@ -3292,7 +3420,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 128,
"line": 152,
"column": 18
}
]
@@ -3328,7 +3456,7 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 104,
"line": 105,
"column": 14
}
]
@@ -3465,7 +3593,7 @@
"refs": [
{
"file": "components/charts/DailyTokenUsageChart.tsx",
"line": 134,
"line": 135,
"column": 15
}
]
@@ -3542,7 +3670,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 78,
"line": 86,
"column": 72
}
]
@@ -3619,7 +3747,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 129,
"line": 153,
"column": 16
}
]
@@ -3648,7 +3776,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 126,
"line": 150,
"column": 45
}
]
@@ -3665,7 +3793,7 @@
},
{
"file": "pages/CursorSettingsPage.tsx",
"line": 122,
"line": 146,
"column": 25
}
]
@@ -3701,7 +3829,7 @@
"refs": [
{
"file": "pages/CursorSettingsPage.tsx",
"line": 54,
"line": 62,
"column": 187
},
{
@@ -3995,6 +4123,11 @@
"kind": "text",
"placeholders": [],
"refs": [
{
"file": "components/cursor/TabSettingsCard.tsx",
"line": 18,
"column": 97
},
{
"file": "components/settings/ProxySettingsCard.tsx",
"line": 33,
+9
View File
@@ -56,6 +56,7 @@
"2eb2bf7c6597ab9a": "Detailed records",
"2f1b67cdaa23351a": "Custom full request URL",
"2f4a361f878176d1": "{label} must be valid JSON",
"2f4a9609285d8f49": "TAB settings saved",
"2f5f1d6fbfb061ed": "Not set",
"2f6416a2c424856b": "Final request URL",
"2f7dec3be28d7597": "{count} selected",
@@ -75,6 +76,7 @@
"3cfae5728b92b334": "Token usage: {tokens}",
"3d13868593ae4eeb": "Display language",
"3da0bf1610ff5db5": "Recommended",
"3f6c25aa329163a4": "The original endpoint path is appended to this service address.",
"3fd47edce45b3603": "Close",
"4125fc7ba333524c": "Default light",
"42655ed8e4108ae2": "Input (non-cached)",
@@ -93,11 +95,14 @@
"4eafa9e925b30bcd": "Custom",
"51d04bc3d286f018": "Last calendar day",
"5228358a6db59fe7": "For example: now, 2026-08-23 18:00",
"5401344227e49e2f": "TAB settings",
"54644705e9c61009": "Port settings",
"54c53e5fe791d1f3": "Initialize CA",
"550eddc3c7fefa99": "Sponsored",
"555737734a6371e6": "Delete provider",
"56432ba297009bdc": "Initialize the CA first",
"59346e82b3dd2998": "TAB service address",
"5a3bd99fa69a40c1": "Use public service",
"5ae715656ffbc35d": "Merge into the request body for every model from this provider.",
"5c55a67935af8f45": "All",
"5f8d556a9c47da3c": "Launch at login disabled",
@@ -132,6 +137,7 @@
"7a3cec4ca715de80": "Call statistics",
"7ba2d6728fe2531b": "Confirm clear",
"7d9f043f8f7ab45c": "Version {version} is available in Settings",
"7e0891860c9e6374": "TAB service address is required",
"7e1845870b528392": "Enable model",
"7e1f06318e80c3af": "Statistics cleared",
"7e9ab9ada2cbf2cb": "Name and Base URL are required",
@@ -149,6 +155,7 @@
"8b6ff498515bcc2f": "Time",
"8d0c47eb9eac2d34": "Call type",
"8df48894086d6fbd": "Reason (optional)",
"8f9b0d6cc477d334": "Choose how Cursor connects to TAB endpoints.",
"90800c48a1dd0655": "{label} must be a JSON object",
"919cb0ce0c8db4e7": "Leave blank to keep the current password",
"91aaf184cfc17ffd": "Overview",
@@ -158,6 +165,7 @@
"94803f35c825e47a": "Full request URL",
"94df1e7f04815daf": "Used only for display; does not change the model name sent to the provider.",
"95f76d30c25d5eda": "CA installation is not supported on this system",
"966498853d801a52": "TAB connection",
"9850ed41a5bfbb0c": "{count} selected",
"997ec8201c2adeda": "Open terminal to install CA",
"9a026819dd1af5c5": "Enter a model identifier directly or select one returned by the current provider.",
@@ -186,6 +194,7 @@
"ad6a60ee93d3ba3e": "Loading call details…",
"ae2d0b7f79cea4a3": "Model output: {tokens} × ${price}/1M = {cost}",
"aee88743413144a2": "Refresh",
"b06325c5660f0c29": "Direct",
"b4411558b932266f": "Provider type",
"b502b1d414664337": "Prompt: {tokens}",
"b5141d3d19e9a048": "Yes",
+9
View File
@@ -56,6 +56,7 @@
"2eb2bf7c6597ab9a": "详细记录",
"2f1b67cdaa23351a": "自定义请求完整地址",
"2f4a361f878176d1": "{label} 必须是有效 JSON",
"2f4a9609285d8f49": "TAB 设置已保存",
"2f5f1d6fbfb061ed": "未设置",
"2f6416a2c424856b": "最终请求地址",
"2f7dec3be28d7597": "已选择 {count} 个",
@@ -75,6 +76,7 @@
"3cfae5728b92b334": "Token 用量:{tokens}",
"3d13868593ae4eeb": "界面语言",
"3da0bf1610ff5db5": "推荐内容",
"3f6c25aa329163a4": "原接口路径会追加到此服务地址。",
"3fd47edce45b3603": "关闭",
"4125fc7ba333524c": "默认亮色",
"42655ed8e4108ae2": "输入(非缓存)",
@@ -93,11 +95,14 @@
"4eafa9e925b30bcd": "自定义",
"51d04bc3d286f018": "近1自然日",
"5228358a6db59fe7": "如:现在、2026-08-23 18:00",
"5401344227e49e2f": "TAB 设置",
"54644705e9c61009": "端口设置",
"54c53e5fe791d1f3": "初始化 CA",
"550eddc3c7fefa99": "推广",
"555737734a6371e6": "删除上游",
"56432ba297009bdc": "请先初始化 CA",
"59346e82b3dd2998": "TAB 服务地址",
"5a3bd99fa69a40c1": "使用公益服务",
"5ae715656ffbc35d": "合并到该上游所有模型的请求体。",
"5c55a67935af8f45": "全部",
"5f8d556a9c47da3c": "已关闭开机启动",
@@ -132,6 +137,7 @@
"7a3cec4ca715de80": "调用统计",
"7ba2d6728fe2531b": "确认清理",
"7d9f043f8f7ab45c": "发现新版本 {version},可在设置中安装",
"7e0891860c9e6374": "TAB 服务地址不能为空",
"7e1845870b528392": "启用模型",
"7e1f06318e80c3af": "统计数据已清理",
"7e9ab9ada2cbf2cb": "名称和 Base URL 不能为空",
@@ -149,6 +155,7 @@
"8b6ff498515bcc2f": "时间",
"8d0c47eb9eac2d34": "调用类型",
"8df48894086d6fbd": "原因(可选)",
"8f9b0d6cc477d334": "控制 Cursor TAB 相关接口的连接方式。",
"90800c48a1dd0655": "{label} 必须是 JSON 对象",
"919cb0ce0c8db4e7": "留空表示保留当前密码",
"91aaf184cfc17ffd": "数据概览",
@@ -158,6 +165,7 @@
"94803f35c825e47a": "请求完整地址",
"94df1e7f04815daf": "仅用于界面展示,不会改变发送给上游的模型名称。",
"95f76d30c25d5eda": "当前系统暂不支持安装 CA",
"966498853d801a52": "TAB 选择",
"9850ed41a5bfbb0c": "已选 {count} 项",
"997ec8201c2adeda": "打开终端安装 CA",
"9a026819dd1af5c5": "可以直接输入模型标识,也可以从当前上游返回的模型列表中选择。",
@@ -186,6 +194,7 @@
"ad6a60ee93d3ba3e": "正在加载调用详情…",
"ae2d0b7f79cea4a3": "模型输出:{tokens} × ${price}/1M = {cost}",
"aee88743413144a2": "刷新",
"b06325c5660f0c29": "直连",
"b4411558b932266f": "上游类型",
"b502b1d414664337": "提示词:{tokens}",
"b5141d3d19e9a048": "是",
+27 -3
View File
@@ -1,7 +1,8 @@
import { useEffect, useMemo, useState } from "react";
import { api, type Model, type ProviderSelection } from "../api";
import { api, type Model, type ProviderSelection, type TabSettings } from "../api";
import { CursorCaGate, CursorCaProvider, CursorModelGate, CursorModelProvider } from "../components/cursor/CursorGates";
import { CursorModelEditor, emptyCursorModelDraft, type CursorModelDraft } from "../components/cursor/CursorModelEditor";
import { TabSettingsCard } from "../components/cursor/TabSettingsCard";
import styles from "../components/cursor/CursorSettings.module.scss";
import { PageContent } from "../components/layout/PageContent";
import controls from "../components/ui/Controls.module.scss";
@@ -24,12 +25,19 @@ export function CursorSettingsPage() {
const [caCommand, setCaCommand] = useState<string | null>(null);
const [waitingForCaRefresh, setWaitingForCaRefresh] = useState(false);
const [deleting, setDeleting] = useState<Model | null>(null);
const [tabDraft, setTabDraft] = useState<TabSettings | null>(null);
const [savingTab, setSavingTab] = useState(false);
const grouped = useMemo(() => providers.map((provider) => ({ provider, models: models.filter((model) => model.provider_id === provider.provider_id) })).filter((group) => group.models.length > 0), [providers, models]);
const caReady = cursorHarness?.ca === "ready";
useEffect(() => {
if (!caCommand) return;
void api.copyCursorText(caCommand);
}, [caCommand]);
useEffect(() => {
void api.tabSettings()
.then(setTabDraft)
.catch((cause) => message(cause instanceof Error ? cause.message : String(cause)));
}, [message]);
const initializeCa = async () => {
const status = await appStore.initializeCursorCa();
if (status?.ca === "untrusted" && status.ca_install_command) setCaCommand(status.ca_install_command);
@@ -111,15 +119,31 @@ export function CursorSettingsPage() {
setCaCommand(null);
setWaitingForCaRefresh(true);
};
const saveTab = async () => {
if (!tabDraft) return;
try {
if (tabDraft.mode === "custom" && !tabDraft.address.trim()) throw new Error(t("TAB 服务地址不能为空"));
setSavingTab(true);
setTabDraft(await api.setTabSettings(tabDraft));
message(t("TAB 设置已保存"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setSavingTab(false);
}
};
const content = <CursorCaProvider><CursorCaGate busy={cursorBusy} waitingForRefresh={waitingForCaRefresh} onInitialize={() => void initializeCa()} onRefresh={() => void refreshCa()}>
<CursorModelProvider><CursorModelGate onAdd={openNew}>{list}</CursorModelGate></CursorModelProvider>
<div className={styles.page}>
{tabDraft && <TabSettingsCard settings={tabDraft} saving={savingTab} onChange={setTabDraft} onSave={() => void saveTab()} />}
<CursorModelProvider><CursorModelGate onAdd={openNew}>{list}</CursorModelGate></CursorModelProvider>
</div>
</CursorCaGate></CursorCaProvider>;
return <>
<PageActions>
<TooltipTrigger label={caReady ? t("添加模型") : t("请先初始化 CA")}><button className={controls.iconButton} aria-label={t("添加模型")} disabled={!caReady || cursorBusy} onClick={openNew}><Icon icon={addIcon} size="1.1em" /></button></TooltipTrigger>
</PageActions>
<PageContent title={t("Cursor 设置")} sections={[{ key: "cursor-settings", estimatedHeight: Math.max(280, models.length * 55 + grouped.length * 62), content }]} />
<PageContent title={t("Cursor 设置")} sections={[{ key: "cursor-settings", estimatedHeight: Math.max(430, models.length * 55 + grouped.length * 62 + 145), content }]} />
<Modal open={draft !== null} title={editing ? t("编辑模型") : t("添加模型")} busy={cursorBusy} onClose={() => setDraft(null)} onSubmit={() => void save()}>
{draft && <CursorModelEditor draft={draft} providers={providers} editing={editing !== null} modelOptions={modelOptions} discovering={discovering} onChange={setDraft} onDiscover={() => void discover()} />}
</Modal>
+4
View File
@@ -155,6 +155,10 @@ pub fn api_router(service: ControlService) -> Router {
"/__byok-api__/api/settings/proxy",
get(settings::get_proxy).put(settings::update_proxy),
)
.route(
"/__byok-api__/api/settings/tab",
get(settings::get_tab).put(settings::update_tab),
)
.route(
"/__byok-api__/api/harness/cursor/status",
get(harness::status),
+11 -1
View File
@@ -17,7 +17,9 @@ use crate::{
LlmCallSummary, Overview, ProviderEndpoint, ProviderEndpointInput, ProviderEndpointSecret,
ProviderModel, ProviderModelInput, ProviderType,
},
store::{PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, Store},
store::{
PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, Store, TabSettings,
},
Error, Result,
};
@@ -372,6 +374,14 @@ impl ControlService {
pub async fn set_proxy_settings(&self, settings: ProxySettingsInput) -> Result<ProxySettings> {
self.store.set_proxy_settings(settings).await
}
pub async fn tab_settings(&self) -> Result<TabSettings> {
self.store.tab_settings().await
}
pub async fn set_tab_settings(&self, settings: TabSettings) -> Result<TabSettings> {
self.cursor_harness.set_tab_settings(settings).await
}
}
fn official_call(trace: CursorRunTraceSummary) -> CallSummary {
+14 -1
View File
@@ -1,7 +1,9 @@
use crate::Result;
use axum::{extract::State, Json};
use crate::store::{PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage};
use crate::store::{
PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, TabSettings,
};
use super::{ControlService, ObservabilitySettings};
@@ -47,3 +49,14 @@ pub async fn update_proxy(
) -> Result<Json<ProxySettings>> {
Ok(Json(service.set_proxy_settings(settings).await?))
}
pub async fn get_tab(State(service): State<ControlService>) -> Result<Json<TabSettings>> {
Ok(Json(service.tab_settings().await?))
}
pub async fn update_tab(
State(service): State<ControlService>,
Json(settings): Json<TabSettings>,
) -> Result<Json<TabSettings>> {
Ok(Json(service.set_tab_settings(settings).await?))
}
+2 -1
View File
@@ -13,7 +13,7 @@ use crate::{
observability::CursorTraceRecorder,
proto::{agent::v1 as agent, aiserver::v1 as ai},
proxy::{self, CursorProxy},
run_sse,
run_sse, tab,
},
cursor::{CursorParent, CursorSessionRegistry},
Result,
@@ -70,6 +70,7 @@ fn router_with_proxy(registry: CursorSessionRegistry, proxy: CursorProxy) -> Rou
post(analytics::bootstrap_statsig),
)
.route("/auth/full_stripe_profile", get(account::stripe_profile))
.merge(tab::router())
.route_layer(DefaultBodyLimit::disable())
.route_layer(RequestDecompressionLayer::new())
.fallback(proxy::forward)
+1
View File
@@ -22,6 +22,7 @@ pub mod request;
pub mod run_sse;
pub mod session;
pub mod sessions;
pub(crate) mod tab;
pub mod tools;
mod usage;
+53 -3
View File
@@ -82,14 +82,34 @@ impl CursorProxy {
pub async fn forward(
Extension(proxy): Extension<CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
forward_request(&proxy, request, None).await
}
pub(crate) async fn forward_to_service(
proxy: &CursorProxy,
request: Request<Body>,
service_url: &str,
) -> Result<Response<Body>> {
forward_request(proxy, request, Some(service_url)).await
}
async fn forward_request(
proxy: &CursorProxy,
request: Request<Body>,
service_url: Option<&str>,
) -> Result<Response<Body>> {
let started = Instant::now();
let (parts, body) = request.into_parts();
let path = parts
.uri
.path_and_query()
.map_or("/", |value| value.as_str());
let url = upstream_url(&parts.headers, &proxy.upstream, path)?;
.map_or("/", |value| value.as_str())
.to_owned();
let url = match service_url {
Some(service_url) => format!("{}{}", service_url.trim_end_matches('/'), path),
None => upstream_url(&parts.headers, &proxy.upstream, &path)?,
};
let mut headers = parts.headers;
headers.remove(UPSTREAM_URL_HEADER);
@@ -239,7 +259,7 @@ mod tests {
};
use tower::ServiceExt;
use super::{forward, CursorProxy};
use super::{forward, forward_to_service, CursorProxy};
#[tokio::test]
async fn preserves_request_and_response() {
@@ -289,4 +309,34 @@ mod tests {
);
server.abort();
}
#[tokio::test]
async fn tab_service_keeps_its_base_path_and_the_original_query() {
let upstream = Router::new().route(
"/base/aiserver.v1.AiService/StreamCpp",
any(|request: Request<Body>| async move {
request.uri().path_and_query().unwrap().as_str().to_owned()
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
let proxy = CursorProxy::for_upstream("http://unused.invalid").unwrap();
let response = forward_to_service(
&proxy,
Request::post("/aiserver.v1.AiService/StreamCpp?client=cursor")
.body(Body::empty())
.unwrap(),
&format!("http://{address}/base"),
)
.await
.unwrap();
assert_eq!(
to_bytes(response.into_body(), usize::MAX).await.unwrap(),
"/base/aiserver.v1.AiService/StreamCpp?client=cursor"
);
server.abort();
}
}
+67
View File
@@ -0,0 +1,67 @@
use axum::{
body::Body,
extract::{Extension, State},
http::{Request, Response},
routing::post,
Router,
};
use crate::{
cursor::{proxy, CursorSessionRegistry},
Result,
};
pub const TAB_PATHS: [&str; 17] = [
"/aiserver.v1.AiService/StreamCpp",
"/aiserver.v1.AiService/StreamNextCursorPrediction",
"/aiserver.v1.AiService/GetCppEditClassification",
"/aiserver.v1.AiService/RefreshTabContext",
"/aiserver.v1.AiService/CppConfig",
"/aiserver.v1.AiService/CppEditHistoryStatus",
"/aiserver.v1.AiService/CppAppend",
"/aiserver.v1.AiService/CppEditHistoryAppend",
"/aiserver.v1.AiService/ReportAiCodeChangeMetrics",
"/aiserver.v1.AiService/WriteGitCommitMessage",
"/aiserver.v1.AiService/WriteGitBranchName",
"/aiserver.v1.CppService/AvailableModels",
"/aiserver.v1.CppService/RecordCppFate",
"/aiserver.v1.FileSyncService/FSSyncFile",
"/aiserver.v1.FileSyncService/FSIsEnabledForUser",
"/aiserver.v1.FileSyncService/FSConfig",
"/aiserver.v1.FileSyncService/FSUploadFile",
];
pub fn is_tab_path(path: &str) -> bool {
TAB_PATHS.contains(&path)
}
pub fn router() -> Router<CursorSessionRegistry> {
TAB_PATHS.into_iter().fold(Router::new(), |router, path| {
router.route(path, post(forward))
})
}
async fn forward(
State(registry): State<CursorSessionRegistry>,
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
let settings = registry.store().tab_settings().await?;
match settings.service_url() {
Some(service_url) => proxy::forward_to_service(&upstream, request, service_url).await,
None => proxy::forward(Extension(upstream), request).await,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_only_legacy_tab_routes() {
assert_eq!(TAB_PATHS.len(), 17);
assert!(is_tab_path("/aiserver.v1.AiService/StreamCpp"));
assert!(is_tab_path("/aiserver.v1.FileSyncService/FSUploadFile"));
assert!(!is_tab_path("/aiserver.v1.AiService/AvailableModels"));
}
}
+21 -2
View File
@@ -9,7 +9,10 @@ use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::{store::Store, Error, Result};
use crate::{
store::{Store, TabMode, TabSettings},
Error, Result,
};
use self::{ca::CaManager, proxy::ProxyRuntime};
@@ -65,6 +68,7 @@ struct Inner {
ca: CaManager,
ca_initialization: Mutex<()>,
backend_addr: RwLock<Option<SocketAddr>>,
tab_mode: Arc<RwLock<TabMode>>,
proxy: Mutex<ProxyRuntime>,
}
@@ -76,6 +80,7 @@ impl CursorHarness {
ca: CaManager::managed()?,
ca_initialization: Mutex::new(()),
backend_addr: RwLock::new(None),
tab_mode: Arc::new(RwLock::new(TabMode::default())),
proxy: Mutex::new(ProxyRuntime::default()),
}),
})
@@ -138,6 +143,12 @@ impl CursorHarness {
self.status().await
}
pub async fn set_tab_settings(&self, settings: TabSettings) -> Result<TabSettings> {
let saved = self.inner.store.set_tab_settings(settings).await?;
*self.inner.tab_mode.write() = saved.mode;
Ok(saved)
}
async fn enable(&self) -> Result<()> {
if !matches!(self.inner.ca.state()?, CaState::Ready) {
return Err(Error::Config(
@@ -158,7 +169,15 @@ impl CursorHarness {
}
let ca = self.inner.ca.load()?;
let requested_port = self.inner.store.port_settings().await?.proxy_port;
let (url, actual_port) = proxy.start(backend_addr, ca, requested_port).await?;
*self.inner.tab_mode.write() = self.inner.store.tab_settings().await?.mode;
let (url, actual_port) = proxy
.start(
backend_addr,
ca,
requested_port,
self.inner.tab_mode.clone(),
)
.await?;
if let Err(error) = self.inner.store.set_proxy_port(actual_port).await {
proxy.stop().await;
return Err(error);
+29 -4
View File
@@ -1,4 +1,4 @@
use std::net::SocketAddr;
use std::{net::SocketAddr, sync::Arc};
use hudsucker::{
certificate_authority::RcgenAuthority,
@@ -8,7 +8,13 @@ use hudsucker::{
};
use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle};
use crate::{cursor::proxy::UPSTREAM_URL_HEADER, Error, Result};
use parking_lot::RwLock;
use crate::{
cursor::{proxy::UPSTREAM_URL_HEADER, tab::is_tab_path},
store::TabMode,
Error, Result,
};
use super::ca::LoadedCa;
@@ -33,6 +39,7 @@ impl ProxyRuntime {
backend: SocketAddr,
ca: LoadedCa,
requested_port: u16,
tab_mode: Arc<RwLock<TabMode>>,
) -> Result<(String, u16)> {
if let Some(url) = self.url() {
return Ok((url, self.port.unwrap_or_default()));
@@ -45,7 +52,7 @@ impl ProxyRuntime {
.with_listener(listener)
.with_ca(authority)
.with_rustls_connector(aws_lc_rs::default_provider())
.with_http_handler(CursorRelay { backend })
.with_http_handler(CursorRelay { backend, tab_mode })
.with_graceful_shutdown(async move {
let _ = done.await;
})
@@ -89,6 +96,7 @@ async fn bind_proxy_listener(requested_port: u16) -> Result<TcpListener> {
#[derive(Clone)]
struct CursorRelay {
backend: SocketAddr,
tab_mode: Arc<RwLock<TabMode>>,
}
impl HttpHandler for CursorRelay {
@@ -98,7 +106,8 @@ impl HttpHandler for CursorRelay {
mut request: Request<Body>,
) -> RequestOrResponse {
let original = request.uri().clone();
if is_cursor_host(original.host().unwrap_or_default()) && is_local_path(original.path()) {
let locally_routed = should_route_locally(original.path(), *self.tab_mode.read());
if is_cursor_host(original.host().unwrap_or_default()) && locally_routed {
if let Ok(value) = original.to_string().parse() {
request.headers_mut().insert(UPSTREAM_URL_HEADER, value);
}
@@ -157,6 +166,10 @@ fn is_local_path(path: &str) -> bool {
)
}
fn should_route_locally(path: &str, tab_mode: TabMode) -> bool {
is_local_path(path) || (is_tab_path(path) && tab_mode != TabMode::Direct)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -179,5 +192,17 @@ mod tests {
"/aiserver.v1.AnalyticsService/BootstrapStatsig"
));
assert!(!is_local_path("/unrelated"));
assert!(should_route_locally(
"/aiserver.v1.AiService/StreamCpp",
TabMode::Public
));
assert!(should_route_locally(
"/aiserver.v1.AiService/StreamCpp",
TabMode::Custom
));
assert!(!should_route_locally(
"/aiserver.v1.AiService/StreamCpp",
TabMode::Direct
));
}
}
+93
View File
@@ -6,8 +6,11 @@ use super::{now_ms, Store};
const PORT_SETTINGS_KEY: &str = "network_ports";
const PROXY_SETTINGS_KEY: &str = "outbound_proxy";
const TAB_SETTINGS_KEY: &str = "cursor_tab";
const INSTALLATION_ID_KEY: &str = "installation_id";
pub const PUBLIC_TAB_SERVICE_URL: &str = "https://tab.leokun.cn";
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct PortSettings {
pub proxy_port: u16,
@@ -28,6 +31,31 @@ impl ProxyMode {
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TabMode {
#[default]
Public,
Direct,
Custom,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct TabSettings {
pub mode: TabMode,
pub address: String,
}
impl TabSettings {
pub fn service_url(&self) -> Option<&str> {
match self.mode {
TabMode::Public => Some(PUBLIC_TAB_SERVICE_URL),
TabMode::Direct => None,
TabMode::Custom => Some(&self.address),
}
}
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct ProxySettingsInput {
pub mode: ProxyMode,
@@ -139,6 +167,47 @@ impl Store {
self.proxy_settings().await
}
pub async fn tab_settings(&self) -> Result<TabSettings> {
let value = sqlx::query_scalar::<_, String>(
"SELECT value_json FROM service_settings WHERE setting_key = ?",
)
.bind(TAB_SETTINGS_KEY)
.fetch_optional(&self.pool)
.await?;
value
.map(|value| serde_json::from_str(&value).map_err(Into::into))
.unwrap_or_else(|| Ok(TabSettings::default()))
}
pub async fn set_tab_settings(&self, mut settings: TabSettings) -> Result<TabSettings> {
settings.address = settings.address.trim().trim_end_matches('/').to_owned();
if settings.mode == TabMode::Custom {
let parsed = url::Url::parse(&settings.address).map_err(|error| {
crate::Error::Config(format!("invalid TAB service address: {error}"))
})?;
if !matches!(parsed.scheme(), "http" | "https") {
return Err(crate::Error::Config(
"TAB service address must use http or https".into(),
));
}
if parsed.host_str().is_none()
|| parsed.query().is_some()
|| parsed.fragment().is_some()
{
return Err(crate::Error::Config(
"TAB service address must be a base URL without a query or fragment".into(),
));
}
}
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
.bind(TAB_SETTINGS_KEY)
.bind(serde_json::to_string(&settings)?)
.bind(now_ms())
.execute(&self.pool)
.await?;
Ok(settings)
}
pub async fn port_settings(&self) -> Result<PortSettings> {
let value = sqlx::query_scalar::<_, String>(
"SELECT value_json FROM service_settings WHERE setting_key = ?",
@@ -244,4 +313,28 @@ mod tests {
"secret"
);
}
#[tokio::test]
async fn tab_settings_default_to_public_and_validate_custom_urls() {
let store = Store::connect("sqlite::memory:").await.unwrap();
assert_eq!(store.tab_settings().await.unwrap(), TabSettings::default());
let saved = store
.set_tab_settings(TabSettings {
mode: TabMode::Custom,
address: " https://tab.example.com/base/ ".into(),
})
.await
.unwrap();
assert_eq!(saved.address, "https://tab.example.com/base");
assert_eq!(store.tab_settings().await.unwrap(), saved);
assert!(store
.set_tab_settings(TabSettings {
mode: TabMode::Custom,
address: "file:///tmp/tab".into(),
})
.await
.is_err());
}
}