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
5 changes: 3 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ jobs:

browser:
name: Browser interactions
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
# Keep this image aligned with @playwright/test in pnpm-lock.yaml.
container: mcr.microsoft.com/playwright:v1.65.1-noble
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
Expand All @@ -92,7 +94,6 @@ jobs:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium webkit
- run: pnpm test:ui
- uses: actions/upload-artifact@v4
if: failure()
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "thinkwatch-lite",
"private": true,
"description": "Desktop app for a local AI API gateway on macOS, Windows and Linux",
"version": "2026.12.2",
"version": "2026.12.4",
"type": "module",
"packageManager": "pnpm@11.13.1",
"scripts": {
Expand Down
2 changes: 2 additions & 0 deletions release-notes/2026.12.4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Dragging an upstream row saves its position to Core. The built-in **All upstreams** group uses that same order for failover.
- Reorder clients, route rules, group members, backup models, plugins, and traffic columns by dragging rows. Plugin ordering is available directly in the plugin list.
9 changes: 7 additions & 2 deletions scripts/shots/mock/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import type { Adopted, ConnView, Tested } from "@/connection/api";
import type { AppInfo, HotkeyView, LanguageView, MenubarStyle, NoticeMode, ThemeView, UiZoom } from "@/settings/api";
import type { Offer, UpdateView } from "@/updateFlow";
import type { UpstreamStats } from "@/upstreams/api";
import type { ClientsResponse, CoreStatus, Dashboard, ImportLink, KeyUsage, McpTargetView, PlanView, ScanReport } from "@/types";
import type { ClientsResponse, ConfigWritten, CoreStatus, Dashboard, ImportLink, KeyUsage, McpTargetView, PlanView, ScanReport } from "@/types";
import { CORE, CHATGPT_WINDOWS } from "./core";
import { LOCAL_GATEWAY, status } from "./config";
import { LOCAL_GATEWAY, setUpstreamOrder, status } from "./config";
import { IN_FLIGHT, costBucketsBy, costBy, dashboard, upstreamLatency, upstreamTokenRate } from "./traffic";
import { clientsResponse, mcpTargets, plan, scanReport, setClientOrder } from "./clients";
import { NOTICES, APP_VERSION, SERVER, autostart, connView, langView, menubar, noticeMode, tested, themeView, updateView } from "./app";
Expand Down Expand Up @@ -58,6 +58,7 @@ interface Commands {
// 概览与用量(Rust 侧从 core 取齐了一起给)
dashboard: [Span, Dashboard];
upstream_stats: [Span & { egressSinceMs: [number, number, number] }, UpstreamStats];
reorder_upstreams: [{ names: string[]; baseVersion: string }, ConfigWritten];
key_usage: [Span, KeyUsage];
// 提醒
notices_list: [void, Notice[]];
Expand Down Expand Up @@ -124,6 +125,10 @@ const COMMANDS: Table = {
// 订阅额度是此刻的状态,和上游页同一份(dashboard.rs 同样问 `/quota`)
return { ...dashboard(sinceMs, bucketMs), quotas: [{ provider: "chatgpt", windows: CHATGPT_WINDOWS() }] };
},
reorder_upstreams: (a) => {
const req = need("reorder_upstreams", a, "names", "baseVersion");
return setUpstreamOrder(req.names, req.baseVersion);
},
upstream_stats: (a) => {
const { sinceMs, bucketMs, egressSinceMs } = need("upstream_stats", a, "sinceMs", "bucketMs", "egressSinceMs");
// 按出口分的流量,每个起点一份、整段一格(upstreams.rs 的 `WHOLE_MS`):直连是空串
Expand Down
24 changes: 22 additions & 2 deletions scripts/shots/mock/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// 使用的时刻、价目表今天刷新过。
import type {
ClientView,
ConfigWritten,
DryRunRequest,
DryRunResult,
ModelRow,
Expand All @@ -18,6 +19,7 @@ import type {
SecurityDetail,
Status,
} from "@/types";
import { sortUpstreams } from "@/upstreams/upstreamOrder";
import OV_EN from "../core/en/overview.json";
import KEYS_EN from "../core/en/keys.json";
import SEC_EN from "../core/en/security.json";
Expand Down Expand Up @@ -235,9 +237,12 @@ const BODY_BYTES = 412 * 1024 ** 2;

export function overview(lastSeen: Map<string, number>): Overview {
const o = clone(FX.overview);
const order = upstreamOrder();
return {
...o,
providers: providers(),
config_version: order?.version ?? o.config_version,
providers: order ? sortUpstreams(providers(), order.names) : providers(),
groups: order ? o.groups.map((group) => group.builtin ? { ...group, providers: order.names } : group) : o.groups,
clients: o.clients.map((c) => ({ ...c, last_seen_ms: lastSeen.get(c.name) ?? null })),
retention: { ...o.retention, body_bytes_now: BODY_BYTES },
};
Expand Down Expand Up @@ -288,7 +293,22 @@ export function status(gatewayAddr: string, inFlight: number): Status {
}

/** 配置的版本号(core 算的内容哈希) */
export const configVersion = () => FX.overview.config_version;
const UPSTREAM_ORDER_KEY = "shot-core-upstream-order";
const upstreamOrder = (): { names: string[]; version: string } | null =>
JSON.parse(localStorage.getItem(UPSTREAM_ORDER_KEY) ?? "null");

export const configVersion = () => upstreamOrder()?.version ?? FX.overview.config_version;

export function setUpstreamOrder(names: string[], baseVersion: string): ConfigWritten {
if (baseVersion !== configVersion()) {
throw msg("control.config_stale", "The configuration has changed.", {
base: baseVersion, current: configVersion(),
});
}
const version = `${baseVersion}-reordered`;
localStorage.setItem(UPSTREAM_ORDER_KEY, JSON.stringify({ names, version }));
return { version };
}

/** 配置文件原文。截图里不打开它,给一份读得通的 */
export const CONFIG_TEXT = "# ~/.thinkwatch/config.yaml\nversion: 1\n";
8 changes: 6 additions & 2 deletions scripts/ui/model-aliases.pw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,10 @@ test("pinned alias searches keep only the chosen upstream ID and permit literal

for (const [n, provider, model] of [[1, "anthropic", "claude-opus-5"], [2, "relay", "claude-sonnet-5"]] as const) {
if (n === 2) await rule.getByRole("button", { name: "添加备用" }).click();
await rule.getByRole("combobox", { name: `第 ${n} 个指定模型的上游` }).click();
const upstream = rule.getByRole("combobox", { name: `第 ${n} 个指定模型的上游` });
await upstream.click();
await page.getByRole("option", { name: provider, exact: true }).click();
await expect(upstream).toBeFocused();
const raw = rule.getByRole("textbox", { name: "上游模型 ID" }).nth(n - 1);
await raw.fill("manual-id");
await raw.press("ArrowDown");
Expand All @@ -121,8 +123,10 @@ test("pinned alias searches keep only the chosen upstream ID and permit literal
await expect(raw).toHaveValue(model);
}
await rule.getByRole("button", { name: "添加备用" }).click();
await rule.getByRole("combobox", { name: "第 3 个指定模型的上游" }).click();
const thirdUpstream = rule.getByRole("combobox", { name: "第 3 个指定模型的上游" });
await thirdUpstream.click();
await page.getByRole("option", { name: "deepseek", exact: true }).click();
await expect(thirdUpstream).toBeFocused();
await rule.getByRole("textbox", { name: "上游模型 ID" }).nth(2).fill("manual-only");
const models = rule.locator("[data-reorder-row]");
const first = (await models.first().boundingBox())!;
Expand Down
27 changes: 26 additions & 1 deletion scripts/ui/upstreams.pw.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, test } from "@playwright/test";
import type {} from "../shots/drive";

test("an upstream row can be dropped below the table and the order survives reload", async ({ page }) => {
test("upstream drag changes the built-in group and the order survives reload", async ({ page }) => {
await page.goto("/scripts/shots/index.html?scene=upstreams&lang=zh");
await page.waitForFunction(() => window.__shot?.state === "ready");
const rows = page.locator("tr[data-reorder-scope]");
Expand Down Expand Up @@ -38,4 +38,29 @@ test("an upstream row can be dropped below the table and the order survives relo
await page.reload();
await page.waitForFunction(() => window.__shot?.state === "ready");
await expect.poll(names).toEqual(reordered);

await page.getByRole("button", { name: "路由", exact: true }).click();
await page.getByRole("tab", { name: "策略组" }).click();
const builtIn = page.getByRole("row", { name: /^全部上游 / });
await expect(builtIn.locator(".font-mono")).toHaveText(reordered.map((name) => name!));
});

test("a rejected upstream reorder restores the order from Core", async ({ page }) => {
await page.goto("/scripts/shots/index.html?scene=upstreams&lang=zh");
await page.waitForFunction(() => window.__shot?.state === "ready");
await page.evaluate(() => {
const ctx = window as unknown as {
__TAURI_INTERNALS__: { invoke(cmd: string, args?: Record<string, unknown>): Promise<unknown> };
};
const invoke = ctx.__TAURI_INTERNALS__.invoke;
ctx.__TAURI_INTERNALS__.invoke = (cmd, args) =>
invoke(cmd, cmd === "reorder_upstreams" ? { ...args, baseVersion: "outdated" } : args);
});
const rows = page.locator("tr[data-reorder-scope]");
const names = () => rows.evaluateAll((list) => list.map((row) => row.getAttribute("data-row")));
await expect.poll(() => rows.count()).toBeGreaterThan(1);
const initial = await names();
await rows.first().press("Alt+ArrowDown");
await expect(page.getByText("无法保存列表顺序")).toBeVisible();
await expect.poll(names).toEqual(initial);
});
4 changes: 3 additions & 1 deletion src-tauri/Cargo.lock

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

4 changes: 3 additions & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "thinkwatch-lite"
version = "2026.12.2"
version = "2026.12.4"
edition = "2024"
# **这个数决定依赖能升到哪一版。**edition 2024 的解析器只挑声明的 Rust
# 版本编得动的依赖:写 1.85 的时候,`cargo update` 一直停在旧的 time 和
Expand Down Expand Up @@ -67,6 +67,7 @@ tw-adopt = { path = "crates/tw-adopt" }
tw-scan = { path = "crates/tw-scan" }
tw-types = { workspace = true }
tw-guard = { workspace = true }
tw-yaml = { workspace = true }
# 控制面的握手与加密(Noise NNpsk0),和 core 用的是同一份实现。握手里交换的控制面
# 版本号来自 tw-api,所以两者必须钉在同一个 tag 上(见上面 `[workspace.dependencies]`)
tw-link = { workspace = true }
Expand All @@ -88,6 +89,7 @@ serde = { version = "1", features = ["derive"] }
url = "2"
ipnet = "2"
serde_json = "1"
serde_yaml_ng = "0.10"
thiserror = "2"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "process", "io-util"] }
# 菜单栏的「今日」从这台机器的本地零点算起(`menubar::day_of`)。**时区只有桌面这边
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ pub fn run() {
export::save_export,
export::open_import,
upstreams::upstream_stats,
upstreams::reorder_upstreams,
aliases::alias_hints,
notices::commands::notices_list,
notices::commands::mark_notice_read,
Expand Down
131 changes: 129 additions & 2 deletions src-tauri/src/upstreams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,122 @@
//!
//! 上游、代理、价目表的增删改与检测都是直接转发的端点,走 `crate::call`。

use tw_api::ep;
use std::collections::HashMap;

use serde_yaml_ng::Value;
use tw_api::{ConfigWrite, ConfigWritten, ep};
use tw_yaml::{PatchError, Put, path};

use crate::AppState;
use crate::control::Pinned;
use crate::dashboard::WHOLE_MS;
use crate::error::Out;
use crate::error::{CmdError, Out};

#[tauri::command]
pub async fn reorder_upstreams(
state: tauri::State<'_, AppState>,
names: Vec<String>,
base_version: String,
) -> Out<ConfigWritten> {
save_order(&state.control.pin()?, &names, &base_version).await
}

/// Stay on one Core even if the active connection switches before the write.
pub async fn save_order(core: &Pinned, names: &[String], base_version: &str) -> Out<ConfigWritten> {
let config = core.call::<ep::GetConfig>(&[], &()).await?;
if config.version != base_version {
return Err(tw_api::Msg {
code: "control.config_stale".into(),
args: [
("base".into(), base_version.into()),
("current".into(), config.version.clone()),
].into(),
text: format!(
"Version mismatch: this edit is based on {base_version}, and the current version is {}. Refresh and edit again.",
config.version,
),
}.into());
}
let text =
reordered_config(&config.text, names).map_err(|error| CmdError::from(error.msg()))?;
if text == config.text {
return Ok(ConfigWritten {
version: config.version,
});
}
Ok(core
.call::<ep::PutConfig>(
&[],
&ConfigWrite {
base_version: config.version,
text,
},
)
.await?)
}

fn reordered_config(text: &str, names: &[String]) -> Result<String, PatchError> {
#[derive(serde::Deserialize)]
struct UpstreamName {
name: String,
}

#[derive(serde::Deserialize)]
struct Upstreams {
#[serde(default)]
providers: Vec<UpstreamName>,
}

let config: Upstreams =
serde_yaml_ng::from_str(text).map_err(|error| PatchError::Parse(error.to_string()))?;
let bad_order =
|| PatchError::SelfCheck("The order must list every upstream exactly once".into());
if config.providers.len() != names.len() {
return Err(bad_order());
}
let mut indices: HashMap<_, _> = config
.providers
.iter()
.enumerate()
.map(|(index, provider)| (provider.name.as_str(), index))
.collect();
let order = names
.iter()
.map(|name| indices.remove(name.as_str()).ok_or_else(bad_order))
.collect::<Result<Vec<_>, _>>()?;
if order.iter().copied().eq(0..order.len()) {
return Ok(text.to_owned());
}

let providers = path!["providers"];
if !tw_yaml::is_flow_at(text, &providers)? {
return tw_yaml::reorder(text, &providers, &order);
}

// Flow-style YAML stores several providers on one line. Replace that sequence
// alone and check that the rest of the configuration still parses to the same values.
let mut expected: Value =
serde_yaml_ng::from_str(text).map_err(|error| PatchError::Parse(error.to_string()))?;
let items = expected
.get_mut("providers")
.and_then(Value::as_sequence_mut)
.ok_or_else(bad_order)?;
*items = order
.into_iter()
.map(|index| items[index].clone())
.collect();
let block = serde_yaml_ng::to_string(items)
.map_err(|error| PatchError::SelfCheck(error.to_string()))?;
let updated = tw_yaml::put(text, &providers, Put::Block(block.trim_end_matches('\n')))?;
let actual: Value = serde_yaml_ng::from_str(&updated)
.map_err(|error| PatchError::SelfCheck(error.to_string()))?;
if actual != expected {
return Err(PatchError::SelfCheck(
"Reordering changed other configuration values".into(),
));
}
Ok(updated)
}

/// 上游列表那几列统计:一段时间里的请求与费用、第一个 token 到的时刻、生成速度、订阅
/// 额度,同一段时间按上游分格的请求数(每一行的走势),以及代理表那一列流量。
Expand Down Expand Up @@ -99,3 +210,19 @@ fn since(from_ms: i64) -> tw_api::Window {
to_ms: None,
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn reorders_flow_style_providers_and_preserves_the_rest() {
let original = "version: 1\nproviders: [{name: 2024, base_url: 'https://a.example'}, {name: b, extra_body: {enabled: false}}]\n# Keep this\nlogs: {}\n";
let ordered = ["b".to_owned(), "2024".to_owned()];
let reordered = reordered_config(original, &ordered).unwrap();
assert!(reordered.contains("# Keep this\nlogs: {}\n"));
assert!(reordered.find("name: b").unwrap() < reordered.find("name: 2024").unwrap());
assert!(reordered_config(original, &["b".into(), "b".into()]).is_err());
assert!(reordered_config(original, &["b".into()]).is_err());
}
}
2 changes: 1 addition & 1 deletion src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "ThinkWatch Lite",
"version": "2026.12.2",
"version": "2026.12.4",
"identifier": "app.thinkwatch.lite",
"build": {
"beforeDevCommand": "pnpm dev",
Expand Down
Loading
Loading