Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ tauri-plugin-shell = "2"
# 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制
# 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从
# 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.2.2" }
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.3.0" }

anyhow = "1"
libc = "0.2"
Expand Down
11 changes: 5 additions & 6 deletions src-tauri/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,12 +540,11 @@ impl ControlClient {
}

/// 按接口地址自动识别会得到什么。不联网
pub async fn preview_provider(&self, base_url: String) -> Result<tw_api::ProviderPreview> {
self.post_json(
"/providers/preview",
&tw_api::ProviderPreviewRequest { base_url },
)
.await
pub async fn preview_provider(
&self,
req: &tw_api::ProviderPreviewRequest,
) -> Result<tw_api::ProviderPreview> {
self.post_json("/providers/preview", req).await
}

pub async fn provider_models(&self, name: &str) -> Result<tw_api::ProviderModelsView> {
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/upstreams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ pub async fn test_provider(
#[tauri::command]
pub async fn preview_provider(
state: tauri::State<'_, AppState>,
base_url: String,
preview: tw_api::ProviderPreviewRequest,
) -> Out<tw_api::ProviderPreview> {
state.control.preview_provider(base_url).await.map_err(text)
state.control.preview_provider(&preview).await.map_err(text)
}

#[tauri::command]
Expand Down
34 changes: 34 additions & 0 deletions src/source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";

function sources(dir: string): string[] {
const out: string[] = [];
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isDirectory()) out.push(...sources(p));
else if (/[.](ts|tsx|css)$/.test(e.name)) out.push(p);
}
return out;
}

/** 制表、换行、回车以外的 C0 控制字符 */
function hasControlChar(text: string): boolean {
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d) return true;
}
return false;
}

