mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-10-06 13:44:21 +08:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81a1afdae9 | ||
|
|
6170778de9 | ||
|
|
0f23a9a9c3 |
Generated
+1
-1
@@ -1128,7 +1128,7 @@ checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cursor-byok-desktop"
|
name = "cursor-byok-desktop"
|
||||||
version = "0.1.0-beta.1"
|
version = "0.1.0-beta.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"cursor-server",
|
"cursor-server",
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "cursor-byok-desktop",
|
"name": "cursor-byok-desktop",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "0.1.0-beta.4",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "cursor-byok-desktop",
|
"name": "cursor-byok-desktop",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "0.1.0-beta.4",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@floating-ui/dom": "^1.8.0",
|
"@floating-ui/dom": "^1.8.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "cursor-byok-desktop",
|
"name": "cursor-byok-desktop",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "0.1.0-beta.4",
|
||||||
"description": "Cursor BYOK desktop management application",
|
"description": "Cursor BYOK desktop management application",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "cursor-byok-desktop"
|
name = "cursor-byok-desktop"
|
||||||
version = "0.1.0-beta.1"
|
version = "0.1.0-beta.4"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Cursor BYOK",
|
"productName": "Cursor BYOK",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "0.1.0-beta.4",
|
||||||
"identifier": "dev.cursorbyok.desktop",
|
"identifier": "dev.cursorbyok.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ import { CursorSettingsPage } from "./pages/CursorSettingsPage";
|
|||||||
import { HomePage } from "./pages/HomePage";
|
import { HomePage } from "./pages/HomePage";
|
||||||
import { ProvidersPage } from "./pages/ProvidersPage";
|
import { ProvidersPage } from "./pages/ProvidersPage";
|
||||||
import { SettingsPage } from "./pages/SettingsPage";
|
import { SettingsPage } from "./pages/SettingsPage";
|
||||||
import { checkForUpdate, hasNativeAppLifecycle } from "./native/appLifecycle";
|
|
||||||
import { useAppStore } from "./store/appStore";
|
import { useAppStore } from "./store/appStore";
|
||||||
|
import { updateStore } from "./store/updateStore";
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
return (
|
return (
|
||||||
@@ -47,11 +47,9 @@ function AppMessages() {
|
|||||||
}, [error, showMessage]);
|
}, [error, showMessage]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hasNativeAppLifecycle()) return;
|
void updateStore.check().then((version) => {
|
||||||
void checkForUpdate().then(async (update) => {
|
if (!version) return;
|
||||||
if (!update) return;
|
showMessage(t("发现新版本 {version},可在设置中安装", { version }), { duration: 6_000 });
|
||||||
showMessage(t("发现新版本 {version},可在设置中安装", { version: update.version }), { duration: 6_000 });
|
|
||||||
await update.close();
|
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
// Startup checks are best-effort; manual checks in Settings report errors.
|
// Startup checks are best-effort; manual checks in Settings report errors.
|
||||||
});
|
});
|
||||||
|
|||||||
+27
-1
@@ -56,6 +56,15 @@ export interface ModelInput {
|
|||||||
supports_image_generation: boolean;
|
supports_image_generation: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ModelConnectivityResult {
|
||||||
|
duration_ms: number;
|
||||||
|
first_text_ms: number | null;
|
||||||
|
output_tokens: number;
|
||||||
|
tokens_per_second: number;
|
||||||
|
tokens_estimated: boolean;
|
||||||
|
output: string;
|
||||||
|
}
|
||||||
|
|
||||||
export type CaState = "missing" | "untrusted" | "ready" | "invalid" | "unsupported";
|
export type CaState = "missing" | "untrusted" | "ready" | "invalid" | "unsupported";
|
||||||
export type IntegrationState = "disabled" | "enabled" | "degraded";
|
export type IntegrationState = "disabled" | "enabled" | "degraded";
|
||||||
export interface CursorHarnessStatus {
|
export interface CursorHarnessStatus {
|
||||||
@@ -97,6 +106,13 @@ export interface ProxySettingsInput {
|
|||||||
password?: string;
|
password?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type TabMode = "public" | "direct" | "custom";
|
||||||
|
|
||||||
|
export interface TabSettings {
|
||||||
|
mode: TabMode;
|
||||||
|
address: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface OverviewMetrics {
|
export interface OverviewMetrics {
|
||||||
llm_calls: number;
|
llm_calls: number;
|
||||||
successful_calls: number;
|
successful_calls: number;
|
||||||
@@ -214,7 +230,14 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
throw new Error(t("无法连接本地管理服务"), { cause });
|
throw new Error(t("无法连接本地管理服务"), { cause });
|
||||||
}
|
}
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const message = await response.text();
|
const body = await response.text();
|
||||||
|
let message = body;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(body) as { message?: unknown };
|
||||||
|
if (typeof parsed.message === "string") message = parsed.message;
|
||||||
|
} catch {
|
||||||
|
// Plain-text errors are already suitable for display.
|
||||||
|
}
|
||||||
throw new Error(message || `${response.status} ${response.statusText}`);
|
throw new Error(message || `${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
if (response.status === 204) return undefined as T;
|
if (response.status === 204) return undefined as T;
|
||||||
@@ -241,6 +264,7 @@ export const api = {
|
|||||||
models: () => request<Model[]>("/models"),
|
models: () => request<Model[]>("/models"),
|
||||||
updateModel: (hash: string, model: ModelInput) => request<Model>(`/models/${hash}`, { method: "PUT", body: JSON.stringify(model) }),
|
updateModel: (hash: string, model: ModelInput) => request<Model>(`/models/${hash}`, { method: "PUT", body: JSON.stringify(model) }),
|
||||||
deleteModel: (hash: string) => request<void>(`/models/${hash}`, { method: "DELETE" }),
|
deleteModel: (hash: string) => request<void>(`/models/${hash}`, { method: "DELETE" }),
|
||||||
|
testModel: (hash: string) => request<ModelConnectivityResult>(`/models/${hash}/test`, { method: "POST" }),
|
||||||
overview: (filter?: { startMs: number; endMs: number; modelHashes?: string[]; providerIds?: number[] }) => {
|
overview: (filter?: { startMs: number; endMs: number; modelHashes?: string[]; providerIds?: number[] }) => {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (filter) {
|
if (filter) {
|
||||||
@@ -283,4 +307,6 @@ export const api = {
|
|||||||
clearStatisticsStorage: () => request<StatisticsStorage>("/settings/storage/statistics", { method: "DELETE" }),
|
clearStatisticsStorage: () => request<StatisticsStorage>("/settings/storage/statistics", { method: "DELETE" }),
|
||||||
proxySettings: () => request<ProxySettings>("/settings/proxy"),
|
proxySettings: () => request<ProxySettings>("/settings/proxy"),
|
||||||
setProxySettings: (settings: ProxySettingsInput) => request<ProxySettings>("/settings/proxy", { method: "PUT", body: JSON.stringify(settings) }),
|
setProxySettings: (settings: ProxySettingsInput) => request<ProxySettings>("/settings/proxy", { method: "PUT", body: JSON.stringify(settings) }),
|
||||||
|
tabSettings: () => request<TabSettings>("/settings/tab"),
|
||||||
|
setTabSettings: (settings: TabSettings) => request<TabSettings>("/settings/tab", { method: "PUT", body: JSON.stringify(settings) }),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { ModelConnectivityResult } from "../../api";
|
||||||
|
import { Icon } from "../ui/Icon";
|
||||||
|
import { TooltipTrigger } from "../ui/TooltipTrigger";
|
||||||
|
import { informationOutlineIcon } from "../ui/icons";
|
||||||
|
import styles from "./CursorSettings.module.scss";
|
||||||
|
|
||||||
|
export type CursorModelTestState =
|
||||||
|
| { status: "success"; result: ModelConnectivityResult }
|
||||||
|
| { status: "error"; error: string };
|
||||||
|
|
||||||
|
export function CursorModelTestResult({ state }: { state: CursorModelTestState }) {
|
||||||
|
const success = state.status === "success";
|
||||||
|
const summary = success
|
||||||
|
? t("速度:{speed} tokens/s", { speed: formatSpeed(state.result.tokens_per_second) })
|
||||||
|
: t("错误:{error}", { error: state.error });
|
||||||
|
const detail = success
|
||||||
|
? t("速度 {speed} tokens/s · 首字 {firstText} ms · 总耗时 {duration} ms · 输出 {tokens} tokens{estimated} · 返回:{output}", {
|
||||||
|
speed: formatSpeed(state.result.tokens_per_second),
|
||||||
|
firstText: state.result.first_text_ms ?? "--",
|
||||||
|
duration: state.result.duration_ms,
|
||||||
|
tokens: state.result.output_tokens,
|
||||||
|
estimated: state.result.tokens_estimated ? t("(估算)") : "",
|
||||||
|
output: state.result.output || "--",
|
||||||
|
})
|
||||||
|
: t("测试失败:{error}", { error: state.error });
|
||||||
|
|
||||||
|
return <div className={`${styles.testResult} ${success ? styles.testSuccess : styles.testError}`}>
|
||||||
|
<span className={styles.testResultText}>{summary}</span>
|
||||||
|
<TooltipTrigger label={detail}><span className={styles.testResultHint} tabIndex={0}><Icon icon={informationOutlineIcon} size="1.1em" /></span></TooltipTrigger>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSpeed(value: number) {
|
||||||
|
return Number.isFinite(value) ? value.toFixed(1) : "0.0";
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
@use "../../styles/typography" as type;
|
@use "../../styles/typography" as type;
|
||||||
|
|
||||||
|
.page {
|
||||||
|
display: grid;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
.gate {
|
.gate {
|
||||||
min-height: 250px;
|
min-height: 250px;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -81,11 +86,46 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
|
.testResult {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 220px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
font-size: type.$font-size-xs;
|
||||||
|
}
|
||||||
|
.testSuccess {
|
||||||
|
color: var(--vscode-testing-iconPassed, #73c991);
|
||||||
|
}
|
||||||
|
.testError {
|
||||||
|
color: var(--vscode-errorForeground, #f48771);
|
||||||
|
}
|
||||||
|
.testResultText {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.testResultHint {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: currentColor;
|
||||||
|
cursor: help;
|
||||||
|
&:focus-visible {
|
||||||
|
outline: 1px solid var(--vscode-focusBorder);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
}
|
||||||
.editor {
|
.editor {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 14px;
|
gap: 14px;
|
||||||
}
|
}
|
||||||
|
.editorTestResult {
|
||||||
|
margin-top: 14px;
|
||||||
|
}
|
||||||
.command {
|
.command {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
@use "../../styles/typography" as type;
|
||||||
|
|
||||||
|
.title {
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
min-height: 62px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 20px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
|
||||||
|
& + & {
|
||||||
|
border-top: 1px solid var(--vscode-sideBar-border);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.description {
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: 5px;
|
||||||
|
|
||||||
|
small {
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: type.$font-size-xs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.selectControl,
|
||||||
|
.addressInput {
|
||||||
|
width: min(300px, 44%);
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 620px) {
|
||||||
|
.row {
|
||||||
|
align-items: stretch;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.selectControl,
|
||||||
|
.addressInput {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import cursorIconUrl from "../../assets/icons/cursor.svg";
|
||||||
|
import type { TabMode, TabSettings } from "../../api";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { TextInput } from "../ui/FormControls";
|
||||||
|
import { Icon } from "../ui/Icon";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
|
import { TitledCard } from "../ui/TitledCard";
|
||||||
|
import styles from "./TabSettingsCard.module.scss";
|
||||||
|
|
||||||
|
export function TabSettingsCard({ settings, saving, onChange, onSave }: {
|
||||||
|
settings: TabSettings;
|
||||||
|
saving: boolean;
|
||||||
|
onChange: (settings: TabSettings) => void;
|
||||||
|
onSave: () => void;
|
||||||
|
}) {
|
||||||
|
return <TitledCard
|
||||||
|
title={<div className={styles.title}><Icon src={cursorIconUrl} size="1.1em" /><span>{t("TAB 设置")}</span></div>}
|
||||||
|
action={<Button size="small" variant="primary" disabled={saving} onClick={onSave}>{saving ? t("保存中…") : t("保存")}</Button>}
|
||||||
|
>
|
||||||
|
<div className={styles.row}>
|
||||||
|
<div className={styles.description}>
|
||||||
|
<strong>{t("TAB 选择")}</strong>
|
||||||
|
<small>{t("控制 Cursor TAB 相关接口的连接方式。")}</small>
|
||||||
|
</div>
|
||||||
|
<div className={styles.selectControl}>
|
||||||
|
<Select
|
||||||
|
value={settings.mode}
|
||||||
|
ariaLabel={t("TAB 选择")}
|
||||||
|
options={[
|
||||||
|
{ value: "public", label: t("使用公益服务") },
|
||||||
|
{ value: "direct", label: t("直连") },
|
||||||
|
{ value: "custom", label: t("自定义") },
|
||||||
|
]}
|
||||||
|
onChange={(mode) => onChange({ ...settings, mode: mode as TabMode })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{settings.mode === "custom" && <div className={styles.row}>
|
||||||
|
<div className={styles.description}>
|
||||||
|
<strong>{t("TAB 服务地址")}</strong>
|
||||||
|
<small>{t("原接口路径会追加到此服务地址。")}</small>
|
||||||
|
</div>
|
||||||
|
<TextInput
|
||||||
|
className={styles.addressInput}
|
||||||
|
value={settings.address}
|
||||||
|
placeholder="https://tab.leokun.cn"
|
||||||
|
aria-label={t("TAB 服务地址")}
|
||||||
|
onChange={(event) => onChange({ ...settings, address: event.target.value })}
|
||||||
|
onKeyDown={(event) => { if (event.key === "Enter") onSave(); }}
|
||||||
|
/>
|
||||||
|
</div>}
|
||||||
|
</TitledCard>;
|
||||||
|
}
|
||||||
@@ -21,3 +21,11 @@
|
|||||||
font-size: type.$font-size-xs;
|
font-size: type.$font-size-xs;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.updateDot {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
flex: 0 0 7px;
|
||||||
|
background: #ef4444;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import type { Update } from "@tauri-apps/plugin-updater";
|
|
||||||
import {
|
import {
|
||||||
checkForUpdate,
|
|
||||||
currentAppVersion,
|
currentAppVersion,
|
||||||
hasNativeAppLifecycle,
|
hasNativeAppLifecycle,
|
||||||
installUpdate,
|
|
||||||
readAutostart,
|
readAutostart,
|
||||||
writeAutostart,
|
writeAutostart,
|
||||||
} from "../../native/appLifecycle";
|
} from "../../native/appLifecycle";
|
||||||
|
import { updateStore, useUpdateStore } from "../../store/updateStore";
|
||||||
import { Button } from "../ui/Button";
|
import { Button } from "../ui/Button";
|
||||||
import { Switch } from "../ui/Switch";
|
import { Switch } from "../ui/Switch";
|
||||||
import { TitledCard } from "../ui/TitledCard";
|
import { TitledCard } from "../ui/TitledCard";
|
||||||
@@ -17,13 +15,10 @@ import styles from "./AppLifecycleSettingsCard.module.scss";
|
|||||||
export function AppLifecycleSettingsCard() {
|
export function AppLifecycleSettingsCard() {
|
||||||
const message = useMessage();
|
const message = useMessage();
|
||||||
const native = hasNativeAppLifecycle();
|
const native = hasNativeAppLifecycle();
|
||||||
const updateRef = useRef<Update | null>(null);
|
const { availableVersion, checking, installing } = useUpdateStore();
|
||||||
const [version, setVersion] = useState("…");
|
const [version, setVersion] = useState("…");
|
||||||
const [autostart, setAutostart] = useState(false);
|
const [autostart, setAutostart] = useState(false);
|
||||||
const [loadingAutostart, setLoadingAutostart] = useState(native);
|
const [loadingAutostart, setLoadingAutostart] = useState(native);
|
||||||
const [checking, setChecking] = useState(false);
|
|
||||||
const [installing, setInstalling] = useState(false);
|
|
||||||
const [availableVersion, setAvailableVersion] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
@@ -34,12 +29,7 @@ export function AppLifecycleSettingsCard() {
|
|||||||
.catch((cause) => message(cause instanceof Error ? cause.message : String(cause)))
|
.catch((cause) => message(cause instanceof Error ? cause.message : String(cause)))
|
||||||
.finally(() => { if (!disposed) setLoadingAutostart(false); });
|
.finally(() => { if (!disposed) setLoadingAutostart(false); });
|
||||||
}
|
}
|
||||||
return () => {
|
return () => { disposed = true; };
|
||||||
disposed = true;
|
|
||||||
const update = updateRef.current;
|
|
||||||
updateRef.current = null;
|
|
||||||
if (update) void update.close();
|
|
||||||
};
|
|
||||||
}, [message, native]);
|
}, [message, native]);
|
||||||
|
|
||||||
const toggleAutostart = async (enabled: boolean) => {
|
const toggleAutostart = async (enabled: boolean) => {
|
||||||
@@ -57,29 +47,17 @@ export function AppLifecycleSettingsCard() {
|
|||||||
|
|
||||||
const checkUpdate = async () => {
|
const checkUpdate = async () => {
|
||||||
try {
|
try {
|
||||||
setChecking(true);
|
const nextVersion = await updateStore.check();
|
||||||
const previous = updateRef.current;
|
message(nextVersion ? t("发现新版本 {version}", { version: nextVersion }) : t("当前已是最新版本"));
|
||||||
updateRef.current = null;
|
|
||||||
if (previous) await previous.close();
|
|
||||||
const update = await checkForUpdate();
|
|
||||||
updateRef.current = update;
|
|
||||||
setAvailableVersion(update?.version ?? null);
|
|
||||||
message(update ? t("发现新版本 {version}", { version: update.version }) : t("当前已是最新版本"));
|
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
message(cause instanceof Error ? cause.message : String(cause));
|
message(cause instanceof Error ? cause.message : String(cause));
|
||||||
} finally {
|
|
||||||
setChecking(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateNow = async () => {
|
const updateNow = async () => {
|
||||||
const update = updateRef.current;
|
|
||||||
if (!update) return;
|
|
||||||
try {
|
try {
|
||||||
setInstalling(true);
|
await updateStore.install();
|
||||||
await installUpdate(update);
|
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
setInstalling(false);
|
|
||||||
message(cause instanceof Error ? cause.message : String(cause));
|
message(cause instanceof Error ? cause.message : String(cause));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -107,6 +85,7 @@ export function AppLifecycleSettingsCard() {
|
|||||||
{availableVersion
|
{availableVersion
|
||||||
? <Button size="small" variant="primary" disabled={installing} onClick={() => void updateNow()}>
|
? <Button size="small" variant="primary" disabled={installing} onClick={() => void updateNow()}>
|
||||||
{installing ? t("安装中…") : t("下载并安装")}
|
{installing ? t("安装中…") : t("下载并安装")}
|
||||||
|
<span className={styles.updateDot} aria-hidden="true" />
|
||||||
</Button>
|
</Button>
|
||||||
: <Button size="small" disabled={!native || checking} onClick={() => void checkUpdate()}>
|
: <Button size="small" disabled={!native || checking} onClick={() => void checkUpdate()}>
|
||||||
{checking ? t("检查中…") : t("检查更新")}
|
{checking ? t("检查中…") : t("检查更新")}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
.region {
|
.region {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
z-index: 11000;
|
z-index: 16000;
|
||||||
top: calc(48px + env(safe-area-inset-top));
|
top: calc(48px + env(safe-area-inset-top));
|
||||||
right: 0;
|
right: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { ScrollableContent } from "../virtual/ScrollableContent";
|
|||||||
import controls from "./Controls.module.scss";
|
import controls from "./Controls.module.scss";
|
||||||
import styles from "./Modal.module.scss";
|
import styles from "./Modal.module.scss";
|
||||||
|
|
||||||
export function Modal({ id, open, title, children, busy, wide, onClose, onSubmit, closeLabel = t("取消"), submitLabel = t("保存") }: { id?: string; open: boolean; title: string; children: ReactNode; busy?: boolean; wide?: boolean; onClose: () => void; onSubmit?: () => void; closeLabel?: string; submitLabel?: string }) {
|
export function Modal({ id, open, title, children, busy, wide, onClose, onSubmit, secondaryAction, closeLabel = t("取消"), submitLabel = t("保存") }: { id?: string; open: boolean; title: string; children: ReactNode; busy?: boolean; wide?: boolean; onClose: () => void; onSubmit?: () => void; secondaryAction?: ReactNode; closeLabel?: string; submitLabel?: string }) {
|
||||||
const dialog = useRef<HTMLDivElement>(null);
|
const dialog = useRef<HTMLDivElement>(null);
|
||||||
const closeRef = useRef(onClose);
|
const closeRef = useRef(onClose);
|
||||||
const busyRef = useRef(Boolean(busy));
|
const busyRef = useRef(Boolean(busy));
|
||||||
@@ -29,6 +29,7 @@ export function Modal({ id, open, title, children, busy, wide, onClose, onSubmit
|
|||||||
<ScrollableContent alwaysShowVertical className={styles.body} viewportClassName={styles.bodyViewport} contentClassName={styles.bodyContent}>{children}</ScrollableContent>
|
<ScrollableContent alwaysShowVertical className={styles.body} viewportClassName={styles.bodyViewport} contentClassName={styles.bodyContent}>{children}</ScrollableContent>
|
||||||
<footer>
|
<footer>
|
||||||
<button type="button" className={controls.primary} disabled={busy} onClick={onClose}>{closeLabel}</button>
|
<button type="button" className={controls.primary} disabled={busy} onClick={onClose}>{closeLabel}</button>
|
||||||
|
{secondaryAction}
|
||||||
{onSubmit && <button type="button" className={controls.primary} disabled={busy} onClick={onSubmit}>{busy ? t("处理中…") : submitLabel}</button>}
|
{onSubmit && <button type="button" className={controls.primary} disabled={busy} onClick={onSubmit}>{busy ? t("处理中…") : submitLabel}</button>}
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@
|
|||||||
"028a4de61bff743d": "Regular input: {tokens} × ${price}/1M = {cost}",
|
"028a4de61bff743d": "Regular input: {tokens} × ${price}/1M = {cost}",
|
||||||
"03ff62ab4b818492": "Cache write: {tokens} × ${price}/1M = {cost}",
|
"03ff62ab4b818492": "Cache write: {tokens} × ${price}/1M = {cost}",
|
||||||
"051836569928a9f9": "Edit",
|
"051836569928a9f9": "Edit",
|
||||||
|
"05468af47054d488": "Connectivity test for {model} succeeded ({duration} ms)",
|
||||||
"0580e0a99a6f1afc": "Artifacts",
|
"0580e0a99a6f1afc": "Artifacts",
|
||||||
"05912a17829faacc": "All call records and detailed traces will be deleted. Providers, models, CA, and application settings are unaffected. This action cannot be undone.",
|
"05912a17829faacc": "All call records and detailed traces will be deleted. Providers, models, CA, and application settings are unaffected. This action cannot be undone.",
|
||||||
"076832c1b2de22c3": "Cache write: {tokens}",
|
"076832c1b2de22c3": "Cache write: {tokens}",
|
||||||
@@ -22,9 +23,11 @@
|
|||||||
"0d5e2bdb15579fc4": "Messages",
|
"0d5e2bdb15579fc4": "Messages",
|
||||||
"0e41f8e3d59ec47b": "Storage management",
|
"0e41f8e3d59ec47b": "Storage management",
|
||||||
"0ec1e85b0c3cfa65": "Call details",
|
"0ec1e85b0c3cfa65": "Call details",
|
||||||
|
"105a9082c346f958": "Testing…",
|
||||||
"124be3f86f197802": "Token usage",
|
"124be3f86f197802": "Token usage",
|
||||||
"12ae77e6202d063e": "Custom Headers",
|
"12ae77e6202d063e": "Custom Headers",
|
||||||
"12b86e89701b0241": "Enter a model name and press Enter to add it",
|
"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.",
|
"13a9ac7a68c5fd96": "The CA is stored only on this device and is used to securely inspect Cursor HTTPS requests.",
|
||||||
"13b61c5f697b6700": "Cache hit rate",
|
"13b61c5f697b6700": "Cache hit rate",
|
||||||
"146da2e2a991493e": "Fetching…",
|
"146da2e2a991493e": "Fetching…",
|
||||||
@@ -56,6 +59,7 @@
|
|||||||
"2eb2bf7c6597ab9a": "Detailed records",
|
"2eb2bf7c6597ab9a": "Detailed records",
|
||||||
"2f1b67cdaa23351a": "Custom full request URL",
|
"2f1b67cdaa23351a": "Custom full request URL",
|
||||||
"2f4a361f878176d1": "{label} must be valid JSON",
|
"2f4a361f878176d1": "{label} must be valid JSON",
|
||||||
|
"2f4a9609285d8f49": "TAB settings saved",
|
||||||
"2f5f1d6fbfb061ed": "Not set",
|
"2f5f1d6fbfb061ed": "Not set",
|
||||||
"2f6416a2c424856b": "Final request URL",
|
"2f6416a2c424856b": "Final request URL",
|
||||||
"2f7dec3be28d7597": "{count} selected",
|
"2f7dec3be28d7597": "{count} selected",
|
||||||
@@ -75,13 +79,14 @@
|
|||||||
"3cfae5728b92b334": "Token usage: {tokens}",
|
"3cfae5728b92b334": "Token usage: {tokens}",
|
||||||
"3d13868593ae4eeb": "Display language",
|
"3d13868593ae4eeb": "Display language",
|
||||||
"3da0bf1610ff5db5": "Recommended",
|
"3da0bf1610ff5db5": "Recommended",
|
||||||
|
"3f6c25aa329163a4": "The original endpoint path is appended to this service address.",
|
||||||
"3fd47edce45b3603": "Close",
|
"3fd47edce45b3603": "Close",
|
||||||
"4125fc7ba333524c": "Default light",
|
"4125fc7ba333524c": "Default light",
|
||||||
"42655ed8e4108ae2": "Input (non-cached)",
|
"42655ed8e4108ae2": "Input (non-cached)",
|
||||||
"42a1d9e5b037c210": "Bytes",
|
"42a1d9e5b037c210": "Bytes",
|
||||||
"42aa8e01e98c0d8c": "Total duration",
|
"42aa8e01e98c0d8c": "Total duration",
|
||||||
"43cb41d62de2d179": "Proxy requires authentication",
|
"43cb41d62de2d179": "Proxy requires authentication",
|
||||||
"4510b63fdcf7451f": "Cursor Assistant v0.1.0",
|
"461d6a57900c2ed7": "Connectivity test failed: {error}",
|
||||||
"470049252e54de6a": "Success rate: {rate}",
|
"470049252e54de6a": "Success rate: {rate}",
|
||||||
"48b970b568a7f8f9": "Proxy settings",
|
"48b970b568a7f8f9": "Proxy settings",
|
||||||
"48d8db17bae06246": "{count} total",
|
"48d8db17bae06246": "{count} total",
|
||||||
@@ -92,14 +97,20 @@
|
|||||||
"4d0680f9efaef147": "Unread",
|
"4d0680f9efaef147": "Unread",
|
||||||
"4eafa9e925b30bcd": "Custom",
|
"4eafa9e925b30bcd": "Custom",
|
||||||
"51d04bc3d286f018": "Last calendar day",
|
"51d04bc3d286f018": "Last calendar day",
|
||||||
|
"51de3bcec137ab1b": "Connectivity tests succeeded for all {count} models",
|
||||||
"5228358a6db59fe7": "For example: now, 2026-08-23 18:00",
|
"5228358a6db59fe7": "For example: now, 2026-08-23 18:00",
|
||||||
|
"5401344227e49e2f": "TAB settings",
|
||||||
"54644705e9c61009": "Port settings",
|
"54644705e9c61009": "Port settings",
|
||||||
"54c53e5fe791d1f3": "Initialize CA",
|
"54c53e5fe791d1f3": "Initialize CA",
|
||||||
"550eddc3c7fefa99": "Sponsored",
|
"550eddc3c7fefa99": "Sponsored",
|
||||||
"555737734a6371e6": "Delete provider",
|
"555737734a6371e6": "Delete provider",
|
||||||
"56432ba297009bdc": "Initialize the CA first",
|
"56432ba297009bdc": "Initialize the CA first",
|
||||||
|
"59346e82b3dd2998": "TAB service address",
|
||||||
|
"5a3bd99fa69a40c1": "Use public service",
|
||||||
"5ae715656ffbc35d": "Merge into the request body for every model from this provider.",
|
"5ae715656ffbc35d": "Merge into the request body for every model from this provider.",
|
||||||
|
"5b17f59d33bde39e": "Error: {error}",
|
||||||
"5c55a67935af8f45": "All",
|
"5c55a67935af8f45": "All",
|
||||||
|
"5d59857bf039cac9": "Cursor Assistant v{version}",
|
||||||
"5f8d556a9c47da3c": "Launch at login disabled",
|
"5f8d556a9c47da3c": "Launch at login disabled",
|
||||||
"5f9acfb945229062": "Are you sure you no longer want to see this ad?",
|
"5f9acfb945229062": "Are you sure you no longer want to see this ad?",
|
||||||
"5fd2ec5a6e9b654c": "Total: {cost}",
|
"5fd2ec5a6e9b654c": "Total: {cost}",
|
||||||
@@ -111,6 +122,7 @@
|
|||||||
"63c73c4730f4473e": "Apply",
|
"63c73c4730f4473e": "Apply",
|
||||||
"6478a5f1218c484e": "Use the desktop app to copy to the system clipboard",
|
"6478a5f1218c484e": "Use the desktop app to copy to the system clipboard",
|
||||||
"651f274470153a05": "Software updates",
|
"651f274470153a05": "Software updates",
|
||||||
|
"652ec5d40c29fd6a": "Speed {speed} tokens/s · first token {firstText} ms · total {duration} ms · output {tokens} tokens{estimated} · response: {output}",
|
||||||
"653b123c956d3bcb": "Calls",
|
"653b123c956d3bcb": "Calls",
|
||||||
"656ab25e264cc4e4": "No models are available to Cursor yet",
|
"656ab25e264cc4e4": "No models are available to Cursor yet",
|
||||||
"65a6318e07ec1e07": "Tools",
|
"65a6318e07ec1e07": "Tools",
|
||||||
@@ -118,6 +130,7 @@
|
|||||||
"68152165b3348852": "Select the request protocol used by this provider.",
|
"68152165b3348852": "Select the request protocol used by this provider.",
|
||||||
"68ea5dd4d7af20e6": "System settings",
|
"68ea5dd4d7af20e6": "System settings",
|
||||||
"6a9906c79f26c0ba": "Start time",
|
"6a9906c79f26c0ba": "Start time",
|
||||||
|
"6aa8f49cc992dfd7": "Test",
|
||||||
"6ae80538c2b2572d": "Minimize window",
|
"6ae80538c2b2572d": "Minimize window",
|
||||||
"6d1876364ac6457d": "Proxy mode",
|
"6d1876364ac6457d": "Proxy mode",
|
||||||
"6e86570183c3cdd0": "You're up to date",
|
"6e86570183c3cdd0": "You're up to date",
|
||||||
@@ -132,6 +145,7 @@
|
|||||||
"7a3cec4ca715de80": "Call statistics",
|
"7a3cec4ca715de80": "Call statistics",
|
||||||
"7ba2d6728fe2531b": "Confirm clear",
|
"7ba2d6728fe2531b": "Confirm clear",
|
||||||
"7d9f043f8f7ab45c": "Version {version} is available in Settings",
|
"7d9f043f8f7ab45c": "Version {version} is available in Settings",
|
||||||
|
"7e0891860c9e6374": "TAB service address is required",
|
||||||
"7e1845870b528392": "Enable model",
|
"7e1845870b528392": "Enable model",
|
||||||
"7e1f06318e80c3af": "Statistics cleared",
|
"7e1f06318e80c3af": "Statistics cleared",
|
||||||
"7e9ab9ada2cbf2cb": "Name and Base URL are required",
|
"7e9ab9ada2cbf2cb": "Name and Base URL are required",
|
||||||
@@ -149,6 +163,7 @@
|
|||||||
"8b6ff498515bcc2f": "Time",
|
"8b6ff498515bcc2f": "Time",
|
||||||
"8d0c47eb9eac2d34": "Call type",
|
"8d0c47eb9eac2d34": "Call type",
|
||||||
"8df48894086d6fbd": "Reason (optional)",
|
"8df48894086d6fbd": "Reason (optional)",
|
||||||
|
"8f9b0d6cc477d334": "Choose how Cursor connects to TAB endpoints.",
|
||||||
"90800c48a1dd0655": "{label} must be a JSON object",
|
"90800c48a1dd0655": "{label} must be a JSON object",
|
||||||
"919cb0ce0c8db4e7": "Leave blank to keep the current password",
|
"919cb0ce0c8db4e7": "Leave blank to keep the current password",
|
||||||
"91aaf184cfc17ffd": "Overview",
|
"91aaf184cfc17ffd": "Overview",
|
||||||
@@ -158,6 +173,7 @@
|
|||||||
"94803f35c825e47a": "Full request URL",
|
"94803f35c825e47a": "Full request URL",
|
||||||
"94df1e7f04815daf": "Used only for display; does not change the model name sent to the provider.",
|
"94df1e7f04815daf": "Used only for display; does not change the model name sent to the provider.",
|
||||||
"95f76d30c25d5eda": "CA installation is not supported on this system",
|
"95f76d30c25d5eda": "CA installation is not supported on this system",
|
||||||
|
"966498853d801a52": "TAB connection",
|
||||||
"9850ed41a5bfbb0c": "{count} selected",
|
"9850ed41a5bfbb0c": "{count} selected",
|
||||||
"997ec8201c2adeda": "Open terminal to install CA",
|
"997ec8201c2adeda": "Open terminal to install CA",
|
||||||
"9a026819dd1af5c5": "Enter a model identifier directly or select one returned by the current provider.",
|
"9a026819dd1af5c5": "Enter a model identifier directly or select one returned by the current provider.",
|
||||||
@@ -175,6 +191,7 @@
|
|||||||
"a3ab741ceb188e9e": "Request content was not recorded. Enable detailed records and try again.",
|
"a3ab741ceb188e9e": "Request content was not recorded. Enable detailed records and try again.",
|
||||||
"a49ffd73bc85333d": "Average",
|
"a49ffd73bc85333d": "Average",
|
||||||
"a621ab606db2a11f": "Password",
|
"a621ab606db2a11f": "Password",
|
||||||
|
"a693d69af48bfe48": "Save and test",
|
||||||
"a748cc074f78de00": "View details",
|
"a748cc074f78de00": "View details",
|
||||||
"a98585871c5313ff": "Display name",
|
"a98585871c5313ff": "Display name",
|
||||||
"a9ab292ea9feecdc": "Provider",
|
"a9ab292ea9feecdc": "Provider",
|
||||||
@@ -186,17 +203,20 @@
|
|||||||
"ad6a60ee93d3ba3e": "Loading call details…",
|
"ad6a60ee93d3ba3e": "Loading call details…",
|
||||||
"ae2d0b7f79cea4a3": "Model output: {tokens} × ${price}/1M = {cost}",
|
"ae2d0b7f79cea4a3": "Model output: {tokens} × ${price}/1M = {cost}",
|
||||||
"aee88743413144a2": "Refresh",
|
"aee88743413144a2": "Refresh",
|
||||||
|
"b06325c5660f0c29": "Direct",
|
||||||
"b4411558b932266f": "Provider type",
|
"b4411558b932266f": "Provider type",
|
||||||
"b502b1d414664337": "Prompt: {tokens}",
|
"b502b1d414664337": "Prompt: {tokens}",
|
||||||
"b5141d3d19e9a048": "Yes",
|
"b5141d3d19e9a048": "Yes",
|
||||||
"b710ec36ad312918": "The model service API root URL, for example https://api.openai.com/v1.",
|
"b710ec36ad312918": "The model service API root URL, for example https://api.openai.com/v1.",
|
||||||
"b75a46aad3e7c132": "Non-cached input: {tokens}",
|
"b75a46aad3e7c132": "Non-cached input: {tokens}",
|
||||||
"b79354009c614ae9": "Statistics",
|
"b79354009c614ae9": "Statistics",
|
||||||
|
"b86967982067d295": " (estimated)",
|
||||||
"b89a0e4584f27ab5": "Open terminal",
|
"b89a0e4584f27ab5": "Open terminal",
|
||||||
"b8c9b486c83b5778": "Hide ad",
|
"b8c9b486c83b5778": "Hide ad",
|
||||||
"b9670c85a4ab939e": "Route",
|
"b9670c85a4ab939e": "Route",
|
||||||
"b97ad406809572e1": "Enable reasoning",
|
"b97ad406809572e1": "Enable reasoning",
|
||||||
"b9af2de88d903be7": "Proxy address",
|
"b9af2de88d903be7": "Proxy address",
|
||||||
|
"baff6c144180b185": "Connectivity tests completed: {successful} succeeded, {failed} failed",
|
||||||
"bb2b7736433ae867": "Cursor tracing",
|
"bb2b7736433ae867": "Cursor tracing",
|
||||||
"bb7efdcb6af6e805": "Default dark",
|
"bb7efdcb6af6e805": "Default dark",
|
||||||
"bda62ce1d5e4ace9": "Tell us why",
|
"bda62ce1d5e4ace9": "Tell us why",
|
||||||
@@ -236,11 +256,13 @@
|
|||||||
"df8b71c74d9b8478": "Response stream",
|
"df8b71c74d9b8478": "Response stream",
|
||||||
"dfb802238b38fbd4": "Enabled",
|
"dfb802238b38fbd4": "Enabled",
|
||||||
"e025f1ff71996425": "Set",
|
"e025f1ff71996425": "Set",
|
||||||
|
"e0fae77446a389a3": "Speed: {speed} tokens/s",
|
||||||
"e1295adecbb77755": "Close ad",
|
"e1295adecbb77755": "Close ad",
|
||||||
"e14115de7f7c5795": "Token usage over the past year",
|
"e14115de7f7c5795": "Token usage over the past year",
|
||||||
"e14a5eee9b0b0f9f": "Whether the model declares reasoning support.",
|
"e14a5eee9b0b0f9f": "Whether the model declares reasoning support.",
|
||||||
"e14f20d572c02611": "Provider call sequence",
|
"e14f20d572c02611": "Provider call sequence",
|
||||||
"e18516550b9a5105": "No usage",
|
"e18516550b9a5105": "No usage",
|
||||||
|
"e24ebe4a866d69bf": "Test failed: {error}",
|
||||||
"e25bf3f419bb68f0": "Call history",
|
"e25bf3f419bb68f0": "Call history",
|
||||||
"e3fee05f688708b4": "LLM calls",
|
"e3fee05f688708b4": "LLM calls",
|
||||||
"e5043c7a2b408271": "Last 10 minutes",
|
"e5043c7a2b408271": "Last 10 minutes",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
"028a4de61bff743d": "普通输入:{tokens} × ${price}/1M = {cost}",
|
"028a4de61bff743d": "普通输入:{tokens} × ${price}/1M = {cost}",
|
||||||
"03ff62ab4b818492": "缓存写入:{tokens} × ${price}/1M = {cost}",
|
"03ff62ab4b818492": "缓存写入:{tokens} × ${price}/1M = {cost}",
|
||||||
"051836569928a9f9": "编辑",
|
"051836569928a9f9": "编辑",
|
||||||
|
"05468af47054d488": "模型 {model} 连通性测试成功({duration} ms)",
|
||||||
"0580e0a99a6f1afc": "工件数",
|
"0580e0a99a6f1afc": "工件数",
|
||||||
"05912a17829faacc": "所有调用记录和详细追踪数据都会被删除。供应商、模型、CA 和应用设置不会受到影响,此操作无法撤销。",
|
"05912a17829faacc": "所有调用记录和详细追踪数据都会被删除。供应商、模型、CA 和应用设置不会受到影响,此操作无法撤销。",
|
||||||
"076832c1b2de22c3": "缓存写入:{tokens}",
|
"076832c1b2de22c3": "缓存写入:{tokens}",
|
||||||
@@ -22,9 +23,11 @@
|
|||||||
"0d5e2bdb15579fc4": "消息数",
|
"0d5e2bdb15579fc4": "消息数",
|
||||||
"0e41f8e3d59ec47b": "存储管理",
|
"0e41f8e3d59ec47b": "存储管理",
|
||||||
"0ec1e85b0c3cfa65": "调用详情",
|
"0ec1e85b0c3cfa65": "调用详情",
|
||||||
|
"105a9082c346f958": "测试中…",
|
||||||
"124be3f86f197802": "Token 消耗",
|
"124be3f86f197802": "Token 消耗",
|
||||||
"12ae77e6202d063e": "自定义 Headers",
|
"12ae77e6202d063e": "自定义 Headers",
|
||||||
"12b86e89701b0241": "输入模型名称后按 Enter 添加",
|
"12b86e89701b0241": "输入模型名称后按 Enter 添加",
|
||||||
|
"133340e53175128a": "一键测试",
|
||||||
"13a9ac7a68c5fd96": "CA 仅保存在本机,用于安全解析 Cursor 的 HTTPS 请求。",
|
"13a9ac7a68c5fd96": "CA 仅保存在本机,用于安全解析 Cursor 的 HTTPS 请求。",
|
||||||
"13b61c5f697b6700": "缓存命中率",
|
"13b61c5f697b6700": "缓存命中率",
|
||||||
"146da2e2a991493e": "获取中…",
|
"146da2e2a991493e": "获取中…",
|
||||||
@@ -56,6 +59,7 @@
|
|||||||
"2eb2bf7c6597ab9a": "详细记录",
|
"2eb2bf7c6597ab9a": "详细记录",
|
||||||
"2f1b67cdaa23351a": "自定义请求完整地址",
|
"2f1b67cdaa23351a": "自定义请求完整地址",
|
||||||
"2f4a361f878176d1": "{label} 必须是有效 JSON",
|
"2f4a361f878176d1": "{label} 必须是有效 JSON",
|
||||||
|
"2f4a9609285d8f49": "TAB 设置已保存",
|
||||||
"2f5f1d6fbfb061ed": "未设置",
|
"2f5f1d6fbfb061ed": "未设置",
|
||||||
"2f6416a2c424856b": "最终请求地址",
|
"2f6416a2c424856b": "最终请求地址",
|
||||||
"2f7dec3be28d7597": "已选择 {count} 个",
|
"2f7dec3be28d7597": "已选择 {count} 个",
|
||||||
@@ -75,13 +79,14 @@
|
|||||||
"3cfae5728b92b334": "Token 用量:{tokens}",
|
"3cfae5728b92b334": "Token 用量:{tokens}",
|
||||||
"3d13868593ae4eeb": "界面语言",
|
"3d13868593ae4eeb": "界面语言",
|
||||||
"3da0bf1610ff5db5": "推荐内容",
|
"3da0bf1610ff5db5": "推荐内容",
|
||||||
|
"3f6c25aa329163a4": "原接口路径会追加到此服务地址。",
|
||||||
"3fd47edce45b3603": "关闭",
|
"3fd47edce45b3603": "关闭",
|
||||||
"4125fc7ba333524c": "默认亮色",
|
"4125fc7ba333524c": "默认亮色",
|
||||||
"42655ed8e4108ae2": "输入(非缓存)",
|
"42655ed8e4108ae2": "输入(非缓存)",
|
||||||
"42a1d9e5b037c210": "字节数",
|
"42a1d9e5b037c210": "字节数",
|
||||||
"42aa8e01e98c0d8c": "总耗时",
|
"42aa8e01e98c0d8c": "总耗时",
|
||||||
"43cb41d62de2d179": "代理需要认证",
|
"43cb41d62de2d179": "代理需要认证",
|
||||||
"4510b63fdcf7451f": "Cursor 助手 v0.1.0",
|
"461d6a57900c2ed7": "连通性测试失败:{error}",
|
||||||
"470049252e54de6a": "成功占比:{rate}",
|
"470049252e54de6a": "成功占比:{rate}",
|
||||||
"48b970b568a7f8f9": "代理设置",
|
"48b970b568a7f8f9": "代理设置",
|
||||||
"48d8db17bae06246": "共 {count} 条",
|
"48d8db17bae06246": "共 {count} 条",
|
||||||
@@ -92,14 +97,20 @@
|
|||||||
"4d0680f9efaef147": "未读",
|
"4d0680f9efaef147": "未读",
|
||||||
"4eafa9e925b30bcd": "自定义",
|
"4eafa9e925b30bcd": "自定义",
|
||||||
"51d04bc3d286f018": "近1自然日",
|
"51d04bc3d286f018": "近1自然日",
|
||||||
|
"51de3bcec137ab1b": "全部 {count} 个模型连通性测试成功",
|
||||||
"5228358a6db59fe7": "如:现在、2026-08-23 18:00",
|
"5228358a6db59fe7": "如:现在、2026-08-23 18:00",
|
||||||
|
"5401344227e49e2f": "TAB 设置",
|
||||||
"54644705e9c61009": "端口设置",
|
"54644705e9c61009": "端口设置",
|
||||||
"54c53e5fe791d1f3": "初始化 CA",
|
"54c53e5fe791d1f3": "初始化 CA",
|
||||||
"550eddc3c7fefa99": "推广",
|
"550eddc3c7fefa99": "推广",
|
||||||
"555737734a6371e6": "删除上游",
|
"555737734a6371e6": "删除上游",
|
||||||
"56432ba297009bdc": "请先初始化 CA",
|
"56432ba297009bdc": "请先初始化 CA",
|
||||||
|
"59346e82b3dd2998": "TAB 服务地址",
|
||||||
|
"5a3bd99fa69a40c1": "使用公益服务",
|
||||||
"5ae715656ffbc35d": "合并到该上游所有模型的请求体。",
|
"5ae715656ffbc35d": "合并到该上游所有模型的请求体。",
|
||||||
|
"5b17f59d33bde39e": "错误:{error}",
|
||||||
"5c55a67935af8f45": "全部",
|
"5c55a67935af8f45": "全部",
|
||||||
|
"5d59857bf039cac9": "Cursor 助手 v{version}",
|
||||||
"5f8d556a9c47da3c": "已关闭开机启动",
|
"5f8d556a9c47da3c": "已关闭开机启动",
|
||||||
"5f9acfb945229062": "你确认不想再看到此广告吗?",
|
"5f9acfb945229062": "你确认不想再看到此广告吗?",
|
||||||
"5fd2ec5a6e9b654c": "合计:{cost}",
|
"5fd2ec5a6e9b654c": "合计:{cost}",
|
||||||
@@ -111,6 +122,7 @@
|
|||||||
"63c73c4730f4473e": "应用",
|
"63c73c4730f4473e": "应用",
|
||||||
"6478a5f1218c484e": "请在桌面应用中复制到系统剪贴板",
|
"6478a5f1218c484e": "请在桌面应用中复制到系统剪贴板",
|
||||||
"651f274470153a05": "软件更新",
|
"651f274470153a05": "软件更新",
|
||||||
|
"652ec5d40c29fd6a": "速度 {speed} tokens/s · 首字 {firstText} ms · 总耗时 {duration} ms · 输出 {tokens} tokens{estimated} · 返回:{output}",
|
||||||
"653b123c956d3bcb": "调用",
|
"653b123c956d3bcb": "调用",
|
||||||
"656ab25e264cc4e4": "还没有可供 Cursor 使用的模型",
|
"656ab25e264cc4e4": "还没有可供 Cursor 使用的模型",
|
||||||
"65a6318e07ec1e07": "工具数",
|
"65a6318e07ec1e07": "工具数",
|
||||||
@@ -118,6 +130,7 @@
|
|||||||
"68152165b3348852": "选择上游服务使用的请求协议。",
|
"68152165b3348852": "选择上游服务使用的请求协议。",
|
||||||
"68ea5dd4d7af20e6": "系统设置",
|
"68ea5dd4d7af20e6": "系统设置",
|
||||||
"6a9906c79f26c0ba": "开始时间",
|
"6a9906c79f26c0ba": "开始时间",
|
||||||
|
"6aa8f49cc992dfd7": "测试",
|
||||||
"6ae80538c2b2572d": "最小化窗口",
|
"6ae80538c2b2572d": "最小化窗口",
|
||||||
"6d1876364ac6457d": "代理方式",
|
"6d1876364ac6457d": "代理方式",
|
||||||
"6e86570183c3cdd0": "当前已是最新版本",
|
"6e86570183c3cdd0": "当前已是最新版本",
|
||||||
@@ -132,6 +145,7 @@
|
|||||||
"7a3cec4ca715de80": "调用统计",
|
"7a3cec4ca715de80": "调用统计",
|
||||||
"7ba2d6728fe2531b": "确认清理",
|
"7ba2d6728fe2531b": "确认清理",
|
||||||
"7d9f043f8f7ab45c": "发现新版本 {version},可在设置中安装",
|
"7d9f043f8f7ab45c": "发现新版本 {version},可在设置中安装",
|
||||||
|
"7e0891860c9e6374": "TAB 服务地址不能为空",
|
||||||
"7e1845870b528392": "启用模型",
|
"7e1845870b528392": "启用模型",
|
||||||
"7e1f06318e80c3af": "统计数据已清理",
|
"7e1f06318e80c3af": "统计数据已清理",
|
||||||
"7e9ab9ada2cbf2cb": "名称和 Base URL 不能为空",
|
"7e9ab9ada2cbf2cb": "名称和 Base URL 不能为空",
|
||||||
@@ -149,6 +163,7 @@
|
|||||||
"8b6ff498515bcc2f": "时间",
|
"8b6ff498515bcc2f": "时间",
|
||||||
"8d0c47eb9eac2d34": "调用类型",
|
"8d0c47eb9eac2d34": "调用类型",
|
||||||
"8df48894086d6fbd": "原因(可选)",
|
"8df48894086d6fbd": "原因(可选)",
|
||||||
|
"8f9b0d6cc477d334": "控制 Cursor TAB 相关接口的连接方式。",
|
||||||
"90800c48a1dd0655": "{label} 必须是 JSON 对象",
|
"90800c48a1dd0655": "{label} 必须是 JSON 对象",
|
||||||
"919cb0ce0c8db4e7": "留空表示保留当前密码",
|
"919cb0ce0c8db4e7": "留空表示保留当前密码",
|
||||||
"91aaf184cfc17ffd": "数据概览",
|
"91aaf184cfc17ffd": "数据概览",
|
||||||
@@ -158,6 +173,7 @@
|
|||||||
"94803f35c825e47a": "请求完整地址",
|
"94803f35c825e47a": "请求完整地址",
|
||||||
"94df1e7f04815daf": "仅用于界面展示,不会改变发送给上游的模型名称。",
|
"94df1e7f04815daf": "仅用于界面展示,不会改变发送给上游的模型名称。",
|
||||||
"95f76d30c25d5eda": "当前系统暂不支持安装 CA",
|
"95f76d30c25d5eda": "当前系统暂不支持安装 CA",
|
||||||
|
"966498853d801a52": "TAB 选择",
|
||||||
"9850ed41a5bfbb0c": "已选 {count} 项",
|
"9850ed41a5bfbb0c": "已选 {count} 项",
|
||||||
"997ec8201c2adeda": "打开终端安装 CA",
|
"997ec8201c2adeda": "打开终端安装 CA",
|
||||||
"9a026819dd1af5c5": "可以直接输入模型标识,也可以从当前上游返回的模型列表中选择。",
|
"9a026819dd1af5c5": "可以直接输入模型标识,也可以从当前上游返回的模型列表中选择。",
|
||||||
@@ -175,6 +191,7 @@
|
|||||||
"a3ab741ceb188e9e": "未记录请求内容,请开启详细记录后重试。",
|
"a3ab741ceb188e9e": "未记录请求内容,请开启详细记录后重试。",
|
||||||
"a49ffd73bc85333d": "平均",
|
"a49ffd73bc85333d": "平均",
|
||||||
"a621ab606db2a11f": "密码",
|
"a621ab606db2a11f": "密码",
|
||||||
|
"a693d69af48bfe48": "保存并测试",
|
||||||
"a748cc074f78de00": "查看详情",
|
"a748cc074f78de00": "查看详情",
|
||||||
"a98585871c5313ff": "显示名称",
|
"a98585871c5313ff": "显示名称",
|
||||||
"a9ab292ea9feecdc": "上游",
|
"a9ab292ea9feecdc": "上游",
|
||||||
@@ -186,17 +203,20 @@
|
|||||||
"ad6a60ee93d3ba3e": "正在加载调用详情…",
|
"ad6a60ee93d3ba3e": "正在加载调用详情…",
|
||||||
"ae2d0b7f79cea4a3": "模型输出:{tokens} × ${price}/1M = {cost}",
|
"ae2d0b7f79cea4a3": "模型输出:{tokens} × ${price}/1M = {cost}",
|
||||||
"aee88743413144a2": "刷新",
|
"aee88743413144a2": "刷新",
|
||||||
|
"b06325c5660f0c29": "直连",
|
||||||
"b4411558b932266f": "上游类型",
|
"b4411558b932266f": "上游类型",
|
||||||
"b502b1d414664337": "提示词:{tokens}",
|
"b502b1d414664337": "提示词:{tokens}",
|
||||||
"b5141d3d19e9a048": "是",
|
"b5141d3d19e9a048": "是",
|
||||||
"b710ec36ad312918": "模型服务的 API 根地址,例如 https://api.openai.com/v1。",
|
"b710ec36ad312918": "模型服务的 API 根地址,例如 https://api.openai.com/v1。",
|
||||||
"b75a46aad3e7c132": "非缓存输入:{tokens}",
|
"b75a46aad3e7c132": "非缓存输入:{tokens}",
|
||||||
"b79354009c614ae9": "统计数据",
|
"b79354009c614ae9": "统计数据",
|
||||||
|
"b86967982067d295": "(估算)",
|
||||||
"b89a0e4584f27ab5": "打开终端",
|
"b89a0e4584f27ab5": "打开终端",
|
||||||
"b8c9b486c83b5778": "不再显示广告",
|
"b8c9b486c83b5778": "不再显示广告",
|
||||||
"b9670c85a4ab939e": "路由",
|
"b9670c85a4ab939e": "路由",
|
||||||
"b97ad406809572e1": "启用推理",
|
"b97ad406809572e1": "启用推理",
|
||||||
"b9af2de88d903be7": "代理地址",
|
"b9af2de88d903be7": "代理地址",
|
||||||
|
"baff6c144180b185": "连通性测试完成:成功 {successful},失败 {failed}",
|
||||||
"bb2b7736433ae867": "Cursor 追踪",
|
"bb2b7736433ae867": "Cursor 追踪",
|
||||||
"bb7efdcb6af6e805": "默认暗色",
|
"bb7efdcb6af6e805": "默认暗色",
|
||||||
"bda62ce1d5e4ace9": "可以告诉我们原因",
|
"bda62ce1d5e4ace9": "可以告诉我们原因",
|
||||||
@@ -236,11 +256,13 @@
|
|||||||
"df8b71c74d9b8478": "响应流",
|
"df8b71c74d9b8478": "响应流",
|
||||||
"dfb802238b38fbd4": "已启用",
|
"dfb802238b38fbd4": "已启用",
|
||||||
"e025f1ff71996425": "已设置",
|
"e025f1ff71996425": "已设置",
|
||||||
|
"e0fae77446a389a3": "速度:{speed} tokens/s",
|
||||||
"e1295adecbb77755": "关闭广告",
|
"e1295adecbb77755": "关闭广告",
|
||||||
"e14115de7f7c5795": "过去一年的 Token 用量",
|
"e14115de7f7c5795": "过去一年的 Token 用量",
|
||||||
"e14a5eee9b0b0f9f": "是否声明模型支持推理能力。",
|
"e14a5eee9b0b0f9f": "是否声明模型支持推理能力。",
|
||||||
"e14f20d572c02611": "上游调用序号",
|
"e14f20d572c02611": "上游调用序号",
|
||||||
"e18516550b9a5105": "无用量",
|
"e18516550b9a5105": "无用量",
|
||||||
|
"e24ebe4a866d69bf": "测试失败:{error}",
|
||||||
"e25bf3f419bb68f0": "调用详细",
|
"e25bf3f419bb68f0": "调用详细",
|
||||||
"e3fee05f688708b4": "LLM 调用",
|
"e3fee05f688708b4": "LLM 调用",
|
||||||
"e5043c7a2b408271": "近10分钟",
|
"e5043c7a2b408271": "近10分钟",
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
import appIcon from "../../src-tauri/icons/32x32.png";
|
import appIcon from "../../src-tauri/icons/32x32.png";
|
||||||
|
import { currentAppVersion } from "../native/appLifecycle";
|
||||||
import type { DesktopPlatform } from "./AppFrame";
|
import type { DesktopPlatform } from "./AppFrame";
|
||||||
import { WindowControls } from "./WindowControls";
|
import { WindowControls } from "./WindowControls";
|
||||||
import styles from "./AppHeader.module.scss";
|
import styles from "./AppHeader.module.scss";
|
||||||
@@ -10,6 +12,15 @@ type AppHeaderProps = {
|
|||||||
|
|
||||||
export function AppHeader({ platform, nativeDesktop }: AppHeaderProps) {
|
export function AppHeader({ platform, nativeDesktop }: AppHeaderProps) {
|
||||||
const showNativeUi = nativeDesktop && platform !== "macos";
|
const showNativeUi = nativeDesktop && platform !== "macos";
|
||||||
|
const [version, setVersion] = useState("…");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let disposed = false;
|
||||||
|
void currentAppVersion().then((next) => {
|
||||||
|
if (!disposed) setVersion(next);
|
||||||
|
});
|
||||||
|
return () => { disposed = true; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
return <header className={styles.root}>
|
return <header className={styles.root}>
|
||||||
<div className={styles.dragLayer} data-tauri-drag-region aria-hidden="true" />
|
<div className={styles.dragLayer} data-tauri-drag-region aria-hidden="true" />
|
||||||
@@ -17,7 +28,7 @@ export function AppHeader({ platform, nativeDesktop }: AppHeaderProps) {
|
|||||||
{showNativeUi && <>
|
{showNativeUi && <>
|
||||||
<div className={styles.identity} aria-label="Cursor BYOK">
|
<div className={styles.identity} aria-label="Cursor BYOK">
|
||||||
<img src={appIcon} alt="" />
|
<img src={appIcon} alt="" />
|
||||||
<span>{t("Cursor 助手 v0.1.0")}</span>
|
<span>{t("Cursor 助手 v{version}", { version })}</span>
|
||||||
</div>
|
</div>
|
||||||
<WindowControls />
|
<WindowControls />
|
||||||
</>}
|
</>}
|
||||||
|
|||||||
@@ -83,7 +83,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.menuUnreadDot {
|
.menuIndicatorDot {
|
||||||
width: 7px;
|
width: 7px;
|
||||||
height: 7px;
|
height: 7px;
|
||||||
flex: 0 0 7px;
|
flex: 0 0 7px;
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { useMessage } from "../components/ui/message";
|
|||||||
import { VirtualList } from "../components/virtual/VirtualList";
|
import { VirtualList } from "../components/virtual/VirtualList";
|
||||||
import { useI18n } from "../i18n/store";
|
import { useI18n } from "../i18n/store";
|
||||||
import { appStore, useAppStore } from "../store/appStore";
|
import { appStore, useAppStore } from "../store/appStore";
|
||||||
|
import { useUpdateStore } from "../store/updateStore";
|
||||||
import styles from "./AppLayout.module.scss";
|
import styles from "./AppLayout.module.scss";
|
||||||
import { PageActionsTarget } from "./PageActions";
|
import { PageActionsTarget } from "./PageActions";
|
||||||
|
|
||||||
@@ -43,10 +44,12 @@ function loadStoredAdIds(key: string): Set<string> {
|
|||||||
|
|
||||||
export function AppLayout() {
|
export function AppLayout() {
|
||||||
const { busy } = useAppStore();
|
const { busy } = useAppStore();
|
||||||
|
const { availableVersion } = useUpdateStore();
|
||||||
const { locale } = useI18n();
|
const { locale } = useI18n();
|
||||||
const message = useMessage();
|
const message = useMessage();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const [actionTarget, setActionTarget] = useState<HTMLDivElement | null>(null);
|
const [leftActionTarget, setLeftActionTarget] = useState<HTMLDivElement | null>(null);
|
||||||
|
const [rightActionTarget, setRightActionTarget] = useState<HTMLDivElement | null>(null);
|
||||||
const [ads, setAds] = useState<AdSlot[]>([]);
|
const [ads, setAds] = useState<AdSlot[]>([]);
|
||||||
const [activeAd, setActiveAd] = useState<AdSlot | null>(null);
|
const [activeAd, setActiveAd] = useState<AdSlot | null>(null);
|
||||||
const [dismissCandidate, setDismissCandidate] = useState<AdSlot | null>(null);
|
const [dismissCandidate, setDismissCandidate] = useState<AdSlot | null>(null);
|
||||||
@@ -198,7 +201,7 @@ export function AppLayout() {
|
|||||||
? <Icon src={item.icon} size="1.3em" />
|
? <Icon src={item.icon} size="1.3em" />
|
||||||
: <Icon icon={item.icon} size="1.3em" />}
|
: <Icon icon={item.icon} size="1.3em" />}
|
||||||
<span>{item.label}</span>
|
<span>{item.label}</span>
|
||||||
{!tutorialRead && <span className={styles.menuUnreadDot} aria-hidden="true" />}
|
{!tutorialRead && <span className={styles.menuIndicatorDot} aria-hidden="true" />}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
: <div className={styles.navigationRow} key={item.path}>
|
: <div className={styles.navigationRow} key={item.path}>
|
||||||
@@ -207,6 +210,7 @@ export function AppLayout() {
|
|||||||
? <Icon src={item.icon} size="1.3em" />
|
? <Icon src={item.icon} size="1.3em" />
|
||||||
: <Icon icon={item.icon} size="1.3em" />}
|
: <Icon icon={item.icon} size="1.3em" />}
|
||||||
<span>{item.label}</span>
|
<span>{item.label}</span>
|
||||||
|
{item.path === "/settings" && availableVersion && <span className={styles.menuIndicatorDot} aria-hidden="true" />}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
</div>}
|
</div>}
|
||||||
</VirtualList>
|
</VirtualList>
|
||||||
@@ -238,13 +242,14 @@ export function AppLayout() {
|
|||||||
<main className={styles.content}>
|
<main className={styles.content}>
|
||||||
<div className={styles.actionRegion}>
|
<div className={styles.actionRegion}>
|
||||||
<Card className={styles.actions}>
|
<Card className={styles.actions}>
|
||||||
|
<div ref={setLeftActionTarget} className={styles.pageActions} />
|
||||||
{location.pathname !== "/" && <TooltipTrigger label={t("刷新")}><button className={controls.iconButton} aria-label={t("刷新")} disabled={busy} onClick={() => void appStore.refresh()}>
|
{location.pathname !== "/" && <TooltipTrigger label={t("刷新")}><button className={controls.iconButton} aria-label={t("刷新")} disabled={busy} onClick={() => void appStore.refresh()}>
|
||||||
<Icon className={busy ? controls.spin : ""} icon={refreshIcon} size="1.1em" />
|
<Icon className={busy ? controls.spin : ""} icon={refreshIcon} size="1.1em" />
|
||||||
</button></TooltipTrigger>}
|
</button></TooltipTrigger>}
|
||||||
<div ref={setActionTarget} className={styles.pageActions} />
|
<div ref={setRightActionTarget} className={styles.pageActions} />
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
<PageActionsTarget.Provider value={actionTarget}>
|
<PageActionsTarget.Provider value={{ left: leftActionTarget, right: rightActionTarget }}>
|
||||||
<KeepAliveRouteOutlet
|
<KeepAliveRouteOutlet
|
||||||
activeCacheKey={location.pathname}
|
activeCacheKey={location.pathname}
|
||||||
include={keptAlivePages}
|
include={keptAlivePages}
|
||||||
|
|||||||
@@ -2,10 +2,16 @@ import { createContext, useContext, type ReactNode } from "react";
|
|||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { useKeepAliveContext } from "keepalive-for-react";
|
import { useKeepAliveContext } from "keepalive-for-react";
|
||||||
|
|
||||||
export const PageActionsTarget = createContext<HTMLElement | null>(null);
|
type PageActionsTargets = {
|
||||||
|
left: HTMLElement | null;
|
||||||
|
right: HTMLElement | null;
|
||||||
|
};
|
||||||
|
|
||||||
export function PageActions({ children }: { children: ReactNode }) {
|
export const PageActionsTarget = createContext<PageActionsTargets>({ left: null, right: null });
|
||||||
const target = useContext(PageActionsTarget);
|
|
||||||
|
export function PageActions({ children, position = "right" }: { children: ReactNode; position?: "left" | "right" }) {
|
||||||
|
const targets = useContext(PageActionsTarget);
|
||||||
const { active } = useKeepAliveContext();
|
const { active } = useKeepAliveContext();
|
||||||
|
const target = targets[position];
|
||||||
return active && target ? createPortal(children, target) : null;
|
return active && target ? createPortal(children, target) : null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { api, type Model, type ProviderSelection } from "../api";
|
import { api, type Model, type ProviderSelection, type TabSettings } from "../api";
|
||||||
import { CursorCaGate, CursorCaProvider, CursorModelGate, CursorModelProvider } from "../components/cursor/CursorGates";
|
import { CursorCaGate, CursorCaProvider, CursorModelGate, CursorModelProvider } from "../components/cursor/CursorGates";
|
||||||
import { CursorModelEditor, emptyCursorModelDraft, type CursorModelDraft } from "../components/cursor/CursorModelEditor";
|
import { CursorModelEditor, emptyCursorModelDraft, type CursorModelDraft } from "../components/cursor/CursorModelEditor";
|
||||||
|
import { CursorModelTestResult, type CursorModelTestState } from "../components/cursor/CursorModelTestResult";
|
||||||
|
import { TabSettingsCard } from "../components/cursor/TabSettingsCard";
|
||||||
import styles from "../components/cursor/CursorSettings.module.scss";
|
import styles from "../components/cursor/CursorSettings.module.scss";
|
||||||
import { PageContent } from "../components/layout/PageContent";
|
import { PageContent } from "../components/layout/PageContent";
|
||||||
import controls from "../components/ui/Controls.module.scss";
|
import controls from "../components/ui/Controls.module.scss";
|
||||||
@@ -24,12 +26,23 @@ export function CursorSettingsPage() {
|
|||||||
const [caCommand, setCaCommand] = useState<string | null>(null);
|
const [caCommand, setCaCommand] = useState<string | null>(null);
|
||||||
const [waitingForCaRefresh, setWaitingForCaRefresh] = useState(false);
|
const [waitingForCaRefresh, setWaitingForCaRefresh] = useState(false);
|
||||||
const [deleting, setDeleting] = useState<Model | null>(null);
|
const [deleting, setDeleting] = useState<Model | null>(null);
|
||||||
|
const [tabDraft, setTabDraft] = useState<TabSettings | null>(null);
|
||||||
|
const [savingTab, setSavingTab] = useState(false);
|
||||||
|
const [testingModelHashes, setTestingModelHashes] = useState<Set<string>>(() => new Set());
|
||||||
|
const [modelTestResults, setModelTestResults] = useState<Map<string, CursorModelTestState>>(() => new Map());
|
||||||
|
const [savingAndTesting, setSavingAndTesting] = useState(false);
|
||||||
|
const [batchTesting, setBatchTesting] = useState(false);
|
||||||
const grouped = useMemo(() => providers.map((provider) => ({ provider, models: models.filter((model) => model.provider_id === provider.provider_id) })).filter((group) => group.models.length > 0), [providers, models]);
|
const grouped = useMemo(() => providers.map((provider) => ({ provider, models: models.filter((model) => model.provider_id === provider.provider_id) })).filter((group) => group.models.length > 0), [providers, models]);
|
||||||
const caReady = cursorHarness?.ca === "ready";
|
const caReady = cursorHarness?.ca === "ready";
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!caCommand) return;
|
if (!caCommand) return;
|
||||||
void api.copyCursorText(caCommand);
|
void api.copyCursorText(caCommand);
|
||||||
}, [caCommand]);
|
}, [caCommand]);
|
||||||
|
useEffect(() => {
|
||||||
|
void api.tabSettings()
|
||||||
|
.then(setTabDraft)
|
||||||
|
.catch((cause) => message(cause instanceof Error ? cause.message : String(cause)));
|
||||||
|
}, [message]);
|
||||||
const initializeCa = async () => {
|
const initializeCa = async () => {
|
||||||
const status = await appStore.initializeCursorCa();
|
const status = await appStore.initializeCursorCa();
|
||||||
if (status?.ca === "untrusted" && status.ca_install_command) setCaCommand(status.ca_install_command);
|
if (status?.ca === "untrusted" && status.ca_install_command) setCaCommand(status.ca_install_command);
|
||||||
@@ -71,29 +84,79 @@ export function CursorSettingsPage() {
|
|||||||
const save = async () => {
|
const save = async () => {
|
||||||
if (!draft) return;
|
if (!draft) return;
|
||||||
try {
|
try {
|
||||||
const modelIds = editing
|
const modelInputs = cursorModelInputs(draft, editing !== null);
|
||||||
? [draft.model.model_id.trim()]
|
const saved = editing
|
||||||
: [...new Set(draft.modelIds.map((modelId) => modelId.trim()).filter(Boolean))];
|
|
||||||
if (!modelIds.length) throw new Error(t("请至少选择或输入一个模型"));
|
|
||||||
if (editing && !draft.model.display_name.trim()) throw new Error(t("Model ID 和显示名称不能为空"));
|
|
||||||
if (draft.customRequestUrl && !draft.model.request_url.trim()) throw new Error(t("请求完整地址不能为空"));
|
|
||||||
const modelInputs = modelIds.map((modelId, index) => ({
|
|
||||||
...draft.model,
|
|
||||||
model_id: modelId,
|
|
||||||
display_name: modelIds.length === 1 ? draft.model.display_name.trim() || modelId : modelId,
|
|
||||||
sort_order: draft.model.sort_order + index,
|
|
||||||
}));
|
|
||||||
const ok = editing
|
|
||||||
? await appStore.updateCursorModel(editing.model_hash, modelInputs[0])
|
? await appStore.updateCursorModel(editing.model_hash, modelInputs[0])
|
||||||
: await appStore.createCursorModels(providerSelection(draft), modelInputs);
|
: await appStore.createCursorModels(providerSelection(draft), modelInputs);
|
||||||
if (ok) { setDraft(null); setEditing(null); }
|
if (saved) { setDraft(null); setEditing(null); }
|
||||||
} catch (cause) { message(cause instanceof Error ? cause.message : String(cause)); }
|
} catch (cause) { message(cause instanceof Error ? cause.message : String(cause)); }
|
||||||
};
|
};
|
||||||
|
const testModel = async (model: Model, notify = true) => {
|
||||||
|
setTestingModelHashes((current) => new Set(current).add(model.model_hash));
|
||||||
|
try {
|
||||||
|
const result = await api.testModel(model.model_hash);
|
||||||
|
setModelTestResults((current) => new Map(current).set(model.model_hash, { status: "success", result }));
|
||||||
|
if (notify) message(t("模型 {model} 连通性测试成功({duration} ms)", { model: model.display_name, duration: result.duration_ms }));
|
||||||
|
return true;
|
||||||
|
} catch (cause) {
|
||||||
|
const error = cause instanceof Error ? cause.message : String(cause);
|
||||||
|
setModelTestResults((current) => new Map(current).set(model.model_hash, { status: "error", error }));
|
||||||
|
if (notify) message(t("连通性测试失败:{error}", { error }), { duration: 5000 });
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
setTestingModelHashes((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
next.delete(model.model_hash);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const testSingleModel = async (model: Model) => {
|
||||||
|
await testModel(model);
|
||||||
|
await appStore.refresh();
|
||||||
|
};
|
||||||
|
const saveAndTest = async () => {
|
||||||
|
if (!draft || !editing) return;
|
||||||
|
setSavingAndTesting(true);
|
||||||
|
try {
|
||||||
|
const [input] = cursorModelInputs(draft, true);
|
||||||
|
const saved = await appStore.updateCursorModel(editing.model_hash, input);
|
||||||
|
if (!saved) {
|
||||||
|
const error = appStore.getSnapshot().error;
|
||||||
|
if (error) message(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setEditing(saved);
|
||||||
|
await testSingleModel(saved);
|
||||||
|
} catch (cause) {
|
||||||
|
message(cause instanceof Error ? cause.message : String(cause));
|
||||||
|
} finally {
|
||||||
|
setSavingAndTesting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const testAllModels = async () => {
|
||||||
|
if (!models.length || batchTesting) return;
|
||||||
|
const targets = [...models];
|
||||||
|
setBatchTesting(true);
|
||||||
|
try {
|
||||||
|
const results = await Promise.all(targets.map((model) => testModel(model, false)));
|
||||||
|
await appStore.refresh();
|
||||||
|
const successful = results.filter(Boolean).length;
|
||||||
|
const failed = targets.length - successful;
|
||||||
|
message(failed === 0
|
||||||
|
? t("全部 {count} 个模型连通性测试成功", { count: targets.length })
|
||||||
|
: t("连通性测试完成:成功 {successful},失败 {failed}", { successful, failed }), { duration: failed === 0 ? 2400 : 5000 });
|
||||||
|
} finally {
|
||||||
|
setBatchTesting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
const list = <div className={styles.groups}>{grouped.map(({ provider, models: childModels }) => <TitledCard key={provider.provider_id} title={<div className={styles.providerTitle}><Icon icon={provider.provider_type === "anthropic" ? claudeIcon : openAiIcon} /><span>{provider.name}</span></div>}>
|
const list = <div className={styles.groups}>{grouped.map(({ provider, models: childModels }) => <TitledCard key={provider.provider_id} title={<div className={styles.providerTitle}><Icon icon={provider.provider_type === "anthropic" ? claudeIcon : openAiIcon} /><span>{provider.name}</span></div>}>
|
||||||
<div className={styles.models}>{childModels.map((model) => <div className={styles.modelRow} key={model.model_hash}>
|
<div className={styles.models}>{childModels.map((model) => <div className={styles.modelRow} key={model.model_hash}>
|
||||||
<div className={styles.modelName}><strong>{model.display_name}</strong><small>{model.model_id} · {model.model_hash}</small></div>
|
<div className={styles.modelName}><strong>{model.display_name}</strong><small>{model.model_id} · {model.model_hash}</small></div>
|
||||||
{/* <span className={styles.badge}>{model.enabled ? t("已启用") : t("已停用")}</span> */}
|
{/* <span className={styles.badge}>{model.enabled ? t("已启用") : t("已停用")}</span> */}
|
||||||
|
{modelTestResults.get(model.model_hash) && <CursorModelTestResult state={modelTestResults.get(model.model_hash)!} />}
|
||||||
<div className={styles.rowActions}>
|
<div className={styles.rowActions}>
|
||||||
|
<button type="button" className={`${controls.secondary} ${controls.small}`} disabled={testingModelHashes.size > 0 || cursorBusy || batchTesting} onClick={() => void testSingleModel(model)}>{testingModelHashes.has(model.model_hash) ? t("测试中…") : t("测试")}</button>
|
||||||
<TooltipTrigger label={t("编辑模型")}><button className={controls.iconButton} aria-label={t("编辑模型")} onClick={() => openEdit(model)}><Icon icon={editIcon} size="1.1em" /></button></TooltipTrigger>
|
<TooltipTrigger label={t("编辑模型")}><button className={controls.iconButton} aria-label={t("编辑模型")} onClick={() => openEdit(model)}><Icon icon={editIcon} size="1.1em" /></button></TooltipTrigger>
|
||||||
<TooltipTrigger label={t("删除模型")}><button className={`${controls.iconButton} ${controls.danger}`} aria-label={t("删除模型")} onClick={() => setDeleting(model)}><Icon icon={trashIcon} size="1.1em" /></button></TooltipTrigger>
|
<TooltipTrigger label={t("删除模型")}><button className={`${controls.iconButton} ${controls.danger}`} aria-label={t("删除模型")} onClick={() => setDeleting(model)}><Icon icon={trashIcon} size="1.1em" /></button></TooltipTrigger>
|
||||||
</div>
|
</div>
|
||||||
@@ -111,17 +174,39 @@ export function CursorSettingsPage() {
|
|||||||
setCaCommand(null);
|
setCaCommand(null);
|
||||||
setWaitingForCaRefresh(true);
|
setWaitingForCaRefresh(true);
|
||||||
};
|
};
|
||||||
|
const saveTab = async () => {
|
||||||
|
if (!tabDraft) return;
|
||||||
|
try {
|
||||||
|
if (tabDraft.mode === "custom" && !tabDraft.address.trim()) throw new Error(t("TAB 服务地址不能为空"));
|
||||||
|
setSavingTab(true);
|
||||||
|
setTabDraft(await api.setTabSettings(tabDraft));
|
||||||
|
message(t("TAB 设置已保存"));
|
||||||
|
} catch (cause) {
|
||||||
|
message(cause instanceof Error ? cause.message : String(cause));
|
||||||
|
} finally {
|
||||||
|
setSavingTab(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
const content = <CursorCaProvider><CursorCaGate busy={cursorBusy} waitingForRefresh={waitingForCaRefresh} onInitialize={() => void initializeCa()} onRefresh={() => void refreshCa()}>
|
const content = <CursorCaProvider><CursorCaGate busy={cursorBusy} waitingForRefresh={waitingForCaRefresh} onInitialize={() => void initializeCa()} onRefresh={() => void refreshCa()}>
|
||||||
<CursorModelProvider><CursorModelGate onAdd={openNew}>{list}</CursorModelGate></CursorModelProvider>
|
<div className={styles.page}>
|
||||||
|
{tabDraft && <TabSettingsCard settings={tabDraft} saving={savingTab} onChange={setTabDraft} onSave={() => void saveTab()} />}
|
||||||
|
<CursorModelProvider><CursorModelGate onAdd={openNew}>{list}</CursorModelGate></CursorModelProvider>
|
||||||
|
</div>
|
||||||
</CursorCaGate></CursorCaProvider>;
|
</CursorCaGate></CursorCaProvider>;
|
||||||
|
|
||||||
return <>
|
return <>
|
||||||
|
{models.length > 0 && <PageActions position="left">
|
||||||
|
<button type="button" className={controls.secondary} disabled={cursorBusy || testingModelHashes.size > 0 || batchTesting} onClick={() => void testAllModels()}>{batchTesting ? t("测试中…") : t("一键测试")}</button>
|
||||||
|
</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>
|
<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>
|
</PageActions>
|
||||||
<PageContent title={t("Cursor 设置")} sections={[{ key: "cursor-settings", estimatedHeight: Math.max(280, models.length * 55 + grouped.length * 62), content }]} />
|
<PageContent title={t("Cursor 设置")} sections={[{ key: "cursor-settings", estimatedHeight: Math.max(430, models.length * 55 + grouped.length * 62 + 145), content }]} />
|
||||||
<Modal open={draft !== null} title={editing ? t("编辑模型") : t("添加模型")} busy={cursorBusy} onClose={() => setDraft(null)} onSubmit={() => void save()}>
|
<Modal open={draft !== null} title={editing ? t("编辑模型") : t("添加模型")} busy={cursorBusy || savingAndTesting} onClose={() => setDraft(null)} onSubmit={() => void save()} secondaryAction={editing ? <button type="button" className={controls.secondary} disabled={cursorBusy || savingAndTesting} onClick={() => void saveAndTest()}>{savingAndTesting ? t("测试中…") : t("保存并测试")}</button> : undefined}>
|
||||||
{draft && <CursorModelEditor draft={draft} providers={providers} editing={editing !== null} modelOptions={modelOptions} discovering={discovering} onChange={setDraft} onDiscover={() => void discover()} />}
|
{draft && <>
|
||||||
|
<CursorModelEditor draft={draft} providers={providers} editing={editing !== null} modelOptions={modelOptions} discovering={discovering} onChange={setDraft} onDiscover={() => void discover()} />
|
||||||
|
{editing && modelTestResults.get(editing.model_hash) && <div className={styles.editorTestResult}><CursorModelTestResult state={modelTestResults.get(editing.model_hash)!} /></div>}
|
||||||
|
</>}
|
||||||
</Modal>
|
</Modal>
|
||||||
<Modal open={caCommand !== null} title={t("安装本地 CA")} closeLabel={t("关闭")} submitLabel={t("打开终端")} onClose={() => setCaCommand(null)} onSubmit={openCaTerminal}>
|
<Modal open={caCommand !== null} title={t("安装本地 CA")} closeLabel={t("关闭")} submitLabel={t("打开终端")} onClose={() => setCaCommand(null)} onSubmit={openCaTerminal}>
|
||||||
<div className={styles.editor}>
|
<div className={styles.editor}>
|
||||||
@@ -143,6 +228,21 @@ function parseObject(text: string, label: string): Record<string, unknown> {
|
|||||||
return parsed as Record<string, unknown>;
|
return parsed as Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function cursorModelInputs(draft: CursorModelDraft, editing: boolean) {
|
||||||
|
const modelIds = editing
|
||||||
|
? [draft.model.model_id.trim()]
|
||||||
|
: [...new Set(draft.modelIds.map((modelId) => modelId.trim()).filter(Boolean))];
|
||||||
|
if (!modelIds.length) throw new Error(t("请至少选择或输入一个模型"));
|
||||||
|
if (editing && !draft.model.display_name.trim()) throw new Error(t("Model ID 和显示名称不能为空"));
|
||||||
|
if (draft.customRequestUrl && !draft.model.request_url.trim()) throw new Error(t("请求完整地址不能为空"));
|
||||||
|
return modelIds.map((modelId, index) => ({
|
||||||
|
...draft.model,
|
||||||
|
model_id: modelId,
|
||||||
|
display_name: modelIds.length === 1 ? draft.model.display_name.trim() || modelId : modelId,
|
||||||
|
sort_order: draft.model.sort_order + index,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
function providerName(baseUrl: string): string {
|
function providerName(baseUrl: string): string {
|
||||||
try {
|
try {
|
||||||
return new URL(baseUrl.trim()).hostname;
|
return new URL(baseUrl.trim()).hostname;
|
||||||
|
|||||||
@@ -198,12 +198,12 @@ export const appStore = {
|
|||||||
async updateCursorModel(hash: string, model: ModelInput) {
|
async updateCursorModel(hash: string, model: ModelInput) {
|
||||||
update({ cursorBusy: true, error: null });
|
update({ cursorBusy: true, error: null });
|
||||||
try {
|
try {
|
||||||
await api.updateModel(hash, model);
|
const updated = await api.updateModel(hash, model);
|
||||||
await appStore.refresh();
|
await appStore.refresh();
|
||||||
return true;
|
return updated;
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
update({ error: cause instanceof Error ? cause.message : String(cause) });
|
update({ error: cause instanceof Error ? cause.message : String(cause) });
|
||||||
return false;
|
return null;
|
||||||
} finally { update({ cursorBusy: false }); }
|
} finally { update({ cursorBusy: false }); }
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { useSyncExternalStore } from "react";
|
||||||
|
import type { Update } from "@tauri-apps/plugin-updater";
|
||||||
|
import {
|
||||||
|
checkForUpdate,
|
||||||
|
hasNativeAppLifecycle,
|
||||||
|
installUpdate,
|
||||||
|
} from "../native/appLifecycle";
|
||||||
|
|
||||||
|
export type UpdateSnapshot = {
|
||||||
|
availableVersion: string | null;
|
||||||
|
checking: boolean;
|
||||||
|
installing: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
let snapshot: UpdateSnapshot = {
|
||||||
|
availableVersion: null,
|
||||||
|
checking: false,
|
||||||
|
installing: false,
|
||||||
|
};
|
||||||
|
let availableUpdate: Update | null = null;
|
||||||
|
let pendingCheck: Promise<string | null> | null = null;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function update(patch: Partial<UpdateSnapshot>) {
|
||||||
|
snapshot = { ...snapshot, ...patch };
|
||||||
|
listeners.forEach((listener) => listener());
|
||||||
|
}
|
||||||
|
|
||||||
|
async function replaceAvailableUpdate(next: Update | null) {
|
||||||
|
const previous = availableUpdate;
|
||||||
|
availableUpdate = next;
|
||||||
|
update({ availableVersion: next?.version ?? null });
|
||||||
|
if (previous && previous !== next) await previous.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const updateStore = {
|
||||||
|
subscribe(listener: () => void) {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => listeners.delete(listener);
|
||||||
|
},
|
||||||
|
getSnapshot: () => snapshot,
|
||||||
|
|
||||||
|
async check(): Promise<string | null> {
|
||||||
|
if (!hasNativeAppLifecycle()) return null;
|
||||||
|
if (pendingCheck) return pendingCheck;
|
||||||
|
update({ checking: true });
|
||||||
|
pendingCheck = (async () => {
|
||||||
|
const next = await checkForUpdate();
|
||||||
|
await replaceAvailableUpdate(next);
|
||||||
|
return next?.version ?? null;
|
||||||
|
})();
|
||||||
|
try {
|
||||||
|
return await pendingCheck;
|
||||||
|
} finally {
|
||||||
|
pendingCheck = null;
|
||||||
|
update({ checking: false });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async install(): Promise<void> {
|
||||||
|
const current = availableUpdate;
|
||||||
|
if (!current) return;
|
||||||
|
update({ installing: true });
|
||||||
|
try {
|
||||||
|
await installUpdate(current);
|
||||||
|
} finally {
|
||||||
|
update({ installing: false });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useUpdateStore(): UpdateSnapshot {
|
||||||
|
return useSyncExternalStore(updateStore.subscribe, updateStore.getSnapshot);
|
||||||
|
}
|
||||||
+3
-2
@@ -41,8 +41,9 @@ impl App {
|
|||||||
config.provider_request_timeout,
|
config.provider_request_timeout,
|
||||||
));
|
));
|
||||||
let run_registry = RunRegistry::default();
|
let run_registry = RunRegistry::default();
|
||||||
let registry = CursorSessionRegistry::new(store.clone(), provider, compiler, run_registry);
|
let registry =
|
||||||
let control = control::ControlService::new(store.clone())?;
|
CursorSessionRegistry::new(store.clone(), provider.clone(), compiler, run_registry);
|
||||||
|
let control = control::ControlService::new(store.clone(), provider)?;
|
||||||
let harness = control.cursor_harness().clone();
|
let harness = control.cursor_harness().clone();
|
||||||
let mut router = handlers::router(registry.clone())?;
|
let mut router = handlers::router(registry.clone())?;
|
||||||
router = match &config.console {
|
router = match &config.console {
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ use tower_http::{
|
|||||||
use url::{Host, Url};
|
use url::{Host, Url};
|
||||||
|
|
||||||
pub use service::{
|
pub use service::{
|
||||||
CallDetail, CallSummary, ControlService, DiscoveredModels, ObservabilitySettings,
|
CallDetail, CallSummary, ControlService, DiscoveredModels, ModelConnectivityResult,
|
||||||
|
ObservabilitySettings,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn web_router(service: ControlService, assets: impl AsRef<std::path::Path>) -> Router {
|
pub fn web_router(service: ControlService, assets: impl AsRef<std::path::Path>) -> Router {
|
||||||
@@ -137,6 +138,10 @@ pub fn api_router(service: ControlService) -> Router {
|
|||||||
"/__byok-api__/api/models/{model_hash}",
|
"/__byok-api__/api/models/{model_hash}",
|
||||||
put(models::update).delete(models::remove),
|
put(models::update).delete(models::remove),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/__byok-api__/api/models/{model_hash}/test",
|
||||||
|
post(models::test),
|
||||||
|
)
|
||||||
.route("/__byok-api__/api/llm-calls", get(calls::list))
|
.route("/__byok-api__/api/llm-calls", get(calls::list))
|
||||||
.route("/__byok-api__/api/llm-calls/{call_id}", get(calls::detail))
|
.route("/__byok-api__/api/llm-calls/{call_id}", get(calls::detail))
|
||||||
.route(
|
.route(
|
||||||
@@ -155,6 +160,10 @@ pub fn api_router(service: ControlService) -> Router {
|
|||||||
"/__byok-api__/api/settings/proxy",
|
"/__byok-api__/api/settings/proxy",
|
||||||
get(settings::get_proxy).put(settings::update_proxy),
|
get(settings::get_proxy).put(settings::update_proxy),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/__byok-api__/api/settings/tab",
|
||||||
|
get(settings::get_tab).put(settings::update_tab),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/__byok-api__/api/harness/cursor/status",
|
"/__byok-api__/api/harness/cursor/status",
|
||||||
get(harness::status),
|
get(harness::status),
|
||||||
@@ -242,7 +251,11 @@ mod tests {
|
|||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let router = api_router(ControlService::new(store).unwrap());
|
let provider = std::sync::Arc::new(crate::provider::ProviderRouter::new(
|
||||||
|
store.clone(),
|
||||||
|
std::time::Duration::from_secs(300),
|
||||||
|
));
|
||||||
|
let router = api_router(ControlService::new(store, provider).unwrap());
|
||||||
|
|
||||||
let response = router
|
let response = router
|
||||||
.clone()
|
.clone()
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::{
|
|||||||
Result,
|
Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{ControlService, DiscoveredModels};
|
use super::{ControlService, DiscoveredModels, ModelConnectivityResult};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct SaveModels {
|
pub struct SaveModels {
|
||||||
@@ -48,6 +48,13 @@ pub async fn update(
|
|||||||
Ok(Json(service.update_model(&model_hash, &input).await?))
|
Ok(Json(service.update_model(&model_hash, &input).await?))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn test(
|
||||||
|
State(service): State<ControlService>,
|
||||||
|
Path(model_hash): Path<String>,
|
||||||
|
) -> Result<Json<ModelConnectivityResult>> {
|
||||||
|
Ok(Json(service.test_model(&model_hash).await?))
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn discover(
|
pub async fn discover(
|
||||||
State(service): State<ControlService>,
|
State(service): State<ControlService>,
|
||||||
Path(provider_id): Path<i64>,
|
Path(provider_id): Path<i64>,
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
use std::collections::BTreeSet;
|
use std::{collections::BTreeSet, sync::Arc, time::Instant};
|
||||||
|
|
||||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
use futures_util::StreamExt;
|
||||||
use reqwest::header::{HeaderName, HeaderValue};
|
use reqwest::header::{HeaderName, HeaderValue};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use super::ads::{
|
use super::ads::{
|
||||||
@@ -13,11 +15,15 @@ use super::ads::{
|
|||||||
use crate::{
|
use crate::{
|
||||||
harness::CursorHarness,
|
harness::CursorHarness,
|
||||||
model::{
|
model::{
|
||||||
CursorRunTraceArtifact, CursorRunTraceSummary, LlmCallRequest, LlmCallResponseChunk,
|
ContentPart, CursorRunTraceArtifact, CursorRunTraceSummary, LlmCallRequest,
|
||||||
LlmCallSummary, Overview, ProviderEndpoint, ProviderEndpointInput, ProviderEndpointSecret,
|
LlmCallResponseChunk, LlmCallSummary, ModelInvocation, ModelRequest, ModelSpec, Overview,
|
||||||
ProviderModel, ProviderModelInput, ProviderType,
|
ProjectedContent, ProjectedMessage, PromptSpec, ProviderEndpoint, ProviderEndpointInput,
|
||||||
|
ProviderEndpointSecret, ProviderModel, ProviderModelInput, ProviderType, Role,
|
||||||
|
},
|
||||||
|
provider::{ModelEvent, Provider},
|
||||||
|
store::{
|
||||||
|
PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, Store, TabSettings,
|
||||||
},
|
},
|
||||||
store::{PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, Store},
|
|
||||||
Error, Result,
|
Error, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -25,6 +31,7 @@ use crate::{
|
|||||||
pub struct ControlService {
|
pub struct ControlService {
|
||||||
store: Store,
|
store: Store,
|
||||||
cursor_harness: CursorHarness,
|
cursor_harness: CursorHarness,
|
||||||
|
provider: Arc<dyn Provider>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize)]
|
#[derive(Clone, Debug, Serialize)]
|
||||||
@@ -32,6 +39,16 @@ pub struct DiscoveredModels {
|
|||||||
pub models: Vec<String>,
|
pub models: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct ModelConnectivityResult {
|
||||||
|
pub duration_ms: u64,
|
||||||
|
pub first_text_ms: Option<u64>,
|
||||||
|
pub output_tokens: u64,
|
||||||
|
pub tokens_per_second: f64,
|
||||||
|
pub tokens_estimated: bool,
|
||||||
|
pub output: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize)]
|
#[derive(Clone, Debug, Serialize)]
|
||||||
pub struct CallDetail {
|
pub struct CallDetail {
|
||||||
pub call: CallSummary,
|
pub call: CallSummary,
|
||||||
@@ -72,10 +89,11 @@ pub struct ObservabilitySettings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ControlService {
|
impl ControlService {
|
||||||
pub fn new(store: Store) -> Result<Self> {
|
pub fn new(store: Store, provider: Arc<dyn Provider>) -> Result<Self> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
cursor_harness: CursorHarness::new(store.clone())?,
|
cursor_harness: CursorHarness::new(store.clone())?,
|
||||||
store,
|
store,
|
||||||
|
provider,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,6 +218,125 @@ impl ControlService {
|
|||||||
self.store.update_provider_model(model_hash, input).await
|
self.store.update_provider_model(model_hash, input).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn test_model(&self, model_hash: &str) -> Result<ModelConnectivityResult> {
|
||||||
|
const TEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(45);
|
||||||
|
const TEST_PROMPT: &str = "Output the numbers 1 through 120 separated by a single space. No commas, no newlines, no explanation.";
|
||||||
|
|
||||||
|
let configured = self
|
||||||
|
.store
|
||||||
|
.provider_model(model_hash)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| Error::RunNotFound(format!("model {model_hash}")))?;
|
||||||
|
let mut model = ModelSpec::new(model_hash);
|
||||||
|
if configured.reasoning_enabled {
|
||||||
|
model.reasoning.enabled = true;
|
||||||
|
model.reasoning.effort = Some(
|
||||||
|
configured
|
||||||
|
.reasoning_effort
|
||||||
|
.filter(|effort| !effort.trim().is_empty())
|
||||||
|
.unwrap_or_else(|| "medium".into()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let test_id = format!("model-test-{}", uuid::Uuid::new_v4());
|
||||||
|
let call_id = test_id.clone();
|
||||||
|
let invocation = ModelInvocation {
|
||||||
|
call_id: test_id.clone(),
|
||||||
|
run_id: test_id.clone(),
|
||||||
|
conversation_id: test_id,
|
||||||
|
provider_call_index: 0,
|
||||||
|
request: ModelRequest {
|
||||||
|
prompt: PromptSpec {
|
||||||
|
instructions: String::new(),
|
||||||
|
tools: Vec::new(),
|
||||||
|
},
|
||||||
|
model,
|
||||||
|
history: vec![ProjectedMessage {
|
||||||
|
message_id: "connectivity-test".into(),
|
||||||
|
role: Role::User,
|
||||||
|
content: ProjectedContent::Parts(vec![ContentPart::Text {
|
||||||
|
text: TEST_PROMPT.into(),
|
||||||
|
}]),
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let cancellation = CancellationToken::new();
|
||||||
|
let started = Instant::now();
|
||||||
|
let mut first_text_at = None;
|
||||||
|
let mut output_tokens = None;
|
||||||
|
let mut output = String::new();
|
||||||
|
let stream = self.provider.stream(invocation, cancellation.clone());
|
||||||
|
let completed = tokio::time::timeout(TEST_TIMEOUT, async {
|
||||||
|
futures_util::pin_mut!(stream);
|
||||||
|
let mut finished = false;
|
||||||
|
while let Some(event) = stream.next().await {
|
||||||
|
match event? {
|
||||||
|
ModelEvent::TextDelta(delta) => {
|
||||||
|
if first_text_at.is_none() && !delta.trim().is_empty() {
|
||||||
|
first_text_at = Some(Instant::now());
|
||||||
|
}
|
||||||
|
output.push_str(&delta);
|
||||||
|
}
|
||||||
|
ModelEvent::Usage(usage) => {
|
||||||
|
if let Some(tokens) = usage.output_tokens.filter(|tokens| *tokens > 0) {
|
||||||
|
output_tokens = Some(
|
||||||
|
output_tokens.map_or(tokens, |current: u64| current.max(tokens)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ModelEvent::Done(_) => finished = true,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !finished {
|
||||||
|
return Err(Error::Protocol(
|
||||||
|
"provider stream ended without Done during connectivity test".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match completed {
|
||||||
|
Ok(result) => result?,
|
||||||
|
Err(_) => {
|
||||||
|
cancellation.cancel();
|
||||||
|
self.store
|
||||||
|
.finish_llm_call(
|
||||||
|
&call_id,
|
||||||
|
"error",
|
||||||
|
None,
|
||||||
|
started.elapsed().as_millis().min(i64::MAX as u128) as i64,
|
||||||
|
Some("timeout"),
|
||||||
|
Some("model connectivity test timed out after 45 seconds"),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
return Err(Error::Provider(
|
||||||
|
"model connectivity test timed out after 45 seconds".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
let output = output.trim().to_string();
|
||||||
|
let tokens_estimated = output_tokens.is_none();
|
||||||
|
let output_tokens = output_tokens.unwrap_or_else(|| estimate_output_tokens(&output));
|
||||||
|
Ok(ModelConnectivityResult {
|
||||||
|
duration_ms: elapsed.as_millis().min(u128::from(u64::MAX)) as u64,
|
||||||
|
first_text_ms: first_text_at.map(|first| {
|
||||||
|
first
|
||||||
|
.duration_since(started)
|
||||||
|
.as_millis()
|
||||||
|
.min(u128::from(u64::MAX)) as u64
|
||||||
|
}),
|
||||||
|
output_tokens,
|
||||||
|
tokens_per_second: if elapsed.is_zero() {
|
||||||
|
0.0
|
||||||
|
} else {
|
||||||
|
output_tokens as f64 / elapsed.as_secs_f64()
|
||||||
|
},
|
||||||
|
tokens_estimated,
|
||||||
|
output,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn create_provider_with_models(
|
pub async fn create_provider_with_models(
|
||||||
&self,
|
&self,
|
||||||
provider: &ProviderEndpointInput,
|
provider: &ProviderEndpointInput,
|
||||||
@@ -372,6 +509,14 @@ impl ControlService {
|
|||||||
pub async fn set_proxy_settings(&self, settings: ProxySettingsInput) -> Result<ProxySettings> {
|
pub async fn set_proxy_settings(&self, settings: ProxySettingsInput) -> Result<ProxySettings> {
|
||||||
self.store.set_proxy_settings(settings).await
|
self.store.set_proxy_settings(settings).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn tab_settings(&self) -> Result<TabSettings> {
|
||||||
|
self.store.tab_settings().await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_tab_settings(&self, settings: TabSettings) -> Result<TabSettings> {
|
||||||
|
self.cursor_harness.set_tab_settings(settings).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn official_call(trace: CursorRunTraceSummary) -> CallSummary {
|
fn official_call(trace: CursorRunTraceSummary) -> CallSummary {
|
||||||
@@ -543,6 +688,17 @@ fn model_ids(value: &serde_json::Value) -> Vec<String> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn estimate_output_tokens(output: &str) -> u64 {
|
||||||
|
let words = output.split_whitespace().count() as u64;
|
||||||
|
if words > 0 {
|
||||||
|
words
|
||||||
|
} else if output.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
((output.chars().count() as u64) + 3) / 4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn apply_custom_headers(
|
fn apply_custom_headers(
|
||||||
mut request: reqwest::RequestBuilder,
|
mut request: reqwest::RequestBuilder,
|
||||||
headers: &serde_json::Value,
|
headers: &serde_json::Value,
|
||||||
@@ -562,3 +718,124 @@ fn apply_custom_headers(
|
|||||||
}
|
}
|
||||||
Ok(request)
|
Ok(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
model::{
|
||||||
|
ModelInvocation, ProjectedContent, ProviderEndpointInput, ProviderModelInput,
|
||||||
|
ProviderType,
|
||||||
|
},
|
||||||
|
provider::{FinishReason, ModelEvent, Provider, ProviderStream},
|
||||||
|
store::Store,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::ControlService;
|
||||||
|
|
||||||
|
struct TestProvider {
|
||||||
|
invocation: Arc<Mutex<Option<ModelInvocation>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Provider for TestProvider {
|
||||||
|
fn stream(
|
||||||
|
&self,
|
||||||
|
invocation: ModelInvocation,
|
||||||
|
_cancellation: CancellationToken,
|
||||||
|
) -> ProviderStream {
|
||||||
|
*self.invocation.lock().unwrap() = Some(invocation);
|
||||||
|
Box::pin(futures_util::stream::iter([
|
||||||
|
Ok(ModelEvent::Start {
|
||||||
|
model_call_id: "test-call".into(),
|
||||||
|
}),
|
||||||
|
Ok(ModelEvent::TextStart),
|
||||||
|
Ok(ModelEvent::TextDelta("OK".into())),
|
||||||
|
Ok(ModelEvent::TextEnd),
|
||||||
|
Ok(ModelEvent::Usage(crate::model::Usage {
|
||||||
|
output_tokens: Some(2),
|
||||||
|
..Default::default()
|
||||||
|
})),
|
||||||
|
Ok(ModelEvent::Done(FinishReason::Stop)),
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn connectivity_test_uses_the_configured_llm_provider() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let store = Store::connect(&format!(
|
||||||
|
"sqlite://{}",
|
||||||
|
directory.path().join("control.db").display()
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let invocation = Arc::new(Mutex::new(None));
|
||||||
|
let provider = store
|
||||||
|
.create_provider(&ProviderEndpointInput {
|
||||||
|
name: "Test".into(),
|
||||||
|
provider_type: ProviderType::OpenAiResponses,
|
||||||
|
base_url: "https://example.com/v1".into(),
|
||||||
|
api_key: None,
|
||||||
|
custom_headers: serde_json::json!({}),
|
||||||
|
extra_params: serde_json::json!({}),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let model = store
|
||||||
|
.save_provider_model(
|
||||||
|
provider.provider_id,
|
||||||
|
&ProviderModelInput {
|
||||||
|
model_id: "reasoning-model".into(),
|
||||||
|
display_name: "Reasoning Model".into(),
|
||||||
|
endpoint_type: ProviderType::OpenAiResponses,
|
||||||
|
request_url: String::new(),
|
||||||
|
enabled: true,
|
||||||
|
sort_order: 0,
|
||||||
|
context_window_tokens: None,
|
||||||
|
max_output_tokens: None,
|
||||||
|
reasoning_enabled: true,
|
||||||
|
reasoning_effort: None,
|
||||||
|
supports_image_generation: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let service = ControlService::new(
|
||||||
|
store,
|
||||||
|
Arc::new(TestProvider {
|
||||||
|
invocation: invocation.clone(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let result = service.test_model(&model.model_hash).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(result.output, "OK");
|
||||||
|
assert_eq!(result.output_tokens, 2);
|
||||||
|
assert!(!result.tokens_estimated);
|
||||||
|
assert!(result.tokens_per_second > 0.0);
|
||||||
|
let invocation = invocation.lock().unwrap().clone().unwrap();
|
||||||
|
assert_eq!(invocation.request.model.model_id, model.model_hash);
|
||||||
|
assert!(invocation.request.model.reasoning.enabled);
|
||||||
|
assert_eq!(
|
||||||
|
invocation.request.model.reasoning.effort.as_deref(),
|
||||||
|
Some("medium")
|
||||||
|
);
|
||||||
|
assert!(invocation.request.prompt.tools.is_empty());
|
||||||
|
assert_eq!(invocation.request.history.len(), 1);
|
||||||
|
assert!(matches!(
|
||||||
|
&invocation.request.history[0].content,
|
||||||
|
ProjectedContent::Parts(parts)
|
||||||
|
if matches!(&parts[..], [crate::model::ContentPart::Text { text }] if text == "Output the numbers 1 through 120 separated by a single space. No commas, no newlines, no explanation.")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn connectivity_output_token_estimate_handles_words_and_empty_text() {
|
||||||
|
assert_eq!(super::estimate_output_tokens("1 2 3"), 3);
|
||||||
|
assert_eq!(super::estimate_output_tokens(""), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
use crate::Result;
|
use crate::Result;
|
||||||
use axum::{extract::State, Json};
|
use axum::{extract::State, Json};
|
||||||
|
|
||||||
use crate::store::{PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage};
|
use crate::store::{
|
||||||
|
PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, TabSettings,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{ControlService, ObservabilitySettings};
|
use super::{ControlService, ObservabilitySettings};
|
||||||
|
|
||||||
@@ -47,3 +49,14 @@ pub async fn update_proxy(
|
|||||||
) -> Result<Json<ProxySettings>> {
|
) -> Result<Json<ProxySettings>> {
|
||||||
Ok(Json(service.set_proxy_settings(settings).await?))
|
Ok(Json(service.set_proxy_settings(settings).await?))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn get_tab(State(service): State<ControlService>) -> Result<Json<TabSettings>> {
|
||||||
|
Ok(Json(service.tab_settings().await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_tab(
|
||||||
|
State(service): State<ControlService>,
|
||||||
|
Json(settings): Json<TabSettings>,
|
||||||
|
) -> Result<Json<TabSettings>> {
|
||||||
|
Ok(Json(service.set_tab_settings(settings).await?))
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use prost::Message;
|
use prost::Message;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
cursor::interaction,
|
||||||
cursor::proto::{agent::v1 as agent, aiserver::v1 as ai},
|
cursor::proto::{agent::v1 as agent, aiserver::v1 as ai},
|
||||||
cursor::{CursorCommand, CursorParent, CursorSessionRegistry},
|
cursor::{CursorCommand, CursorParent, CursorSessionRegistry},
|
||||||
Error, Result,
|
Error, Result,
|
||||||
@@ -166,6 +167,12 @@ pub async fn append(
|
|||||||
if let Some(parent) = parent {
|
if let Some(parent) = parent {
|
||||||
handle.set_parent(parent)?;
|
handle.set_parent(parent)?;
|
||||||
}
|
}
|
||||||
|
if matches!(
|
||||||
|
request.message.message.as_ref(),
|
||||||
|
Some(agent::agent_client_message::Message::ClientHeartbeat(_))
|
||||||
|
) {
|
||||||
|
handle.emit(&interaction::heartbeat())?;
|
||||||
|
}
|
||||||
handle
|
handle
|
||||||
.command(CursorCommand::Append {
|
.command(CursorCommand::Append {
|
||||||
seqno: request.seqno,
|
seqno: request.seqno,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ use crate::{
|
|||||||
observability::CursorTraceRecorder,
|
observability::CursorTraceRecorder,
|
||||||
proto::{agent::v1 as agent, aiserver::v1 as ai},
|
proto::{agent::v1 as agent, aiserver::v1 as ai},
|
||||||
proxy::{self, CursorProxy},
|
proxy::{self, CursorProxy},
|
||||||
run_sse,
|
run_sse, tab,
|
||||||
},
|
},
|
||||||
cursor::{CursorParent, CursorSessionRegistry},
|
cursor::{CursorParent, CursorSessionRegistry},
|
||||||
Result,
|
Result,
|
||||||
@@ -70,6 +70,7 @@ fn router_with_proxy(registry: CursorSessionRegistry, proxy: CursorProxy) -> Rou
|
|||||||
post(analytics::bootstrap_statsig),
|
post(analytics::bootstrap_statsig),
|
||||||
)
|
)
|
||||||
.route("/auth/full_stripe_profile", get(account::stripe_profile))
|
.route("/auth/full_stripe_profile", get(account::stripe_profile))
|
||||||
|
.merge(tab::router())
|
||||||
.route_layer(DefaultBodyLimit::disable())
|
.route_layer(DefaultBodyLimit::disable())
|
||||||
.route_layer(RequestDecompressionLayer::new())
|
.route_layer(RequestDecompressionLayer::new())
|
||||||
.fallback(proxy::forward)
|
.fallback(proxy::forward)
|
||||||
|
|||||||
@@ -66,6 +66,12 @@ pub fn thinking_completed(elapsed: Duration) -> pb::AgentServerMessage {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn heartbeat() -> pb::AgentServerMessage {
|
||||||
|
server_interaction(pb::interaction_update::Message::Heartbeat(
|
||||||
|
pb::HeartbeatUpdate {},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn arguments_delta(call: &ToolCall, delta: &str) -> Result<pb::AgentServerMessage> {
|
pub fn arguments_delta(call: &ToolCall, delta: &str) -> Result<pb::AgentServerMessage> {
|
||||||
Ok(server_interaction(
|
Ok(server_interaction(
|
||||||
pb::interaction_update::Message::PartialToolCall(pb::PartialToolCallUpdate {
|
pb::interaction_update::Message::PartialToolCall(pb::PartialToolCallUpdate {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ pub mod request;
|
|||||||
pub mod run_sse;
|
pub mod run_sse;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod sessions;
|
pub mod sessions;
|
||||||
|
pub(crate) mod tab;
|
||||||
pub mod tools;
|
pub mod tools;
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
|
|||||||
@@ -82,14 +82,34 @@ impl CursorProxy {
|
|||||||
pub async fn forward(
|
pub async fn forward(
|
||||||
Extension(proxy): Extension<CursorProxy>,
|
Extension(proxy): Extension<CursorProxy>,
|
||||||
request: Request<Body>,
|
request: Request<Body>,
|
||||||
|
) -> Result<Response<Body>> {
|
||||||
|
forward_request(&proxy, request, None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn forward_to_service(
|
||||||
|
proxy: &CursorProxy,
|
||||||
|
request: Request<Body>,
|
||||||
|
service_url: &str,
|
||||||
|
) -> Result<Response<Body>> {
|
||||||
|
forward_request(proxy, request, Some(service_url)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn forward_request(
|
||||||
|
proxy: &CursorProxy,
|
||||||
|
request: Request<Body>,
|
||||||
|
service_url: Option<&str>,
|
||||||
) -> Result<Response<Body>> {
|
) -> Result<Response<Body>> {
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let (parts, body) = request.into_parts();
|
let (parts, body) = request.into_parts();
|
||||||
let path = parts
|
let path = parts
|
||||||
.uri
|
.uri
|
||||||
.path_and_query()
|
.path_and_query()
|
||||||
.map_or("/", |value| value.as_str());
|
.map_or("/", |value| value.as_str())
|
||||||
let url = upstream_url(&parts.headers, &proxy.upstream, path)?;
|
.to_owned();
|
||||||
|
let url = match service_url {
|
||||||
|
Some(service_url) => format!("{}{}", service_url.trim_end_matches('/'), path),
|
||||||
|
None => upstream_url(&parts.headers, &proxy.upstream, &path)?,
|
||||||
|
};
|
||||||
|
|
||||||
let mut headers = parts.headers;
|
let mut headers = parts.headers;
|
||||||
headers.remove(UPSTREAM_URL_HEADER);
|
headers.remove(UPSTREAM_URL_HEADER);
|
||||||
@@ -239,7 +259,7 @@ mod tests {
|
|||||||
};
|
};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
use super::{forward, CursorProxy};
|
use super::{forward, forward_to_service, CursorProxy};
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn preserves_request_and_response() {
|
async fn preserves_request_and_response() {
|
||||||
@@ -289,4 +309,34 @@ mod tests {
|
|||||||
);
|
);
|
||||||
server.abort();
|
server.abort();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tab_service_keeps_its_base_path_and_the_original_query() {
|
||||||
|
let upstream = Router::new().route(
|
||||||
|
"/base/aiserver.v1.AiService/StreamCpp",
|
||||||
|
any(|request: Request<Body>| async move {
|
||||||
|
request.uri().path_and_query().unwrap().as_str().to_owned()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
|
||||||
|
let proxy = CursorProxy::for_upstream("http://unused.invalid").unwrap();
|
||||||
|
|
||||||
|
let response = forward_to_service(
|
||||||
|
&proxy,
|
||||||
|
Request::post("/aiserver.v1.AiService/StreamCpp?client=cursor")
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap(),
|
||||||
|
&format!("http://{address}/base"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
to_bytes(response.into_body(), usize::MAX).await.unwrap(),
|
||||||
|
"/base/aiserver.v1.AiService/StreamCpp?client=cursor"
|
||||||
|
);
|
||||||
|
server.abort();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+102
-11
@@ -3,29 +3,24 @@ use axum::{
|
|||||||
http::{header, HeaderValue, Response, StatusCode},
|
http::{header, HeaderValue, Response, StatusCode},
|
||||||
};
|
};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use std::convert::Infallible;
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use tokio_stream::StreamExt;
|
use tokio_stream::StreamExt;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
cursor::{observability::CursorTraceRecorder, CursorSessionRegistry},
|
cursor::{connect::END_STREAM_FLAG, observability::CursorTraceRecorder, CursorSessionRegistry},
|
||||||
Result,
|
Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn stream(registry: &CursorSessionRegistry, request_id: &str) -> Result<Response<Body>> {
|
pub async fn stream(registry: &CursorSessionRegistry, request_id: &str) -> Result<Response<Body>> {
|
||||||
let handle = registry.get_or_create(request_id).await?;
|
let handle = registry.get_or_create(request_id).await?;
|
||||||
let mut receiver = handle.subscribe();
|
let receiver = handle.subscribe();
|
||||||
let trace = handle.trace().cloned();
|
let trace = handle.trace().cloned();
|
||||||
if let Some(trace) = &trace {
|
if let Some(trace) = &trace {
|
||||||
trace.response_started(StatusCode::OK.as_u16()).await;
|
trace.response_started(StatusCode::OK.as_u16()).await;
|
||||||
}
|
}
|
||||||
let body_stream = async_stream::stream! {
|
let body_stream = local_body_stream(receiver, handle.cancellation(), trace);
|
||||||
let mut trace = TraceStreamSink::new(trace, "byok_server");
|
|
||||||
while let Some(chunk) = receiver.recv().await {
|
|
||||||
trace.chunk(&chunk);
|
|
||||||
yield Ok::<Bytes, std::convert::Infallible>(chunk);
|
|
||||||
}
|
|
||||||
trace.finish(None);
|
|
||||||
};
|
|
||||||
let mut response = Response::new(Body::from_stream(body_stream));
|
let mut response = Response::new(Body::from_stream(body_stream));
|
||||||
*response.status_mut() = StatusCode::OK;
|
*response.status_mut() = StatusCode::OK;
|
||||||
response.headers_mut().insert(
|
response.headers_mut().insert(
|
||||||
@@ -41,6 +36,63 @@ pub async fn stream(registry: &CursorSessionRegistry, request_id: &str) -> Resul
|
|||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn local_body_stream(
|
||||||
|
mut receiver: mpsc::UnboundedReceiver<Bytes>,
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
trace: Option<CursorTraceRecorder>,
|
||||||
|
) -> impl tokio_stream::Stream<Item = std::result::Result<Bytes, Infallible>> {
|
||||||
|
async_stream::stream! {
|
||||||
|
let mut guard = LocalRunGuard::new(cancellation);
|
||||||
|
let mut trace = TraceStreamSink::new(trace, "byok_server");
|
||||||
|
while let Some(chunk) = receiver.recv().await {
|
||||||
|
let terminal = is_end_stream_frame(&chunk);
|
||||||
|
trace.chunk(&chunk);
|
||||||
|
if terminal {
|
||||||
|
guard.complete();
|
||||||
|
trace.finish(None);
|
||||||
|
}
|
||||||
|
yield Ok::<Bytes, Infallible>(chunk);
|
||||||
|
if terminal {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard.complete();
|
||||||
|
trace.finish(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_end_stream_frame(frame: &Bytes) -> bool {
|
||||||
|
frame
|
||||||
|
.first()
|
||||||
|
.is_some_and(|flags| flags & END_STREAM_FLAG != 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct LocalRunGuard {
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
completed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LocalRunGuard {
|
||||||
|
fn new(cancellation: CancellationToken) -> Self {
|
||||||
|
Self {
|
||||||
|
cancellation,
|
||||||
|
completed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn complete(&mut self) {
|
||||||
|
self.completed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for LocalRunGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.completed {
|
||||||
|
self.cancellation.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn upstream(
|
pub async fn upstream(
|
||||||
registry: CursorSessionRegistry,
|
registry: CursorSessionRegistry,
|
||||||
request_id: String,
|
request_id: String,
|
||||||
@@ -127,7 +179,11 @@ impl TraceStreamSink {
|
|||||||
|
|
||||||
impl Drop for TraceStreamSink {
|
impl Drop for TraceStreamSink {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.finish(None);
|
if self.sender.is_some() {
|
||||||
|
self.finish(Some(
|
||||||
|
"response stream dropped before completion".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,3 +199,38 @@ impl Drop for UpstreamRunGuard {
|
|||||||
.finish_upstream(self.request_id.clone(), self.generation);
|
.finish_upstream(self.request_id.clone(), self.generation);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::cursor::{connect, proto::agent::v1 as pb};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn local_stream_cancels_when_the_client_disconnects() {
|
||||||
|
let (sender, receiver) = mpsc::unbounded_channel();
|
||||||
|
let cancellation = CancellationToken::new();
|
||||||
|
sender
|
||||||
|
.send(connect::encode_message(&pb::AgentServerMessage::default()).unwrap())
|
||||||
|
.unwrap();
|
||||||
|
let mut stream = Box::pin(local_body_stream(receiver, cancellation.clone(), None));
|
||||||
|
|
||||||
|
stream.next().await.unwrap().unwrap();
|
||||||
|
|
||||||
|
drop(sender);
|
||||||
|
drop(stream);
|
||||||
|
assert!(cancellation.is_cancelled());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn terminal_frame_does_not_cancel_a_completed_local_run() {
|
||||||
|
let (sender, receiver) = mpsc::unbounded_channel();
|
||||||
|
let cancellation = CancellationToken::new();
|
||||||
|
sender.send(connect::encode_end_stream()).unwrap();
|
||||||
|
let mut stream = Box::pin(local_body_stream(receiver, cancellation.clone(), None));
|
||||||
|
|
||||||
|
let terminal = stream.next().await.unwrap().unwrap();
|
||||||
|
assert!(is_end_stream_frame(&terminal));
|
||||||
|
drop(stream);
|
||||||
|
assert!(!cancellation.is_cancelled());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
use axum::{
|
||||||
|
body::Body,
|
||||||
|
extract::{Extension, State},
|
||||||
|
http::{Request, Response},
|
||||||
|
routing::post,
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
cursor::{proxy, CursorSessionRegistry},
|
||||||
|
Result,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const TAB_PATHS: [&str; 17] = [
|
||||||
|
"/aiserver.v1.AiService/StreamCpp",
|
||||||
|
"/aiserver.v1.AiService/StreamNextCursorPrediction",
|
||||||
|
"/aiserver.v1.AiService/GetCppEditClassification",
|
||||||
|
"/aiserver.v1.AiService/RefreshTabContext",
|
||||||
|
"/aiserver.v1.AiService/CppConfig",
|
||||||
|
"/aiserver.v1.AiService/CppEditHistoryStatus",
|
||||||
|
"/aiserver.v1.AiService/CppAppend",
|
||||||
|
"/aiserver.v1.AiService/CppEditHistoryAppend",
|
||||||
|
"/aiserver.v1.AiService/ReportAiCodeChangeMetrics",
|
||||||
|
"/aiserver.v1.AiService/WriteGitCommitMessage",
|
||||||
|
"/aiserver.v1.AiService/WriteGitBranchName",
|
||||||
|
"/aiserver.v1.CppService/AvailableModels",
|
||||||
|
"/aiserver.v1.CppService/RecordCppFate",
|
||||||
|
"/aiserver.v1.FileSyncService/FSSyncFile",
|
||||||
|
"/aiserver.v1.FileSyncService/FSIsEnabledForUser",
|
||||||
|
"/aiserver.v1.FileSyncService/FSConfig",
|
||||||
|
"/aiserver.v1.FileSyncService/FSUploadFile",
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn is_tab_path(path: &str) -> bool {
|
||||||
|
TAB_PATHS.contains(&path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn router() -> Router<CursorSessionRegistry> {
|
||||||
|
TAB_PATHS.into_iter().fold(Router::new(), |router, path| {
|
||||||
|
router.route(path, post(forward))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn forward(
|
||||||
|
State(registry): State<CursorSessionRegistry>,
|
||||||
|
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||||
|
request: Request<Body>,
|
||||||
|
) -> Result<Response<Body>> {
|
||||||
|
let settings = registry.store().tab_settings().await?;
|
||||||
|
match settings.service_url() {
|
||||||
|
Some(service_url) => proxy::forward_to_service(&upstream, request, service_url).await,
|
||||||
|
None => proxy::forward(Extension(upstream), request).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matches_only_legacy_tab_routes() {
|
||||||
|
assert_eq!(TAB_PATHS.len(), 17);
|
||||||
|
assert!(is_tab_path("/aiserver.v1.AiService/StreamCpp"));
|
||||||
|
assert!(is_tab_path("/aiserver.v1.FileSyncService/FSUploadFile"));
|
||||||
|
assert!(!is_tab_path("/aiserver.v1.AiService/AvailableModels"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,10 @@ use parking_lot::RwLock;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use crate::{store::Store, Error, Result};
|
use crate::{
|
||||||
|
store::{Store, TabMode, TabSettings},
|
||||||
|
Error, Result,
|
||||||
|
};
|
||||||
|
|
||||||
use self::{ca::CaManager, proxy::ProxyRuntime};
|
use self::{ca::CaManager, proxy::ProxyRuntime};
|
||||||
|
|
||||||
@@ -65,6 +68,7 @@ struct Inner {
|
|||||||
ca: CaManager,
|
ca: CaManager,
|
||||||
ca_initialization: Mutex<()>,
|
ca_initialization: Mutex<()>,
|
||||||
backend_addr: RwLock<Option<SocketAddr>>,
|
backend_addr: RwLock<Option<SocketAddr>>,
|
||||||
|
tab_mode: Arc<RwLock<TabMode>>,
|
||||||
proxy: Mutex<ProxyRuntime>,
|
proxy: Mutex<ProxyRuntime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +80,7 @@ impl CursorHarness {
|
|||||||
ca: CaManager::managed()?,
|
ca: CaManager::managed()?,
|
||||||
ca_initialization: Mutex::new(()),
|
ca_initialization: Mutex::new(()),
|
||||||
backend_addr: RwLock::new(None),
|
backend_addr: RwLock::new(None),
|
||||||
|
tab_mode: Arc::new(RwLock::new(TabMode::default())),
|
||||||
proxy: Mutex::new(ProxyRuntime::default()),
|
proxy: Mutex::new(ProxyRuntime::default()),
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
@@ -138,6 +143,12 @@ impl CursorHarness {
|
|||||||
self.status().await
|
self.status().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn set_tab_settings(&self, settings: TabSettings) -> Result<TabSettings> {
|
||||||
|
let saved = self.inner.store.set_tab_settings(settings).await?;
|
||||||
|
*self.inner.tab_mode.write() = saved.mode;
|
||||||
|
Ok(saved)
|
||||||
|
}
|
||||||
|
|
||||||
async fn enable(&self) -> Result<()> {
|
async fn enable(&self) -> Result<()> {
|
||||||
if !matches!(self.inner.ca.state()?, CaState::Ready) {
|
if !matches!(self.inner.ca.state()?, CaState::Ready) {
|
||||||
return Err(Error::Config(
|
return Err(Error::Config(
|
||||||
@@ -158,7 +169,15 @@ impl CursorHarness {
|
|||||||
}
|
}
|
||||||
let ca = self.inner.ca.load()?;
|
let ca = self.inner.ca.load()?;
|
||||||
let requested_port = self.inner.store.port_settings().await?.proxy_port;
|
let requested_port = self.inner.store.port_settings().await?.proxy_port;
|
||||||
let (url, actual_port) = proxy.start(backend_addr, ca, requested_port).await?;
|
*self.inner.tab_mode.write() = self.inner.store.tab_settings().await?.mode;
|
||||||
|
let (url, actual_port) = proxy
|
||||||
|
.start(
|
||||||
|
backend_addr,
|
||||||
|
ca,
|
||||||
|
requested_port,
|
||||||
|
self.inner.tab_mode.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
if let Err(error) = self.inner.store.set_proxy_port(actual_port).await {
|
if let Err(error) = self.inner.store.set_proxy_port(actual_port).await {
|
||||||
proxy.stop().await;
|
proxy.stop().await;
|
||||||
return Err(error);
|
return Err(error);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::net::SocketAddr;
|
use std::{net::SocketAddr, sync::Arc};
|
||||||
|
|
||||||
use hudsucker::{
|
use hudsucker::{
|
||||||
certificate_authority::RcgenAuthority,
|
certificate_authority::RcgenAuthority,
|
||||||
@@ -8,7 +8,13 @@ use hudsucker::{
|
|||||||
};
|
};
|
||||||
use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle};
|
use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle};
|
||||||
|
|
||||||
use crate::{cursor::proxy::UPSTREAM_URL_HEADER, Error, Result};
|
use parking_lot::RwLock;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
cursor::{proxy::UPSTREAM_URL_HEADER, tab::is_tab_path},
|
||||||
|
store::TabMode,
|
||||||
|
Error, Result,
|
||||||
|
};
|
||||||
|
|
||||||
use super::ca::LoadedCa;
|
use super::ca::LoadedCa;
|
||||||
|
|
||||||
@@ -33,6 +39,7 @@ impl ProxyRuntime {
|
|||||||
backend: SocketAddr,
|
backend: SocketAddr,
|
||||||
ca: LoadedCa,
|
ca: LoadedCa,
|
||||||
requested_port: u16,
|
requested_port: u16,
|
||||||
|
tab_mode: Arc<RwLock<TabMode>>,
|
||||||
) -> Result<(String, u16)> {
|
) -> Result<(String, u16)> {
|
||||||
if let Some(url) = self.url() {
|
if let Some(url) = self.url() {
|
||||||
return Ok((url, self.port.unwrap_or_default()));
|
return Ok((url, self.port.unwrap_or_default()));
|
||||||
@@ -45,7 +52,7 @@ impl ProxyRuntime {
|
|||||||
.with_listener(listener)
|
.with_listener(listener)
|
||||||
.with_ca(authority)
|
.with_ca(authority)
|
||||||
.with_rustls_connector(aws_lc_rs::default_provider())
|
.with_rustls_connector(aws_lc_rs::default_provider())
|
||||||
.with_http_handler(CursorRelay { backend })
|
.with_http_handler(CursorRelay { backend, tab_mode })
|
||||||
.with_graceful_shutdown(async move {
|
.with_graceful_shutdown(async move {
|
||||||
let _ = done.await;
|
let _ = done.await;
|
||||||
})
|
})
|
||||||
@@ -89,6 +96,7 @@ async fn bind_proxy_listener(requested_port: u16) -> Result<TcpListener> {
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct CursorRelay {
|
struct CursorRelay {
|
||||||
backend: SocketAddr,
|
backend: SocketAddr,
|
||||||
|
tab_mode: Arc<RwLock<TabMode>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpHandler for CursorRelay {
|
impl HttpHandler for CursorRelay {
|
||||||
@@ -98,7 +106,8 @@ impl HttpHandler for CursorRelay {
|
|||||||
mut request: Request<Body>,
|
mut request: Request<Body>,
|
||||||
) -> RequestOrResponse {
|
) -> RequestOrResponse {
|
||||||
let original = request.uri().clone();
|
let original = request.uri().clone();
|
||||||
if is_cursor_host(original.host().unwrap_or_default()) && is_local_path(original.path()) {
|
let locally_routed = should_route_locally(original.path(), *self.tab_mode.read());
|
||||||
|
if is_cursor_host(original.host().unwrap_or_default()) && locally_routed {
|
||||||
if let Ok(value) = original.to_string().parse() {
|
if let Ok(value) = original.to_string().parse() {
|
||||||
request.headers_mut().insert(UPSTREAM_URL_HEADER, value);
|
request.headers_mut().insert(UPSTREAM_URL_HEADER, value);
|
||||||
}
|
}
|
||||||
@@ -157,6 +166,10 @@ fn is_local_path(path: &str) -> bool {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn should_route_locally(path: &str, tab_mode: TabMode) -> bool {
|
||||||
|
is_local_path(path) || (is_tab_path(path) && tab_mode != TabMode::Direct)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -179,5 +192,17 @@ mod tests {
|
|||||||
"/aiserver.v1.AnalyticsService/BootstrapStatsig"
|
"/aiserver.v1.AnalyticsService/BootstrapStatsig"
|
||||||
));
|
));
|
||||||
assert!(!is_local_path("/unrelated"));
|
assert!(!is_local_path("/unrelated"));
|
||||||
|
assert!(should_route_locally(
|
||||||
|
"/aiserver.v1.AiService/StreamCpp",
|
||||||
|
TabMode::Public
|
||||||
|
));
|
||||||
|
assert!(should_route_locally(
|
||||||
|
"/aiserver.v1.AiService/StreamCpp",
|
||||||
|
TabMode::Custom
|
||||||
|
));
|
||||||
|
assert!(!should_route_locally(
|
||||||
|
"/aiserver.v1.AiService/StreamCpp",
|
||||||
|
TabMode::Direct
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,11 +140,11 @@ impl Provider for OpenAiResponsesProvider {
|
|||||||
}
|
}
|
||||||
if text_open { text_open = false; yield ModelEvent::TextEnd; }
|
if text_open { text_open = false; yield ModelEvent::TextEnd; }
|
||||||
}
|
}
|
||||||
"response.reasoning_summary_text.delta" => {
|
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => {
|
||||||
if !thinking_open { thinking_open = true; yield ModelEvent::ThinkingStart; }
|
if !thinking_open { thinking_open = true; yield ModelEvent::ThinkingStart; }
|
||||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) { yield ModelEvent::ThinkingDelta(delta.into()); }
|
if let Some(delta) = value.get("delta").and_then(Value::as_str) { yield ModelEvent::ThinkingDelta(delta.into()); }
|
||||||
}
|
}
|
||||||
"response.reasoning_summary_text.done" => {
|
"response.reasoning_summary_text.done" | "response.reasoning_text.done" => {
|
||||||
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
if thinking_open { thinking_open = false; yield ModelEvent::ThinkingEnd; }
|
||||||
}
|
}
|
||||||
"response.output_item.added" => {
|
"response.output_item.added" => {
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ use super::{now_ms, Store};
|
|||||||
|
|
||||||
const PORT_SETTINGS_KEY: &str = "network_ports";
|
const PORT_SETTINGS_KEY: &str = "network_ports";
|
||||||
const PROXY_SETTINGS_KEY: &str = "outbound_proxy";
|
const PROXY_SETTINGS_KEY: &str = "outbound_proxy";
|
||||||
|
const TAB_SETTINGS_KEY: &str = "cursor_tab";
|
||||||
const INSTALLATION_ID_KEY: &str = "installation_id";
|
const INSTALLATION_ID_KEY: &str = "installation_id";
|
||||||
|
|
||||||
|
pub const PUBLIC_TAB_SERVICE_URL: &str = "https://tab.leokun.cn";
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||||
pub struct PortSettings {
|
pub struct PortSettings {
|
||||||
pub proxy_port: u16,
|
pub proxy_port: u16,
|
||||||
@@ -28,6 +31,31 @@ impl ProxyMode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum TabMode {
|
||||||
|
#[default]
|
||||||
|
Public,
|
||||||
|
Direct,
|
||||||
|
Custom,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct TabSettings {
|
||||||
|
pub mode: TabMode,
|
||||||
|
pub address: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TabSettings {
|
||||||
|
pub fn service_url(&self) -> Option<&str> {
|
||||||
|
match self.mode {
|
||||||
|
TabMode::Public => Some(PUBLIC_TAB_SERVICE_URL),
|
||||||
|
TabMode::Direct => None,
|
||||||
|
TabMode::Custom => Some(&self.address),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||||
pub struct ProxySettingsInput {
|
pub struct ProxySettingsInput {
|
||||||
pub mode: ProxyMode,
|
pub mode: ProxyMode,
|
||||||
@@ -139,6 +167,47 @@ impl Store {
|
|||||||
self.proxy_settings().await
|
self.proxy_settings().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn tab_settings(&self) -> Result<TabSettings> {
|
||||||
|
let value = sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||||
|
)
|
||||||
|
.bind(TAB_SETTINGS_KEY)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
value
|
||||||
|
.map(|value| serde_json::from_str(&value).map_err(Into::into))
|
||||||
|
.unwrap_or_else(|| Ok(TabSettings::default()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_tab_settings(&self, mut settings: TabSettings) -> Result<TabSettings> {
|
||||||
|
settings.address = settings.address.trim().trim_end_matches('/').to_owned();
|
||||||
|
if settings.mode == TabMode::Custom {
|
||||||
|
let parsed = url::Url::parse(&settings.address).map_err(|error| {
|
||||||
|
crate::Error::Config(format!("invalid TAB service address: {error}"))
|
||||||
|
})?;
|
||||||
|
if !matches!(parsed.scheme(), "http" | "https") {
|
||||||
|
return Err(crate::Error::Config(
|
||||||
|
"TAB service address must use http or https".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if parsed.host_str().is_none()
|
||||||
|
|| parsed.query().is_some()
|
||||||
|
|| parsed.fragment().is_some()
|
||||||
|
{
|
||||||
|
return Err(crate::Error::Config(
|
||||||
|
"TAB service address must be a base URL without a query or fragment".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
|
||||||
|
.bind(TAB_SETTINGS_KEY)
|
||||||
|
.bind(serde_json::to_string(&settings)?)
|
||||||
|
.bind(now_ms())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(settings)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn port_settings(&self) -> Result<PortSettings> {
|
pub async fn port_settings(&self) -> Result<PortSettings> {
|
||||||
let value = sqlx::query_scalar::<_, String>(
|
let value = sqlx::query_scalar::<_, String>(
|
||||||
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||||
@@ -244,4 +313,28 @@ mod tests {
|
|||||||
"secret"
|
"secret"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tab_settings_default_to_public_and_validate_custom_urls() {
|
||||||
|
let store = Store::connect("sqlite::memory:").await.unwrap();
|
||||||
|
assert_eq!(store.tab_settings().await.unwrap(), TabSettings::default());
|
||||||
|
|
||||||
|
let saved = store
|
||||||
|
.set_tab_settings(TabSettings {
|
||||||
|
mode: TabMode::Custom,
|
||||||
|
address: " https://tab.example.com/base/ ".into(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(saved.address, "https://tab.example.com/base");
|
||||||
|
assert_eq!(store.tab_settings().await.unwrap(), saved);
|
||||||
|
|
||||||
|
assert!(store
|
||||||
|
.set_tab_settings(TabSettings {
|
||||||
|
mode: TabMode::Custom,
|
||||||
|
address: "file:///tmp/tab".into(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -146,6 +146,59 @@ async fn registry_shutdown_cancels_runs_and_closes_run_sse_outputs() {
|
|||||||
assert_eq!(output.recv().await, None);
|
assert_eq!(output.recv().await, None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn client_heartbeat_returns_a_server_protocol_heartbeat() {
|
||||||
|
let (_directory, store) = fixtures::temp_store().await;
|
||||||
|
let assets = PromptAssets::load(
|
||||||
|
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("prompt/cursor")
|
||||||
|
.as_path(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let registry = CursorSessionRegistry::new(
|
||||||
|
store,
|
||||||
|
Arc::new(fake_provider::FakeProvider::default()),
|
||||||
|
PromptCompiler::new(assets),
|
||||||
|
Default::default(),
|
||||||
|
);
|
||||||
|
let handle = registry.get_or_create("heartbeat-run").await.unwrap();
|
||||||
|
let mut output = handle.subscribe();
|
||||||
|
|
||||||
|
cursor_server::cursor::bidi_append::append(
|
||||||
|
®istry,
|
||||||
|
cursor_server::cursor::bidi_append::DecodedAppend {
|
||||||
|
request_id: "heartbeat-run".into(),
|
||||||
|
// A transport heartbeat must not wait for missing application messages.
|
||||||
|
seqno: 1,
|
||||||
|
message: pb::AgentClientMessage {
|
||||||
|
message: Some(pb::agent_client_message::Message::ClientHeartbeat(
|
||||||
|
pb::ClientHeartbeat {},
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let frame = tokio::time::timeout(std::time::Duration::from_secs(1), output.recv())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
let (_, payload) = connect::decode_frames(&frame).unwrap().pop().unwrap();
|
||||||
|
let message = pb::AgentServerMessage::decode(payload).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
message.message,
|
||||||
|
Some(pb::agent_server_message::Message::InteractionUpdate(
|
||||||
|
pb::InteractionUpdate {
|
||||||
|
message: Some(pb::interaction_update::Message::Heartbeat(_)),
|
||||||
|
}
|
||||||
|
))
|
||||||
|
));
|
||||||
|
|
||||||
|
registry.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn runtime_user_message_action_aborts_active_exec_before_canceled_end_stream() {
|
async fn runtime_user_message_action_aborts_active_exec_before_canceled_end_stream() {
|
||||||
let (_directory, store) = fixtures::temp_store().await;
|
let (_directory, store) = fixtures::temp_store().await;
|
||||||
|
|||||||
@@ -329,6 +329,37 @@ async fn openai_responses_raw_stream_does_not_invent_reasoning_effort() {
|
|||||||
assert_eq!(replayed, ["opaque-1", "opaque-2"]);
|
assert_eq!(replayed, ["opaque-1", "opaque-2"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn openai_responses_streams_openrouter_reasoning_text_events() {
|
||||||
|
let (base_url, _requests, server) = fixture_server(
|
||||||
|
"/v1/responses",
|
||||||
|
concat!(
|
||||||
|
"data: {\"type\":\"response.reasoning_text.delta\",\"delta\":\"still working\"}\n\n",
|
||||||
|
"data: {\"type\":\"response.reasoning_text.done\"}\n\n",
|
||||||
|
"data: {\"type\":\"response.completed\",\"response\":{}}\n\n",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let provider = OpenAiResponsesProvider::new(
|
||||||
|
reqwest::Client::new(),
|
||||||
|
config(ProviderKind::OpenAiResponses, base_url, None),
|
||||||
|
);
|
||||||
|
|
||||||
|
let events = collect(provider.stream(invocation(), CancellationToken::new())).await;
|
||||||
|
server.abort();
|
||||||
|
|
||||||
|
assert!(events
|
||||||
|
.iter()
|
||||||
|
.any(|event| matches!(event, ModelEvent::ThinkingStart)));
|
||||||
|
assert!(events.iter().any(
|
||||||
|
|event| matches!(event, ModelEvent::ThinkingDelta(delta) if delta == "still working")
|
||||||
|
));
|
||||||
|
assert!(events
|
||||||
|
.iter()
|
||||||
|
.any(|event| matches!(event, ModelEvent::ThinkingEnd)));
|
||||||
|
assert_eq!(events.last(), Some(&ModelEvent::Done(FinishReason::Stop)));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn openai_responses_reasoning_item_done_closes_an_open_summary() {
|
async fn openai_responses_reasoning_item_done_closes_an_open_summary() {
|
||||||
let (base_url, _requests, server) = fixture_server(
|
let (base_url, _requests, server) = fixture_server(
|
||||||
|
|||||||
Reference in New Issue
Block a user