feat: update desktop settings and server compatibility
@@ -0,0 +1,86 @@
|
||||
---
|
||||
name: model-selection
|
||||
description: Implement and review desktop selection of configured models through the unified grouped ModelSelect component. Use when adding or changing model dropdowns, model filters, Commit model settings, single-model selection, multi-model selection, provider grouping, or configured-model option construction under apps/desktop.
|
||||
---
|
||||
|
||||
# Model Selection
|
||||
|
||||
Use one presentation component for every UI that selects from already configured models:
|
||||
|
||||
```text
|
||||
apps/desktop/src/
|
||||
├── shared/ui/
|
||||
│ ├── ModelSelect.tsx # Single/multiple selection behavior and grouped floating menu
|
||||
│ └── ModelSelect.module.scss # Trigger, provider headers, checkbox rows, and footer
|
||||
├── shared/utils/
|
||||
│ └── modelProvider.ts # Built-in model provider display name
|
||||
└── features/
|
||||
├── home/ # Builds overview multi-select options
|
||||
└── settings/ # Builds Commit single-select options and persists selection
|
||||
|
||||
server/src/
|
||||
├── cursor/services/commit_message.rs # Validates built-in/plugin IDs and creates Commit invocation
|
||||
├── provider/router.rs # Routes stable IDs to built-in or plugin providers
|
||||
└── plugin/registry.rs # Resolves plugin model IDs and executes plugin streams
|
||||
```
|
||||
|
||||
## Component boundary
|
||||
|
||||
- Use `ModelSelect` when choosing one or more existing configured models.
|
||||
- Do not implement another model dropdown, reuse generic `Select`, or add a compatibility wrapper for configured-model selection.
|
||||
- Keep `ModelSelect` presentation-only. Pages own model/plugin state, option construction, filtering, and persistence.
|
||||
- Keep editable model-ID entry in `Combobox`; creating or editing a model identifier is input, not configured-model selection.
|
||||
- Delete replaced model-selection components, exports, styles, helpers, and compatibility paths once references are gone.
|
||||
|
||||
## Option contract
|
||||
|
||||
Construct every `ModelSelectOption` with:
|
||||
|
||||
- `value`: stable persisted/request identifier. Built-in models use `model_hash`; plugin models use plugin model `id`.
|
||||
- `label`: user-facing model display name.
|
||||
- `group`: supplier display name.
|
||||
- `icon`/`iconSrc`: model/provider icon when available.
|
||||
|
||||
For built-in models, derive `group` with `modelProviderName(model)`. It uses the configured `group_name` first and the API hostname otherwise. For plugin models, use the localized provider display name.
|
||||
|
||||
Preserve source order within each supplier. The first occurrence of a supplier determines group order.
|
||||
|
||||
## Modes
|
||||
|
||||
```text
|
||||
Single owner value: string
|
||||
└── <ModelSelect mode="single"> ── choose one ── close ── persist
|
||||
|
||||
Multiple owner value: string[]
|
||||
└── <ModelSelect mode="multiple"> ── toggle many ── remain open ── apply/filter
|
||||
```
|
||||
|
||||
- Both modes render classic checkbox controls in option rows.
|
||||
- Single mode allows exactly one checked option and closes immediately after selection.
|
||||
- Multiple mode supports toggling, clearing, selecting all, and selecting none.
|
||||
- In multiple mode, every supplier header has a checkbox: unchecked means none selected, checked means all selected, and indeterminate means some selected. Toggling it selects or clears that supplier.
|
||||
- Indent child model rows relative to their supplier header so hierarchy remains visible.
|
||||
- Commit always uses single mode and includes both configured built-in and configured plugin models. Its `直连` option has value `""`, belongs to the `Cursor` group, and is the first option.
|
||||
- Commit settings follow the settings-card edit-state pattern: read mode shows the persisted model, Edit creates a local draft, selection only changes that draft, Cancel restores the persisted value, and Save persists once before returning to read mode.
|
||||
- Persist the stable plugin model `id` unchanged. Commit generation validates that identifier through `PluginRegistry`, then lets `ProviderRouter` dispatch it; do not query the built-in model table for plugin IDs.
|
||||
- Overview filtering uses multiple mode.
|
||||
|
||||
## Floating-menu invariants
|
||||
|
||||
Also apply the project `floating-ui` and `frontend` skills:
|
||||
|
||||
- Render the menu through a body portal and position it with `@floating-ui/dom`.
|
||||
- Keep supplier headers and checkbox options inside the virtualized list; keep multi-select bulk actions outside it.
|
||||
- Close on Escape and outside pointer interaction, then restore trigger focus.
|
||||
- Preserve `aria-expanded`, `aria-controls`, `aria-haspopup`, listbox semantics, and multi-select semantics.
|
||||
- Keep the trigger's open/focus border visible while the portaled menu owns focus.
|
||||
|
||||
## Review checklist
|
||||
|
||||
- Search the repository for old model-selection components and zero-reference model option helpers; delete them instead of retaining fallbacks.
|
||||
- Confirm all configured-model selectors import `shared/ui/ModelSelect`.
|
||||
- Confirm no feature implements checkbox selection, supplier grouping, portal positioning, or bulk actions independently.
|
||||
- Confirm single/multiple value types cannot be mixed.
|
||||
- Confirm Commit has `直连` first and cannot select multiple values.
|
||||
- Confirm supplier labels are based on supplier identity, not request protocol type.
|
||||
- Follow the user's validation instruction; when automated tests are not requested, report manual checks without running test or build commands.
|
||||
@@ -1,20 +1,16 @@
|
||||
LOCAL_TAURI_SIGNING_KEY := $(CURDIR)/.tauri/cursor-byok.local.key
|
||||
|
||||
.PHONY: check dev-web dev-docs dev-server dev-desktop build-web build-docs build-server build-desktop build-docker
|
||||
.PHONY: check dev-web dev-server dev-desktop build-web build-server build-desktop build-docker
|
||||
|
||||
check:
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace --all-targets
|
||||
npm --prefix apps/desktop run check
|
||||
npm --prefix apps/docs run check
|
||||
|
||||
dev-web:
|
||||
npm --prefix apps/desktop run dev:web
|
||||
|
||||
dev-docs:
|
||||
npm --prefix apps/docs run dev
|
||||
|
||||
dev-server:
|
||||
CURSOR_CONSOLE_DIR=apps/desktop/dist cargo run --package cursor-server --bin cursor-server
|
||||
|
||||
@@ -24,9 +20,6 @@ dev-desktop:
|
||||
build-web:
|
||||
npm --prefix apps/desktop run build
|
||||
|
||||
build-docs:
|
||||
npm --prefix apps/docs run build
|
||||
|
||||
build-server:
|
||||
cargo build --release --package cursor-server --bin cursor-server
|
||||
|
||||
|
||||
@@ -128,7 +128,6 @@ cursor-byok/
|
||||
│ │ │ ├── i18n/ # 本地化运行时与语言目录
|
||||
│ │ │ └── styles/ # 全局主题与排版令牌
|
||||
│ │ └── src-tauri/ # Tauri 桌面生命周期
|
||||
│ └── docs/ # Next.js 与 Fumadocs 中文/英文文档站
|
||||
├── server/
|
||||
│ ├── src/
|
||||
│ │ ├── cursor/ # Cursor 协议适配
|
||||
@@ -167,7 +166,6 @@ cursor-byok/
|
||||
|
||||
```bash
|
||||
npm --prefix apps/desktop install
|
||||
npm --prefix apps/docs install
|
||||
```
|
||||
|
||||
### 启动开发环境
|
||||
@@ -184,14 +182,6 @@ make dev-web
|
||||
make dev-desktop
|
||||
```
|
||||
|
||||
启动文档站:
|
||||
|
||||
```bash
|
||||
make dev-docs
|
||||
```
|
||||
|
||||
文档站默认地址为 <http://localhost:3000>。
|
||||
|
||||
### 检查与构建
|
||||
|
||||
运行完整检查:
|
||||
@@ -205,13 +195,10 @@ make check
|
||||
```bash
|
||||
make build-web # 构建桌面前端
|
||||
make build-server # 构建 Rust 本地服务
|
||||
make build-docs # 构建文档站
|
||||
make build-desktop # 构建 Tauri 桌面安装包
|
||||
make build-docker # 构建 Docker 镜像
|
||||
```
|
||||
|
||||
文档内容位于 `apps/docs/content/docs` 和 `apps/docs/content/blog`。修改文档侧边栏时同步更新 `apps/docs/content/docs/meta.json`。
|
||||
|
||||
## 路线图
|
||||
|
||||
项目将继续改进模型兼容性、Agent 工具、本地运行稳定性和自托管体验,并探索支持更多 IDE、聊天和 Agent 工作流。
|
||||
|
||||
@@ -13,6 +13,8 @@ import { SettingsPage } from "./features/settings/SettingsPage";
|
||||
import { useAppStore } from "./shared/store/appStore";
|
||||
import { updateStore } from "./shared/store/updateStore";
|
||||
|
||||
const AUTO_UPDATE_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1_000;
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<>
|
||||
@@ -39,6 +41,7 @@ export function App() {
|
||||
function AppMessages() {
|
||||
const { error } = useAppStore();
|
||||
const previousError = useRef<string | null>(null);
|
||||
const lastAutomaticUpdateCheckAt = useRef(0);
|
||||
const showMessage = useMessage();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -47,12 +50,36 @@ function AppMessages() {
|
||||
}, [error, showMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
void updateStore.check().then((version) => {
|
||||
if (!version) return;
|
||||
showMessage(t("发现新版本 {version},可在设置中安装", { version }), { duration: 6_000 });
|
||||
}).catch(() => {
|
||||
// Startup checks are best-effort; manual checks in Settings report errors.
|
||||
});
|
||||
let disposed = false;
|
||||
const checkAutomatically = () => {
|
||||
const now = Date.now();
|
||||
if (now - lastAutomaticUpdateCheckAt.current < AUTO_UPDATE_CHECK_INTERVAL_MS) return;
|
||||
lastAutomaticUpdateCheckAt.current = now;
|
||||
const previousVersion = updateStore.getSnapshot().availableVersion;
|
||||
void updateStore.check().then((version) => {
|
||||
if (disposed || !version || version === previousVersion) return;
|
||||
showMessage(t("发现新版本 {version},可在设置中安装", { version }), { duration: 6_000 });
|
||||
}).catch(() => {
|
||||
if (!disposed) lastAutomaticUpdateCheckAt.current = 0;
|
||||
// Automatic checks are best-effort; manual checks in Settings report errors.
|
||||
});
|
||||
};
|
||||
const checkWhenVisible = () => {
|
||||
if (document.visibilityState === "visible") checkAutomatically();
|
||||
};
|
||||
|
||||
checkAutomatically();
|
||||
window.addEventListener("focus", checkAutomatically);
|
||||
window.addEventListener("online", checkAutomatically);
|
||||
document.addEventListener("visibilitychange", checkWhenVisible);
|
||||
const timer = window.setInterval(checkAutomatically, AUTO_UPDATE_CHECK_INTERVAL_MS);
|
||||
return () => {
|
||||
disposed = true;
|
||||
window.removeEventListener("focus", checkAutomatically);
|
||||
window.removeEventListener("online", checkAutomatically);
|
||||
document.removeEventListener("visibilitychange", checkWhenVisible);
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [showMessage]);
|
||||
|
||||
return <MessageProvider />;
|
||||
|
||||
@@ -73,12 +73,13 @@ const calls: LlmCall[] = Array.from({ length: 24 }, (_, index) => {
|
||||
};
|
||||
});
|
||||
|
||||
const harnessStatus: CursorHarnessStatus = {
|
||||
let harnessStatus: CursorHarnessStatus = {
|
||||
platform: "macos",
|
||||
ca: "ready",
|
||||
configured_models: models.length,
|
||||
enabled_models: models.length,
|
||||
integration: "enabled",
|
||||
settings_applied: true,
|
||||
proxy_url: "http://127.0.0.1:54321",
|
||||
ca_install_command: null,
|
||||
};
|
||||
@@ -126,7 +127,17 @@ export function installDemoApi() {
|
||||
if (path === "/llm-calls") return json(calls);
|
||||
if (path.startsWith("/llm-calls/")) return json(createCallDetail(path.slice("/llm-calls/".length)));
|
||||
if (path === "/harness/cursor/status") return json(harnessStatus);
|
||||
if (path === "/harness/cursor/ca/initialize" || path === "/harness/cursor/enabled") return json(harnessStatus);
|
||||
if (path === "/harness/cursor/ca/initialize") return json(harnessStatus);
|
||||
if (path === "/harness/cursor/enabled") {
|
||||
const enabled = Boolean((body as { enabled?: unknown } | null)?.enabled);
|
||||
harnessStatus = {
|
||||
...harnessStatus,
|
||||
integration: enabled ? "enabled" : "disabled",
|
||||
settings_applied: enabled,
|
||||
proxy_url: enabled ? "http://127.0.0.1:54321" : null,
|
||||
};
|
||||
return json(harnessStatus);
|
||||
}
|
||||
if (path === "/settings/observability" && method === "GET") return json({ detailed });
|
||||
if (path === "/settings/observability") {
|
||||
detailed = Boolean((body as { detailed?: unknown } | null)?.detailed);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, configuredPluginModels, type Overview } from "../../shared/api";
|
||||
import { api, pluginText, type Overview } from "../../shared/api";
|
||||
import { ContributionCalendarChart } from "./charts/ContributionCalendarChart";
|
||||
import { DailyTokenUsageChart } from "./charts/DailyTokenUsageChart";
|
||||
import { HomeMetrics } from "./metrics/HomeMetrics";
|
||||
@@ -9,7 +9,9 @@ import { OverviewTimeRangeFilter, type OverviewRangePreset } from "./overview/Ov
|
||||
import { PageActions } from "../../shell/PageActions";
|
||||
import { appStore, useAppStore } from "../../shared/store/appStore";
|
||||
import { formatTimeInput, parseTimeInput } from "../../shared/utils/parseTimeInput";
|
||||
import { modelProviderName } from "../../shared/utils/modelProvider";
|
||||
import { claudeIcon, flatColorOrganizationIcon, openAiIcon } from "../../shared/ui/icons";
|
||||
import { useI18n } from "../../i18n/store";
|
||||
|
||||
type TimeRange = { startMs: number; endMs: number };
|
||||
|
||||
@@ -31,6 +33,7 @@ function presetRange(preset: Exclude<OverviewRangePreset, "custom">, now = new D
|
||||
|
||||
export function HomePage() {
|
||||
const { overview, busy, models, plugins } = useAppStore();
|
||||
const { locale } = useI18n();
|
||||
const [preset, setPreset] = useState<OverviewRangePreset>("month");
|
||||
const [customRange, setCustomRange] = useState<TimeRange | null>(null);
|
||||
const [customOpen, setCustomOpen] = useState(false);
|
||||
@@ -105,13 +108,18 @@ export function HomePage() {
|
||||
...models.map((model) => ({
|
||||
value: model.model_hash,
|
||||
label: model.display_name,
|
||||
group: modelProviderName(model),
|
||||
icon: iconFor(model.type),
|
||||
})),
|
||||
...configuredPluginModels(plugins).map((model) => ({
|
||||
value: model.id,
|
||||
label: model.displayName,
|
||||
icon: flatColorOrganizationIcon,
|
||||
})),
|
||||
...plugins.flatMap((plugin) => plugin.providers.flatMap((provider) =>
|
||||
provider.configured ? provider.models.map((model) => ({
|
||||
value: model.id,
|
||||
label: model.displayName,
|
||||
group: pluginText(provider.displayName, locale) || model.pluginName,
|
||||
iconSrc: model.icon || undefined,
|
||||
icon: model.icon ? undefined : flatColorOrganizationIcon,
|
||||
})) : [],
|
||||
)),
|
||||
];
|
||||
const sections: VirtualPageSection[] = [
|
||||
{
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createPortal } from "react-dom";
|
||||
import { parseTimeInput } from "../../../shared/utils/parseTimeInput";
|
||||
import controls from "../../../shared/ui/Controls.module.scss";
|
||||
import { Icon } from "../../../shared/ui/Icon";
|
||||
import { MultiSelect, type MultiSelectOption } from "../../../shared/ui/MultiSelect";
|
||||
import { ModelSelect, type ModelSelectOption } from "../../../shared/ui/ModelSelect";
|
||||
import { TooltipTrigger } from "../../../shared/ui/TooltipTrigger";
|
||||
import { refreshIcon } from "../../../shared/ui/icons";
|
||||
import styles from "./OverviewTimeRangeFilter.module.scss";
|
||||
@@ -16,7 +16,7 @@ export function OverviewTimeRangeFilter({ value, customOpen, customStart, custom
|
||||
customOpen: boolean;
|
||||
customStart: string;
|
||||
customEnd: string;
|
||||
modelOptions: MultiSelectOption[];
|
||||
modelOptions: ModelSelectOption[];
|
||||
selectedModels: string[];
|
||||
busy: boolean;
|
||||
onSelect: (value: Exclude<OverviewRangePreset, "custom">) => void;
|
||||
@@ -105,7 +105,7 @@ export function OverviewTimeRangeFilter({ value, customOpen, customStart, custom
|
||||
>
|
||||
<label><span>{t("开始时间")}</span><input type="text" placeholder={t("如:2026-08-23 09:00、1小时前")} value={customStart} onChange={(event) => onCustomStartChange(event.target.value)} /></label>
|
||||
<label><span>{t("结束时间")}</span><input type="text" placeholder={t("如:现在、2026-08-23 18:00")} value={customEnd} onChange={(event) => onCustomEndChange(event.target.value)} /></label>
|
||||
<div className={styles.filterRow}><MultiSelect label={t("模型")} value={selectedModels} options={modelOptions} onChange={onSelectedModelsChange} /></div>
|
||||
<div className={styles.filterRow}><ModelSelect mode="multiple" label={t("模型")} value={selectedModels} options={modelOptions} onChange={onSelectedModelsChange} /></div>
|
||||
<div className={styles.popoverActions}>
|
||||
<button type="button" className={controls.secondary} onClick={() => onCustomOpenChange(false)}>{t("取消")}</button>
|
||||
<button type="button" className={controls.primary} disabled={!customValid} onClick={onCustomApply}>{t("应用")}</button>
|
||||
|
||||
@@ -4,7 +4,7 @@ import Sortable from "sortablejs";
|
||||
import type { Model, PluginModelDescriptor } from "../../shared/api";
|
||||
import { Card } from "../../shared/ui/Card";
|
||||
import { Icon } from "../../shared/ui/Icon";
|
||||
import { chevronDownIcon, chevronRightIcon, claudeIcon, dragIcon, flatColorOrganizationIcon, openAiIcon } from "../../shared/ui/icons";
|
||||
import { chevronDownIcon, chevronRightIcon, claudeIcon, dragIcon, editIcon, flatColorOrganizationIcon, openAiIcon } from "../../shared/ui/icons";
|
||||
import { TruncatedButton } from "../../shared/ui/TruncatedButton";
|
||||
import { CursorModelTestResult, type CursorModelTestState } from "./CursorModelTestResult";
|
||||
import styles from "./CursorSettings.module.scss";
|
||||
@@ -61,6 +61,7 @@ export function CursorModelCards(props: CursorModelCardsProps) {
|
||||
key={group.key}
|
||||
label={group.label}
|
||||
icon={group.icon}
|
||||
defaultOpen={false}
|
||||
onSettings={props.grouping === "provider" ? () => props.onGroupSettings(group) : undefined}
|
||||
>
|
||||
{group.models.map((model) => <ModelListRow
|
||||
@@ -79,9 +80,10 @@ export function CursorModelCards(props: CursorModelCardsProps) {
|
||||
return <div className={styles.modelGroups}>
|
||||
{builtins}
|
||||
{pluginGroups(props.pluginModels).map((group) => <CollapsibleGroup
|
||||
key={group.pluginId}
|
||||
key={`${props.grouping}:${group.pluginId}`}
|
||||
label={group.pluginName}
|
||||
iconSrc={group.icon}
|
||||
defaultOpen={props.grouping === "flat"}
|
||||
>
|
||||
{group.models.map((model) => <PluginModelRow
|
||||
key={model.id}
|
||||
@@ -109,14 +111,15 @@ function pluginGroups(models: PluginModelDescriptor[]) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
function CollapsibleGroup({ label, icon, iconSrc, onSettings, children }: {
|
||||
function CollapsibleGroup({ label, icon, iconSrc, defaultOpen = true, onSettings, children }: {
|
||||
label: string;
|
||||
icon?: IconifyIcon;
|
||||
iconSrc?: string;
|
||||
defaultOpen?: boolean;
|
||||
onSettings?: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(true);
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
return <Card className={styles.groupCard}>
|
||||
<div className={styles.groupHeader}>
|
||||
<button
|
||||
@@ -129,7 +132,10 @@ function CollapsibleGroup({ label, icon, iconSrc, onSettings, children }: {
|
||||
{iconSrc && <Icon src={iconSrc} size="1.1em" />}
|
||||
<span className={styles.groupLabel}>{label}</span>
|
||||
</button>
|
||||
{onSettings && <button type="button" className={styles.groupSettings} onClick={onSettings}>{t("分组设置")}</button>}
|
||||
{onSettings && <button type="button" className={styles.groupSettings} onClick={onSettings}>
|
||||
<Icon icon={editIcon} size="1em" />
|
||||
{t("分组设置")}
|
||||
</button>}
|
||||
<button
|
||||
type="button"
|
||||
className={styles.groupChevron}
|
||||
|
||||
@@ -5,6 +5,20 @@
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.takeoverActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.takeoverStatus {
|
||||
min-width: 39px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: type.$font-size-xs;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.groupActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -79,6 +93,9 @@
|
||||
gap: 8px;
|
||||
}
|
||||
.groupSettings {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 2px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
background: none;
|
||||
|
||||
@@ -13,6 +13,7 @@ import { FormField, SecretTextInput, TextInput } from "../../shared/ui/FormContr
|
||||
import controls from "../../shared/ui/Controls.module.scss";
|
||||
import { Icon } from "../../shared/ui/Icon";
|
||||
import { Modal } from "../../shared/ui/Modal";
|
||||
import { Switch } from "../../shared/ui/Switch";
|
||||
import { TooltipTrigger } from "../../shared/ui/TooltipTrigger";
|
||||
import { addIcon } from "../../shared/ui/icons";
|
||||
import { useMessage } from "../../shared/ui/message";
|
||||
@@ -30,6 +31,7 @@ export function CursorSettingsPage() {
|
||||
const [caCommand, setCaCommand] = useState<string | null>(null);
|
||||
const [waitingForCaRefresh, setWaitingForCaRefresh] = useState(false);
|
||||
const [deleting, setDeleting] = useState<Model | null>(null);
|
||||
const [confirmDisableTakeover, setConfirmDisableTakeover] = useState(false);
|
||||
const [testingModelHashes, setTestingModelHashes] = useState<Set<string>>(() => new Set());
|
||||
const [modelTestResults, setModelTestResults] = useState<Map<string, CursorModelTestState>>(() => new Map());
|
||||
const [savingAndTesting, setSavingAndTesting] = useState(false);
|
||||
@@ -42,6 +44,8 @@ export function CursorSettingsPage() {
|
||||
const [groupSettingsBusy, setGroupSettingsBusy] = useState(false);
|
||||
const activeModelTests = useRef(new Map<string, { testId: string; controller: AbortController; cancelling: boolean }>());
|
||||
const caReady = cursorHarness?.ca === "ready";
|
||||
const cursorTakenOver = cursorHarness?.settings_applied ?? false;
|
||||
const takeoverLabel = cursorTakenOver ? t("关闭接管Cursor") : t("开启接管Cursor");
|
||||
const pluginModels = configuredPluginModels(plugins);
|
||||
const testTargets = [
|
||||
...models.map((model) => ({ model_hash: model.model_hash, display_name: model.display_name })),
|
||||
@@ -123,11 +127,10 @@ export function CursorSettingsPage() {
|
||||
const active = activeModelTests.current.get(modelHash);
|
||||
if (!active || active.cancelling) return;
|
||||
active.cancelling = true;
|
||||
active.controller.abort();
|
||||
try {
|
||||
await api.cancelModelTest(modelHash, active.testId);
|
||||
active.controller.abort();
|
||||
} catch (cause) {
|
||||
active.cancelling = false;
|
||||
message(t("取消测试失败:{error}", { error: errorText(cause) }), { duration: 5000 });
|
||||
}
|
||||
};
|
||||
@@ -296,16 +299,43 @@ export function CursorSettingsPage() {
|
||||
: Math.max(380, activeGroups.reduce((height, group) => height + 60 + group.models.length * 56, 0) + Math.max(0, activeGroups.length - 1) * 20 + pluginSectionHeight);
|
||||
|
||||
return <>
|
||||
{testTargets.length > 0 && <PageActions position="left">
|
||||
<div className={styles.groupActions} role="group" aria-label={t("操作")}>
|
||||
<button type="button" aria-pressed={grouping === "flat"} onClick={() => setGrouping("flat")}>{t("默认平铺")}</button>
|
||||
{canGroupByProvider && <button type="button" aria-pressed={grouping === "provider"} onClick={() => setGrouping("provider")}>{t("按供应商")}</button>}
|
||||
{canGroupByType && <button type="button" aria-pressed={grouping === "type"} onClick={() => setGrouping("type")}>{t("按类型")}</button>}
|
||||
<button type="button" disabled={cursorBusy || (!batchTesting && testingModelHashes.size > 0)} onClick={() => void (batchTesting ? cancelAllModelTests() : testAllModels())}>{batchTesting ? t("取消全部测试") : t("一键测试")}</button>
|
||||
<PageActions position="left">
|
||||
<div className={styles.takeoverActions}>
|
||||
<span className={styles.takeoverStatus}>{cursorTakenOver ? t("已接管") : t("未接管")}</span>
|
||||
<TooltipTrigger label={takeoverLabel}>
|
||||
<Switch
|
||||
checked={cursorTakenOver}
|
||||
disabled={cursorBusy || (!cursorTakenOver && !caReady)}
|
||||
label={takeoverLabel}
|
||||
onChange={(enabled) => {
|
||||
if (enabled) void appStore.setCursorEnabled(true);
|
||||
else setConfirmDisableTakeover(true);
|
||||
}}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
{testTargets.length > 0 && <div className={styles.groupActions} role="group" aria-label={t("操作")}>
|
||||
<button type="button" aria-pressed={grouping === "flat"} onClick={() => setGrouping("flat")}>{t("默认平铺")}</button>
|
||||
{canGroupByProvider && <button type="button" aria-pressed={grouping === "provider"} onClick={() => setGrouping("provider")}>{t("按供应商")}</button>}
|
||||
{canGroupByType && <button type="button" aria-pressed={grouping === "type"} onClick={() => setGrouping("type")}>{t("按类型")}</button>}
|
||||
<button type="button" disabled={cursorBusy || (!batchTesting && testingModelHashes.size > 0)} onClick={() => void (batchTesting ? cancelAllModelTests() : testAllModels())}>{batchTesting ? t("取消全部测试") : t("一键测试")}</button>
|
||||
</div>}
|
||||
</div>
|
||||
</PageActions>}
|
||||
</PageActions>
|
||||
<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="Cursor" sections={[{ key: "cursor-settings", estimatedHeight: estimatedModelHeight, content }]} />
|
||||
<ConfirmDialog
|
||||
open={confirmDisableTakeover}
|
||||
title={t("关闭接管Cursor?")}
|
||||
cancelLabel={t("取消")}
|
||||
confirmLabel={t("关闭接管")}
|
||||
onCancel={() => setConfirmDisableTakeover(false)}
|
||||
onConfirm={() => {
|
||||
setConfirmDisableTakeover(false);
|
||||
void appStore.setCursorEnabled(false);
|
||||
}}
|
||||
>
|
||||
<p>{t("关闭后将移除 Cursor 本地代理配置。如果你需要登陆官方账号,通常不需要关闭操作,推荐直接登陆你的账号即可(byok模型与官方账号的模型已支持无缝衔接),是否继续关闭并清理代理?")}</p>
|
||||
</ConfirmDialog>
|
||||
<Modal fullHeight open={draft !== null} title={editing ? t("编辑模型") : t("添加模型")} banner={draft && (editorTesting || editorTestState) ? <CursorModelTestResult state={editorTestState} testing={editorTesting} /> : undefined} busy={cursorBusy || savingAndTesting} onClose={() => { if (editing && editorTesting) void cancelModelTest(editing.model_hash); setDraft(null); setEditing(null); }} onSubmit={() => void save()} submitLabel={t("保存")} secondaryAction={<button type="button" className={controls.secondary} disabled={cursorBusy || savingAndTesting} onClick={() => void (editorTesting && editing ? cancelModelTest(editing.model_hash) : saveAndTest())}>{savingAndTesting ? t("处理中…") : editorTesting ? t("取消测试") : t("保存并测试")}</button>}>
|
||||
{draft && <>
|
||||
<CursorModelEditor draft={draft} modelOptions={modelOptions} discovering={discovering} onChange={setDraft} onDiscover={() => void discover()} />
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
@use "../../styles/typography" as type;
|
||||
|
||||
.content {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.row {
|
||||
min-width: 0;
|
||||
min-height: 34px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
padding: 16px;
|
||||
|
||||
> div:first-child {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
small {
|
||||
color: var(--vscode-descriptionForeground);
|
||||
@@ -18,8 +18,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
.details {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.select {
|
||||
min-width: 280px;
|
||||
width: min(320px, 50%);
|
||||
}
|
||||
|
||||
.value {
|
||||
min-width: 0;
|
||||
max-width: 70%;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
overflow-wrap: anywhere;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.actionGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.textButton {
|
||||
@@ -51,3 +70,7 @@
|
||||
outline: 1px solid var(--vscode-focusBorder);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 680px) {
|
||||
.select { width: 68%; }
|
||||
}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { api, type CommitSettingsView } from "../../shared/api";
|
||||
import { api, pluginText, type CommitSettingsView } from "../../shared/api";
|
||||
import { useI18n } from "../../i18n/store";
|
||||
import { useAppStore } from "../../shared/store/appStore";
|
||||
import { Button } from "../../shared/ui/Button";
|
||||
import { Modal } from "../../shared/ui/Modal";
|
||||
import { Select } from "../../shared/ui/Select";
|
||||
import { ModelSelect, type ModelSelectOption } from "../../shared/ui/ModelSelect";
|
||||
import { claudeIcon, flatColorOrganizationIcon, openAiIcon } from "../../shared/ui/icons";
|
||||
import { TitledCard } from "../../shared/ui/TitledCard";
|
||||
import { useMessage } from "../../shared/ui/message";
|
||||
import controls from "../../shared/ui/Controls.module.scss";
|
||||
import { modelProviderName } from "../../shared/utils/modelProvider";
|
||||
import styles from "./CommitSettingsCard.module.scss";
|
||||
|
||||
function errorText(cause: unknown) {
|
||||
@@ -13,20 +17,44 @@ function errorText(cause: unknown) {
|
||||
}
|
||||
|
||||
export function CommitSettingsCard() {
|
||||
const { models } = useAppStore();
|
||||
const { models, plugins } = useAppStore();
|
||||
const { locale } = useI18n();
|
||||
const message = useMessage();
|
||||
const [view, setView] = useState<CommitSettingsView | null>(null);
|
||||
const [modelDraft, setModelDraft] = useState("");
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [savingModel, setSavingModel] = useState(false);
|
||||
const [promptOpen, setPromptOpen] = useState(false);
|
||||
const [promptDraft, setPromptDraft] = useState("");
|
||||
const [savingPrompt, setSavingPrompt] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void api.commitSettings().then(setView).catch((cause) => message(errorText(cause)));
|
||||
}, [message]);
|
||||
let active = true;
|
||||
void (async () => {
|
||||
try {
|
||||
let loaded = await api.commitSettings(locale);
|
||||
if (!loaded.prompt.trim() && loaded.prompt_locale !== locale) {
|
||||
loaded = await api.setCommitSettings({
|
||||
model_id: loaded.model_id,
|
||||
prompt: "",
|
||||
prompt_locale: locale,
|
||||
});
|
||||
}
|
||||
if (active) {
|
||||
setView(loaded);
|
||||
setModelDraft(loaded.model_id);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active) message(errorText(cause));
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [locale, message]);
|
||||
|
||||
const modelOptions = useMemo(() => {
|
||||
const options: Array<{ value: string; label: string }> = [{ value: "", label: t("直连") }];
|
||||
const options: ModelSelectOption[] = [{ value: "", label: t("直连"), group: "Cursor" }];
|
||||
const seen = new Set<string>();
|
||||
for (const model of models) {
|
||||
seen.add(model.model_hash);
|
||||
@@ -35,41 +63,73 @@ export function CommitSettingsCard() {
|
||||
label: model.display_name && model.display_name !== model.model_id
|
||||
? `${model.display_name}(${model.model_id})`
|
||||
: model.display_name || model.model_id,
|
||||
group: modelProviderName(model),
|
||||
icon: model.type === "anthropic" ? claudeIcon : openAiIcon,
|
||||
});
|
||||
}
|
||||
for (const plugin of plugins) {
|
||||
for (const provider of plugin.providers) {
|
||||
if (!provider.configured) continue;
|
||||
const group = pluginText(provider.displayName, locale) || plugin.name;
|
||||
for (const model of provider.models) {
|
||||
seen.add(model.id);
|
||||
options.push({
|
||||
value: model.id,
|
||||
label: model.displayName,
|
||||
group,
|
||||
iconSrc: model.icon || undefined,
|
||||
icon: model.icon ? undefined : flatColorOrganizationIcon,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (view?.model_id && !seen.has(view.model_id)) {
|
||||
options.push({ value: view.model_id, label: view.model_id });
|
||||
options.push({ value: view.model_id, label: view.model_id, group: "Cursor" });
|
||||
}
|
||||
return options;
|
||||
}, [models, view]);
|
||||
|
||||
const selectedModelId = view?.model_id ?? "";
|
||||
}, [locale, models, plugins, view]);
|
||||
|
||||
const persist = useCallback(
|
||||
async (modelId: string, prompt: string) => {
|
||||
if (!view) return null;
|
||||
const normalizedPrompt =
|
||||
prompt.trim() === view.default_prompt.trim() ? "" : prompt.trim();
|
||||
return api.setCommitSettings({ model_id: modelId, prompt: normalizedPrompt });
|
||||
return api.setCommitSettings({
|
||||
model_id: modelId,
|
||||
prompt: normalizedPrompt,
|
||||
prompt_locale: locale,
|
||||
});
|
||||
},
|
||||
[view],
|
||||
[view, locale],
|
||||
);
|
||||
|
||||
const changeModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (!view) return;
|
||||
setSavingModel(true);
|
||||
try {
|
||||
const saved = await persist(modelId, view.prompt);
|
||||
if (saved) setView(saved);
|
||||
} catch (cause) {
|
||||
message(errorText(cause));
|
||||
} finally {
|
||||
setSavingModel(false);
|
||||
const editModel = useCallback(() => {
|
||||
if (!view) return;
|
||||
setModelDraft(view.model_id);
|
||||
setEditing(true);
|
||||
}, [view]);
|
||||
|
||||
const cancelModelEdit = useCallback(() => {
|
||||
setModelDraft(view?.model_id ?? "");
|
||||
setEditing(false);
|
||||
}, [view]);
|
||||
|
||||
const saveModel = useCallback(async () => {
|
||||
if (!view) return;
|
||||
setSavingModel(true);
|
||||
try {
|
||||
const saved = await persist(modelDraft, view.prompt);
|
||||
if (saved) {
|
||||
setView(saved);
|
||||
setModelDraft(saved.model_id);
|
||||
setEditing(false);
|
||||
}
|
||||
},
|
||||
[view, persist, message],
|
||||
);
|
||||
} catch (cause) {
|
||||
message(errorText(cause));
|
||||
} finally {
|
||||
setSavingModel(false);
|
||||
}
|
||||
}, [modelDraft, view, persist, message]);
|
||||
|
||||
const openPrompt = useCallback(() => {
|
||||
if (!view) return;
|
||||
@@ -97,29 +157,45 @@ export function CommitSettingsCard() {
|
||||
setPromptDraft(view.default_prompt);
|
||||
}, [view]);
|
||||
|
||||
const selectedModelLabel = modelOptions.find((option) => option.value === view?.model_id)?.label
|
||||
?? view?.model_id
|
||||
?? t("加载中…");
|
||||
const action = editing ? (
|
||||
<div className={styles.actionGroup}>
|
||||
<Button size="small" disabled={savingModel} onClick={cancelModelEdit}>{t("取消")}</Button>
|
||||
<Button variant="primary" size="small" disabled={savingModel} onClick={() => void saveModel()}>
|
||||
{savingModel ? t("保存中…") : t("保存")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.actionGroup}>
|
||||
<button type="button" className={styles.textButton} disabled={!view} onClick={openPrompt}>
|
||||
{t("提示词设置")}
|
||||
</button>
|
||||
<button type="button" className={styles.textButton} disabled={!view} onClick={editModel}>
|
||||
{t("编辑")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<TitledCard
|
||||
title={t("Commit 设置")}
|
||||
action={
|
||||
<button type="button" className={styles.textButton} disabled={!view} onClick={openPrompt}>
|
||||
{t("提示词设置")}
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<div className={styles.row}>
|
||||
<div>
|
||||
<strong>{t("生成模型")}</strong>
|
||||
<small>{t("直连走 Cursor 原有通道;选择 Cursor 页已配置的模型后由本地生成。")}</small>
|
||||
</div>
|
||||
<div className={styles.select}>
|
||||
<Select
|
||||
value={selectedModelId}
|
||||
options={modelOptions}
|
||||
disabled={!view || savingModel}
|
||||
ariaLabel={t("生成模型")}
|
||||
onChange={(value) => void changeModel(value)}
|
||||
/>
|
||||
<TitledCard title={t("Commit 提交代码模型设置")} action={action}>
|
||||
<div className={styles.content}>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.details}>
|
||||
<strong>{t("生成模型")}</strong>
|
||||
</div>
|
||||
{editing ? <div className={styles.select}>
|
||||
<ModelSelect
|
||||
mode="single"
|
||||
value={modelDraft}
|
||||
options={modelOptions}
|
||||
disabled={savingModel}
|
||||
label={t("生成模型")}
|
||||
onChange={setModelDraft}
|
||||
/>
|
||||
</div> : <span className={styles.value}>{selectedModelLabel}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</TitledCard>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
}
|
||||
|
||||
.control {
|
||||
width: min(420px, 62%);
|
||||
width: min(320px, 50%);
|
||||
}
|
||||
|
||||
.value {
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
}
|
||||
|
||||
.control {
|
||||
width: min(420px, 62%);
|
||||
width: min(320px, 50%);
|
||||
}
|
||||
|
||||
.value {
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
"105a9082c346f958": "Testing…",
|
||||
"124be3f86f197802": "Token usage",
|
||||
"12ae77e6202d063e": "Custom Headers",
|
||||
"12b86e89701b0241": "Enter a model name and press Enter to add it",
|
||||
"133340e53175128a": "Test all",
|
||||
"13a9ac7a68c5fd96": "The CA is stored only on this device and is used to securely inspect Cursor HTTPS requests.",
|
||||
"13b61c5f697b6700": "Cache hit rate",
|
||||
@@ -64,11 +63,13 @@
|
||||
"24a0a24864454575": "Existing, skipped",
|
||||
"2555d6c7fbb7e070": "Enter a model ID directly or load models returned by the API.",
|
||||
"29585d7193539200": "Current version {version}",
|
||||
"296da37506328d89": "Disable Cursor takeover",
|
||||
"29fbbef32a6eb58b": "Do not show this ad again",
|
||||
"2a2773134a829016": "Aggregated from historical LLM calls; in-progress calls are excluded.",
|
||||
"2caeaec539e78898": "Thinking budget tokens",
|
||||
"2cbc58108d78b06c": "Waiting for browser authorization…",
|
||||
"2cd0f3be8738a86c": "Cancel",
|
||||
"2cdf7d3275016cc2": "Disable Cursor takeover?",
|
||||
"2d30c2a98ebb5278": "Current: {rate}",
|
||||
"2eb2bf7c6597ab9a": "Detailed records",
|
||||
"2f280a8120c0db12": "Used only for display and does not change the model name sent to the model service.",
|
||||
@@ -77,7 +78,6 @@
|
||||
"2f5f1d6fbfb061ed": "Not set",
|
||||
"2f6416a2c424856b": "Final request URL",
|
||||
"2f7ba5fd1d12f7f9": "Open the tutorial?",
|
||||
"2f7dec3be28d7597": "{count} selected",
|
||||
"2f9daa828907b93f": "Delete",
|
||||
"2fe5a8d0eee9f14c": "Invalid",
|
||||
"303c30f301514250": "Search resources",
|
||||
@@ -91,7 +91,6 @@
|
||||
"382f2e3419a02fef": "Only clear detailed records",
|
||||
"38844b135cf70dfc": "More",
|
||||
"393e1241552b1870": "Request",
|
||||
"398f8e6c6f0a0b97": "Continue selecting or typing",
|
||||
"39f52eee100131d7": "Cached input",
|
||||
"3a0fb74abe2460b6": "Chunks",
|
||||
"3a3f595df70ec8ff": "Clear storage",
|
||||
@@ -134,11 +133,13 @@
|
||||
"51d04bc3d286f018": "Last calendar day",
|
||||
"51de3bcec137ab1b": "Connectivity tests succeeded for all {count} models",
|
||||
"5228358a6db59fe7": "For example: now, 2026-08-23 18:00",
|
||||
"5319e7374f78fb38": "Taken over",
|
||||
"5401344227e49e2f": "TAB settings",
|
||||
"54644705e9c61009": "Port settings",
|
||||
"54c53e5fe791d1f3": "Initialize CA",
|
||||
"54e6745ff43c9c74": "Unable to save model order",
|
||||
"550eddc3c7fefa99": "Sponsored",
|
||||
"552a5d4baf45d878": "Commit Message Model Settings",
|
||||
"56432ba297009bdc": "Initialize the CA first",
|
||||
"56627c94a9decee6": "Maximum output tokens",
|
||||
"576d81bb0631b165": "Import",
|
||||
@@ -225,11 +226,13 @@
|
||||
"91af6e57e7453fbe": "Add account",
|
||||
"92156a483d4ba248": "Only request, response, and trace attachments are deleted; call summaries, metrics, and configuration are kept.",
|
||||
"92e26b27d5ea8f0e": "Failed to check for updates: {error}",
|
||||
"9305c0e13642cab4": "Not taken over",
|
||||
"940a168911ade998": "Items per page",
|
||||
"945fb1c67eca8493": "Installing the plugin runtime",
|
||||
"946b3ffc02f026c0": "Delete this model?",
|
||||
"954ec984cd4f49d1": "Syncing…",
|
||||
"966498853d801a52": "TAB connection",
|
||||
"96f7642963ca0dbf": "Enable Cursor takeover",
|
||||
"9850ed41a5bfbb0c": "{count} selected",
|
||||
"997ec8201c2adeda": "Open terminal to install CA",
|
||||
"9b1b7ed518ee401d": "This will open the tutorial in your system browser. Continue?",
|
||||
@@ -293,7 +296,6 @@
|
||||
"ba2e93e73037c71e": "Restore default",
|
||||
"ba5865fbc734e672": "For example: Primary model",
|
||||
"ba6403d22876d626": "Cooling down",
|
||||
"bac36835ace45f3a": "Commit settings",
|
||||
"baff6c144180b185": "Connectivity tests completed: {successful} succeeded, {failed} failed",
|
||||
"bb2b7736433ae867": "Cursor tracing",
|
||||
"bb7efdcb6af6e805": "Default dark",
|
||||
@@ -331,6 +333,7 @@
|
||||
"d59e47070f7f358e": "Callable",
|
||||
"d60669bb26a22f5d": "Leave blank to use the default",
|
||||
"d6b1f203680f5496": "Leave blank to use adaptive thinking",
|
||||
"d71b0171c44b668a": "Disabling this will remove Cursor's local proxy configuration. If you need to sign in to an official account, you usually do not need to disable it. You can sign in directly because BYOK models and official-account models now work together seamlessly. Do you want to continue disabling and clearing the proxy configuration?",
|
||||
"d766536c18e8e990": "Plugin runtime {version} is installed and ready to use.",
|
||||
"d7e266bdc8064193": "Group name",
|
||||
"d8c47e9776cf1082": "Main menu",
|
||||
@@ -393,13 +396,13 @@
|
||||
"f9615d05d8e18595": "Clear {label} filter",
|
||||
"f9aa11dbb15ce647": "Saturday",
|
||||
"f9b55ca75425161b": "Response content was not recorded. Enable detailed records and try again.",
|
||||
"fa2352729a82e74b": "Direct uses Cursor's original channel; pick a model configured on the Cursor page to generate locally.",
|
||||
"fa5b4b8a751c7d1b": "The local proxy port used by Cursor. Enter 0 to select a random port at startup.",
|
||||
"fad86bf65f72c747": "Download progress",
|
||||
"fb11aa6f29827095": "Checking…",
|
||||
"fbe8778fa8b9bab5": "Initialize the local CA first",
|
||||
"fc22d1ab9ac73c6f": "Checking the plugin runtime",
|
||||
"fc3947ebe6b2177b": "Default {defaultRate} / include creation {reuseRate}",
|
||||
"fc50d0b72bc871db": "Disable takeover",
|
||||
"fcd311fd8ad42462": "Open model list",
|
||||
"fd415f8e0097c832": "Cache reads and writes are included in prompt-side statistics.",
|
||||
"fd77192739703811": "Bulk import",
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
"105a9082c346f958": "测试中…",
|
||||
"124be3f86f197802": "Token 消耗",
|
||||
"12ae77e6202d063e": "自定义 Headers",
|
||||
"12b86e89701b0241": "输入模型名称后按 Enter 添加",
|
||||
"133340e53175128a": "一键测试",
|
||||
"13a9ac7a68c5fd96": "CA 仅保存在本机,用于安全解析 Cursor 的 HTTPS 请求。",
|
||||
"13b61c5f697b6700": "缓存命中率",
|
||||
@@ -64,11 +63,13 @@
|
||||
"24a0a24864454575": "已存在,跳过",
|
||||
"2555d6c7fbb7e070": "可以直接输入模型标识,也可以读取接口返回的模型列表。",
|
||||
"29585d7193539200": "当前版本 {version}",
|
||||
"296da37506328d89": "关闭接管Cursor",
|
||||
"29fbbef32a6eb58b": "不再显示此广告",
|
||||
"2a2773134a829016": "按历史 LLM 调用记录汇总,进行中的调用不计入。",
|
||||
"2caeaec539e78898": "思考预算 Token",
|
||||
"2cbc58108d78b06c": "等待网页端确认授权中…",
|
||||
"2cd0f3be8738a86c": "取消",
|
||||
"2cdf7d3275016cc2": "关闭接管Cursor?",
|
||||
"2d30c2a98ebb5278": "当前:{rate}",
|
||||
"2eb2bf7c6597ab9a": "详细记录",
|
||||
"2f280a8120c0db12": "仅用于界面展示,不会改变发送给模型服务的模型名称。",
|
||||
@@ -77,7 +78,6 @@
|
||||
"2f5f1d6fbfb061ed": "未设置",
|
||||
"2f6416a2c424856b": "最终请求地址",
|
||||
"2f7ba5fd1d12f7f9": "打开使用教程?",
|
||||
"2f7dec3be28d7597": "已选择 {count} 个",
|
||||
"2f9daa828907b93f": "删除",
|
||||
"2fe5a8d0eee9f14c": "已失效",
|
||||
"303c30f301514250": "搜索资源",
|
||||
@@ -91,7 +91,6 @@
|
||||
"382f2e3419a02fef": "仅清理详细记录",
|
||||
"38844b135cf70dfc": "更多",
|
||||
"393e1241552b1870": "请求",
|
||||
"398f8e6c6f0a0b97": "继续选择或输入",
|
||||
"39f52eee100131d7": "缓存输入",
|
||||
"3a0fb74abe2460b6": "分块数",
|
||||
"3a3f595df70ec8ff": "清理存储空间",
|
||||
@@ -134,11 +133,13 @@
|
||||
"51d04bc3d286f018": "近1自然日",
|
||||
"51de3bcec137ab1b": "全部 {count} 个模型连通性测试成功",
|
||||
"5228358a6db59fe7": "如:现在、2026-08-23 18:00",
|
||||
"5319e7374f78fb38": "已接管",
|
||||
"5401344227e49e2f": "TAB 设置",
|
||||
"54644705e9c61009": "端口设置",
|
||||
"54c53e5fe791d1f3": "初始化 CA",
|
||||
"54e6745ff43c9c74": "排序失败",
|
||||
"550eddc3c7fefa99": "推广",
|
||||
"552a5d4baf45d878": "Commit 提交代码模型设置",
|
||||
"56432ba297009bdc": "请先初始化 CA",
|
||||
"56627c94a9decee6": "最大输出 Token",
|
||||
"576d81bb0631b165": "导入",
|
||||
@@ -225,11 +226,13 @@
|
||||
"91af6e57e7453fbe": "添加账号",
|
||||
"92156a483d4ba248": "仅删除请求、响应和追踪附件等详细内容,保留调用汇总、统计指标和配置。",
|
||||
"92e26b27d5ea8f0e": "检查更新失败:{error}",
|
||||
"9305c0e13642cab4": "未接管",
|
||||
"940a168911ade998": "每页条数",
|
||||
"945fb1c67eca8493": "正在安装插件运行时",
|
||||
"946b3ffc02f026c0": "确定删除这个模型吗?",
|
||||
"954ec984cd4f49d1": "正在同步…",
|
||||
"966498853d801a52": "TAB 选择",
|
||||
"96f7642963ca0dbf": "开启接管Cursor",
|
||||
"9850ed41a5bfbb0c": "已选 {count} 项",
|
||||
"997ec8201c2adeda": "打开终端安装 CA",
|
||||
"9b1b7ed518ee401d": "将在系统浏览器中打开使用教程,是否继续?",
|
||||
@@ -293,7 +296,6 @@
|
||||
"ba2e93e73037c71e": "恢复默认",
|
||||
"ba5865fbc734e672": "例如:主力模型",
|
||||
"ba6403d22876d626": "冷却中",
|
||||
"bac36835ace45f3a": "Commit 设置",
|
||||
"baff6c144180b185": "连通性测试完成:成功 {successful},失败 {failed}",
|
||||
"bb2b7736433ae867": "Cursor 追踪",
|
||||
"bb7efdcb6af6e805": "默认暗色",
|
||||
@@ -331,6 +333,7 @@
|
||||
"d59e47070f7f358e": "可调用",
|
||||
"d60669bb26a22f5d": "留空使用默认值",
|
||||
"d6b1f203680f5496": "留空使用 adaptive thinking",
|
||||
"d71b0171c44b668a": "关闭后将移除 Cursor 本地代理配置。如果你需要登陆官方账号,通常不需要关闭操作,推荐直接登陆你的账号即可(byok模型与官方账号的模型已支持无缝衔接),是否继续关闭并清理代理?",
|
||||
"d766536c18e8e990": "插件运行时 {version} 已安装,可以开始使用插件。",
|
||||
"d7e266bdc8064193": "分组名称",
|
||||
"d8c47e9776cf1082": "主菜单",
|
||||
@@ -393,13 +396,13 @@
|
||||
"f9615d05d8e18595": "清除{label}筛选",
|
||||
"f9aa11dbb15ce647": "周六",
|
||||
"f9b55ca75425161b": "未记录响应内容,请开启详细记录后重试。",
|
||||
"fa2352729a82e74b": "直连走 Cursor 原有通道;选择 Cursor 页已配置的模型后由本地生成。",
|
||||
"fa5b4b8a751c7d1b": "Cursor 使用的本地代理端口;填写 0 时启动时随机选择。",
|
||||
"fad86bf65f72c747": "下载进度",
|
||||
"fb11aa6f29827095": "检查中…",
|
||||
"fbe8778fa8b9bab5": "需要先初始化本地 CA",
|
||||
"fc22d1ab9ac73c6f": "正在检查插件运行时",
|
||||
"fc3947ebe6b2177b": "默认 {defaultRate} / 计入创建 {reuseRate}",
|
||||
"fc50d0b72bc871db": "关闭接管",
|
||||
"fcd311fd8ad42462": "打开模型列表",
|
||||
"fd415f8e0097c832": "缓存读写已计入提示词侧统计。",
|
||||
"fd77192739703811": "批量导入",
|
||||
|
||||
@@ -103,6 +103,7 @@ export interface CursorHarnessStatus {
|
||||
configured_models: number;
|
||||
enabled_models: number;
|
||||
integration: IntegrationState;
|
||||
settings_applied: boolean;
|
||||
proxy_url: string | null;
|
||||
ca_install_command: string | null;
|
||||
}
|
||||
@@ -153,6 +154,7 @@ export interface DesktopSettings {
|
||||
export interface CommitSettings {
|
||||
model_id: string;
|
||||
prompt: string;
|
||||
prompt_locale: Locale;
|
||||
}
|
||||
|
||||
export interface CommitSettingsView extends CommitSettings {
|
||||
@@ -297,22 +299,11 @@ export interface PluginImportResult {
|
||||
modelSyncError: string | null;
|
||||
}
|
||||
|
||||
export type ConfiguredModel =
|
||||
| { kind: "builtin"; id: string; name: string; builtin: Model }
|
||||
| { kind: "plugin"; id: string; name: string; plugin: PluginModelDescriptor };
|
||||
|
||||
export function configuredPluginModels(plugins: PluginDescriptor[]): PluginModelDescriptor[] {
|
||||
return plugins.flatMap((plugin) =>
|
||||
plugin.providers.flatMap((provider) => provider.configured ? provider.models : []));
|
||||
}
|
||||
|
||||
export function configuredModels(models: Model[], plugins: PluginDescriptor[]): ConfiguredModel[] {
|
||||
return [
|
||||
...models.map((model): ConfiguredModel => ({ kind: "builtin", id: model.model_hash, name: model.display_name, builtin: model })),
|
||||
...configuredPluginModels(plugins).map((model): ConfiguredModel => ({ kind: "plugin", id: model.id, name: model.displayName, plugin: model })),
|
||||
];
|
||||
}
|
||||
|
||||
export interface OverviewMetrics {
|
||||
llm_calls: number;
|
||||
successful_calls: number;
|
||||
@@ -517,6 +508,6 @@ export const api = {
|
||||
setTabSettings: (settings: TabSettings) => request<TabSettings>("/settings/tab", { method: "PUT", body: JSON.stringify(settings) }),
|
||||
desktopSettings: () => request<DesktopSettings>("/settings/desktop"),
|
||||
setDesktopSettings: (settings: DesktopSettings) => request<DesktopSettings>("/settings/desktop", { method: "PUT", body: JSON.stringify(settings) }),
|
||||
commitSettings: () => request<CommitSettingsView>("/settings/commit"),
|
||||
commitSettings: (locale: Locale) => request<CommitSettingsView>("/settings/commit", { headers: { "accept-language": locale } }),
|
||||
setCommitSettings: (settings: CommitSettings) => request<CommitSettingsView>("/settings/commit", { method: "PUT", body: JSON.stringify(settings) }),
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
&:focus-within,
|
||||
&[data-open] { border-color: var(--vscode-focusBorder); }
|
||||
&[data-disabled] { opacity: 0.55; }
|
||||
}
|
||||
|
||||
.trigger {
|
||||
@@ -64,35 +65,6 @@
|
||||
border: 1px solid var(--vscode-dropdown-border);
|
||||
border-radius: var(--oa-overlay-radius);
|
||||
box-shadow: var(--oa-dropdown-shadow);
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 5px 8px;
|
||||
color: var(--vscode-dropdown-foreground);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
font-size: type.$font-size-xs;
|
||||
|
||||
&:hover {
|
||||
color: var(--vscode-list-hoverForeground, var(--vscode-dropdown-foreground));
|
||||
background: var(--vscode-list-hoverBackground);
|
||||
}
|
||||
|
||||
&[aria-selected="true"] {
|
||||
color: var(--vscode-list-activeSelectionForeground);
|
||||
background: var(--vscode-list-activeSelectionBackground);
|
||||
}
|
||||
|
||||
&[aria-selected="true"]:hover {
|
||||
background: var(--vscode-list-inactiveSelectionBackground, var(--vscode-list-activeSelectionBackground));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.listFrame,
|
||||
@@ -106,6 +78,101 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.group,
|
||||
.groupLabel {
|
||||
height: 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: type.$font-size-xs;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.group {
|
||||
gap: 8px;
|
||||
padding: 7px 8px 3px;
|
||||
cursor: pointer;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&:has(input:focus-visible) .checkbox {
|
||||
outline: 1px solid var(--vscode-focusBorder);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.groupLabel {
|
||||
padding: 7px 8px 3px;
|
||||
}
|
||||
|
||||
.optionRow {
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 5px 8px 5px 32px;
|
||||
box-sizing: border-box;
|
||||
color: var(--vscode-dropdown-foreground);
|
||||
background: transparent;
|
||||
border-radius: 4px;
|
||||
font-size: type.$font-size-xs;
|
||||
cursor: pointer;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: var(--vscode-list-hoverForeground, var(--vscode-dropdown-foreground));
|
||||
background: var(--vscode-list-hoverBackground);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 1px solid var(--vscode-focusBorder);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: 0 0 16px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--vscode-checkbox-foreground, var(--vscode-button-foreground));
|
||||
background: var(--vscode-checkbox-background, var(--vscode-input-background));
|
||||
border: 1px solid var(--vscode-checkbox-border, var(--vscode-input-border));
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.optionRow:has(input:checked) .checkbox,
|
||||
.group:has(input:checked) .checkbox,
|
||||
.checkbox[data-indeterminate] {
|
||||
color: var(--vscode-button-foreground);
|
||||
background: var(--vscode-button-background);
|
||||
border-color: var(--vscode-button-background);
|
||||
}
|
||||
|
||||
.checkbox[data-indeterminate]::after {
|
||||
width: 8px;
|
||||
height: 2px;
|
||||
content: "";
|
||||
background: currentColor;
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
.option {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
@@ -119,7 +186,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.check { width: 1.1em; flex: 0 0 1.1em; }
|
||||
.empty { padding: 8px; color: var(--vscode-descriptionForeground); font-size: type.$font-size-xs; }
|
||||
|
||||
.footer {
|
||||
@@ -133,7 +199,16 @@
|
||||
button {
|
||||
width: auto;
|
||||
min-height: 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 5px 8px;
|
||||
color: var(--vscode-textLink-foreground);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
font-size: type.$font-size-xs;
|
||||
|
||||
&:hover { background: var(--vscode-list-hoverBackground); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import { autoUpdate, computePosition, flip, offset, shift, size } from "@floating-ui/dom";
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Icon, type IconProps } from "./Icon";
|
||||
import { checkIcon, chevronDownIcon, windowCloseIcon } from "./icons";
|
||||
import { VirtualList } from "../virtual/VirtualList";
|
||||
import styles from "./ModelSelect.module.scss";
|
||||
|
||||
export type ModelSelectOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
group: string;
|
||||
icon?: IconProps["icon"];
|
||||
iconSrc?: string;
|
||||
};
|
||||
|
||||
type ModelSelectProps = {
|
||||
label: string;
|
||||
options: ModelSelectOption[];
|
||||
disabled?: boolean;
|
||||
} & (
|
||||
| { mode: "single"; value: string; onChange: (value: string) => void }
|
||||
| { mode: "multiple"; value: string[]; onChange: (value: string[]) => void }
|
||||
);
|
||||
|
||||
type MenuItem =
|
||||
| { kind: "group"; key: string; label: string; options: ModelSelectOption[] }
|
||||
| { kind: "option"; key: string; option: ModelSelectOption };
|
||||
|
||||
function groupedItems(options: ModelSelectOption[]): MenuItem[] {
|
||||
const groups = new Map<string, ModelSelectOption[]>();
|
||||
for (const option of options) {
|
||||
const group = groups.get(option.group);
|
||||
if (group) group.push(option);
|
||||
else groups.set(option.group, [option]);
|
||||
}
|
||||
return [...groups].flatMap(([group, groupOptions]) => [
|
||||
{ kind: "group" as const, key: `group:${group}`, label: group, options: groupOptions },
|
||||
...groupOptions.map((option) => ({ kind: "option" as const, key: `option:${option.value}`, option })),
|
||||
]);
|
||||
}
|
||||
|
||||
function GroupCheckbox({ label, options, selected, onChange }: {
|
||||
label: string;
|
||||
options: ModelSelectOption[];
|
||||
selected: Set<string>;
|
||||
onChange: (checked: boolean) => void;
|
||||
}) {
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const selectedCount = options.filter((option) => selected.has(option.value)).length;
|
||||
const checked = selectedCount === options.length;
|
||||
const indeterminate = selectedCount > 0 && !checked;
|
||||
|
||||
useEffect(() => {
|
||||
if (input.current) input.current.indeterminate = indeterminate;
|
||||
}, [indeterminate]);
|
||||
|
||||
return <label className={styles.group}>
|
||||
<input
|
||||
ref={input}
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
aria-checked={indeterminate ? "mixed" : checked}
|
||||
onChange={(event) => onChange(event.target.checked)}
|
||||
/>
|
||||
<span className={styles.checkbox} data-indeterminate={indeterminate || undefined} aria-hidden="true">
|
||||
{checked && <Icon icon={checkIcon} size="0.875em" />}
|
||||
</span>
|
||||
<span>{label}</span>
|
||||
</label>;
|
||||
}
|
||||
|
||||
export function ModelSelect(props: ModelSelectProps) {
|
||||
const { label, options, disabled, mode } = props;
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const menu = useRef<HTMLDivElement>(null);
|
||||
const firstOption = useRef<HTMLLabelElement>(null);
|
||||
const menuId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0, width: 220, maxHeight: 280 });
|
||||
const items = useMemo(() => groupedItems(options), [options]);
|
||||
const selected = useMemo(
|
||||
() => new Set(mode === "multiple" ? props.value : [props.value]),
|
||||
[mode, props.value],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !root.current || !menu.current) return;
|
||||
return autoUpdate(root.current, menu.current, () => void computePosition(root.current!, menu.current!, {
|
||||
placement: "bottom-start",
|
||||
middleware: [offset(5), flip({ padding: 10 }), shift({ padding: 10 }), size({
|
||||
padding: 10,
|
||||
apply: ({ rects, availableHeight }) => setPosition((current) => ({
|
||||
...current,
|
||||
width: rects.reference.width,
|
||||
maxHeight: Math.max(120, availableHeight),
|
||||
})),
|
||||
})],
|
||||
}).then(({ x, y }) => setPosition((current) => ({ ...current, left: x, top: y }))));
|
||||
}, [open]);
|
||||
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
trigger.current?.focus();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
firstOption.current?.focus();
|
||||
const closeOutside = (event: PointerEvent) => {
|
||||
const target = event.target as Node;
|
||||
if (!root.current?.contains(target) && !menu.current?.contains(target)) close();
|
||||
};
|
||||
document.addEventListener("pointerdown", closeOutside);
|
||||
return () => document.removeEventListener("pointerdown", closeOutside);
|
||||
}, [open]);
|
||||
|
||||
const summary = mode === "multiple"
|
||||
? props.value.length === 0 ? t("全部") : t("已选 {count} 项", { count: props.value.length })
|
||||
: options.find((option) => option.value === props.value)?.label ?? props.value;
|
||||
|
||||
const choose = (option: ModelSelectOption) => {
|
||||
if (mode === "single") {
|
||||
props.onChange(option.value);
|
||||
close();
|
||||
return;
|
||||
}
|
||||
props.onChange(selected.has(option.value)
|
||||
? props.value.filter((item) => item !== option.value)
|
||||
: [...props.value, option.value]);
|
||||
};
|
||||
|
||||
const toggleGroup = (groupOptions: ModelSelectOption[], checked: boolean) => {
|
||||
if (mode !== "multiple") return;
|
||||
const groupValues = new Set(groupOptions.map((option) => option.value));
|
||||
props.onChange(checked
|
||||
? [...props.value, ...groupOptions.filter((option) => !selected.has(option.value)).map((option) => option.value)]
|
||||
: props.value.filter((value) => !groupValues.has(value)));
|
||||
};
|
||||
|
||||
const openMenu = () => {
|
||||
if (disabled) return;
|
||||
const width = root.current?.getBoundingClientRect().width;
|
||||
if (width) setPosition((current) => ({ ...current, width }));
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
return <>
|
||||
<div ref={root} className={styles.target} data-open={open || undefined} data-disabled={disabled || undefined}>
|
||||
<button
|
||||
ref={trigger}
|
||||
type="button"
|
||||
className={styles.trigger}
|
||||
disabled={disabled}
|
||||
aria-label={t("筛选项:{label},{summary}", { label, summary })}
|
||||
aria-haspopup="listbox"
|
||||
aria-controls={open ? menuId : undefined}
|
||||
aria-expanded={open}
|
||||
onClick={() => { if (open) close(); else openMenu(); }}
|
||||
onKeyDown={(event) => { if (event.key === "ArrowDown") { event.preventDefault(); openMenu(); } }}
|
||||
>
|
||||
<span>{label}</span><span className={styles.summary} aria-hidden="true">{summary}</span><Icon icon={chevronDownIcon} size="1.1em" />
|
||||
</button>
|
||||
{mode === "multiple" && props.value.length > 0 && <button
|
||||
type="button"
|
||||
className={styles.clear}
|
||||
aria-label={t("清除{label}筛选", { label })}
|
||||
onClick={() => props.onChange([])}
|
||||
><Icon icon={windowCloseIcon} size="1.1em" /></button>}
|
||||
</div>
|
||||
{open && createPortal(<div
|
||||
id={menuId}
|
||||
ref={menu}
|
||||
className={styles.menu}
|
||||
aria-label={label}
|
||||
style={position}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); close(); } }}
|
||||
>
|
||||
<div
|
||||
className={styles.listFrame}
|
||||
role="listbox"
|
||||
aria-label={label}
|
||||
aria-multiselectable={mode === "multiple" ? "true" : undefined}
|
||||
style={{ height: Math.min(items.length * 32, Math.max(32, position.maxHeight - (mode === "multiple" ? 45 : 0))) }}
|
||||
><VirtualList
|
||||
items={items}
|
||||
itemKey="key"
|
||||
className={styles.list}
|
||||
style={{ height: "100%" }}
|
||||
estimatedItemHeight={32}
|
||||
overscan={4}
|
||||
empty={<div className={styles.empty}>{t("暂无选项")}</div>}
|
||||
>{(item, index) => item.kind === "group"
|
||||
? mode === "multiple"
|
||||
? <GroupCheckbox
|
||||
label={item.label}
|
||||
options={item.options}
|
||||
selected={selected}
|
||||
onChange={(checked) => toggleGroup(item.options, checked)}
|
||||
/>
|
||||
: <div className={styles.groupLabel}>{item.label}</div>
|
||||
: <label
|
||||
ref={index === 1 ? firstOption : undefined}
|
||||
className={styles.optionRow}
|
||||
role="option"
|
||||
aria-selected={selected.has(item.option.value)}
|
||||
tabIndex={index === 1 ? 0 : -1}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === " " || event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
choose(item.option);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.has(item.option.value)}
|
||||
tabIndex={-1}
|
||||
onChange={() => choose(item.option)}
|
||||
/>
|
||||
<span className={styles.checkbox} aria-hidden="true">
|
||||
{selected.has(item.option.value) && <Icon icon={checkIcon} size="0.875em" />}
|
||||
</span>
|
||||
<span className={styles.option}>
|
||||
{(item.option.icon || item.option.iconSrc) && <Icon icon={item.option.icon} src={item.option.iconSrc} />}
|
||||
<span>{item.option.label}</span>
|
||||
</span>
|
||||
</label>}</VirtualList></div>
|
||||
{mode === "multiple" && options.length > 0 && <div className={styles.footer}>
|
||||
<button type="button" onClick={() => props.onChange(options.map((option) => option.value))}>{t("全选")}</button>
|
||||
<button type="button" onClick={() => props.onChange([])}>{t("全不选")}</button>
|
||||
</div>}
|
||||
</div>, document.body)}
|
||||
</>;
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import { autoUpdate, computePosition, flip, offset, shift, size } from "@floating-ui/dom";
|
||||
import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Icon, type IconProps } from "./Icon";
|
||||
import { checkIcon, chevronDownIcon, windowCloseIcon } from "./icons";
|
||||
import { VirtualList } from "../virtual/VirtualList";
|
||||
import styles from "./MultiSelect.module.scss";
|
||||
|
||||
export type MultiSelectOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
icon?: IconProps["icon"];
|
||||
};
|
||||
|
||||
export function MultiSelect({ label, value, options, onChange }: {
|
||||
label: string;
|
||||
value: string[];
|
||||
options: MultiSelectOption[];
|
||||
onChange: (value: string[]) => void;
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const menu = useRef<HTMLDivElement>(null);
|
||||
const firstOption = useRef<HTMLButtonElement>(null);
|
||||
const menuId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0, width: 220, maxHeight: 280 });
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !root.current || !menu.current) return;
|
||||
return autoUpdate(root.current, menu.current, () => void computePosition(root.current!, menu.current!, {
|
||||
placement: "bottom-start",
|
||||
middleware: [offset(5), flip({ padding: 10 }), shift({ padding: 10 }), size({
|
||||
padding: 10,
|
||||
apply: ({ rects, availableHeight }) => setPosition((current) => ({
|
||||
...current,
|
||||
width: rects.reference.width,
|
||||
maxHeight: Math.max(120, availableHeight),
|
||||
})),
|
||||
})],
|
||||
}).then(({ x, y }) => setPosition((current) => ({ ...current, left: x, top: y }))));
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
firstOption.current?.focus();
|
||||
const closeOutside = (event: PointerEvent) => {
|
||||
const target = event.target as Node;
|
||||
if (!root.current?.contains(target) && !menu.current?.contains(target)) setOpen(false);
|
||||
};
|
||||
document.addEventListener("pointerdown", closeOutside);
|
||||
return () => document.removeEventListener("pointerdown", closeOutside);
|
||||
}, [open]);
|
||||
|
||||
const selected = new Set(value);
|
||||
const summary = value.length === 0 ? t("全部") : t("已选 {count} 项", { count: value.length });
|
||||
const toggle = (option: string) => onChange(selected.has(option)
|
||||
? value.filter((item) => item !== option)
|
||||
: [...value, option]);
|
||||
|
||||
const close = () => { setOpen(false); trigger.current?.focus(); };
|
||||
const openMenu = () => {
|
||||
const width = root.current?.getBoundingClientRect().width;
|
||||
if (width) setPosition((current) => ({ ...current, width }));
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
return <>
|
||||
<div ref={root} className={styles.target} data-open={open || undefined}>
|
||||
<button
|
||||
ref={trigger}
|
||||
type="button"
|
||||
className={styles.trigger}
|
||||
aria-label={t("筛选项:{label},{summary}", { label, summary })}
|
||||
aria-haspopup="listbox"
|
||||
aria-controls={open ? menuId : undefined}
|
||||
aria-expanded={open}
|
||||
onClick={() => { if (open) close(); else openMenu(); }}
|
||||
onKeyDown={(event) => { if (event.key === "ArrowDown") { event.preventDefault(); openMenu(); } }}
|
||||
>
|
||||
<span>{label}</span><span className={styles.summary} aria-hidden="true">{summary}</span><Icon icon={chevronDownIcon} size="1.1em" />
|
||||
</button>
|
||||
{value.length > 0 && <button type="button" className={styles.clear} aria-label={t("清除{label}筛选", { label })} onClick={() => onChange([])}>
|
||||
<Icon icon={windowCloseIcon} size="1.1em" />
|
||||
</button>}
|
||||
</div>
|
||||
{open && createPortal(<div
|
||||
id={menuId}
|
||||
ref={menu}
|
||||
className={styles.menu}
|
||||
aria-label={label}
|
||||
style={position}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); close(); } }}
|
||||
>
|
||||
<div
|
||||
className={styles.listFrame}
|
||||
role="listbox"
|
||||
aria-label={label}
|
||||
aria-multiselectable="true"
|
||||
style={{ height: Math.min(options.length * 32, Math.max(32, position.maxHeight - 45)) }}
|
||||
><VirtualList
|
||||
items={options}
|
||||
itemKey="value"
|
||||
className={styles.list}
|
||||
style={{ height: "100%" }}
|
||||
estimatedItemHeight={32}
|
||||
overscan={4}
|
||||
empty={<div className={styles.empty}>{t("暂无选项")}</div>}
|
||||
>{(option, index) => <button
|
||||
ref={index === 0 ? firstOption : undefined}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-label={option.label}
|
||||
aria-selected={selected.has(option.value)}
|
||||
onClick={() => toggle(option.value)}
|
||||
>
|
||||
<span className={styles.option}>{option.icon && <Icon icon={option.icon} />}<span>{option.label}</span></span>
|
||||
<span className={styles.check} aria-hidden="true">{selected.has(option.value) && <Icon icon={checkIcon} size="1.1em" />}</span>
|
||||
</button>}</VirtualList></div>
|
||||
{options.length > 0 && <div className={styles.footer}>
|
||||
<button type="button" onClick={() => onChange(options.map((option) => option.value))}>{t("全选")}</button>
|
||||
<button type="button" onClick={() => onChange([])}>{t("全不选")}</button>
|
||||
</div>}
|
||||
</div>, document.body)}
|
||||
</>;
|
||||
}
|
||||
@@ -62,55 +62,6 @@
|
||||
border-color: var(--vscode-focusBorder);
|
||||
}
|
||||
}
|
||||
|
||||
.multiCombo {
|
||||
min-width: 0;
|
||||
min-height: 34px;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
overflow: hidden;
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, transparent);
|
||||
border-radius: 6px;
|
||||
|
||||
&:focus-within,
|
||||
&[data-open] {
|
||||
border-color: var(--vscode-focusBorder);
|
||||
}
|
||||
}
|
||||
|
||||
.multiValues {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 6px;
|
||||
|
||||
> input {
|
||||
min-width: 120px;
|
||||
min-height: 24px;
|
||||
flex: 1;
|
||||
padding: 0 3px;
|
||||
color: var(--vscode-input-foreground);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
font-size: type.$font-size-xs;
|
||||
}
|
||||
}
|
||||
|
||||
.multiCount {
|
||||
height: 24px;
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 3px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: type.$font-size-xs;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.combo input {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
@@ -172,23 +123,3 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.menu .multiOption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
|
||||
> span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 8px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: type.$font-size-xs;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createPortal } from "react-dom";
|
||||
import { VirtualList } from "../virtual/VirtualList";
|
||||
import type { VirtualListApi } from "../virtual/virtualTypes";
|
||||
import { Icon, type IconProps } from "./Icon";
|
||||
import { checkIcon, chevronDownIcon } from "./icons";
|
||||
import { chevronDownIcon } from "./icons";
|
||||
import styles from "./Select.module.scss";
|
||||
|
||||
export type SelectOption = { value: string; label: string; icon?: IconProps["icon"]; iconSrc?: string };
|
||||
@@ -117,86 +117,3 @@ export function Combobox({ value, options = [], placeholder, disabled, append, o
|
||||
</div>{append}</div>;
|
||||
}
|
||||
|
||||
export function MultiCombobox({ value, options = [], placeholder, disabled, append, onChange }: {
|
||||
value: string[];
|
||||
options?: string[];
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
append?: ReactNode;
|
||||
onChange: (value: string[]) => void;
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const menu = useRef<HTMLDivElement>(null);
|
||||
const listApi = useRef<VirtualListApi | null>(null);
|
||||
const menuId = useId();
|
||||
const [query, setQuery] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [active, setActive] = useState(0);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0, width: 0, maxHeight: 280 });
|
||||
const selected = useMemo(() => new Set(value), [value]);
|
||||
const filtered = useMemo(() => {
|
||||
const normalized = query.trim().toLocaleLowerCase();
|
||||
return options.filter((option) => !normalized || option.toLocaleLowerCase().includes(normalized));
|
||||
}, [options, query]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !root.current || !menu.current) return;
|
||||
return autoUpdate(root.current, menu.current, () => void computePosition(root.current!, menu.current!, {
|
||||
placement: "bottom-start",
|
||||
middleware: [offset(6), flip({ padding: 12 }), shift({ padding: 12 }), size({ padding: 12, apply: ({ rects, availableHeight }) => setPosition((current) => ({ ...current, width: rects.reference.width, maxHeight: Math.max(160, availableHeight) })) })],
|
||||
}).then(({ x, y }) => setPosition((current) => ({ ...current, left: x, top: y }))));
|
||||
}, [filtered.length, open]);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const outside = (event: PointerEvent) => {
|
||||
if (!root.current?.contains(event.target as Node) && !menu.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener("pointerdown", outside);
|
||||
return () => document.removeEventListener("pointerdown", outside);
|
||||
}, [open]);
|
||||
useEffect(() => {
|
||||
if (open && active >= 0) listApi.current?.scrollToIndex(active);
|
||||
}, [active, open]);
|
||||
|
||||
const add = (modelId: string) => {
|
||||
const normalized = modelId.trim();
|
||||
if (normalized && !selected.has(normalized)) onChange([...value, normalized]);
|
||||
setQuery("");
|
||||
};
|
||||
const toggle = (modelId: string) => {
|
||||
onChange(selected.has(modelId) ? value.filter((item) => item !== modelId) : [...value, modelId]);
|
||||
setQuery("");
|
||||
input.current?.focus();
|
||||
};
|
||||
const move = (step: number) => {
|
||||
if (!filtered.length) return;
|
||||
setOpen(true);
|
||||
setActive((index) => (index + step + filtered.length) % filtered.length);
|
||||
};
|
||||
|
||||
return <div className={styles.comboRow}><div ref={root} className={styles.multiCombo} data-open={open || undefined}>
|
||||
<div className={styles.multiValues}>
|
||||
{value.length > 0 && <span className={styles.multiCount}>{t("已选择 {count} 个", { count: value.length })}</span>}
|
||||
<input ref={input} value={query} placeholder={value.length ? t("继续选择或输入") : placeholder} disabled={disabled} role="combobox" aria-haspopup="listbox" aria-controls={open ? menuId : undefined} aria-expanded={open} aria-autocomplete="list" onFocus={() => { if (options.length) setOpen(true); }} onBlur={() => add(query)} onChange={(event) => { setQuery(event.target.value); setActive(0); if (options.length) setOpen(true); }} onKeyDown={(event) => {
|
||||
if (event.key === "ArrowDown") { event.preventDefault(); move(1); }
|
||||
if (event.key === "ArrowUp") { event.preventDefault(); move(-1); }
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
const normalized = query.trim();
|
||||
const exact = filtered.find((option) => option.toLocaleLowerCase() === normalized.toLocaleLowerCase());
|
||||
if (normalized && !exact) add(normalized);
|
||||
else if (open && filtered[active]) toggle(filtered[active]);
|
||||
}
|
||||
if (event.key === "Backspace" && !query && value.length) onChange(value.slice(0, -1));
|
||||
if (event.key === "Escape") { setOpen(false); input.current?.focus(); }
|
||||
}} />
|
||||
</div>
|
||||
<button type="button" className={styles.comboToggle} disabled={disabled || !options.length} aria-label={t("打开模型列表")} aria-expanded={open} tabIndex={-1} onMouseDown={(event) => event.preventDefault()} onClick={() => { setOpen(!open); input.current?.focus(); }}><Icon icon={chevronDownIcon} size="1.1em" className={[styles.dropdownIcon, open && styles.dropdownIconOpen].filter(Boolean).join(" ")} /></button>
|
||||
{open && createPortal(<div id={menuId} ref={menu} className={styles.menu} role="listbox" aria-multiselectable="true" style={{ left: position.left, top: position.top, width: position.width }} onPointerDown={(event) => event.stopPropagation()} onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); setOpen(false); input.current?.focus(); } }}>
|
||||
{filtered.length ? <VirtualList items={filtered} itemKey={(option) => option} estimatedItemHeight={30} onReady={(api) => { listApi.current = api; api.scrollToIndex(active); }} style={{ height: Math.min(filtered.length * 30, Math.max(30, position.maxHeight - 8)) }}>
|
||||
{(option, index) => <button type="button" className={styles.multiOption} role="option" aria-selected={selected.has(option)} data-active={index === active || undefined} onMouseEnter={() => setActive(index)} onMouseDown={(event) => event.preventDefault()} onClick={() => toggle(option)}><span>{option}</span>{selected.has(option) && <Icon icon={checkIcon} size="1.1em" />}</button>}
|
||||
</VirtualList> : <div className={styles.empty}>{t("输入模型名称后按 Enter 添加")}</div>}
|
||||
</div>, document.body)}
|
||||
</div>{append}</div>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
import type { ButtonHTMLAttributes } from "react";
|
||||
import styles from "./Switch.module.scss";
|
||||
|
||||
export function Switch({ checked, disabled, label, onChange }: { checked: boolean; disabled?: boolean; label: string; onChange: (checked: boolean) => void }) {
|
||||
type SwitchProps = {
|
||||
checked: boolean;
|
||||
label: string;
|
||||
onChange: (checked: boolean) => void;
|
||||
} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, "aria-label" | "children" | "onChange" | "role">;
|
||||
|
||||
export function Switch({ checked, disabled, label, onChange, onClick, ...props }: SwitchProps) {
|
||||
return <button
|
||||
{...props}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
className={styles.root}
|
||||
className={[styles.root, props.className].filter(Boolean).join(" ")}
|
||||
data-checked={checked || undefined}
|
||||
onClick={() => onChange(!checked)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
if (!event.defaultPrevented) onChange(!checked);
|
||||
}}
|
||||
><span /></button>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Model } from "../api";
|
||||
|
||||
export function modelProviderName(model: Pick<Model, "group_name" | "base_url">): string {
|
||||
const configuredName = model.group_name?.trim();
|
||||
if (configuredName) return configuredName;
|
||||
|
||||
const value = model.base_url.trim();
|
||||
try {
|
||||
return new URL(value).hostname.toLowerCase() || value;
|
||||
} catch {
|
||||
try {
|
||||
return new URL(`https://${value}`).hostname.toLowerCase() || value;
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,24 @@
|
||||
}
|
||||
}
|
||||
|
||||
.menuStatusTag {
|
||||
flex: 0 0 auto;
|
||||
margin-left: auto;
|
||||
padding: 1px 5px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
background: color-mix(in srgb, var(--vscode-descriptionForeground) 10%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--vscode-descriptionForeground) 28%, transparent);
|
||||
border-radius: 999px;
|
||||
font-size: type.$font-size-2xs;
|
||||
line-height: 1.4;
|
||||
|
||||
&[data-taken] {
|
||||
color: var(--vscode-testing-iconPassed, #73c991);
|
||||
background: color-mix(in srgb, var(--vscode-testing-iconPassed, #73c991) 10%, transparent);
|
||||
border-color: color-mix(in srgb, var(--vscode-testing-iconPassed, #73c991) 28%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.menuIndicatorDot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
|
||||
@@ -43,7 +43,7 @@ function loadStoredAdIds(key: string): Set<string> {
|
||||
}
|
||||
|
||||
export function AppLayout() {
|
||||
const { busy } = useAppStore();
|
||||
const { busy, cursorHarness } = useAppStore();
|
||||
const { availableVersion } = useUpdateStore();
|
||||
const { locale } = useI18n();
|
||||
const message = useMessage();
|
||||
@@ -215,6 +215,12 @@ export function AppLayout() {
|
||||
? <Icon src={item.icon} size="1.3em" />
|
||||
: <Icon icon={item.icon} size="1.3em" />}
|
||||
<span>{item.label}</span>
|
||||
{item.path === "/harness/cursor" && cursorHarness && <span
|
||||
className={styles.menuStatusTag}
|
||||
data-taken={cursorHarness.settings_applied || undefined}
|
||||
>
|
||||
{cursorHarness.settings_applied ? t("已接管") : t("未接管")}
|
||||
</span>}
|
||||
{item.path === "/settings" && availableVersion && <span className={styles.menuIndicatorDot} aria-hidden="true" />}
|
||||
</NavLink>
|
||||
</div>}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# deps
|
||||
/node_modules
|
||||
|
||||
# generated desktop product demo
|
||||
/public/product-demo
|
||||
|
||||
# generated content
|
||||
.source
|
||||
|
||||
# test & build
|
||||
/coverage
|
||||
/.next/
|
||||
/out/
|
||||
/build
|
||||
*.tsbuildinfo
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
/.pnp
|
||||
.pnp.js
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# others
|
||||
.env*.local
|
||||
.vercel
|
||||
next-env.d.ts
|
||||
|
||||
# cloudflare / opennext
|
||||
/.open-next/
|
||||
/.wrangler/
|
||||
cloudflare-env.d.ts
|
||||
@@ -1,9 +0,0 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -1 +0,0 @@
|
||||
@AGENTS.md
|
||||
@@ -1,48 +0,0 @@
|
||||
# cursor-byok 文档站
|
||||
|
||||
基于 [Fumadocs](https://fumadocs.dev) 和 Next.js 的独立内容应用。
|
||||
|
||||
## 目录
|
||||
|
||||
```text
|
||||
apps/docs/
|
||||
├── app/
|
||||
│ ├── (home)/ # Hero 首页与开发者博客
|
||||
│ └── docs/ # 用户文档布局和页面
|
||||
├── components/ # MDX 组件
|
||||
├── content/
|
||||
│ ├── docs/ # 用户文档
|
||||
│ └── blog/ # 开发者博客
|
||||
└── lib/ # 内容源、站点信息与布局配置
|
||||
```
|
||||
|
||||
## 本地开发
|
||||
|
||||
先安装依赖:
|
||||
|
||||
```bash
|
||||
npm --prefix apps/docs install
|
||||
```
|
||||
|
||||
从仓库根目录启动:
|
||||
|
||||
```bash
|
||||
make dev-docs
|
||||
```
|
||||
|
||||
浏览器打开 <http://localhost:3000>。
|
||||
|
||||
## 修改内容
|
||||
|
||||
- 在 `content/docs` 中维护面向使用者的 `.mdx` 文档。
|
||||
- 在 `content/docs/meta.json` 中维护文档侧边栏标题与页面顺序。
|
||||
- 在 `content/blog` 中维护开发者文章,文件名以 `YYYY-MM-DD-` 开头用于排序和展示日期。
|
||||
- 在 `lib/shared.ts` 中维护站点名称、仓库和发布地址。
|
||||
|
||||
## 检查与构建
|
||||
|
||||
```bash
|
||||
npm --prefix apps/docs run check
|
||||
```
|
||||
|
||||
生产构建输出由 Next.js 管理。部署环境可通过 `NEXT_PUBLIC_SITE_URL` 设置站点公开地址;未设置时使用 `https://docs.leokun.cn`。
|
||||
@@ -1,79 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import type { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
import { InlineTOC } from 'fumadocs-ui/components/inline-toc';
|
||||
import { createRelativeLink } from 'fumadocs-ui/mdx';
|
||||
import { getMDXComponents } from '@/components/mdx';
|
||||
import { blogSource, formatBlogDate } from '@/lib/blog';
|
||||
import { i18n, isLanguage, type Language } from '@/lib/i18n';
|
||||
|
||||
const copy: Record<Language, { back: string; team: string }> = {
|
||||
zh: { back: '返回开发者博客', team: 'Cursor Byok 开发团队' },
|
||||
en: { back: 'Back to Developer Blog', team: 'The Cursor Byok team' },
|
||||
};
|
||||
|
||||
export default async function BlogPostPage(props: PageProps<'/[lang]/blog/[slug]'>) {
|
||||
const { lang, slug } = await props.params;
|
||||
if (!isLanguage(lang)) notFound();
|
||||
|
||||
const page = blogSource.getPage([slug], lang);
|
||||
if (!page) notFound();
|
||||
|
||||
const t = copy[lang];
|
||||
const prefix = `/${lang}`;
|
||||
const MDX = page.data.body;
|
||||
|
||||
return (
|
||||
<main className="mx-auto w-full max-w-3xl px-6 py-12 sm:py-20">
|
||||
<article>
|
||||
<Link
|
||||
href={`${prefix}/blog`}
|
||||
className="mb-10 inline-flex items-center gap-2 text-sm text-fd-muted-foreground transition-colors hover:text-fd-foreground"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
{t.back}
|
||||
</Link>
|
||||
|
||||
<header className="border-b pb-8">
|
||||
<time className="text-sm text-fd-muted-foreground">
|
||||
{formatBlogDate(page.path, lang)}
|
||||
</time>
|
||||
<h1 className="mt-4 text-3xl font-bold tracking-tight sm:text-4xl">{page.data.title}</h1>
|
||||
<p className="mt-4 text-lg leading-8 text-fd-muted-foreground">{page.data.description}</p>
|
||||
<p className="mt-5 text-sm font-medium">{t.team}</p>
|
||||
</header>
|
||||
|
||||
<div className="prose mt-10 min-w-0">
|
||||
<InlineTOC items={page.data.toc} />
|
||||
<MDX
|
||||
components={getMDXComponents({
|
||||
a: createRelativeLink(blogSource, page),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function generateStaticParams() {
|
||||
return i18n.languages.flatMap((lang) =>
|
||||
blogSource.getPages(lang).map((page) => ({ lang, slug: page.slugs[0] })),
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateMetadata(
|
||||
props: PageProps<'/[lang]/blog/[slug]'>,
|
||||
): Promise<Metadata> {
|
||||
const { lang, slug } = await props.params;
|
||||
if (!isLanguage(lang)) notFound();
|
||||
|
||||
const page = blogSource.getPage([slug], lang);
|
||||
if (!page) notFound();
|
||||
|
||||
return {
|
||||
title: page.data.title,
|
||||
description: page.data.description,
|
||||
};
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import type { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
import { blogSource, formatBlogDate, sortBlogPages } from '@/lib/blog';
|
||||
import { isLanguage, type Language } from '@/lib/i18n';
|
||||
|
||||
const copy: Record<Language, { title: string; description: string; intro: string; empty: string }> = {
|
||||
zh: {
|
||||
title: '开发者博客',
|
||||
description: 'Cursor Byok 的架构决策、协议实现与开发进展。',
|
||||
intro: '记录 Cursor Byok 的架构决策、协议实现和开发进展。',
|
||||
empty: '文章正在准备中。',
|
||||
},
|
||||
en: {
|
||||
title: 'Developer Blog',
|
||||
description: 'Architecture decisions, protocol work, and development progress of Cursor Byok.',
|
||||
intro: 'Notes on architecture decisions, protocol work, and development progress of Cursor Byok.',
|
||||
empty: 'Articles are being prepared.',
|
||||
},
|
||||
};
|
||||
|
||||
export async function generateMetadata(props: PageProps<'/[lang]/blog'>): Promise<Metadata> {
|
||||
const { lang } = await props.params;
|
||||
if (!isLanguage(lang)) notFound();
|
||||
|
||||
return {
|
||||
title: copy[lang].title,
|
||||
description: copy[lang].description,
|
||||
};
|
||||
}
|
||||
|
||||
export default async function BlogPage(props: PageProps<'/[lang]/blog'>) {
|
||||
const { lang } = await props.params;
|
||||
if (!isLanguage(lang)) notFound();
|
||||
|
||||
const t = copy[lang];
|
||||
const posts = sortBlogPages(blogSource.getPages(lang));
|
||||
|
||||
return (
|
||||
<main className="mx-auto w-full max-w-5xl px-6 py-16 sm:py-24">
|
||||
<div className="max-w-2xl">
|
||||
<p className="font-mono text-sm font-medium text-fd-primary">DEVELOPER BLOG</p>
|
||||
<h1 className="mt-4 text-4xl font-bold tracking-tight">{t.title}</h1>
|
||||
<p className="mt-4 text-lg leading-8 text-fd-muted-foreground">{t.intro}</p>
|
||||
</div>
|
||||
|
||||
{posts.length > 0 ? (
|
||||
<div className="mt-12 divide-y border-y">
|
||||
{posts.map((post) => (
|
||||
<Link
|
||||
key={post.url}
|
||||
href={post.url}
|
||||
className="group grid gap-3 py-7 transition-colors hover:text-fd-primary sm:grid-cols-[10rem_1fr_auto] sm:items-center"
|
||||
>
|
||||
<time className="text-sm text-fd-muted-foreground">
|
||||
{formatBlogDate(post.path, lang)}
|
||||
</time>
|
||||
<div>
|
||||
<h2 className="font-semibold">{post.data.title}</h2>
|
||||
<p className="mt-1 text-sm leading-6 text-fd-muted-foreground">
|
||||
{post.data.description}
|
||||
</p>
|
||||
</div>
|
||||
<ArrowRight className="hidden size-4 transition-transform group-hover:translate-x-1 sm:block" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-12 border-y py-8 text-fd-muted-foreground">{t.empty}</p>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { HomeLayout } from 'fumadocs-ui/layouts/home';
|
||||
import { baseOptions } from '@/lib/layout.shared';
|
||||
import { isLanguage, i18n } from '@/lib/i18n';
|
||||
|
||||
export default async function Layout({ params, children }: LayoutProps<'/[lang]'>) {
|
||||
const { lang } = await params;
|
||||
const base = baseOptions(isLanguage(lang) ? lang : i18n.defaultLanguage);
|
||||
|
||||
return (
|
||||
<HomeLayout
|
||||
{...base}
|
||||
nav={{ ...base.nav, transparentMode: 'always' }}
|
||||
className="home-fullbleed-nav"
|
||||
>
|
||||
{children}
|
||||
</HomeLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import {
|
||||
ArrowRight,
|
||||
BookOpen,
|
||||
Settings2,
|
||||
Star,
|
||||
Wrench,
|
||||
} from 'lucide-react';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { DesktopDemo } from '@/components/hero/DesktopDemo';
|
||||
import { DownloadButton } from '@/components/hero/DownloadButton';
|
||||
import { blogSource, formatBlogDate, sortBlogPages } from '@/lib/blog';
|
||||
import { formatStars, getRepoStats } from '@/lib/github';
|
||||
import { isLanguage, type Language } from '@/lib/i18n';
|
||||
import { releaseUrl, repositoryUrl } from '@/lib/shared';
|
||||
|
||||
const copy: Record<
|
||||
Language,
|
||||
{
|
||||
pillReleased: (version: string) => string;
|
||||
pillFallback: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
readDocs: string;
|
||||
flow: [string, string, string];
|
||||
docsEyebrow: string;
|
||||
docsTitle: string;
|
||||
viewAll: string;
|
||||
docs: { icon: typeof BookOpen; title: string; description: string; href: string }[];
|
||||
blogEyebrow: string;
|
||||
blogTitle: string;
|
||||
}
|
||||
> = {
|
||||
zh: {
|
||||
pillReleased: (version) => `${version} 已发布 · 开源 · 本地运行`,
|
||||
pillFallback: '开源 · 本地运行 · 自由接入',
|
||||
title: 'Cursor 服务端的开源替代',
|
||||
subtitle:
|
||||
'在本机运行自己的模型网关,用自己的 API Key 接入 OpenAI、Anthropic 兼容服务或自定义端点,完整保留 Cursor Agent 的工具调用、Skills 和 MCP。',
|
||||
readDocs: '阅读文档',
|
||||
flow: ['Cursor 客户端', 'Cursor Byok 本地服务', '你的模型 API(OpenAI / Anthropic 兼容)'],
|
||||
docsEyebrow: 'DOCUMENTATION',
|
||||
docsTitle: '文档',
|
||||
viewAll: '查看全部',
|
||||
docs: [
|
||||
{
|
||||
icon: BookOpen,
|
||||
title: '快速开始',
|
||||
description: '完成安装、初始化和第一次模型调用。',
|
||||
href: '/docs',
|
||||
},
|
||||
{
|
||||
icon: Settings2,
|
||||
title: '模型配置',
|
||||
description: '配置协议、服务地址、凭据和生成参数。',
|
||||
href: '/docs/model-configuration',
|
||||
},
|
||||
{
|
||||
icon: Wrench,
|
||||
title: '常见问题',
|
||||
description: '回答常见问题。',
|
||||
href: '/docs/faq',
|
||||
},
|
||||
],
|
||||
blogEyebrow: 'DEVELOPER BLOG',
|
||||
blogTitle: '开发者博客',
|
||||
},
|
||||
en: {
|
||||
pillReleased: (version) => `${version} released · Open source · Runs locally`,
|
||||
pillFallback: 'Open source · Runs locally · Any provider',
|
||||
title: "The open-source alternative to Cursor's backend",
|
||||
subtitle:
|
||||
'Run your own model gateway locally, connect OpenAI- and Anthropic-compatible services or custom endpoints with your own API keys, and keep Cursor Agent tool calling, Skills, and MCP intact.',
|
||||
readDocs: 'Read the docs',
|
||||
flow: ['Cursor client', 'Cursor Byok local service', 'Your model API (OpenAI / Anthropic compatible)'],
|
||||
docsEyebrow: 'DOCUMENTATION',
|
||||
docsTitle: 'Documentation',
|
||||
viewAll: 'View all',
|
||||
docs: [
|
||||
{
|
||||
icon: BookOpen,
|
||||
title: 'Quick Start',
|
||||
description: 'Install, initialize, and make your first model call.',
|
||||
href: '/docs',
|
||||
},
|
||||
{
|
||||
icon: Settings2,
|
||||
title: 'Model Configuration',
|
||||
description: 'Configure protocols, server addresses, credentials, and parameters.',
|
||||
href: '/docs/model-configuration',
|
||||
},
|
||||
{
|
||||
icon: Wrench,
|
||||
title: 'Frequently Asked Questions',
|
||||
description: 'Answer common questions.',
|
||||
href: '/docs/faq',
|
||||
},
|
||||
],
|
||||
blogEyebrow: 'DEVELOPER BLOG',
|
||||
blogTitle: 'Developer Blog',
|
||||
},
|
||||
};
|
||||
|
||||
export default async function HomePage(props: PageProps<'/[lang]'>) {
|
||||
const { lang } = await props.params;
|
||||
if (!isLanguage(lang)) notFound();
|
||||
|
||||
const t = copy[lang];
|
||||
const prefix = `/${lang}`;
|
||||
const posts = sortBlogPages(blogSource.getPages(lang)).slice(0, 3);
|
||||
const { stars, version } = await getRepoStats();
|
||||
|
||||
return (
|
||||
<main className="flex flex-1 flex-col">
|
||||
<section className="relative -mt-14 overflow-hidden border-b px-4 pb-16 pt-34 sm:px-6 sm:pb-24 sm:pt-42">
|
||||
<div aria-hidden className="pointer-events-none absolute inset-0 -z-10">
|
||||
<div className="absolute inset-0 bg-[linear-gradient(to_right,var(--color-fd-border)_1px,transparent_1px),linear-gradient(to_bottom,var(--color-fd-border)_1px,transparent_1px)] bg-[size:56px_56px] opacity-40 [mask-image:radial-gradient(ellipse_70%_60%_at_50%_0%,#000_20%,transparent_75%)]" />
|
||||
<div className="absolute left-1/2 top-[-14rem] h-[26rem] w-[44rem] -translate-x-1/2 rounded-full bg-fd-primary/10 blur-3xl" />
|
||||
</div>
|
||||
<div className="mx-auto max-w-6xl">
|
||||
<div className="mx-auto max-w-3xl text-center">
|
||||
<a
|
||||
href={releaseUrl}
|
||||
className="inline-flex items-center gap-2 rounded-full border bg-fd-card px-4 py-1.5 text-sm text-fd-muted-foreground transition-colors hover:text-fd-foreground"
|
||||
>
|
||||
<span className="relative flex size-2">
|
||||
<span className="absolute inline-flex size-full animate-ping rounded-full bg-fd-primary opacity-50" />
|
||||
<span className="relative inline-flex size-2 rounded-full bg-fd-primary" />
|
||||
</span>
|
||||
{version ? t.pillReleased(version) : t.pillFallback}
|
||||
<ArrowRight className="size-3.5" />
|
||||
</a>
|
||||
<h1 className="mt-6 text-4xl font-bold tracking-tight sm:text-6xl">{t.title}</h1>
|
||||
<p className="mx-auto mt-6 max-w-2xl text-lg leading-8 text-fd-muted-foreground">
|
||||
{t.subtitle}
|
||||
</p>
|
||||
<div className="mt-10 flex flex-wrap items-center justify-center gap-3">
|
||||
<DownloadButton lang={lang} />
|
||||
<Link
|
||||
href={`${prefix}/docs`}
|
||||
className="inline-flex items-center gap-2 rounded-lg border bg-fd-card px-5 py-3 font-medium transition-colors hover:bg-fd-accent"
|
||||
>
|
||||
{t.readDocs}
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
<a
|
||||
href={repositoryUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-lg border bg-fd-card px-5 py-3 font-medium transition-colors hover:bg-fd-accent"
|
||||
>
|
||||
<GitHubIcon className="size-4" />
|
||||
GitHub
|
||||
{stars !== null ? (
|
||||
<span className="flex items-center gap-1 border-l pl-2.5 text-sm text-fd-muted-foreground">
|
||||
<Star className="size-3.5" />
|
||||
{formatStars(stars)}
|
||||
</span>
|
||||
) : null}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<DesktopDemo lang={lang} />
|
||||
<div className="mx-auto mt-10 flex flex-wrap items-center justify-center gap-x-3 gap-y-2 font-mono text-xs text-fd-muted-foreground sm:text-sm">
|
||||
<span>{t.flow[0]}</span>
|
||||
<ArrowRight className="size-3.5 shrink-0" />
|
||||
<span className="font-medium text-fd-foreground">{t.flow[1]}</span>
|
||||
<ArrowRight className="size-3.5 shrink-0" />
|
||||
<span>{t.flow[2]}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="border-b px-6 py-16 sm:py-20">
|
||||
<div className="mx-auto max-w-5xl">
|
||||
<div className="flex items-end justify-between gap-6">
|
||||
<div>
|
||||
<p className="font-mono text-sm font-medium text-fd-primary">{t.docsEyebrow}</p>
|
||||
<h2 className="mt-3 text-3xl font-bold tracking-tight">{t.docsTitle}</h2>
|
||||
</div>
|
||||
<Link
|
||||
href={`${prefix}/docs`}
|
||||
className="hidden items-center gap-2 text-sm font-medium sm:flex"
|
||||
>
|
||||
{t.viewAll}
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="mt-10 grid gap-4 md:grid-cols-3">
|
||||
{t.docs.map(({ icon: Icon, title, description, href }) => (
|
||||
<Link
|
||||
key={href}
|
||||
href={`${prefix}${href}`}
|
||||
className="group rounded-xl border bg-fd-card p-6 transition-colors hover:bg-fd-accent"
|
||||
>
|
||||
<Icon className="mb-5 size-5 text-fd-primary" />
|
||||
<h3 className="flex items-center justify-between font-semibold">
|
||||
{title}
|
||||
<ArrowRight className="size-4 transition-transform group-hover:translate-x-1" />
|
||||
</h3>
|
||||
<p className="mt-2 text-sm leading-6 text-fd-muted-foreground">{description}</p>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{posts.length > 0 ? (
|
||||
<section className="px-6 py-16 sm:py-20">
|
||||
<div className="mx-auto max-w-5xl">
|
||||
<div className="flex items-end justify-between gap-6">
|
||||
<div>
|
||||
<p className="font-mono text-sm font-medium text-fd-primary">{t.blogEyebrow}</p>
|
||||
<h2 className="mt-3 text-3xl font-bold tracking-tight">{t.blogTitle}</h2>
|
||||
</div>
|
||||
<Link href={`${prefix}/blog`} className="flex items-center gap-2 text-sm font-medium">
|
||||
{t.viewAll}
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="mt-10 divide-y border-y">
|
||||
{posts.map((post) => (
|
||||
<Link
|
||||
key={post.url}
|
||||
href={post.url}
|
||||
className="group grid gap-3 py-6 transition-colors hover:text-fd-primary sm:grid-cols-[10rem_1fr_auto] sm:items-center"
|
||||
>
|
||||
<time className="text-sm text-fd-muted-foreground">
|
||||
{formatBlogDate(post.path, lang)}
|
||||
</time>
|
||||
<div>
|
||||
<h3 className="font-semibold">{post.data.title}</h3>
|
||||
<p className="mt-1 text-sm text-fd-muted-foreground">
|
||||
{post.data.description}
|
||||
</p>
|
||||
</div>
|
||||
<ArrowRight className="hidden size-4 transition-transform group-hover:translate-x-1 sm:block" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function GitHubIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden className={className}>
|
||||
<path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0 1 12 6.844a9.59 9.59 0 0 1 2.504.337c1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.02 10.02 0 0 0 22 12.017C22 6.484 17.522 2 12 2Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import { getPageImageUrl, getPageMarkdownUrl, source } from '@/lib/source';
|
||||
import {
|
||||
DocsBody,
|
||||
DocsDescription,
|
||||
DocsPage,
|
||||
DocsTitle,
|
||||
MarkdownCopyButton,
|
||||
ViewOptionsPopover,
|
||||
} from 'fumadocs-ui/layouts/docs/page';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { getMDXComponents } from '@/components/mdx';
|
||||
import type { Metadata } from 'next';
|
||||
import { createRelativeLink } from 'fumadocs-ui/mdx';
|
||||
import { gitConfig } from '@/lib/shared';
|
||||
|
||||
export default async function Page(props: PageProps<'/[lang]/docs/[[...slug]]'>) {
|
||||
const params = await props.params;
|
||||
const page = source.getPage(params.slug, params.lang);
|
||||
if (!page) notFound();
|
||||
|
||||
const MDX = page.data.body;
|
||||
const markdownUrl = getPageMarkdownUrl(page).url;
|
||||
|
||||
return (
|
||||
<DocsPage toc={page.data.toc} full={page.data.full} tableOfContent={{ style: 'clerk' }}>
|
||||
<DocsTitle>{page.data.title}</DocsTitle>
|
||||
<DocsDescription className="mb-0">{page.data.description}</DocsDescription>
|
||||
<div className="flex flex-row gap-2 items-center border-b pb-6">
|
||||
<MarkdownCopyButton markdownUrl={markdownUrl} />
|
||||
<ViewOptionsPopover
|
||||
markdownUrl={markdownUrl}
|
||||
githubUrl={`https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/content/docs/${page.path}`}
|
||||
/>
|
||||
</div>
|
||||
<DocsBody>
|
||||
<MDX
|
||||
components={getMDXComponents({
|
||||
// this allows you to link to other pages with relative file paths
|
||||
a: createRelativeLink(source, page),
|
||||
})}
|
||||
/>
|
||||
</DocsBody>
|
||||
</DocsPage>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateStaticParams() {
|
||||
return source.generateParams();
|
||||
}
|
||||
|
||||
export async function generateMetadata(
|
||||
props: PageProps<'/[lang]/docs/[[...slug]]'>,
|
||||
): Promise<Metadata> {
|
||||
const params = await props.params;
|
||||
const page = source.getPage(params.slug, params.lang);
|
||||
if (!page) notFound();
|
||||
|
||||
return {
|
||||
title: page.data.title,
|
||||
description: page.data.description,
|
||||
openGraph: {
|
||||
images: getPageImageUrl(page).url,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { source } from '@/lib/source';
|
||||
import { DocsLayout } from 'fumadocs-ui/layouts/docs';
|
||||
import { baseOptions } from '@/lib/layout.shared';
|
||||
import { i18n, isLanguage } from '@/lib/i18n';
|
||||
|
||||
export default async function Layout({ params, children }: LayoutProps<'/[lang]/docs'>) {
|
||||
const { lang } = await params;
|
||||
const language = isLanguage(lang) ? lang : i18n.defaultLanguage;
|
||||
|
||||
return (
|
||||
<DocsLayout tree={source.getPageTree(language)} {...baseOptions(language)}>
|
||||
{children}
|
||||
</DocsLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import { RootProvider } from 'fumadocs-ui/provider/next';
|
||||
import { i18nProvider } from 'fumadocs-ui/i18n';
|
||||
import { notFound } from 'next/navigation';
|
||||
import type { Metadata } from 'next';
|
||||
import { htmlLang, i18n, isLanguage } from '@/lib/i18n';
|
||||
import { translations } from '@/lib/layout.shared';
|
||||
import '../global.css';
|
||||
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? 'https://docs.leokun.cn';
|
||||
|
||||
export async function generateMetadata(props: LayoutProps<'/[lang]'>): Promise<Metadata> {
|
||||
const { lang } = await props.params;
|
||||
|
||||
if (lang === 'en') {
|
||||
return {
|
||||
metadataBase: new URL(siteUrl),
|
||||
title: {
|
||||
default: 'Cursor Byok Docs',
|
||||
template: '%s | Cursor Byok',
|
||||
},
|
||||
description: 'Installation, model configuration, and frequently asked questions for Cursor Byok.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
metadataBase: new URL(siteUrl),
|
||||
title: {
|
||||
default: 'Cursor Byok 文档',
|
||||
template: '%s | Cursor Byok',
|
||||
},
|
||||
description: '安装、模型配置与常见问题指南。',
|
||||
};
|
||||
}
|
||||
|
||||
export function generateStaticParams() {
|
||||
return i18n.languages.map((lang) => ({ lang }));
|
||||
}
|
||||
|
||||
export default async function Layout({ params, children }: LayoutProps<'/[lang]'>) {
|
||||
const { lang } = await params;
|
||||
if (!isLanguage(lang)) notFound();
|
||||
|
||||
return (
|
||||
<html lang={htmlLang[lang]} suppressHydrationWarning>
|
||||
<body className="flex min-h-screen flex-col">
|
||||
<RootProvider i18n={i18nProvider(translations, lang)}>{children}</RootProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { getLLMText, getPageMarkdownUrl, source } from '@/lib/source';
|
||||
import { i18n } from '@/lib/i18n';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
export const revalidate = false;
|
||||
|
||||
export async function GET(
|
||||
_req: Request,
|
||||
{ params }: RouteContext<'/[lang]/llms.mdx/docs/[[...slug]]'>,
|
||||
) {
|
||||
const { lang, slug } = await params;
|
||||
const page = source.getPage(slug?.slice(0, -1), lang);
|
||||
if (!page) notFound();
|
||||
|
||||
return new Response(await getLLMText(page), {
|
||||
headers: {
|
||||
'Content-Type': 'text/markdown',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function generateStaticParams() {
|
||||
return i18n.languages.flatMap((lang) =>
|
||||
source.getPages(lang).map((page) => ({
|
||||
lang,
|
||||
slug: getPageMarkdownUrl(page).segments,
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { getPageImageUrl, source } from '@/lib/source';
|
||||
import { i18n } from '@/lib/i18n';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { ImageResponse } from 'next/og';
|
||||
import { generate as DefaultImage } from 'fumadocs-ui/og';
|
||||
import { appName } from '@/lib/shared';
|
||||
|
||||
export const revalidate = false;
|
||||
|
||||
export async function GET(_req: Request, { params }: RouteContext<'/[lang]/og/docs/[...slug]'>) {
|
||||
const { lang, slug } = await params;
|
||||
const page = source.getPage(slug.slice(0, -1), lang);
|
||||
if (!page) notFound();
|
||||
|
||||
return new ImageResponse(
|
||||
<DefaultImage title={page.data.title} description={page.data.description} site={appName} />,
|
||||
{
|
||||
width: 1200,
|
||||
height: 630,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function generateStaticParams() {
|
||||
return i18n.languages.flatMap((lang) =>
|
||||
source.getPages(lang).map((page) => ({
|
||||
lang,
|
||||
slug: getPageImageUrl(page).segments,
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import { source } from '@/lib/source';
|
||||
import { createFromSource } from 'fumadocs-core/search/server';
|
||||
|
||||
export const { GET } = createFromSource(source);
|
||||
@@ -1,40 +0,0 @@
|
||||
@import 'tailwindcss';
|
||||
@import 'fumadocs-ui/css/neutral.css';
|
||||
@import 'fumadocs-ui/css/preset.css';
|
||||
|
||||
:root {
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
html {
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
html > body[data-scroll-locked] {
|
||||
margin-right: 0 !important;
|
||||
--removed-body-scroll-bar-size: 0px !important;
|
||||
}
|
||||
|
||||
/* 文档页目录:隐藏默认折线,改用单条直线导轨 */
|
||||
#nd-toc a[href^='#'] > svg,
|
||||
#nd-toc div.absolute:has(> svg) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#nd-toc a[href^='#'] {
|
||||
border-inline-start: 1px solid var(--color-fd-border);
|
||||
}
|
||||
|
||||
#nd-toc a[href^='#'][data-active='true'] {
|
||||
border-inline-start-color: var(--color-fd-primary);
|
||||
}
|
||||
|
||||
/* 首页导航:通铺整行、无背景无分隔线 */
|
||||
.home-fullbleed-nav {
|
||||
--fd-layout-width: 100%;
|
||||
}
|
||||
|
||||
.home-fullbleed-nav #nd-nav > * {
|
||||
border-bottom-color: transparent;
|
||||
backdrop-filter: none;
|
||||
}
|
||||
|
Before Width: | Height: | Size: 4.6 KiB |
@@ -1,10 +0,0 @@
|
||||
import { getLLMText, source } from '@/lib/source';
|
||||
|
||||
export const revalidate = false;
|
||||
|
||||
export async function GET() {
|
||||
const scan = source.getPages().map(getLLMText);
|
||||
const scanned = await Promise.all(scan);
|
||||
|
||||
return new Response(scanned.join('\n\n'));
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import { source } from '@/lib/source';
|
||||
import { llms } from 'fumadocs-core/source';
|
||||
|
||||
export const revalidate = false;
|
||||
|
||||
export function GET() {
|
||||
return new Response(llms(source).index());
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
.stage {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 960px;
|
||||
margin: 64px auto 0;
|
||||
}
|
||||
|
||||
.halo {
|
||||
position: absolute;
|
||||
inset: -10% -14%;
|
||||
background: radial-gradient(
|
||||
50% 55% at 50% 45%,
|
||||
color-mix(in srgb, var(--color-fd-primary) 9%, transparent),
|
||||
transparent 72%
|
||||
);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.viewport {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 960 / 620;
|
||||
overflow: hidden;
|
||||
background: #f5f5f5;
|
||||
border: 1px solid var(--color-fd-border);
|
||||
border-radius: 14px;
|
||||
box-shadow:
|
||||
0 42px 90px -34px rgb(0 0 0 / 35%),
|
||||
0 12px 32px -16px rgb(0 0 0 / 28%);
|
||||
}
|
||||
|
||||
.viewport[data-dark] {
|
||||
background: #141414;
|
||||
box-shadow:
|
||||
0 42px 90px -34px rgb(0 0 0 / 50%),
|
||||
0 12px 32px -16px rgb(0 0 0 / 42%);
|
||||
}
|
||||
|
||||
.demo {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.poster {
|
||||
object-fit: cover;
|
||||
transition: opacity 0.6s ease;
|
||||
}
|
||||
|
||||
.posterHidden {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (max-width: 680px) {
|
||||
.stage {
|
||||
margin-top: 42px;
|
||||
}
|
||||
|
||||
.viewport {
|
||||
border-radius: 10px;
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import Image from 'next/image';
|
||||
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { demoLocale, type Language } from '@/lib/i18n';
|
||||
import styles from './DesktopDemo.module.css';
|
||||
|
||||
// 小屏或触屏设备内嵌交互体验差,只展示 poster 静态图
|
||||
const embedQuery = '(min-width: 680px) and (hover: hover)';
|
||||
|
||||
const alt: Record<Language, string> = {
|
||||
zh: 'Cursor Byok 桌面端数据概览界面',
|
||||
en: 'Cursor Byok desktop overview dashboard',
|
||||
};
|
||||
|
||||
function subscribeEmbedQuery(callback: () => void) {
|
||||
const media = window.matchMedia(embedQuery);
|
||||
media.addEventListener('change', callback);
|
||||
return () => media.removeEventListener('change', callback);
|
||||
}
|
||||
|
||||
function subscribeTheme(callback: () => void) {
|
||||
const observer = new MutationObserver(callback);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
|
||||
export function DesktopDemo({ lang }: { lang: Language }) {
|
||||
const stageRef = useRef<HTMLDivElement>(null);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const embeddable = useSyncExternalStore(
|
||||
subscribeEmbedQuery,
|
||||
() => window.matchMedia(embedQuery).matches,
|
||||
() => true,
|
||||
);
|
||||
const dark = useSyncExternalStore(
|
||||
subscribeTheme,
|
||||
() => document.documentElement.classList.contains('dark'),
|
||||
() => true,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!embeddable) return;
|
||||
const stage = stageRef.current;
|
||||
if (!stage) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
setMounted(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: '240px' },
|
||||
);
|
||||
observer.observe(stage);
|
||||
return () => observer.disconnect();
|
||||
}, [embeddable]);
|
||||
|
||||
return (
|
||||
<div ref={stageRef} className={styles.stage}>
|
||||
<div className={styles.halo} aria-hidden />
|
||||
<DemoViewport
|
||||
// key 含挂载状态:视口变小卸载 iframe 时整体重置,poster 重新显示
|
||||
key={`${dark ? 'dark' : 'light'}-${lang}-${embeddable && mounted ? 'live' : 'poster'}`}
|
||||
dark={dark}
|
||||
lang={lang}
|
||||
mounted={embeddable && mounted}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DemoViewport({
|
||||
dark,
|
||||
lang,
|
||||
mounted,
|
||||
}: {
|
||||
dark: boolean;
|
||||
lang: Language;
|
||||
mounted: boolean;
|
||||
}) {
|
||||
const [frameLoaded, setFrameLoaded] = useState(false);
|
||||
const [revealed, setRevealed] = useState(false);
|
||||
const theme = dark ? 'default-dark' : 'default-light';
|
||||
const demoUrl = `/product-demo/demo/index.html?theme=${theme}&locale=${demoLocale[lang]}`;
|
||||
const posterUrl = `/images/product-demo-${dark ? 'dark' : 'light'}-${lang}.png`;
|
||||
|
||||
useEffect(() => {
|
||||
if (!frameLoaded) return;
|
||||
// iframe onLoad 只代表文档加载完成,等内部应用渲染后再揭开 poster
|
||||
const timer = setTimeout(() => setRevealed(true), 900);
|
||||
return () => clearTimeout(timer);
|
||||
}, [frameLoaded]);
|
||||
|
||||
return (
|
||||
<div className={styles.viewport} data-dark={dark || undefined}>
|
||||
{mounted ? (
|
||||
<iframe
|
||||
title={alt[lang]}
|
||||
src={demoUrl}
|
||||
className={styles.demo}
|
||||
onLoad={() => setFrameLoaded(true)}
|
||||
/>
|
||||
) : null}
|
||||
<Image
|
||||
src={posterUrl}
|
||||
alt={alt[lang]}
|
||||
fill
|
||||
priority
|
||||
unoptimized
|
||||
className={revealed ? `${styles.poster} ${styles.posterHidden}` : styles.poster}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { Download } from 'lucide-react';
|
||||
import type { Language } from '@/lib/i18n';
|
||||
import { releaseUrl } from '@/lib/shared';
|
||||
|
||||
function detectPlatform(): string | null {
|
||||
const ua = navigator.userAgent;
|
||||
if (/Mac/i.test(ua)) return 'macOS';
|
||||
if (/Win/i.test(ua)) return 'Windows';
|
||||
if (/Linux|X11/i.test(ua)) return 'Linux';
|
||||
return null;
|
||||
}
|
||||
|
||||
const labels: Record<Language, { platform: (platform: string) => string; fallback: string }> = {
|
||||
zh: { platform: (platform) => `下载 ${platform} 版`, fallback: '下载最新版' },
|
||||
en: { platform: (platform) => `Download for ${platform}`, fallback: 'Download' },
|
||||
};
|
||||
|
||||
const subscribeNoop = () => () => {};
|
||||
|
||||
export function DownloadButton({ lang }: { lang: Language }) {
|
||||
// 平台只在客户端可知;SSR 用通用文案,水合后替换为平台文案
|
||||
const platform = useSyncExternalStore(subscribeNoop, detectPlatform, () => null);
|
||||
const label = labels[lang];
|
||||
|
||||
return (
|
||||
<a
|
||||
href={releaseUrl}
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-fd-primary px-5 py-3 font-medium text-fd-primary-foreground transition-opacity hover:opacity-90"
|
||||
>
|
||||
<Download className="size-4" />
|
||||
{platform ? label.platform(platform) : label.fallback}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import defaultMdxComponents from 'fumadocs-ui/mdx';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
import type { MDXComponents } from 'mdx/types';
|
||||
|
||||
export function getMDXComponents(components?: MDXComponents) {
|
||||
return {
|
||||
...defaultMdxComponents,
|
||||
Step,
|
||||
Steps,
|
||||
...components,
|
||||
} satisfies MDXComponents;
|
||||
}
|
||||
|
||||
export const useMDXComponents = getMDXComponents;
|
||||
|
||||
declare global {
|
||||
type MDXProvidedComponents = ReturnType<typeof getMDXComponents>;
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
---
|
||||
title: Frequently Asked Questions
|
||||
description: Answers to common Cursor Byok questions about setup, accounts, models, and TAB completion.
|
||||
icon: Wrench
|
||||
---
|
||||
|
||||
## Q: Why does Cursor show “not signed in,” omit the model, or show `An unexpected error occurred` after an upgrade or first setup?
|
||||
|
||||
**A:** After upgrading Cursor or configuring a model for the first time, Cursor needs to establish a new connection. If you see the following error, run the complete restart sequence instead of continuing in the current conversation:
|
||||
|
||||
```text
|
||||
An unexpected error occurred. Request ID: 3871795e-2a93-4628-8308-c641047e9e43
|
||||
```
|
||||
|
||||
Complete these steps in order:
|
||||
|
||||
1. Keep Cursor Byok running.
|
||||
2. Quit Cursor completely, confirm the process has stopped, and restart it.
|
||||
3. Start a new conversation instead of continuing one opened before setup or the switch.
|
||||
4. Select your configured model from the model list.
|
||||
|
||||
The same sequence is required after a first-time Cursor upgrade or model setup. Conversations created with the current version stay synchronized with official Cursor conversations and can continue with official models.
|
||||
|
||||
## Q: Do I need to sign in to my own Cursor account when switching to the current version?
|
||||
|
||||
**A:** No. You can use your own models without a Cursor account. Signing in to any Cursor account is recommended because it provides better access to official plugins, MCP, Skills, codebase indexing, and official models. Switching Cursor accounts does not require quitting Cursor Byok.
|
||||
|
||||
## Q: Can I continue a conversation that was opened with the old version?
|
||||
|
||||
**A:** Conversations created by the old assistant cannot be continued directly in the current version; start a new conversation. Conversations created with the current version synchronize with Cursor and can switch between your models and official models.
|
||||
|
||||
## Q: Does the current version support official Cursor models?
|
||||
|
||||
**A:** Yes. Official Cursor models and your configured local models can coexist. Auto, Composer, and other official models continue to use Cursor's official service, while your configured models are routed through Cursor Byok.
|
||||
|
||||
## Q: Why does selecting Auto show a quota or account error?
|
||||
|
||||
**A:** Auto uses only official Cursor models and does not automatically use your configured models. If your account has no official quota, select your own model manually from the model list. With official quota, you can switch freely between official and configured models.
|
||||
|
||||
## Q: Can I still use Cursor plugins, MCP, Skills, and codebase indexing?
|
||||
|
||||
**A:** Yes. The current version coexists with Cursor's official service. After signing in to any Cursor account, you can continue using official plugins, MCP, Skills, Auto, and codebase indexing. Codebase indexing uses Cursor's official indexing service, so upgrade Cursor to the latest version.
|
||||
|
||||
## Q: Why is the first semantic search slow?
|
||||
|
||||
**A:** The first semantic search call automatically downloads the embedding model. Later searches use the local model. Keep the network connection available and wait for the initial download to finish.
|
||||
|
||||
## Q: Where do I configure TAB completion?
|
||||
|
||||
**A:** Go to **System Settings → TAB Settings** in Cursor Byok and choose one of these modes:
|
||||
|
||||
- **Direct connection**: connects to the official TAB service for the account signed in to Cursor.
|
||||
- **Community service**: uses the free TAB service provided by the author.
|
||||
- **Custom**: connects to a TAB completion service that you deploy separately.
|
||||
|
||||
These TAB completion capabilities all come from Cursor's official service. Custom BYOK models are generally not suitable for code completion and are not used for TAB completion. After changing this setting, restart Cursor and start a new conversation.
|
||||
|
||||
## Q: Why do Agent requests fail even though the model test passes?
|
||||
|
||||
**A:** The model test verifies basic connectivity only. Agent requests also include longer context, tool definitions, and streaming responses. Check:
|
||||
|
||||
- Whether the upstream model supports tool calling.
|
||||
- Whether the context window and maximum output tokens fit the model's limits.
|
||||
- Whether the model type, request protocol, and server address match.
|
||||
- Whether custom headers and extra parameters follow the upstream protocol.
|
||||
- The upstream status code and response body in **Call Statistics** or call details.
|
||||
|
||||
## Q: What is the local CA, and what should I do if initialization fails?
|
||||
|
||||
**A:** The local CA (certificate authority) allows Cursor Byok to inspect HTTPS requests from Cursor. Its files stay on your machine. Go to **Cursor Settings** and click **Initialize CA**. When the system asks for authorization, follow the app's terminal instructions to install and trust it, then return to the app and click **I have initialized, refresh**.
|
||||
|
||||
If the status does not update, quit and restart Cursor Byok completely, then open Cursor Settings again.
|
||||
|
||||
## Q: What should I do if the model connectivity test fails?
|
||||
|
||||
**A:** Check the error category:
|
||||
|
||||
- **Authentication error**: confirm the API key is valid and the account can access the target model.
|
||||
- **Endpoint not found**: confirm the model type, request protocol, and server address match.
|
||||
- **Model not found**: use **Fetch Models** to check the model identifiers returned by the upstream.
|
||||
- **Invalid parameters**: temporarily remove custom headers and extra parameters, then test again.
|
||||
- **Connection timeout**: check your network, system proxy, and upstream service status.
|
||||
|
||||
## Q: What should I do about a fake account generated by the old version?
|
||||
|
||||
**A:** Sign out of the fake account in Cursor, then sign in to any Cursor account, or remain signed out while using your own models. The current version does not require a fake account or a “stop service” workflow to switch between official and configured models.
|
||||
|
||||
## Q: What information should I include when reporting another issue?
|
||||
|
||||
**A:** Open a report on [GitHub Issues](https://github.com/leookun/cursor-byok/issues) with your operating system, Cursor Byok version, model type, request protocol, redacted server address, error message, and reproduction steps. Never share API keys or other credentials.
|
||||
@@ -1,90 +0,0 @@
|
||||
---
|
||||
title: 常见问题
|
||||
description: 以问答形式解答 Cursor Byok 的配置、账号、模型和 TAB 补全问题。
|
||||
icon: Wrench
|
||||
---
|
||||
|
||||
## Q:首次升级或配置后,为什么 Cursor 提示“未登录”、看不到模型或出现 `An unexpected error occurred`?
|
||||
|
||||
**A:** 首次升级 Cursor 或首次配置模型后,Cursor 需要重新建立连接。遇到以下错误时,请先执行完整重启流程,而不是继续使用当前对话:
|
||||
|
||||
```text
|
||||
An unexpected error occurred. Request ID: 3871795e-2a93-4628-8308-c641047e9e43
|
||||
```
|
||||
|
||||
请按顺序完成以下操作:
|
||||
|
||||
1. 保持 Cursor Byok 运行。
|
||||
2. 完全退出 Cursor,确认进程结束后重新启动。
|
||||
3. 新建一个对话,不要继续使用配置前或切换前已经打开的对话。
|
||||
4. 在模型列表中选择你配置的模型。
|
||||
|
||||
首次升级或首次配置模型后也需要执行这套流程。新版创建的对话会与 Cursor 官方对话同步,可以和官方模型继续衔接。
|
||||
|
||||
## Q:切换到新版需要登录自己的 Cursor 账号吗?
|
||||
|
||||
**A:** 不需要。新版可以在没有 Cursor 账号的情况下使用自己的模型;不过建议在 Cursor 中登录任意账号,这样可以更好地使用官方插件、MCP、Skills、代码库索引和官方模型等功能。切换 Cursor 账号时不需要退出 Cursor Byok。
|
||||
|
||||
## Q:旧版已经打开的对话可以继续使用吗?
|
||||
|
||||
**A:** 旧助手产生的对话无法直接在新版中续接,需要新开一个对话。新版产生的对话与 Cursor 官方同步,可以在新版和官方模型之间无缝切换或继续对话。
|
||||
|
||||
## Q:新版支持 Cursor 官方模型吗?
|
||||
|
||||
**A:** 支持。新版可以让 Cursor 官方模型与自己配置的本地模型同时存在,例如 Auto、Composer 等官方模型仍由 Cursor 官方服务处理,自己配置的模型则通过 Cursor Byok 转发。
|
||||
|
||||
## Q:为什么选择 Auto 会提示额度或账号错误?
|
||||
|
||||
**A:** Auto 只会使用 Cursor 官方模型,不会自动使用你配置的本地模型。账号没有官方额度时,请在模型列表中手动选择自己的模型;有官方额度时,可以在官方模型和自己的模型之间自由切换。
|
||||
|
||||
## Q:Cursor 的插件、MCP、Skills 和代码库索引还能使用吗?
|
||||
|
||||
**A:** 可以。新版与 Cursor 官方服务并存,登录任意 Cursor 账号后可以继续使用官方插件、MCP、Skills、Auto 模型和代码库索引。代码库索引使用 Cursor 官方索引服务,需要将 Cursor 升级到最新版。
|
||||
|
||||
## Q:语意搜索第一次使用为什么比较慢?
|
||||
|
||||
**A:** 首次调用语意搜索时,应用会自动下载 Embedding Model(文本向量模型)。下载完成后,后续搜索会直接使用本地模型。模型文件较大时,请保持网络连接并耐心等待首次下载完成。
|
||||
|
||||
## Q:TAB 补全在哪里设置?
|
||||
|
||||
**A:** 在 Cursor Byok 的 **系统设置 → TAB 设置** 中选择:
|
||||
|
||||
- **直连**:连接你在 Cursor 中登录的账号对应的官方 TAB 服务。
|
||||
- **公益服务**:使用作者提供的免费 TAB 服务。
|
||||
- **自定义**:连接你自己额外部署的 TAB 补全服务。
|
||||
|
||||
这些 TAB 补全能力都来自 Cursor 官方服务。自定义的 BYOK 模型通常不适合处理代码补全,因此不会用于 TAB 补全。修改设置后,请重启 Cursor 并新建一个对话。
|
||||
|
||||
## Q:为什么模型测试通过了,Agent 请求仍然失败?
|
||||
|
||||
**A:** 模型测试只验证基础连接。Agent 请求还会包含更长的上下文、工具定义和流式响应,请检查:
|
||||
|
||||
- 上游模型是否支持工具调用。
|
||||
- 上下文窗口和最大输出 Token 是否符合模型限制。
|
||||
- 模型类型、请求协议和服务地址是否匹配。
|
||||
- 自定义 Headers 和额外参数是否符合上游协议。
|
||||
- **调用统计**或调用详情中的上游状态码和响应内容。
|
||||
|
||||
## Q:本地 CA 是什么?初始化失败怎么办?
|
||||
|
||||
**A:** 本地 CA(证书颁发机构)用于让 Cursor Byok 解析 Cursor 发出的 HTTPS 请求,相关文件只保存在本机。进入 **Cursor 配置**,点击 **初始化 CA**;系统要求授权时,按照应用提示在终端中完成安装和信任,然后返回应用点击 **我已初始化,刷新**。
|
||||
|
||||
如果状态没有更新,请完全退出并重新启动 Cursor Byok,再次打开 Cursor 配置页面。
|
||||
|
||||
## Q:模型连通性测试失败怎么办?
|
||||
|
||||
**A:** 根据测试错误检查:
|
||||
|
||||
- **认证错误**:确认 API Key 有效,并且账户有权访问目标模型。
|
||||
- **接口不存在**:确认模型类型、请求协议和服务器地址匹配。
|
||||
- **模型不存在**:使用 **获取模型** 检查上游返回的模型标识。
|
||||
- **参数错误**:暂时移除自定义 Headers 和额外参数,再重新测试。
|
||||
- **连接超时**:检查网络、系统代理和上游服务状态。
|
||||
|
||||
## Q:还在使用旧版生成的 fake 账户怎么办?
|
||||
|
||||
**A:** 在 Cursor 中退出旧版生成的 fake 账户,然后登录任意 Cursor 账号,或直接保持未登录状态使用自己的模型。新版不再需要 fake 账户,也不需要通过“停止服务”来切换官方服务和本地模型。
|
||||
|
||||
## Q:遇到其他问题时,需要提供什么信息?
|
||||
|
||||
**A:** 请在 [GitHub Issues](https://github.com/leookun/cursor-byok/issues) 提交问题,并附上操作系统、Cursor Byok 版本、模型类型、请求协议、已脱敏的服务地址、错误信息和复现步骤。请勿公开 API Key 或其他凭据。
|
||||
@@ -1,97 +0,0 @@
|
||||
---
|
||||
title: Quick Start
|
||||
description: Install Cursor Byok and let Cursor use your own model APIs.
|
||||
icon: Rocket
|
||||
---
|
||||
|
||||
Cursor Byok is a Cursor model gateway that runs on your machine. It receives Cursor Agent requests, converts them, and forwards them to the OpenAI- or Anthropic-compatible service you configure.
|
||||
|
||||
<Callout type="warn" title="Before you start">
|
||||
Cursor Byok is an independent open-source project and is not affiliated with Cursor or its developers. The software itself is free, but model providers may charge for usage.
|
||||
</Callout>
|
||||
|
||||
<Callout type="warn" title="Restart Cursor and start a new conversation after an upgrade or first setup">
|
||||
After upgrading Cursor or configuring a model for the first time, quit Cursor completely and restart it once, then start a new conversation before selecting the model. Existing conversations do not load the new connection settings and may show “not signed in,” omit the model, or show `An unexpected error occurred`.
|
||||
</Callout>
|
||||
|
||||
## Install and configure
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
|
||||
### Update Cursor
|
||||
|
||||
Download the latest official Cursor from [cursor.com](https://cursor.com) and install it over your existing copy, so the client stays up to date.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Download and launch Cursor Byok
|
||||
|
||||
Download the latest release for your operating system from [GitHub Releases](https://github.com/leookun/cursor-byok/releases/latest), then launch cursor-byok.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Initialize and configure a model
|
||||
|
||||
Open **Cursor Configuration**, follow the prompts to initialize the local CA, then add a model. Fill in the server address, API key, and model name, and run the connectivity test until it passes.
|
||||
|
||||

|
||||
|
||||
See [Model Configuration](./model-configuration.mdx) for how to choose the type and protocol for different models.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Restart Cursor after an upgrade or first setup
|
||||
|
||||
After upgrading Cursor or configuring a model for the first time, **quit Cursor completely and restart it once**. Closing only the window or continuing in the current conversation does not load the new connection settings.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Start a new conversation and select the model
|
||||
|
||||
Once Cursor has restarted, start a new conversation and select the model you just configured from the model list (do not select Auto). Do not continue a conversation that was already open before setup.
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Coexists with your official account
|
||||
|
||||
The current design goal is coexistence with the official service — there is no more "stop the service" or account juggling:
|
||||
|
||||
- Sign in to Cursor with your own account. If you previously used a fake account generated by an old version, sign out of it first, then sign in with your own.
|
||||
- If your account has official quota, there is no boundary between official models and your local models — switch and mix freely.
|
||||
- **Auto always routes to official models**: picking Auto without quota results in an error, so select your configured model instead.
|
||||
- Cursor features such as plugins and codebase indexing keep working as usual.
|
||||
|
||||
## Next steps
|
||||
|
||||
<Cards>
|
||||
<Card title="Installation" description="Download, initialize, and run for the first time." href="/docs/installation" />
|
||||
<Card title="Model Configuration" description="Choose a protocol and fill in upstream model parameters." href="/docs/model-configuration" />
|
||||
<Card title="TAB Service" description="Choose how Cursor connects to Tab completion endpoints." href="/docs/tab-service" />
|
||||
<Card title="Frequently Asked Questions" description="Answer common certificate, connection, and model configuration questions." href="/docs/faq" />
|
||||
</Cards>
|
||||
|
||||
## How data flows
|
||||
|
||||
```text
|
||||
Cursor client
|
||||
│ Agent requests and tool results
|
||||
▼
|
||||
Cursor Byok local service
|
||||
│ OpenAI- / Anthropic-compatible requests
|
||||
▼
|
||||
Your model API
|
||||
```
|
||||
|
||||
API keys, model configurations, and app settings are stored on your machine. Model requests are still sent to the upstream provider you choose.
|
||||
@@ -1,97 +0,0 @@
|
||||
---
|
||||
title: 快速开始
|
||||
description: 安装 Cursor Byok,并让 Cursor 使用你自己的模型 API。
|
||||
icon: Rocket
|
||||
---
|
||||
|
||||
Cursor Byok 是运行在本机的 Cursor 模型网关。它接收 Cursor Agent 请求,将请求转换后发送到你配置的 OpenAI 或 Anthropic 兼容服务。
|
||||
|
||||
<Callout type="warn" title="使用前须知">
|
||||
Cursor Byok 是独立开源项目,与 Cursor 及其开发者没有关联。软件本身免费,但模型服务商可能按用量收费。
|
||||
</Callout>
|
||||
|
||||
<Callout type="warn" title="首次升级或配置后必须重启 Cursor,并新建对话">
|
||||
首次升级 Cursor 或首次配置模型后,请完全退出并重新启动一次 Cursor,然后新建一个对话再选择模型。现有对话不会加载新的连接配置,继续使用可能提示“未登录”、无法看到模型,或出现 `An unexpected error occurred`。
|
||||
</Callout>
|
||||
|
||||
## 安装与配置
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
|
||||
### 更新 Cursor
|
||||
|
||||
从 [cursor.com](https://cursor.com) 下载官方最新版 Cursor,直接覆盖安装,保持客户端为最新版本。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 下载并启动 Cursor Byok
|
||||
|
||||
从 [GitHub Releases](https://github.com/leookun/cursor-byok/releases/latest) 下载与你的操作系统对应的最新版本,然后启动 Cursor Byok。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 初始化并配置模型
|
||||
|
||||
打开 **Cursor 配置**,按界面提示初始化本地 CA,然后添加模型。填写服务地址、API Key 和模型名称,并运行连通性测试,测试通过即可。
|
||||
|
||||

|
||||
|
||||
不同模型如何选择类型与协议,见[模型配置](./model-configuration.mdx)。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 首次升级或配置后重启 Cursor
|
||||
|
||||
首次升级 Cursor 或首次配置模型后,**必须完全退出 Cursor 并重新启动一次**。仅关闭窗口或继续使用当前对话,都不会加载新的连接配置。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 新建对话并选择模型
|
||||
|
||||
Cursor 重启完成后,点击新建对话,再从模型列表中选择你刚配置的模型(不要选 Auto)。请勿继续使用配置前已经打开的对话。
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## 与官方账号并存
|
||||
|
||||
新版的设计目标是与官方服务并存,不再需要“关服务”“切账号”之类的操作:
|
||||
|
||||
- 直接在 Cursor 中登录你自己的账号。如果之前用过旧版生成的 fake 账户,先退出它,再登录自己的账号。
|
||||
- 账号有官方额度时,官方模型和本地模型没有使用上的边界,可以随时切换混用。
|
||||
- **Auto 走的是官方模型**:账号没有额度时选 Auto 会报错,请手动选择你配置的模型。
|
||||
- 插件、代码库索引等 Cursor 功能都可以正常使用。
|
||||
|
||||
## 接下来
|
||||
|
||||
<Cards>
|
||||
<Card title="安装指南" description="下载、初始化和首次运行。" href="/docs/installation" />
|
||||
<Card title="模型配置" description="选择协议并填写上游模型参数。" href="/docs/model-configuration" />
|
||||
<Card title="TAB 服务" description="选择 Cursor Tab 补全接口的连接方式。" href="/docs/tab-service" />
|
||||
<Card title="常见问题" description="回答常见的证书、连接和模型配置问题。" href="/docs/faq" />
|
||||
</Cards>
|
||||
|
||||
## 数据如何流转
|
||||
|
||||
```text
|
||||
Cursor 客户端
|
||||
│ Agent 请求与工具结果
|
||||
▼
|
||||
Cursor Byok 本地服务
|
||||
│ OpenAI / Anthropic 兼容请求
|
||||
▼
|
||||
你配置的模型 API
|
||||
```
|
||||
|
||||
API Key、模型配置和应用设置保存在本机。模型请求仍会发送到你选择的上游服务商。
|
||||
@@ -1,86 +0,0 @@
|
||||
---
|
||||
title: Installation
|
||||
description: Download Cursor Byok, complete local initialization, and verify it is running.
|
||||
icon: Download
|
||||
---
|
||||
|
||||
## Download the app
|
||||
|
||||
Go to the [latest release page](https://github.com/leookun/cursor-byok/releases/latest) and download the installer for macOS, Windows, or Linux.
|
||||
|
||||
<Callout type="info">
|
||||
Prefer the latest stable release. The release page lists the installers and release notes for each version.
|
||||
</Callout>
|
||||
|
||||
## First launch
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
|
||||
### Open Cursor Settings
|
||||
|
||||
After launching the app, go to **Cursor Settings**. If the local CA has not been initialized, the page shows an initialization entry.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Initialize the local CA
|
||||
|
||||
Click **Initialize CA**. The local CA is used to inspect HTTPS requests from Cursor on your device; its files never leave your machine.
|
||||
|
||||
When the system asks for authorization, follow the instructions shown in the app to complete the trust step in your terminal, then return to the app and click **I have initialized, refresh**.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Add your first model
|
||||
|
||||
Click **Add Model**, choose the OpenAI or Anthropic type, fill in the upstream service parameters, and save. See [Model Configuration](./model-configuration.mdx) for details on each field.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Run the connectivity test
|
||||
|
||||
Click **Test** on the model. Once the test passes, the model appears in Cursor's model list.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Completely restart Cursor after an upgrade or first setup
|
||||
|
||||
After upgrading Cursor or configuring a model for the first time, **quit Cursor completely and restart it once**. Closing only the window is not enough; make sure the Cursor process has stopped before opening it again.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### Start a new conversation
|
||||
|
||||
After Cursor restarts, start a new conversation and select your configured model from the model list. Do not continue a conversation opened before setup, and do not select **Auto**.
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Verify the installation
|
||||
|
||||
After configuration, confirm that:
|
||||
|
||||
- The Cursor Settings page no longer shows the CA initialization prompt.
|
||||
- At least one model passes the connectivity test.
|
||||
- Cursor Byok stays running.
|
||||
- Cursor has been quit completely and restarted once.
|
||||
- You started a new conversation instead of continuing one opened before setup.
|
||||
- The configured display name shows up in Cursor's model list.
|
||||
|
||||
If any of these steps fail, head to [Frequently Asked Questions](./faq.mdx).
|
||||
|
||||
## Updates
|
||||
|
||||
Check for new versions in the app settings, or visit [GitHub Releases](https://github.com/leookun/cursor-byok/releases/latest) directly. You do not need to delete existing model configurations before updating.
|
||||
@@ -1,86 +0,0 @@
|
||||
---
|
||||
title: 安装指南
|
||||
description: 下载 Cursor Byok,完成本地初始化并验证运行状态。
|
||||
icon: Download
|
||||
---
|
||||
|
||||
## 下载应用
|
||||
|
||||
前往 [最新版本页面](https://github.com/leookun/cursor-byok/releases/latest),下载适用于 macOS、Windows 或 Linux 的安装包。
|
||||
|
||||
<Callout type="info">
|
||||
优先使用最新正式版本。发行页面会列出该版本包含的安装包和更新说明。
|
||||
</Callout>
|
||||
|
||||
## 首次启动
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
|
||||
### 打开 Cursor 配置
|
||||
|
||||
启动应用后进入 **Cursor 配置**。如果本地 CA 尚未初始化,页面会显示初始化入口。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 初始化本地 CA
|
||||
|
||||
点击 **初始化 CA**。本地 CA 用于在你的设备上解析 Cursor 发出的 HTTPS 请求,其文件只保存在本机。
|
||||
|
||||
系统要求授权时,按照应用显示的说明在终端中完成信任操作,然后返回应用点击 **我已初始化,刷新**。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 添加第一个模型
|
||||
|
||||
点击 **添加模型**,选择 OpenAI 或 Anthropic 类型,填写上游服务参数并保存。详细字段说明见[模型配置](./model-configuration.mdx)。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 运行连通性测试
|
||||
|
||||
点击模型的 **测试**。测试成功后,该模型即可出现在 Cursor 的模型列表中。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 首次升级或配置后完全重启 Cursor
|
||||
|
||||
首次升级 Cursor 或首次配置模型后,**必须完全退出并重新启动一次 Cursor**。仅关闭窗口不等于退出;请确认 Cursor 进程已经结束后再重新打开。
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
### 新建对话
|
||||
|
||||
Cursor 重启后新建一个对话,再从模型列表中选择你配置的模型。不要继续使用配置前已打开的对话,也不要选择 **Auto**。
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## 验证安装
|
||||
|
||||
完成配置后,请确认:
|
||||
|
||||
- Cursor 配置页面不再显示 CA 初始化提示。
|
||||
- 至少一个模型的连通性测试成功。
|
||||
- Cursor Byok 保持运行。
|
||||
- 已完全退出并重新启动一次 Cursor。
|
||||
- 已新建对话,而不是继续使用配置前打开的对话。
|
||||
- Cursor 模型列表中能看到配置的显示名称。
|
||||
|
||||
如果其中任何一步失败,请前往[常见问题](./faq.mdx)。
|
||||
|
||||
## 更新
|
||||
|
||||
在应用设置中检查新版本,或直接访问 [GitHub Releases](https://github.com/leookun/cursor-byok/releases/latest)。更新前无需删除现有模型配置。
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"title": "User Guide",
|
||||
"root": true,
|
||||
"pages": ["index", "installation", "model-configuration", "plugin-development", "tab-service", "faq"]
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"title": "使用指南",
|
||||
"root": true,
|
||||
"pages": ["index", "installation", "model-configuration", "plugin-development", "tab-service", "faq"]
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
---
|
||||
title: Model Configuration
|
||||
description: Configure the model protocol, server address, credentials, and generation parameters.
|
||||
icon: Settings2
|
||||
---
|
||||
|
||||
Each model configuration is an independent upstream channel that can use a different provider, protocol, credentials, and generation parameters.
|
||||
|
||||

|
||||
|
||||
## Choosing the type and protocol
|
||||
|
||||
Picking by model family avoids most compatibility issues:
|
||||
|
||||
| Model family | Model type | Request protocol |
|
||||
| --- | --- | --- |
|
||||
| Claude family | **Anthropic** | — |
|
||||
| GPT / OpenAI family | **OpenAI** | **Responses API** |
|
||||
| Everything else | **OpenAI** | **Chat Completions API** |
|
||||
|
||||
<Callout type="warn" title="Always use the Responses API for GPT models">
|
||||
Running GPT models through Chat Completions loses prompt caching, which makes them noticeably slower and more expensive.
|
||||
</Callout>
|
||||
|
||||
## Required fields
|
||||
|
||||
### Model type
|
||||
|
||||
Choose the upstream interface format:
|
||||
|
||||
- **OpenAI**: supports the Responses API and the Chat Completions API.
|
||||
- **Anthropic**: supports Messages API-compatible services.
|
||||
|
||||
### Request protocol
|
||||
|
||||
For the OpenAI type, also choose **Responses API** or **Chat Completions API**. This option determines the request and response format; it does not change the server address you entered.
|
||||
|
||||
### Server address
|
||||
|
||||
You can enter the provider's base URL, or choose to use a full request URL:
|
||||
|
||||
- With a base URL, Cursor Byok appends the standard endpoint path for the chosen protocol.
|
||||
- With a full request URL, Cursor Byok uses the address as-is.
|
||||
|
||||
Prefer the built-in provider presets in the UI to avoid protocol and endpoint mismatches.
|
||||
|
||||
### API key
|
||||
|
||||
Enter the access key required by the upstream service. The key is stored on your machine and used to send model requests.
|
||||
|
||||
### Model name
|
||||
|
||||
Enter the model identifier accepted by the provider's API. You can also click **Fetch Models** to load the model list returned by the API.
|
||||
|
||||
## Display information
|
||||
|
||||
- **Display name**: the name shown in Cursor's model list; it does not change the model identifier sent upstream.
|
||||
- **Notes**: shown in Cursor's model description.
|
||||
|
||||
## Optional parameters
|
||||
|
||||
Fill in the following fields based on the model's capabilities; when left empty, the app or upstream defaults are used:
|
||||
|
||||
- Context window tokens
|
||||
- Max output tokens
|
||||
- Reasoning or thinking effort
|
||||
- Custom headers
|
||||
- Extra OpenAI or Anthropic parameters
|
||||
|
||||
<Callout type="warn" title="Extra parameter format">
|
||||
Custom headers and extra parameters must be JSON objects. Extra parameters directly affect upstream requests, so only add fields the provider explicitly supports.
|
||||
</Callout>
|
||||
|
||||
## Test the configuration
|
||||
|
||||
Run **Test** after saving. The result shows time to first token, generation speed, total duration, and the model output, which helps you confirm:
|
||||
|
||||
1. The address and protocol match.
|
||||
2. The API key is valid.
|
||||
3. The model identifier exists and is accessible.
|
||||
4. The upstream returns streamed content correctly.
|
||||
|
||||
Once the test passes, switch to Cursor and start using the model.
|
||||
@@ -1,83 +0,0 @@
|
||||
---
|
||||
title: 模型配置
|
||||
description: 配置模型协议、服务地址、凭据与生成参数。
|
||||
icon: Settings2
|
||||
---
|
||||
|
||||
每个模型配置都是一个独立的上游通道,可以使用不同服务商、协议、凭据和生成参数。
|
||||
|
||||

|
||||
|
||||
## 如何选择类型与协议
|
||||
|
||||
按上游模型系列选择,可以避免绝大多数兼容性问题:
|
||||
|
||||
| 模型系列 | 模型类型 | 请求协议 |
|
||||
| --- | --- | --- |
|
||||
| Claude 系列 | **Anthropic** | — |
|
||||
| GPT / OpenAI 系列 | **OpenAI** | **Responses API** |
|
||||
| 其他所有模型 | **OpenAI** | **Chat Completions API** |
|
||||
|
||||
<Callout type="warn" title="GPT 系列务必用 Responses API">
|
||||
GPT 系列走 Chat Completions 会丢失提示词缓存,速度和费用都会明显变差。
|
||||
</Callout>
|
||||
|
||||
## 必填字段
|
||||
|
||||
### 模型类型
|
||||
|
||||
选择上游接口格式:
|
||||
|
||||
- **OpenAI**:支持 Responses API 和 Chat Completions API。
|
||||
- **Anthropic**:支持 Messages API 兼容服务。
|
||||
|
||||
### 请求协议
|
||||
|
||||
OpenAI 类型需要继续选择 **Responses API** 或 **Chat Completions API**。该选项决定请求和响应格式,不会单独改变你填写的服务地址。
|
||||
|
||||
### 服务器地址
|
||||
|
||||
可以填写服务商的基础地址,也可以选择使用完整请求 URL:
|
||||
|
||||
- 使用基础地址时,Cursor Byok 会根据协议追加标准端点路径。
|
||||
- 使用完整请求 URL 时,Cursor Byok 会原样使用该地址。
|
||||
|
||||
优先使用界面中的常用服务商预设,减少协议与端点不匹配的情况。
|
||||
|
||||
### API Key
|
||||
|
||||
填写上游服务要求的访问密钥。密钥保存在本机,用于发送模型请求。
|
||||
|
||||
### 模型名称
|
||||
|
||||
填写服务商接口接受的模型标识。你也可以点击 **获取模型** 读取接口返回的模型列表。
|
||||
|
||||
## 展示信息
|
||||
|
||||
- **显示名称**:Cursor 模型列表中看到的名称,不会改变发送给上游的模型标识。
|
||||
- **备注**:显示在 Cursor 的模型说明中。
|
||||
|
||||
## 可选参数
|
||||
|
||||
按模型能力填写以下字段;留空时使用应用或上游的默认值:
|
||||
|
||||
- 上下文窗口 Token
|
||||
- 最大输出 Token
|
||||
- 推理强度或思考强度
|
||||
- 自定义 Headers
|
||||
- OpenAI 或 Anthropic 额外参数
|
||||
|
||||
<Callout type="warn" title="额外参数格式">
|
||||
自定义 Headers 和额外参数必须是 JSON 对象。额外参数会直接影响上游请求,只添加服务商明确支持的字段。
|
||||
</Callout>
|
||||
|
||||
## 测试配置
|
||||
|
||||
保存后运行 **测试**。结果会显示首字延迟、生成速度、总耗时和模型输出,便于确认:
|
||||
|
||||
1. 地址和协议是否匹配。
|
||||
2. API Key 是否有效。
|
||||
3. 模型标识是否存在且可访问。
|
||||
4. 上游是否能正常返回流式内容。
|
||||
|
||||
测试通过后再前往 Cursor 使用该模型。
|
||||
@@ -1,145 +0,0 @@
|
||||
---
|
||||
title: Plugin Development
|
||||
description: Build stateless TypeScript plugins that execute providers, enumerate models, and manage credential resources with OAuth sign-in.
|
||||
icon: Blocks
|
||||
---
|
||||
|
||||
Plugins implement three capability interfaces defined by the core: **Provider** (execute one LLM call), **Model** (enumerate available models), and **Resource** (credential resources such as accounts). Plugins hold no persistent state — resources and model catalogs are stored by the core, and every call receives the data it needs as arguments.
|
||||
|
||||
## Layout
|
||||
|
||||
```text
|
||||
~/.cursor-byok-v3/plugins/
|
||||
├── installed/
|
||||
│ └── com.example.subscription/
|
||||
│ ├── plugin.json # static identity, entry, icon, HTTPS host allowlist
|
||||
│ ├── main.ts # defineProviderPlugin composing providers and resources
|
||||
│ └── assets/icon.svg # local icon, 1 MiB max
|
||||
└── data/
|
||||
└── com.example.subscription/
|
||||
├── resources-<type>.json # resource records persisted by the core (0600)
|
||||
└── models-<provider>.json # model catalogs persisted by the core
|
||||
```
|
||||
|
||||
Built-in plugin sources live at `server/plugins/build-in/` (such as `codex-auth`); they are bundled into the binary and pre-installed into `plugins/installed/` keyed by version. Debug builds load the source directory first so edits take effect immediately.
|
||||
|
||||
## Static manifest
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"id": "com.example.subscription",
|
||||
"name": "Example Subscription",
|
||||
"version": "0.1.0",
|
||||
"author": "@example",
|
||||
"minAppVersion": "0.1.0",
|
||||
"icon": "assets/icon.svg",
|
||||
"entry": "main.ts",
|
||||
"permissions": {
|
||||
"network": ["auth.example.com", "api.example.com"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`permissions.network` accepts exact hostnames only. All plugin network requests must use HTTPS and hit this allowlist. `version` is required; the plugin is ignored when the app version is older than `minAppVersion`. Built-in plugins are pre-installed into `plugins/installed/` keyed by `version`: startup writes nothing when the version matches and resyncs the whole directory (pruning stale files) when it changes.
|
||||
|
||||
## Entry and capabilities
|
||||
|
||||
The host injects `cursor-byok:plugin`, `cursor-byok:provider`, `cursor-byok:model`, `cursor-byok:resource`, and the protocol helper `cursor-byok:protocol/openai-responses`.
|
||||
|
||||
```ts
|
||||
import { defineProviderPlugin } from "cursor-byok:plugin";
|
||||
import { streamOpenAiResponses, HttpError } from "cursor-byok:protocol/openai-responses";
|
||||
|
||||
export default defineProviderPlugin({
|
||||
providers: [{
|
||||
id: "subscription",
|
||||
displayName: "Example Subscription",
|
||||
providerType: "openai",
|
||||
resourceType: "account",
|
||||
models: {
|
||||
list: async ({ resource }, context) => {
|
||||
// Discover upstream models with the first ready resource; the return
|
||||
// value replaces the core-side catalog.
|
||||
return [{ id: "model-1", displayName: "Model 1", capabilities: { thinking: true } }];
|
||||
},
|
||||
},
|
||||
invoke: async (input, output, context) => {
|
||||
try {
|
||||
await streamOpenAiResponses({
|
||||
url: "https://api.example.com/v1/responses",
|
||||
model: input.model.id,
|
||||
request: input.request,
|
||||
headers: { authorization: `Bearer ${token(input.resource)}` },
|
||||
}, output, context);
|
||||
return { status: "completed" };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError && error.status === 401) {
|
||||
return {
|
||||
status: "resource-error",
|
||||
message: error.message,
|
||||
patch: { state: { status: "invalid", message: "sign in again" } },
|
||||
};
|
||||
}
|
||||
return { status: "request-error", message: String(error) };
|
||||
}
|
||||
},
|
||||
}],
|
||||
resources: [{
|
||||
type: "account",
|
||||
displayName: "Accounts",
|
||||
add: [{
|
||||
type: "oauth2.0",
|
||||
id: "device",
|
||||
displayName: "Sign in",
|
||||
begin: async (context) => ({
|
||||
session: { deviceCode: "..." },
|
||||
userCode: "ABCD-EFGH",
|
||||
verificationUrl: "https://auth.example.com/device",
|
||||
expiresAtMs: Date.now() + 900_000,
|
||||
pollIntervalMs: 5_000,
|
||||
}),
|
||||
poll: async (session, context) => ({
|
||||
status: "completed",
|
||||
resources: [{ key: "account:1", privateData: { accessToken: "..." } }],
|
||||
}),
|
||||
}],
|
||||
present: (resource) => ({
|
||||
displayName: "person@example.com",
|
||||
metrics: [{ id: "weekly", label: "Weekly quota", unit: "percent", value: 75 }],
|
||||
}),
|
||||
refresh: async (resource, context) => ({ privateData: { /* updated quota */ } }),
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
## Ownership boundaries
|
||||
|
||||
- **The core owns**: resource persistence and dedupe (upsert by `draft.key`), resource list UI, the OAuth poll loop (interval, slow-down, expiry), model catalog storage, per-call resource selection (currently the first ready resource; cooling expires automatically), call records and statistics.
|
||||
- **The plugin owns**: authentication HTTP transitions (`begin`/`poll`), credential parsing (`import.parse`), resource presentation (`present`), quota refresh (`refresh`), and protocol adaptation with streaming execution (`invoke`).
|
||||
|
||||
`invoke` receives the full `LlmRequest` (instructions, message history, tools, reasoning config), parses the upstream SSE while emitting normalized events through `output.emit()` (text/thinking boundaries, incremental tool arguments, replay state, usage, finish reason), and finally returns `completed` or a typed error. The `patch` carried by `resource-error` is applied atomically to the selected resource and is the basis for future load-balanced retries.
|
||||
|
||||
Stable model IDs take the form `plugin:<plugin-id>/<provider-id>/<model-id>`; every enumerated model enters the Cursor catalog independently.
|
||||
|
||||
## Host context
|
||||
|
||||
- `context.network.fetch(url, init)`: one-shot HTTPS request, strictly allowlisted.
|
||||
- `context.network.stream(url, init)`: streaming response iterated line by line (for SSE).
|
||||
- `context.signal`: fires when the host cancels the call.
|
||||
|
||||
## Sandbox
|
||||
|
||||
The Deno process can only read its own plugin directory and the host SDK directory. Remote modules, npm packages, direct network access, environment variables, subprocesses, and file writes are all disabled. The worker multiplexes requests by request ID; a crash fails the current request and restarts on demand.
|
||||
|
||||
## Validation
|
||||
|
||||
```bash
|
||||
deno check --no-config --no-lock --no-npm --no-remote \
|
||||
--import-map=server/src/plugin/sdk/import-map.json \
|
||||
server/plugins/build-in/my-plugin/main.ts
|
||||
|
||||
deno test --no-config --no-lock --no-npm --no-remote \
|
||||
--import-map=server/src/plugin/sdk/import-map.json \
|
||||
server/plugins/build-in/my-plugin/plugin_test.ts
|
||||
```
|
||||
@@ -1,144 +0,0 @@
|
||||
---
|
||||
title: 插件开发
|
||||
description: 用无状态 TypeScript 插件实现 Provider 执行、模型枚举、资源接入与 OAuth 登录。
|
||||
icon: Blocks
|
||||
---
|
||||
|
||||
插件实现核心定义的三种能力接口:**Provider**(执行一次 LLM 调用)、**Model**(枚举可用模型)、**Resource**(账号等凭证资源)。插件不持有任何持久状态——资源与模型目录由核心存储,每次调用所需数据都通过参数传入。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```text
|
||||
~/.cursor-byok-v3/plugins/
|
||||
├── installed/
|
||||
│ └── com.example.subscription/
|
||||
│ ├── plugin.json # 静态身份、入口、图标和 HTTPS 主机白名单
|
||||
│ ├── main.ts # defineProviderPlugin 组合 providers 与 resources
|
||||
│ └── assets/icon.svg # 本地图标,最大 1 MiB
|
||||
└── data/
|
||||
└── com.example.subscription/
|
||||
├── resources-<type>.json # 核心持久化的资源记录(0600)
|
||||
└── models-<provider>.json # 核心持久化的模型目录
|
||||
```
|
||||
|
||||
内置插件源码位于 `server/plugins/build-in/`(如 `codex-auth`),随二进制打包并按版本预装进 `plugins/installed/`;Debug 构建下源码目录优先加载,便于热改。
|
||||
|
||||
## 静态清单
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"id": "com.example.subscription",
|
||||
"name": "Example Subscription",
|
||||
"version": "0.1.0",
|
||||
"author": "@example",
|
||||
"minAppVersion": "0.1.0",
|
||||
"icon": "assets/icon.svg",
|
||||
"entry": "main.ts",
|
||||
"permissions": {
|
||||
"network": ["auth.example.com", "api.example.com"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`permissions.network` 只能包含精确主机名。所有插件网络请求都必须是 HTTPS 且命中该白名单。`version` 必填;应用版本低于 `minAppVersion` 时插件会被忽略。内置插件按 `version` 预装进 `plugins/installed/`:版本一致时启动零写盘,版本变化时整目录同步并清理旧文件。
|
||||
|
||||
## 入口与能力
|
||||
|
||||
宿主注入 `cursor-byok:plugin`、`cursor-byok:provider`、`cursor-byok:model`、`cursor-byok:resource` 与协议帮助库 `cursor-byok:protocol/openai-responses`。
|
||||
|
||||
```ts
|
||||
import { defineProviderPlugin } from "cursor-byok:plugin";
|
||||
import { streamOpenAiResponses, HttpError } from "cursor-byok:protocol/openai-responses";
|
||||
|
||||
export default defineProviderPlugin({
|
||||
providers: [{
|
||||
id: "subscription",
|
||||
displayName: "Example Subscription",
|
||||
providerType: "openai",
|
||||
resourceType: "account",
|
||||
models: {
|
||||
list: async ({ resource }, context) => {
|
||||
// 用首个可用资源发现上游模型;返回值整体替换核心目录。
|
||||
return [{ id: "model-1", displayName: "Model 1", capabilities: { thinking: true } }];
|
||||
},
|
||||
},
|
||||
invoke: async (input, output, context) => {
|
||||
try {
|
||||
await streamOpenAiResponses({
|
||||
url: "https://api.example.com/v1/responses",
|
||||
model: input.model.id,
|
||||
request: input.request,
|
||||
headers: { authorization: `Bearer ${token(input.resource)}` },
|
||||
}, output, context);
|
||||
return { status: "completed" };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError && error.status === 401) {
|
||||
return {
|
||||
status: "resource-error",
|
||||
message: error.message,
|
||||
patch: { state: { status: "invalid", message: "sign in again" } },
|
||||
};
|
||||
}
|
||||
return { status: "request-error", message: String(error) };
|
||||
}
|
||||
},
|
||||
}],
|
||||
resources: [{
|
||||
type: "account",
|
||||
displayName: "Accounts",
|
||||
add: [{
|
||||
type: "oauth2.0",
|
||||
id: "device",
|
||||
displayName: "Sign in",
|
||||
begin: async (context) => ({
|
||||
session: { deviceCode: "..." },
|
||||
userCode: "ABCD-EFGH",
|
||||
verificationUrl: "https://auth.example.com/device",
|
||||
expiresAtMs: Date.now() + 900_000,
|
||||
pollIntervalMs: 5_000,
|
||||
}),
|
||||
poll: async (session, context) => ({
|
||||
status: "completed",
|
||||
resources: [{ key: "account:1", privateData: { accessToken: "..." } }],
|
||||
}),
|
||||
}],
|
||||
present: (resource) => ({
|
||||
displayName: "person@example.com",
|
||||
metrics: [{ id: "weekly", label: "Weekly quota", unit: "percent", value: 75 }],
|
||||
}),
|
||||
refresh: async (resource, context) => ({ privateData: { /* 更新额度 */ } }),
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
## 职责边界
|
||||
|
||||
- **核心负责**:资源持久化与去重(按 `draft.key` upsert)、资源列表 UI、OAuth 轮询循环(间隔、slow-down、超时)、模型目录存储、每次调用的资源选择(当前取首个可用,冷却到期自动恢复)、调用记录与统计。
|
||||
- **插件负责**:认证 HTTP 转移(`begin`/`poll`)、凭证解析(`import.parse`)、资源展示投影(`present`)、额度刷新(`refresh`)、协议适配与流式执行(`invoke`)。
|
||||
|
||||
`invoke` 接收完整 `LlmRequest`(指令、消息历史、工具、思考配置),边解析上游 SSE 边 `output.emit()` 标准化事件(文本/思考边界、工具参数增量、回放状态、用量、结束原因),最后返回 `completed` 或类型化错误。`resource-error` 携带的 `patch` 会被核心原子应用到选中的资源,是未来负载均衡换资源重试的依据。
|
||||
|
||||
稳定模型 ID 为 `plugin:<plugin-id>/<provider-id>/<model-id>`,每个枚举出的模型都独立进入 Cursor 模型目录。
|
||||
|
||||
## 宿主上下文
|
||||
|
||||
- `context.network.fetch(url, init)`:一次性 HTTPS 请求,严格执行清单白名单。
|
||||
- `context.network.stream(url, init)`:流式响应,按行异步迭代(用于 SSE)。
|
||||
- `context.signal`:宿主取消本次调用时触发。
|
||||
|
||||
## 沙箱
|
||||
|
||||
Deno 进程只能读取自身插件目录和宿主 SDK 目录。远程模块、npm 包、直接网络、环境变量、子进程和文件写入均被禁用。Worker 按请求 ID 多路复用,崩溃时当前请求失败并按需重启。
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
deno check --no-config --no-lock --no-npm --no-remote \
|
||||
--import-map=server/src/plugin/sdk/import-map.json \
|
||||
server/plugins/build-in/my-plugin/main.ts
|
||||
|
||||
deno test --no-config --no-lock --no-npm --no-remote \
|
||||
--import-map=server/src/plugin/sdk/import-map.json \
|
||||
server/plugins/build-in/my-plugin/plugin_test.ts
|
||||
```
|
||||
@@ -1,27 +0,0 @@
|
||||
---
|
||||
title: TAB Service
|
||||
description: Choose how Cursor connects to Tab completion endpoints.
|
||||
icon: Zap
|
||||
---
|
||||
|
||||
Cursor's Tab completion does not go through model channels — it is handled by a separate Tab service. Cursor Byok offers three connection modes under **System settings → TAB settings**.
|
||||
|
||||

|
||||
|
||||
## The three modes
|
||||
|
||||
### Use public service (default)
|
||||
|
||||
Uses the public Tab service hosted by the project author. Works out of the box with no configuration.
|
||||
|
||||
### Direct
|
||||
|
||||
Connects directly to the official Tab service of the account signed in to your Cursor client. Suitable if your account has official quota.
|
||||
|
||||
### Custom
|
||||
|
||||
Deploy your own [cursor-tab-server](https://github.com/leookun/cursor-byok/tree/archive/v0.0.49/cursor-tab-server), then enter your service URL in **TAB service address**. The original endpoint path is appended to that address.
|
||||
|
||||
<Callout type="info">
|
||||
After changing TAB settings, restart Cursor and start a new conversation to make sure the connection mode takes effect.
|
||||
</Callout>
|
||||
@@ -1,27 +0,0 @@
|
||||
---
|
||||
title: TAB 服务
|
||||
description: 选择 Cursor Tab 补全接口的连接方式。
|
||||
icon: Zap
|
||||
---
|
||||
|
||||
Cursor 的 Tab 补全不走模型通道,而是由单独的 Tab 服务处理。Cursor Byok 在 **系统设置 → TAB 设置** 中提供三种连接方式。
|
||||
|
||||

|
||||
|
||||
## 三种模式
|
||||
|
||||
### 使用公益服务(默认)
|
||||
|
||||
使用由项目作者部署的公共 Tab 服务,开箱即用,无需任何配置。
|
||||
|
||||
### 直连
|
||||
|
||||
直接使用你在 Cursor 客户端中登录账号的官方 Tab 服务。适合账号本身有官方额度的用户。
|
||||
|
||||
### 自定义
|
||||
|
||||
自行部署 [cursor-tab-server](https://github.com/leookun/cursor-byok/tree/archive/v0.0.49/cursor-tab-server),然后在 **TAB 服务地址** 中填入你的服务地址。原接口路径会追加到该地址之后。
|
||||
|
||||
<Callout type="info">
|
||||
修改 TAB 设置后,建议重启 Cursor 并新开一个对话,确保连接方式生效。
|
||||
</Callout>
|
||||
@@ -1,19 +0,0 @@
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import nextVitals from 'eslint-config-next/core-web-vitals';
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
globalIgnores([
|
||||
'.next/**',
|
||||
'out/**',
|
||||
'build/**',
|
||||
'next-env.d.ts',
|
||||
'.source/**',
|
||||
'public/product-demo/**',
|
||||
'.open-next/**',
|
||||
'.wrangler/**',
|
||||
'cloudflare-env.d.ts',
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -1,37 +0,0 @@
|
||||
import { loader } from 'fumadocs-core/source';
|
||||
import { pageSchema } from 'fumadocs-core/source/schema';
|
||||
import { defineCollections } from 'fumadocs-mdx/macro';
|
||||
import { htmlLang, i18n, type Language } from './i18n';
|
||||
|
||||
const blog = defineCollections({
|
||||
type: 'doc',
|
||||
dir: 'content/blog',
|
||||
schema: pageSchema,
|
||||
});
|
||||
|
||||
export const blogSource = loader({
|
||||
baseUrl: '/blog',
|
||||
source: blog.toFumadocsSource(),
|
||||
i18n,
|
||||
});
|
||||
|
||||
export function getBlogDate(path: string): Date {
|
||||
const fileName = path.split('/').at(-1) ?? '';
|
||||
const match = /^(\d{4}-\d{2}-\d{2})/.exec(fileName);
|
||||
return match ? new Date(`${match[1]}T00:00:00Z`) : new Date(0);
|
||||
}
|
||||
|
||||
export function formatBlogDate(path: string, lang: Language = i18n.defaultLanguage): string {
|
||||
return new Intl.DateTimeFormat(htmlLang[lang], {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
timeZone: 'UTC',
|
||||
}).format(getBlogDate(path));
|
||||
}
|
||||
|
||||
export function sortBlogPages<T extends { path: string }>(pages: T[]): T[] {
|
||||
return [...pages].sort((left, right) => {
|
||||
return getBlogDate(right.path).getTime() - getBlogDate(left.path).getTime();
|
||||
});
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { cn } from 'cnfast';
|
||||
@@ -1,40 +0,0 @@
|
||||
import { gitConfig } from './shared';
|
||||
|
||||
export type RepoStats = {
|
||||
stars: number | null;
|
||||
version: string | null;
|
||||
};
|
||||
|
||||
async function fetchJson(url: string): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
// 构建期取一次并静态化;数据随每次部署更新,运行时无需 ISR 缓存设施
|
||||
const res = await fetch(url, {
|
||||
headers: { Accept: 'application/vnd.github+json' },
|
||||
cache: 'force-cache',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRepoStats(): Promise<RepoStats> {
|
||||
const base = `https://api.github.com/repos/${gitConfig.user}/${gitConfig.repo}`;
|
||||
const [repo, release] = await Promise.all([
|
||||
fetchJson(base),
|
||||
fetchJson(`${base}/releases/latest`),
|
||||
]);
|
||||
|
||||
return {
|
||||
stars: typeof repo?.stargazers_count === 'number' ? repo.stargazers_count : null,
|
||||
version: typeof release?.tag_name === 'string' ? release.tag_name : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStars(stars: number): string {
|
||||
return new Intl.NumberFormat('en', {
|
||||
notation: 'compact',
|
||||
maximumFractionDigits: 1,
|
||||
}).format(stars);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { defineI18n } from 'fumadocs-core/i18n';
|
||||
|
||||
export const i18n = defineI18n({
|
||||
defaultLanguage: 'zh',
|
||||
languages: ['zh', 'en'],
|
||||
// 所有语言显式带前缀;未带前缀的访问由中间件按浏览器 Accept-Language 协商后重定向
|
||||
hideLocale: 'never',
|
||||
});
|
||||
|
||||
export type Language = (typeof i18n)['languages'][number];
|
||||
|
||||
export function isLanguage(value: string): value is Language {
|
||||
return i18n.languages.some((lang) => lang === value);
|
||||
}
|
||||
|
||||
/** HTML `lang` attribute values. */
|
||||
export const htmlLang: Record<Language, string> = {
|
||||
zh: 'zh-CN',
|
||||
en: 'en',
|
||||
};
|
||||
|
||||
/** Locale ids understood by the desktop app / demo. */
|
||||
export const demoLocale: Record<Language, string> = {
|
||||
zh: 'zh-CN',
|
||||
en: 'en-US',
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
import Image from 'next/image';
|
||||
import { zhCN } from '@fumadocs/language/zh-cn';
|
||||
import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';
|
||||
import { uiTranslations } from 'fumadocs-ui/i18n';
|
||||
import { blogSource } from './blog';
|
||||
import { i18n, type Language } from './i18n';
|
||||
import { appName, gitConfig, releaseUrl } from './shared';
|
||||
|
||||
export const translations = i18n.translations().extend(uiTranslations()).preset('zh', zhCN());
|
||||
|
||||
const navLabels: Record<Language, { docs: string; blog: string; download: string }> = {
|
||||
zh: { docs: '文档', blog: '开发者博客', download: '下载' },
|
||||
en: { docs: 'Docs', blog: 'Blog', download: 'Download' },
|
||||
};
|
||||
|
||||
export function baseOptions(lang: Language): BaseLayoutProps {
|
||||
const labels = navLabels[lang];
|
||||
const prefix = `/${lang}`;
|
||||
|
||||
return {
|
||||
nav: {
|
||||
title: (
|
||||
<>
|
||||
<Image src="/images/logo.png" alt="" width={20} height={20} className="rounded-[5px]" />
|
||||
{appName}
|
||||
</>
|
||||
),
|
||||
},
|
||||
links: [
|
||||
{
|
||||
text: labels.docs,
|
||||
url: `${prefix}/docs`,
|
||||
},
|
||||
...(blogSource.getPages(lang).length > 0
|
||||
? [
|
||||
{
|
||||
text: labels.blog,
|
||||
url: `${prefix}/blog`,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
text: labels.download,
|
||||
url: releaseUrl,
|
||||
external: true,
|
||||
},
|
||||
],
|
||||
githubUrl: `https://github.com/${gitConfig.user}/${gitConfig.repo}`,
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
export const appName = 'Cursor Byok';
|
||||
export const appDescription = 'Cursor 服务端的开源替代';
|
||||
export const docsRoute = '/docs';
|
||||
export const docsImageRoute = '/og/docs';
|
||||
export const docsContentRoute = '/llms.mdx/docs';
|
||||
export const repositoryUrl = 'https://github.com/leookun/cursor-byok';
|
||||
export const releaseUrl = `${repositoryUrl}/releases/latest`;
|
||||
|
||||
export const gitConfig = {
|
||||
user: 'leookun',
|
||||
repo: 'cursor-byok',
|
||||
branch: 'main',
|
||||
};
|
||||
@@ -1,62 +0,0 @@
|
||||
import { loader } from 'fumadocs-core/source';
|
||||
import { lucideIconsPlugin } from 'fumadocs-core/source/lucide-icons';
|
||||
import { docsContentRoute, docsImageRoute, docsRoute } from './shared';
|
||||
import { defineDocs } from 'fumadocs-mdx/macro';
|
||||
import { metaSchema, pageSchema } from 'fumadocs-core/source/schema';
|
||||
import { i18n } from './i18n';
|
||||
|
||||
const docs = defineDocs({
|
||||
dir: 'content/docs',
|
||||
docs: {
|
||||
schema: pageSchema,
|
||||
postprocess: {
|
||||
includeProcessedMarkdown: true,
|
||||
},
|
||||
},
|
||||
meta: {
|
||||
schema: metaSchema,
|
||||
},
|
||||
});
|
||||
|
||||
// See https://fumadocs.dev/docs/headless/source-api for more info
|
||||
export const source = loader({
|
||||
baseUrl: docsRoute,
|
||||
source: docs.toFumadocsSource(),
|
||||
plugins: [lucideIconsPlugin()],
|
||||
i18n,
|
||||
});
|
||||
|
||||
/** Locale URL prefix segment; all locales are explicit (hideLocale: 'never'). */
|
||||
function localeSegment(page: (typeof source)['$inferPage']): string | undefined {
|
||||
return page.locale;
|
||||
}
|
||||
|
||||
export function getPageImageUrl(page: (typeof source)['$inferPage']) {
|
||||
const segments = [...page.slugs, 'image.png'];
|
||||
|
||||
return {
|
||||
segments,
|
||||
url:
|
||||
'/' +
|
||||
[localeSegment(page), ...docsImageRoute.split('/'), ...segments].filter(Boolean).join('/'),
|
||||
};
|
||||
}
|
||||
|
||||
export function getPageMarkdownUrl(page: (typeof source)['$inferPage']) {
|
||||
const segments = [...page.slugs, 'content.md'];
|
||||
|
||||
return {
|
||||
segments,
|
||||
url:
|
||||
'/' +
|
||||
[localeSegment(page), ...docsContentRoute.split('/'), ...segments].filter(Boolean).join('/'),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getLLMText(page: (typeof source)['$inferPage']) {
|
||||
const processed = await page.data.getText('processed');
|
||||
|
||||
return `# ${page.data.title} (${page.url})
|
||||
|
||||
${processed}`;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { createMDX } from 'fumadocs-mdx/next';
|
||||
|
||||
const withMDX = createMDX();
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const config = {
|
||||
reactStrictMode: true,
|
||||
images: {
|
||||
// 站内图片均为已按展示尺寸截取的静态资源,直接由 CDN 提供,
|
||||
// 避免在 Cloudflare Workers 上依赖运行时图片优化服务。
|
||||
unoptimized: true,
|
||||
},
|
||||
};
|
||||
|
||||
export default withMDX(config);
|
||||
@@ -1,4 +0,0 @@
|
||||
import { defineCloudflareConfig } from '@opennextjs/cloudflare';
|
||||
|
||||
// 站点全部页面在构建期静态生成,无需增量缓存 / 队列等运行时缓存设施。
|
||||
export default defineCloudflareConfig({});
|
||||
@@ -1,45 +0,0 @@
|
||||
{
|
||||
"name": "cursor-byok-docs",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build:product-demo": "node scripts/build-product-demo.mjs",
|
||||
"prebuild": "npm run build:product-demo",
|
||||
"build": "next build",
|
||||
"predev": "npm run build:product-demo",
|
||||
"dev": "next dev",
|
||||
"start": "next start",
|
||||
"types:check": "next typegen && tsc --noEmit",
|
||||
"lint": "eslint",
|
||||
"check": "npm run types:check && npm run lint && npm run build",
|
||||
"preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
|
||||
"deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
|
||||
"upload": "opennextjs-cloudflare build && opennextjs-cloudflare upload",
|
||||
"cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fumadocs/language": "^0.2.4",
|
||||
"@opennextjs/cloudflare": "^1.20.4",
|
||||
"cnfast": "^0.1.0",
|
||||
"fumadocs-core": "16.15.2",
|
||||
"fumadocs-mdx": "15.3.1",
|
||||
"fumadocs-ui": "npm:@fumadocs/base-ui@16.15.2",
|
||||
"lucide-react": "^1.34.0",
|
||||
"next": "16.3",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@types/mdx": "^2.0.14",
|
||||
"@types/node": "^26.3.0",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.5",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-config-next": "16.3",
|
||||
"postcss": "^8.5.26",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.3",
|
||||
"wrangler": "^4.127.0"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -1,53 +0,0 @@
|
||||
import { NextRequest, NextResponse, type NextFetchEvent } from 'next/server';
|
||||
import { isMarkdownPreferred, rewritePath } from 'fumadocs-core/negotiation';
|
||||
import { createI18nMiddleware } from 'fumadocs-core/i18n/middleware';
|
||||
import { i18n, type Language } from '@/lib/i18n';
|
||||
import { docsContentRoute, docsRoute } from '@/lib/shared';
|
||||
|
||||
const { rewrite: rewriteDocs } = rewritePath(
|
||||
`${docsRoute}{/*path}`,
|
||||
`${docsContentRoute}{/*path}/content.md`,
|
||||
);
|
||||
const { rewrite: rewriteSuffix } = rewritePath(
|
||||
`${docsRoute}{/*path}.md`,
|
||||
`${docsContentRoute}{/*path}/content.md`,
|
||||
);
|
||||
|
||||
const i18nMiddleware = createI18nMiddleware(i18n);
|
||||
|
||||
/** Split the locale prefix (if any) from a pathname. */
|
||||
function splitLocale(pathname: string): { locale: Language; rest: string } {
|
||||
for (const lang of i18n.languages) {
|
||||
if (pathname === `/${lang}`) return { locale: lang, rest: '/' };
|
||||
if (pathname.startsWith(`/${lang}/`)) {
|
||||
return { locale: lang, rest: pathname.slice(lang.length + 1) };
|
||||
}
|
||||
}
|
||||
return { locale: i18n.defaultLanguage, rest: pathname };
|
||||
}
|
||||
|
||||
export default function proxy(request: NextRequest, event: NextFetchEvent) {
|
||||
const { locale, rest } = splitLocale(request.nextUrl.pathname);
|
||||
|
||||
const suffixTarget = rewriteSuffix(rest);
|
||||
if (suffixTarget) {
|
||||
return NextResponse.rewrite(new URL(`/${locale}${suffixTarget}`, request.nextUrl));
|
||||
}
|
||||
|
||||
if (isMarkdownPreferred(request)) {
|
||||
const target = rewriteDocs(rest);
|
||||
|
||||
if (target) {
|
||||
return NextResponse.rewrite(new URL(`/${locale}${target}`, request.nextUrl), {
|
||||
// this URL has two representations, selected by `Accept`
|
||||
headers: { Vary: 'Accept' },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return i18nMiddleware(request, event);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/((?!api|_next|favicon.ico|icon.png|images/|product-demo/|llms\\.txt|llms-full\\.txt).*)'],
|
||||
};
|
||||
|
Before Width: | Height: | Size: 179 KiB |
|
Before Width: | Height: | Size: 172 KiB |
|
Before Width: | Height: | Size: 248 KiB |
|
Before Width: | Height: | Size: 244 KiB |
|
Before Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 130 KiB |
|
Before Width: | Height: | Size: 128 KiB |
|
Before Width: | Height: | Size: 130 KiB |
|
Before Width: | Height: | Size: 128 KiB |
@@ -1,22 +0,0 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
|
||||
const docsRoot = path.dirname(fileURLToPath(new URL('../package.json', import.meta.url)));
|
||||
const desktopRoot = path.resolve(docsRoot, '../desktop');
|
||||
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const vite = path.join(desktopRoot, 'node_modules', '.bin', process.platform === 'win32' ? 'vite.cmd' : 'vite');
|
||||
|
||||
if (!existsSync(vite)) run(['ci'], desktopRoot);
|
||||
run(['run', 'build:demo'], desktopRoot);
|
||||
|
||||
function run(args, cwd) {
|
||||
const result = spawnSync(npm, args, {
|
||||
cwd,
|
||||
stdio: 'inherit',
|
||||
shell: process.platform === 'win32',
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"name": "cursor-byok-docs",
|
||||
"main": ".open-next/worker.js",
|
||||
"compatibility_date": "2025-09-01",
|
||||
"compatibility_flags": [
|
||||
// 启用 Node.js API,OpenNext 运行时需要
|
||||
"nodejs_compat",
|
||||
// 只允许 fetch 公网地址
|
||||
"global_fetch_strictly_public"
|
||||
],
|
||||
"assets": {
|
||||
"directory": ".open-next/assets",
|
||||
"binding": "ASSETS"
|
||||
},
|
||||
"services": [
|
||||
{
|
||||
"binding": "WORKER_SELF_REFERENCE",
|
||||
"service": "cursor-byok-docs"
|
||||
}
|
||||
]
|
||||
// 绑定自定义域名(要求 leokun.cn 的 DNS 托管在同一 Cloudflare 账号)时取消注释:
|
||||
// "routes": [{ "pattern": "docs.leokun.cn", "custom_domain": true }]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# Git Commit Message Generation Guide
|
||||
|
||||
## Role and objective
|
||||
|
||||
You are a Git commit message generator. Given a Git diff, output only the commit message itself, without explanations, preambles, quotation marks, or additional text. Your entire response will be passed directly to `git commit`.
|
||||
|
||||
## General rules for subjects
|
||||
|
||||
- Use the present tense and describe the key change in the diff precisely.
|
||||
- Focus on what changed instead of listing file names.
|
||||
- Be specific: include concrete details such as package names, versions, or features, and avoid vague descriptions.
|
||||
- Exclude unnecessary content such as translation notes.
|
||||
- Keep the subject at or below 50 characters.
|
||||
- Write the commit message in English regardless of the language used in the diff.
|
||||
- Output only the commit message text, without quotation marks, formatting wrappers, explanations, or preambles.
|
||||
|
||||
## Output format
|
||||
|
||||
Choose exactly one format based on `type`:
|
||||
|
||||
| type | Format template |
|
||||
| ----------------- | ----------------------------------------------------------- |
|
||||
| plain | `<commit message>` |
|
||||
| conventional | `<type>[optional (<scope>)]: <commit message>` |
|
||||
| conventional+body | `<type>[optional (<scope>)]: <commit message subject>` |
|
||||
| gitmoji | `:emoji: <commit message>` |
|
||||
| subject+body | `<commit message subject>` |
|
||||
|
||||
For `conventional` and `conventional+body`, the subject must begin with a lowercase letter. The output must strictly follow the selected format.
|
||||
|
||||
## Conventional type selection
|
||||
|
||||
Choose the single type that best matches the diff. The type must be lowercase, such as `feat`, never `Feat` or `FEAT`.
|
||||
|
||||
```json
|
||||
{
|
||||
"docs": "documentation-only changes",
|
||||
"style": "changes that do not affect code meaning, such as whitespace, formatting, or missing semicolons",
|
||||
"refactor": "code structure improvements that do not change behavior, such as renaming, restructuring methods, or extracting functions",
|
||||
"perf": "code changes that improve performance",
|
||||
"test": "adding missing tests or correcting existing tests",
|
||||
"build": "changes that affect the build system or external dependencies",
|
||||
"ci": "changes to CI configuration and scripts",
|
||||
"chore": "other changes that do not modify src or test files",
|
||||
"revert": "reverting a previous commit",
|
||||
"feat": "a new feature",
|
||||
"fix": "a bug fix"
|
||||
}
|
||||
```
|
||||
|
||||
- For `conventional`, output the complete conventional subject line.
|
||||
- For `conventional+body`, output only the conventional subject line; the body is generated separately.
|
||||
|
||||
## Body generation rules
|
||||
|
||||
When a commit subject is already provided and a description is requested, output only the commit body:
|
||||
|
||||
- Keep it concise: use 3–6 short bullet points, one per line, or 2–4 short sentences.
|
||||
- Use the present tense and focus on what changed and why.
|
||||
- Keep every line at or below 72 characters. Indent wrapped bullet lines by two spaces so they align with the bullet text.
|
||||
- Do not repeat the subject or add meta commentary such as “This commit”.
|
||||
- Write in English.
|
||||
- Output only the body, without any additional text.
|
||||
- Describe concrete changes clearly; avoid vague phrases such as “update functionality” or “modify resources”.
|
||||
- Every commit subject must have a prefix and must not use emoji. If the changes cover separate concerns, such as visual improvements and bug fixes, split them into separate entries, for example:
|
||||
- `fix(<specific area>): fix the xxx issue`
|
||||
- `chore(<specific area>): update visual assets`
|
||||
@@ -49,7 +49,6 @@
|
||||
- `conventional`:直接按上表选择类型并输出完整主题行。
|
||||
- `conventional+body`:只输出 conventional 主题行,body 会单独生成。
|
||||
|
||||
|
||||
## 描述(body)生成规则
|
||||
|
||||
当已有提交标题、需要生成描述时,给你标题与 diff,你只输出提交描述正文:
|
||||
@@ -60,7 +59,7 @@
|
||||
- 不要重复标题,不要元评论(如「本次提交……」)。
|
||||
- 语言:简体中文。
|
||||
- 只输出提交描述正文,不要有其他内容。
|
||||
- 修改点要列举清除明白,不能笼统的说「更新功能,修改资源」这种概括性描述。
|
||||
- 提交必须要有前缀,提交信息不允许有emoji,如果存在多个提交功能,比如美化和bug修改,分开写多个 例如:
|
||||
- bugfix(*具体修改项*): 修复xxxbug问题
|
||||
- chore(*具体修改项*): 修改美术资源
|
||||
- 修改点要列举清楚明白,不能笼统地说“更新功能、修改资源”。
|
||||
- 提交必须有前缀,且不允许使用 emoji。如果存在多个提交功能,例如美化和缺陷修复,应拆分成多条,例如:
|
||||
- `fix(<具体修改项>): 修复 xxx 问题`
|
||||
- `chore(<具体修改项>): 修改美术资源`
|
||||
@@ -20,7 +20,8 @@ use crate::{
|
||||
proto::{agent::v1 as agent, aiserver::v1 as ai},
|
||||
},
|
||||
services::{
|
||||
account, analytics, commit_message, knowledge, model_catalog, server_config, tab,
|
||||
account, analytics, commit_message, compatibility, entitlement::FreeEntitlementCache,
|
||||
knowledge, model_catalog, server_config, tab,
|
||||
},
|
||||
transport::{TransportParent, TransportRegistry},
|
||||
},
|
||||
@@ -42,10 +43,27 @@ fn router_with_proxy(
|
||||
knowledge_service: knowledge::KnowledgeService,
|
||||
) -> Router {
|
||||
let web_cache = registry.web_cache().router();
|
||||
let free_entitlements = FreeEntitlementCache::default();
|
||||
Router::new()
|
||||
.route("/__byok-api__/healthz", get(health))
|
||||
.route("/agent.v1.AgentService/RunSSE", post(run_sse_handler))
|
||||
.route("/aiserver.v1.BidiService/BidiAppend", post(bidi_handler))
|
||||
.route(
|
||||
"/aiserver.v1.AiService/AvailableDocs",
|
||||
post(compatibility::available_docs),
|
||||
)
|
||||
.route(
|
||||
"/aiserver.v1.DashboardService/GetEffectiveUserPlugins",
|
||||
post(compatibility::effective_user_plugins),
|
||||
)
|
||||
.route(
|
||||
"/aiserver.v1.DashboardService/GetUserPrivacyMode",
|
||||
post(compatibility::user_privacy_mode),
|
||||
)
|
||||
.route(
|
||||
"/agent.v1.AgentService/UpdateConversationMetadata",
|
||||
post(compatibility::update_conversation_metadata),
|
||||
)
|
||||
.route(
|
||||
"/aiserver.v1.AiService/GetServerConfig",
|
||||
post(server_config::get),
|
||||
@@ -94,6 +112,10 @@ fn router_with_proxy(
|
||||
"/aiserver.v1.AuthService/GetEmail",
|
||||
post(account::get_email),
|
||||
)
|
||||
.route(
|
||||
"/aiserver.v1.AuthService/GetUserMeta",
|
||||
post(account::get_user_meta),
|
||||
)
|
||||
.route("/aiserver.v1.DashboardService/GetMe", post(account::get_me))
|
||||
.route(
|
||||
"/aiserver.v1.DashboardService/GetTeams",
|
||||
@@ -132,6 +154,7 @@ fn router_with_proxy(
|
||||
post(analytics::bootstrap_statsig),
|
||||
)
|
||||
.route("/auth/full_stripe_profile", get(account::stripe_profile))
|
||||
.route("/auth/stripe_profile", get(account::stripe_profile))
|
||||
.merge(tab::router())
|
||||
.route_layer(DefaultBodyLimit::disable())
|
||||
.route_layer(RequestDecompressionLayer::new())
|
||||
@@ -139,6 +162,7 @@ fn router_with_proxy(
|
||||
.method_not_allowed_fallback(proxy::forward)
|
||||
.layer(Extension(proxy))
|
||||
.layer(Extension(knowledge_service))
|
||||
.layer(Extension(free_entitlements))
|
||||
.with_state(registry)
|
||||
.merge(web_cache)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
//! Implements advertisement configuration endpoints.
|
||||
//! Advertisement service contract and desktop HTTP handler.
|
||||
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
path::{Path as FilePath, PathBuf},
|
||||
};
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
http::{header, HeaderMap, HeaderValue, Response, StatusCode},
|
||||
Json,
|
||||
};
|
||||
use bytes::BytesMut;
|
||||
use futures_util::StreamExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{Error, Result};
|
||||
use crate::{config, Error, Result};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
@@ -23,6 +33,9 @@ pub(super) const OS_HEADER: &str = "X-Cursor-Assistant-OS";
|
||||
pub(super) const APP_VERSION_HEADER: &str = "X-Cursor-Assistant-Version";
|
||||
pub(super) const DISABLED_AD_IDS_HEADER: &str = "disable-ad-ids";
|
||||
pub(super) const LANGUAGE_HEADER: &str = "accept-language";
|
||||
const ADS_IMAGE_ROUTE: &str = "/__byok-api__/api/ads/images";
|
||||
const MAX_AD_IMAGE_BYTES: usize = 10 * 1024 * 1024;
|
||||
const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "gif", "webp", "avif"];
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdRuntime {
|
||||
@@ -104,6 +117,137 @@ impl AdRuntime {
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub(super) async fn cache_images(&mut self, client: &reqwest::Client) {
|
||||
let cache_dir = match config::managed_data_dir() {
|
||||
Ok(path) => path.join("ads"),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to resolve advertisement image cache directory");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let urls = self
|
||||
.slots
|
||||
.iter()
|
||||
.flat_map(|slot| [&slot.target.image_url, &slot.content.image_url])
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
let downloads = futures_util::future::join_all(urls.iter().map(|url| {
|
||||
let cache_dir = &cache_dir;
|
||||
async move {
|
||||
let result = cache_image(client, cache_dir, url).await;
|
||||
(url, result)
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
let mut cached_urls = HashMap::new();
|
||||
for (url, result) in downloads {
|
||||
match result {
|
||||
Ok(cached_url) => {
|
||||
cached_urls.insert(url.as_str(), cached_url);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, image_url = %url, "failed to cache advertisement image")
|
||||
}
|
||||
}
|
||||
}
|
||||
for slot in &mut self.slots {
|
||||
if let Some(url) = cached_urls.get(slot.target.image_url.as_str()) {
|
||||
slot.target.image_url.clone_from(url);
|
||||
}
|
||||
if let Some(url) = cached_urls.get(slot.content.image_url.as_str()) {
|
||||
slot.content.image_url.clone_from(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn cache_image(client: &reqwest::Client, cache_dir: &FilePath, url: &str) -> Result<String> {
|
||||
tokio::fs::create_dir_all(cache_dir).await?;
|
||||
let hash = hex::encode(Sha256::digest(url.as_bytes()));
|
||||
if let Some(file_name) = cached_file_name(cache_dir, &hash).await {
|
||||
return Ok(format!("{ADS_IMAGE_ROUTE}/{file_name}"));
|
||||
}
|
||||
|
||||
let response = client
|
||||
.get(url)
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.send()
|
||||
.await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(Error::Provider(format!(
|
||||
"advertisement image download failed ({})",
|
||||
response.status()
|
||||
)));
|
||||
}
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(image_extension)
|
||||
.ok_or_else(|| {
|
||||
Error::Provider("advertisement image has an unsupported content type".into())
|
||||
})?;
|
||||
if response
|
||||
.content_length()
|
||||
.is_some_and(|length| length > MAX_AD_IMAGE_BYTES as u64)
|
||||
{
|
||||
return Err(Error::Provider("advertisement image exceeds 10 MiB".into()));
|
||||
}
|
||||
|
||||
let mut bytes = BytesMut::new();
|
||||
let mut stream = response.bytes_stream();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk?;
|
||||
if bytes.len() + chunk.len() > MAX_AD_IMAGE_BYTES {
|
||||
return Err(Error::Provider("advertisement image exceeds 10 MiB".into()));
|
||||
}
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
|
||||
let file_name = format!("{hash}.{content_type}");
|
||||
let destination = cache_dir.join(&file_name);
|
||||
let temporary = cache_dir.join(format!(".{file_name}.{}.tmp", Uuid::new_v4()));
|
||||
tokio::fs::write(&temporary, &bytes).await?;
|
||||
if let Err(error) = tokio::fs::rename(&temporary, &destination).await {
|
||||
if !destination.exists() {
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
return Err(error.into());
|
||||
}
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
}
|
||||
Ok(format!("{ADS_IMAGE_ROUTE}/{file_name}"))
|
||||
}
|
||||
|
||||
async fn cached_file_name(cache_dir: &FilePath, hash: &str) -> Option<String> {
|
||||
for extension in IMAGE_EXTENSIONS {
|
||||
let file_name = format!("{hash}.{extension}");
|
||||
if tokio::fs::metadata(cache_dir.join(&file_name))
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return Some(file_name);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn image_extension(content_type: &str) -> Option<&'static str> {
|
||||
match content_type
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
.as_str()
|
||||
{
|
||||
"image/png" => Some("png"),
|
||||
"image/jpeg" => Some("jpg"),
|
||||
"image/gif" => Some("gif"),
|
||||
"image/webp" => Some("webp"),
|
||||
"image/avif" => Some("avif"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_http_url(value: &str, field: &str) -> Result<()> {
|
||||
@@ -117,6 +261,54 @@ fn validate_http_url(value: &str, field: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn image(
|
||||
Path(file_name): Path<String>,
|
||||
) -> std::result::Result<Response<Body>, StatusCode> {
|
||||
let (hash, extension) = file_name.rsplit_once('.').ok_or(StatusCode::NOT_FOUND)?;
|
||||
if hash.len() != 64
|
||||
|| !hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
|| !IMAGE_EXTENSIONS.contains(&extension)
|
||||
{
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let path: PathBuf = config::managed_data_dir()
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.join("ads")
|
||||
.join(&file_name);
|
||||
let bytes = tokio::fs::read(path).await.map_err(|error| {
|
||||
if error.kind() == std::io::ErrorKind::NotFound {
|
||||
StatusCode::NOT_FOUND
|
||||
} else {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
})?;
|
||||
let mut response = Response::new(Body::from(bytes));
|
||||
response.headers_mut().insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static(content_type_for_extension(extension)),
|
||||
);
|
||||
response.headers_mut().insert(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("public, max-age=31536000, immutable"),
|
||||
);
|
||||
response.headers_mut().insert(
|
||||
header::X_CONTENT_TYPE_OPTIONS,
|
||||
HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn content_type_for_extension(extension: &str) -> &'static str {
|
||||
match extension {
|
||||
"png" => "image/png",
|
||||
"jpg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"avif" => "image/avif",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(service): State<ControlService>,
|
||||
headers: HeaderMap,
|
||||
@@ -147,3 +339,70 @@ pub async fn dismiss(
|
||||
service.dismiss_ad(&ad_id, &input).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{header, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_supported_image_content_types() {
|
||||
assert_eq!(image_extension("image/png"), Some("png"));
|
||||
assert_eq!(image_extension("image/jpeg; charset=binary"), Some("jpg"));
|
||||
assert_eq!(image_extension("IMAGE/WEBP"), Some("webp"));
|
||||
assert_eq!(image_extension("image/svg+xml"), None);
|
||||
assert_eq!(image_extension("text/html"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn downloads_an_ad_image_once_and_reuses_the_cache() {
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
let request_counter = requests.clone();
|
||||
let app = Router::new().route(
|
||||
"/ad.png",
|
||||
get(move || {
|
||||
request_counter.fetch_add(1, Ordering::SeqCst);
|
||||
async {
|
||||
Response::builder()
|
||||
.header(header::CONTENT_TYPE, "image/png")
|
||||
.body(Body::from(&b"cached image"[..]))
|
||||
.unwrap()
|
||||
}
|
||||
}),
|
||||
);
|
||||
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, app).await.unwrap() });
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let client = reqwest::Client::new();
|
||||
let remote_url = format!("http://{address}/ad.png");
|
||||
|
||||
let first = cache_image(&client, root.path(), &remote_url)
|
||||
.await
|
||||
.unwrap();
|
||||
let second = cache_image(&client, root.path(), &remote_url)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(first, second);
|
||||
assert!(first.starts_with(ADS_IMAGE_ROUTE));
|
||||
assert_eq!(requests.load(Ordering::SeqCst), 1);
|
||||
let file_name = first.rsplit('/').next().unwrap();
|
||||
assert_eq!(
|
||||
tokio::fs::read(root.path().join(file_name)).await.unwrap(),
|
||||
b"cached image"
|
||||
);
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,7 @@ fn proxy_error(error: impl std::fmt::Display) -> Response<Body> {
|
||||
pub fn api_router(service: ControlService) -> Router {
|
||||
Router::new()
|
||||
.route("/__byok-api__/api/ads", get(ads::get))
|
||||
.route("/__byok-api__/api/ads/images/{file_name}", get(ads::image))
|
||||
.route(
|
||||
"/__byok-api__/api/ads/{ad_id}/dismissals",
|
||||
post(ads::dismiss),
|
||||
|
||||
@@ -283,7 +283,9 @@ impl ControlService {
|
||||
message.chars().take(200).collect::<String>()
|
||||
)));
|
||||
}
|
||||
response.json::<AdRuntime>().await?.into_menu_slots()
|
||||
let mut runtime = response.json::<AdRuntime>().await?.into_menu_slots()?;
|
||||
runtime.cache_images(&client).await;
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
pub(super) async fn dismiss_ad(&self, ad_id: &str, input: &AdDismissalInput) -> Result<()> {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
//! Implements settings management endpoints.
|
||||
use crate::Result;
|
||||
use axum::{extract::State, Json};
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{header, HeaderMap},
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::store::{
|
||||
CommitSettings, DesktopSettings, PortSettings, ProxySettings, ProxySettingsInput,
|
||||
StatisticsStorage, StatisticsStorageScope, TabSettings, DEFAULT_COMMIT_PROMPT,
|
||||
CommitPromptLocale, CommitSettings, DesktopSettings, PortSettings, ProxySettings,
|
||||
ProxySettingsInput, StatisticsStorage, StatisticsStorageScope, TabSettings,
|
||||
};
|
||||
|
||||
use super::{ControlService, ObservabilitySettings};
|
||||
@@ -90,27 +94,35 @@ pub async fn update_desktop(
|
||||
|
||||
/// Settings view for commit message generation. Empty `model_id` means 直连
|
||||
/// (forward the original Cursor RPC). A non-empty value is a configured
|
||||
/// Cursor model hash. Empty `prompt` means "use the built-in default".
|
||||
/// built-in or plugin model identifier. Empty `prompt` means "use the built-in default".
|
||||
#[derive(Serialize)]
|
||||
pub struct CommitSettingsView {
|
||||
pub model_id: String,
|
||||
pub prompt: String,
|
||||
pub prompt_locale: CommitPromptLocale,
|
||||
pub default_prompt: &'static str,
|
||||
}
|
||||
|
||||
impl From<CommitSettings> for CommitSettingsView {
|
||||
fn from(settings: CommitSettings) -> Self {
|
||||
impl CommitSettingsView {
|
||||
fn new(settings: CommitSettings, default_locale: CommitPromptLocale) -> Self {
|
||||
Self {
|
||||
model_id: settings.model_id,
|
||||
prompt: settings.prompt,
|
||||
default_prompt: DEFAULT_COMMIT_PROMPT.trim(),
|
||||
prompt_locale: settings.prompt_locale,
|
||||
default_prompt: default_locale.default_prompt(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_commit(State(service): State<ControlService>) -> Result<Json<CommitSettingsView>> {
|
||||
pub async fn get_commit(
|
||||
State(service): State<ControlService>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<CommitSettingsView>> {
|
||||
let settings = service.commit_settings().await?;
|
||||
Ok(Json(CommitSettingsView::from(settings)))
|
||||
Ok(Json(CommitSettingsView::new(
|
||||
settings,
|
||||
requested_commit_locale(&headers),
|
||||
)))
|
||||
}
|
||||
|
||||
pub async fn update_commit(
|
||||
@@ -118,5 +130,31 @@ pub async fn update_commit(
|
||||
Json(settings): Json<CommitSettings>,
|
||||
) -> Result<Json<CommitSettingsView>> {
|
||||
let saved = service.set_commit_settings(settings).await?;
|
||||
Ok(Json(CommitSettingsView::from(saved)))
|
||||
let default_locale = saved.prompt_locale;
|
||||
Ok(Json(CommitSettingsView::new(saved, default_locale)))
|
||||
}
|
||||
|
||||
fn requested_commit_locale(headers: &HeaderMap) -> CommitPromptLocale {
|
||||
match headers
|
||||
.get(header::ACCEPT_LANGUAGE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
{
|
||||
Some(value) if value.eq_ignore_ascii_case("zh-CN") => CommitPromptLocale::ZhCn,
|
||||
_ => CommitPromptLocale::EnUs,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commit_default_prompt_locale_comes_from_interface_language() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::ACCEPT_LANGUAGE, "zh-CN".parse().unwrap());
|
||||
assert_eq!(requested_commit_locale(&headers), CommitPromptLocale::ZhCn);
|
||||
|
||||
headers.insert(header::ACCEPT_LANGUAGE, "en-US".parse().unwrap());
|
||||
assert_eq!(requested_commit_locale(&headers), CommitPromptLocale::EnUs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Implements Cursor account information services.
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
body::{to_bytes, Body},
|
||||
extract::Extension,
|
||||
http::{header, Request, Response},
|
||||
http::{header, HeaderValue, Request, Response},
|
||||
};
|
||||
use prost::Message;
|
||||
use serde_json::{Map, Value};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{api::cursor::proxy, Result};
|
||||
use crate::{api::cursor::proxy, local_app, Result};
|
||||
|
||||
const LOCAL_AUTH_ID: &str = "local_ultra";
|
||||
use super::entitlement::FreeEntitlementCache;
|
||||
|
||||
const LOCAL_AUTH_ID: &str = "cursor-local-user";
|
||||
const LOCAL_EMAIL: &str = "cursor@ai.com";
|
||||
const LOCAL_ULTRA_PLAN_INCLUDED_CENTS: i32 = 20_000;
|
||||
|
||||
@@ -21,6 +23,20 @@ struct GetEmailResponse {
|
||||
sign_up_type: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
struct GetUserMetaResponse {
|
||||
#[prost(string, tag = "1")]
|
||||
email: String,
|
||||
#[prost(int32, tag = "2")]
|
||||
sign_up_type: i32,
|
||||
#[prost(int64, tag = "3")]
|
||||
user_id: i64,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
workos_id: Option<String>,
|
||||
#[prost(string, optional, tag = "5")]
|
||||
profile_picture_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
struct GetMeResponse {
|
||||
#[prost(string, tag = "1")]
|
||||
@@ -41,6 +57,8 @@ struct GetMeResponse {
|
||||
email_domain_type: Option<String>,
|
||||
#[prost(string, optional, tag = "12")]
|
||||
country: Option<String>,
|
||||
#[prost(string, optional, tag = "13")]
|
||||
profile_picture_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
@@ -134,7 +152,7 @@ pub async fn get_email(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetEmailResponse {
|
||||
email: LOCAL_EMAIL.into(),
|
||||
sign_up_type: 3,
|
||||
@@ -143,11 +161,27 @@ pub async fn get_email(
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_user_meta(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetUserMetaResponse {
|
||||
email: LOCAL_EMAIL.into(),
|
||||
sign_up_type: 3,
|
||||
user_id: 1,
|
||||
workos_id: None,
|
||||
profile_picture_url: None,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_me(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetMeResponse {
|
||||
auth_id: LOCAL_AUTH_ID.into(),
|
||||
user_id: 1,
|
||||
@@ -158,6 +192,7 @@ pub async fn get_me(
|
||||
is_enterprise_user: Some(false),
|
||||
email_domain_type: Some("personal".into()),
|
||||
country: Some("US".into()),
|
||||
profile_picture_url: None,
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -167,14 +202,14 @@ pub async fn get_teams(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || proto(Empty {})).await
|
||||
local_or_forward(upstream, request, || proto(Empty {})).await
|
||||
}
|
||||
|
||||
pub async fn get_user_profile(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetUserProfileResponse {
|
||||
public_visibility_allowed: Some(true),
|
||||
max_visibility: Some("PUBLIC".into()),
|
||||
@@ -183,85 +218,170 @@ pub async fn get_user_profile(
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn current_period_usage() -> Result<Response<Body>> {
|
||||
let now = chrono::Utc::now();
|
||||
proto(GetCurrentPeriodUsageResponse {
|
||||
billing_cycle_start: (now - chrono::Duration::days(30)).timestamp_millis(),
|
||||
billing_cycle_end: (now + chrono::Duration::days(10 * 365)).timestamp_millis(),
|
||||
plan_usage: Some(PlanUsage {
|
||||
total_spend: 0,
|
||||
included_spend: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
limit: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining_bonus: Some(false),
|
||||
bonus_tooltip: Some("Ultra local account mock is active.".into()),
|
||||
auto_spend: Some(0),
|
||||
api_spend: Some(0),
|
||||
auto_percent_used: Some(0.0),
|
||||
api_percent_used: Some(0.0),
|
||||
total_percent_used: Some(0.0),
|
||||
}),
|
||||
spend_limit_usage: Some(SpendLimitUsage {
|
||||
limit_type: "user".into(),
|
||||
}),
|
||||
display_threshold: Some(99_999_999),
|
||||
enabled: true,
|
||||
display_message: "Ultra plan active".into(),
|
||||
auto_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
named_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
pub async fn current_period_usage(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(free_entitlements): Extension<FreeEntitlementCache>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
local_or_confirmed_free_or_forward(upstream, &free_entitlements, request, || {
|
||||
let now = chrono::Utc::now();
|
||||
proto(GetCurrentPeriodUsageResponse {
|
||||
billing_cycle_start: (now - chrono::Duration::days(30)).timestamp_millis(),
|
||||
billing_cycle_end: (now + chrono::Duration::days(10 * 365)).timestamp_millis(),
|
||||
plan_usage: Some(PlanUsage {
|
||||
total_spend: 0,
|
||||
included_spend: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
limit: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining_bonus: Some(false),
|
||||
bonus_tooltip: Some("Ultra local account mock is active.".into()),
|
||||
auto_spend: Some(0),
|
||||
api_spend: Some(0),
|
||||
auto_percent_used: Some(0.0),
|
||||
api_percent_used: Some(0.0),
|
||||
total_percent_used: Some(0.0),
|
||||
}),
|
||||
spend_limit_usage: Some(SpendLimitUsage {
|
||||
limit_type: "user".into(),
|
||||
}),
|
||||
display_threshold: Some(99_999_999),
|
||||
enabled: true,
|
||||
display_message: "Ultra plan active".into(),
|
||||
auto_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
named_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn usage_limit_status() -> Result<Response<Body>> {
|
||||
proto(GetUsageLimitStatusAndActiveGrantsResponse {
|
||||
usage_limit_policy_status: Some(UsageLimitPolicyStatus {
|
||||
is_in_slow_pool: false,
|
||||
features: Default::default(),
|
||||
can_configure_spend_limit: true,
|
||||
has_pending_request: false,
|
||||
allowed_model_ids: Vec::new(),
|
||||
allowed_model_tags: Vec::new(),
|
||||
}),
|
||||
pub async fn usage_limit_status(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(free_entitlements): Extension<FreeEntitlementCache>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
local_or_confirmed_free_or_forward(upstream, &free_entitlements, request, || {
|
||||
proto(GetUsageLimitStatusAndActiveGrantsResponse {
|
||||
usage_limit_policy_status: Some(UsageLimitPolicyStatus {
|
||||
is_in_slow_pool: false,
|
||||
features: Default::default(),
|
||||
can_configure_spend_limit: true,
|
||||
has_pending_request: false,
|
||||
allowed_model_ids: Vec::new(),
|
||||
allowed_model_tags: Vec::new(),
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn stripe_profile(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(free_entitlements): Extension<FreeEntitlementCache>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) if response.status.is_success() => {
|
||||
let mut profile = serde_json::from_slice::<Map<String, Value>>(&response.body)?;
|
||||
ultra(&mut profile);
|
||||
Ok(response.with_body(Bytes::from(serde_json::to_vec(&profile)?)))
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "Cursor account upstream rejected profile; using local Ultra identity");
|
||||
json(ultra_profile())
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Cursor account upstream unavailable; using local Ultra identity");
|
||||
json(ultra_profile())
|
||||
}
|
||||
if local_app::request_uses_local_cursor_token(request.headers()) {
|
||||
return local_stripe_profile(request.headers().get(header::ORIGIN).cloned());
|
||||
}
|
||||
|
||||
let request_headers = request.headers().clone();
|
||||
let origin = request.headers().get(header::ORIGIN).cloned();
|
||||
let upstream_response = match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) => response,
|
||||
Err(error) if free_entitlements.is_confirmed_free(&request_headers) => {
|
||||
tracing::warn!(%error, "using cached Free entitlement after Stripe upstream failure");
|
||||
return local_stripe_profile(origin);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if !upstream_response.status.is_success() {
|
||||
if should_fallback_to_cached_free(
|
||||
upstream_response.status,
|
||||
&free_entitlements,
|
||||
&request_headers,
|
||||
) {
|
||||
tracing::warn!(
|
||||
status = %upstream_response.status,
|
||||
"using cached Free entitlement after Stripe upstream failure"
|
||||
);
|
||||
return local_stripe_profile(origin);
|
||||
}
|
||||
return Ok(upstream_response.into_response());
|
||||
}
|
||||
|
||||
let Some(membership_type) = membership_type(&upstream_response.body) else {
|
||||
return Ok(upstream_response.into_response());
|
||||
};
|
||||
let observed = free_entitlements.observe_membership(&request_headers, &membership_type);
|
||||
if observed && membership_type.eq_ignore_ascii_case("free") {
|
||||
return local_stripe_profile(origin);
|
||||
}
|
||||
|
||||
Ok(upstream_response.into_response())
|
||||
}
|
||||
|
||||
async fn forward_or(
|
||||
fn should_fallback_to_cached_free(
|
||||
status: axum::http::StatusCode,
|
||||
free_entitlements: &FreeEntitlementCache,
|
||||
headers: &axum::http::HeaderMap,
|
||||
) -> bool {
|
||||
status.is_server_error() && free_entitlements.is_confirmed_free(headers)
|
||||
}
|
||||
|
||||
fn membership_type(body: &[u8]) -> Option<String> {
|
||||
let profile: Value = serde_json::from_slice(body).ok()?;
|
||||
let membership_type = profile.get("membershipType")?.as_str()?.trim();
|
||||
(!membership_type.is_empty()).then(|| membership_type.to_owned())
|
||||
}
|
||||
|
||||
fn local_stripe_profile(origin: Option<HeaderValue>) -> Result<Response<Body>> {
|
||||
let mut response = json(ultra_profile())?;
|
||||
if let Some(origin) = origin {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
|
||||
response.headers_mut().insert(
|
||||
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
|
||||
HeaderValue::from_static("true"),
|
||||
);
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::VARY, HeaderValue::from_static("Origin"));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn local_or_confirmed_free_or_forward(
|
||||
upstream: proxy::CursorProxy,
|
||||
free_entitlements: &FreeEntitlementCache,
|
||||
request: Request<Body>,
|
||||
local: impl FnOnce() -> Result<Response<Body>>,
|
||||
) -> Result<Response<Body>> {
|
||||
if local_app::request_uses_local_cursor_token(request.headers())
|
||||
|| free_entitlements.is_confirmed_free(request.headers())
|
||||
{
|
||||
consume_body(request).await?;
|
||||
return local();
|
||||
}
|
||||
proxy::forward(Extension(upstream), request).await
|
||||
}
|
||||
|
||||
async fn local_or_forward(
|
||||
upstream: proxy::CursorProxy,
|
||||
request: Request<Body>,
|
||||
fallback: impl FnOnce() -> Result<Response<Body>>,
|
||||
local: impl FnOnce() -> Result<Response<Body>>,
|
||||
) -> Result<Response<Body>> {
|
||||
match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) if response.status.is_success() => Ok(response.into_response()),
|
||||
Ok(response) => {
|
||||
tracing::debug!(status = %response.status, "Cursor identity upstream rejected request; using local identity");
|
||||
fallback()
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Cursor identity upstream unavailable; using local identity");
|
||||
fallback()
|
||||
}
|
||||
if local_app::request_uses_local_cursor_token(request.headers()) {
|
||||
consume_body(request).await?;
|
||||
return local();
|
||||
}
|
||||
proxy::forward(Extension(upstream), request).await
|
||||
}
|
||||
|
||||
async fn consume_body(request: Request<Body>) -> Result<()> {
|
||||
to_bytes(request.into_body(), usize::MAX)
|
||||
.await
|
||||
.map_err(|error| crate::Error::Protocol(format!("cannot read request body: {error}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn proto(message: impl Message) -> Result<Response<Body>> {
|
||||
@@ -289,15 +409,6 @@ fn response(content_type: &'static str, body: Vec<u8>) -> Result<Response<Body>>
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn ultra(profile: &mut Map<String, Value>) {
|
||||
profile.insert("membershipType".into(), Value::String("ultra".into()));
|
||||
profile.insert(
|
||||
"individualMembershipType".into(),
|
||||
Value::String("ultra".into()),
|
||||
);
|
||||
profile.insert("subscriptionStatus".into(), Value::String("active".into()));
|
||||
}
|
||||
|
||||
fn ultra_profile() -> Value {
|
||||
serde_json::json!({
|
||||
"membershipType": "ultra",
|
||||
@@ -310,3 +421,87 @@ fn ultra_profile() -> Value {
|
||||
"isTeamMember": false
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use axum::body::Bytes;
|
||||
use futures_util::stream;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_account_response_consumes_request_body_before_replying() {
|
||||
let polled = Arc::new(AtomicBool::new(false));
|
||||
let observed = polled.clone();
|
||||
let body = Body::from_stream(stream::once(async move {
|
||||
observed.store(true, Ordering::SeqCst);
|
||||
Ok::<_, std::convert::Infallible>(Bytes::from_static(b"request"))
|
||||
}));
|
||||
|
||||
consume_body(Request::new(body)).await.unwrap();
|
||||
|
||||
assert!(polled.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_free_fallback_accepts_server_failures_but_not_auth_failures() {
|
||||
let cache = FreeEntitlementCache::default();
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer official-free-token"),
|
||||
);
|
||||
assert!(cache.observe_membership(&headers, "free"));
|
||||
|
||||
assert!(should_fallback_to_cached_free(
|
||||
axum::http::StatusCode::BAD_GATEWAY,
|
||||
&cache,
|
||||
&headers
|
||||
));
|
||||
assert!(!should_fallback_to_cached_free(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
&cache,
|
||||
&headers
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_only_a_non_empty_membership_type() {
|
||||
assert_eq!(
|
||||
membership_type(br#"{"membershipType":"free"}"#).as_deref(),
|
||||
Some("free")
|
||||
);
|
||||
assert_eq!(membership_type(br#"{"membershipType":""}"#), None);
|
||||
assert_eq!(membership_type(br#"{"subscriptionStatus":"active"}"#), None);
|
||||
assert_eq!(membership_type(b"not-json"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_stripe_profile_allows_the_cursor_app_origin() {
|
||||
let origin = HeaderValue::from_static("vscode-file://vscode-app");
|
||||
let response = local_stripe_profile(Some(origin.clone())).unwrap();
|
||||
assert_eq!(
|
||||
response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN),
|
||||
Some(&origin)
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS),
|
||||
Some(&HeaderValue::from_static("true"))
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::VARY),
|
||||
Some(&HeaderValue::from_static("Origin"))
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_TYPE),
|
||||
Some(&HeaderValue::from_static("application/json"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||