describe("源码文件", () => {
/**
* **下拉框里的占位值曾经是一个字面的 NUL 字节。**编译和运行都没问题,
* 但 git 从此把整个文件当二进制:PR 里看不到这个文件的 diff,评审时等于
* 没审。
*/
it("不含 NUL 等控制字符", () => {
const bad = sources("src").filter((f) => hasControlChar(readFileSync(f, "utf8")));
expect(bad).toEqual([]);
});
});
69 changes: 54 additions & 15 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -733,14 +733,14 @@ export interface ProviderView {
base_url: string;
/** 地址里有被打码的部分 */
base_url_masked: boolean;
/** 密钥的来源,不是值 */
key_source: string;
/** `key` / `env` / `oauth` */
key_kind: "key" | "env" | "oauth";
/** `env` 时的变量名 */
key_env?: string | null;
oauth_endpoint?: string | null;
oauth_client_id?: string | null;
/** API 密钥:打过码的值或环境变量名。没有密钥是 null */
key?: SecretView | null;
/** 密钥放在哪个请求头里发:`x-api-key` / `authorization` / `x-goog-api-key` */
auth_header: string;
/** 其余请求头,按配置里的顺序 */
headers?: HeaderView[];
/** OAuth 的 token 端点和 client id。refresh token 和 client secret 不出 core */
oauth?: OAuthView | null;
/** 实际生效的协议。推断不出时为 null */
protocol: string | null;
/** 协议是配置里写明的,还是按地址推断的 */
Expand Down Expand Up @@ -775,6 +775,28 @@ export interface ProviderView {
pricing?: string | null;
}

/** 一个可能是密钥的值给界面看的样子 */
export interface SecretView {
/** 打过码的值,或者 `环境变量 ${NAME}` */
display: string;
/** 整个值恰好是一个 `${NAME}` 时的变量名 */
env?: string | null;
}

/** 一行请求头 */
export interface HeaderView {
name: string;
/** 可能是密钥的值是打过码的 */
value: string;
/** 值打过码。编辑时这一行不回填,留空表示保持原值 */
masked: boolean;
}

export interface OAuthView {
endpoint: string;
client_id?: string | null;
}

/** 配置里引用了某个上游的一处 */
export type ReferenceView =
| { kind: "rule_target"; route: string; rule: string }
Expand Down Expand Up @@ -1172,12 +1194,24 @@ export interface ConfigWritten {
version: string;
}

/** 凭据的三种写法 */
export type CredentialInput =
| { kind: "key"; value: string }
| { kind: "env"; var: string }
/** 一个密钥类的值怎么改。视图里拿不到原值,所以有「保持原样」 */
export type SecretChange =
| { mode: "keep" }
| { mode: "none" }
/** 可以写 `${ENV}` 从环境变量读 */
| { mode: "set"; value: string };

export interface HeaderInput {
name: string;
/** 不给表示沿用同名那一行的原值 */
value?: string;
}

export type OAuthChange =
| { mode: "keep" }
| { mode: "none" }
| {
kind: "oauth";
mode: "set";
refresh: string;
endpoint: string;
client_id?: string;
Expand All @@ -1191,8 +1225,11 @@ export interface ProviderInput {
name: string;
/** 修改时不给就是保持原样 */
base_url?: string;
/** 修改时不给就是保持原样 —— 界面拿不到原值 */
key?: CredentialInput;
/** 修改时默认保持原样 —— 界面拿不到原值 */
key: SecretChange;
/** 整张表就是保存之后的样子:没列出来的行被删掉 */
headers: HeaderInput[];
oauth: OAuthChange;
/** 不给就按地址推断 */
protocol?: string;
proxy: string;
Expand Down Expand Up @@ -1227,6 +1264,8 @@ export interface ProviderPreview {
protocol?: string | null;
official: boolean;
redact: string[];
/** 按推断出的协议,API 密钥放在哪个请求头里 */
auth_header: string;
}

/** 一个上游的模型清单 */
Expand Down
Binary file modified src/upstreams/BillingSection.tsx
Binary file not shown.
Binary file modified src/upstreams/ConnectionSection.tsx
Binary file not shown.
73 changes: 73 additions & 0 deletions src/upstreams/HeaderEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useState } from "react";
import { PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/ui/button";
import { Input } from "@/ui/input";
import { headerRow, keepsSavedValue, type HeaderRow, type UpstreamForm } from "./upstreamForm";

/**
* 发给上游的请求头,一行一个。
*
* **已保存的敏感值不回填**:那一行的值留空表示沿用,和 API 密钥同一个约定。
* 名称和值写得对不对(保留头、重名、占位符)由 core 在检测和保存时说。
*/
export function HeaderEditor({
form,
set,
}: {
form: UpstreamForm;
set: (patch: Partial<UpstreamForm>) => void;
}) {
// 新加的那一行自动聚焦到名称
const [focus, setFocus] = useState<number | null>(null);
const rows = form.headers;

function update(id: number, patch: Partial<HeaderRow>) {
set({ headers: rows.map((r) => (r.id === id ? { ...r, ...patch } : r)) });
}

function add() {
const row = headerRow();
setFocus(row.id);
set({ headers: [...rows, row] });
}

return (
<div className="flex flex-col gap-2">
{rows.map((r) => (
<div key={r.id} className="grid grid-cols-[minmax(0,2fr)_minmax(0,3fr)_auto] items-center gap-2">
<Input
aria-label="请求头名称"
autoFocus={r.id === focus}
autoComplete="off"
spellCheck={false}
className="font-mono"
placeholder="名称"
value={r.name}
onChange={(e) => update(r.id, { name: e.target.value })}
/>
<Input
aria-label={r.name.trim() ? `请求头「${r.name.trim()}」的值` : "请求头的值"}
autoComplete="off"
spellCheck={false}
className="font-mono"
placeholder={keepsSavedValue(form, r) ? "已保存,留空即保持不变" : "值"}
value={r.value}
onChange={(e) => update(r.id, { value: e.target.value })}
/>
<Button
variant="ghost"
size="icon-sm"
aria-label="删除此请求头"
onClick={() => set({ headers: rows.filter((x) => x.id !== r.id) })}
>
<XIcon />
</Button>
</div>
))}
<Button variant="outline" size="sm" className="w-fit" onClick={add}>
<PlusIcon />
添加请求头
</Button>
</div>
);
}
17 changes: 9 additions & 8 deletions src/upstreams/UpstreamDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { ProxyDialog } from "./ProxyDialog";
import { SecuritySection } from "./SecuritySection";
import {
blankForm,
connectionChanged,
connectionMissing,
describeModelList,
formFromView,
Expand Down Expand Up @@ -106,7 +107,7 @@ export function UpstreamDialog({
| { kind: "sheet"; name: string | null; add?: string[] }
>(null);

// 「自动识别」此刻会判成什么。只看地址,不联网
// 「自动识别」此刻会判成什么、密钥放在哪个请求头。只看地址和选定的协议,不联网
useEffect(() => {
const url = form.baseUrl.trim();
if (!url) {
Expand All @@ -115,25 +116,25 @@ export function UpstreamDialog({
}
const t = setTimeout(() => {
api
.previewProvider(url)
.previewProvider(url, form.protocol || undefined)
.then(setPreview)
.catch(() => setPreview(null));
}, 250);
return () => clearTimeout(t);
}, [form.baseUrl]);
}, [form.baseUrl, form.protocol]);

// 新建:连接信息一改,之前检测到的结果和模型列表就不再对应这一家
const connectionKey = [
const connectionKey = JSON.stringify([
form.baseUrl,
form.protocol,
form.credKind,
form.authMode,
form.key,
form.envVar,
form.headers.map((h) => [h.name, h.value]),
form.oauthRefresh,
form.oauthEndpoint,
form.oauthAccess,
form.proxy,
].join("\n");
]);
useEffect(() => {
if (editing) return;
setTest(null);
Expand Down Expand Up @@ -223,7 +224,7 @@ export function UpstreamDialog({

async function refreshModels() {
// 连接信息改过:按表单里的新值去问;没改过:让 core 刷新已保存的那一家
if (!editing || form.baseUrlTouched || form.credTouched) {
if (!editing || connectionChanged(form, editing)) {
await runTest();
return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/upstreams/UpstreamTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export function UpstreamTable({
title={`${protocolLabel(p.protocol)} · ${p.base_url}`}
>
{protocolLabel(p.protocol)} · {shortUrl(p.base_url)}
{p.key_kind === "oauth" && " · OAuth"}
{p.oauth && " · OAuth"}
</div>
</TableCell>
<ModelsCell p={p} />
Expand Down
4 changes: 3 additions & 1 deletion src/upstreams/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ export const api = {
deleteProvider: (name: string, baseVersion: Base) =>
invoke<ConfigWritten>("delete_provider", { name, baseVersion }),
testProvider: (test: ProviderTest) => invoke<ProviderTestResult>("test_provider", { test }),
previewProvider: (baseUrl: string) => invoke<ProviderPreview>("preview_provider", { baseUrl }),
/** `protocol`:表单里选定的协议,不给就是自动识别 */
previewProvider: (baseUrl: string, protocol?: string) =>
invoke<ProviderPreview>("preview_provider", { preview: { base_url: baseUrl, protocol } }),
providerModels: (name: string) => invoke<ProviderModelsView>("provider_models", { name }),
refreshProviderModels: (name: string) =>
invoke<ProviderModelsView>("refresh_provider_models", { name }),
Expand Down
8 changes: 6 additions & 2 deletions src/upstreams/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,16 @@ export function redactLabel(id: string): string {
return REDACT_KINDS.find((k) => k.id === id)?.label ?? id;
}

export const CREDENTIAL_KINDS: { id: "key" | "env" | "oauth"; label: string }[] = [
export const AUTH_MODES: { id: "key" | "oauth"; label: string }[] = [
{ id: "key", label: "API 密钥" },
{ id: "env", label: "环境变量" },
{ id: "oauth", label: "OAuth" },
];

/** 密钥所在的请求头,按 HTTP 报文里的写法 */
export function authHeaderLabel(header: string): string {
return header === "authorization" ? "Authorization: Bearer" : header;
}

export function modelSourceLabel(source: string): string {
switch (source) {
case "discovered":
Expand Down
3 changes: 0 additions & 3 deletions src/upstreams/presets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ export interface Preset {
/** 空字符串 = 自动识别 */
protocol: string;
billing?: string;
/** 这类服务不需要密钥时的占位值 */
keyPlaceholder?: string;
}

export const CUSTOM: Preset = {
Expand Down Expand Up @@ -61,7 +59,6 @@ export const PRESETS: Preset[] = [
baseUrl: "http://127.0.0.1:11434",
protocol: "openai-chat",
billing: "free",
keyPlaceholder: "ollama",
},
];

Expand Down
Loading
Loading