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.
8 changes: 7 additions & 1 deletion scripts/shots/mock/clients.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,13 +496,19 @@ function manualNow(): ManualClient[] {
];
}

const ORDER_KEY = "shot-client-order";

export function setClientOrder(order: string[]) {
localStorage.setItem(ORDER_KEY, JSON.stringify(order));
}

export function clientsResponse(): ClientsResponse {
return {
gateway_base: base(),
keys: ["default", "claude-code", "codex", "cursor"],
clients: clientsNow(),
manual: manualNow(),
order: [],
order: JSON.parse(localStorage.getItem(ORDER_KEY) ?? "[]") as string[],
};
}

Expand Down
13 changes: 10 additions & 3 deletions scripts/shots/mock/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ 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 } from "./clients";
import { clientsResponse, mcpTargets, plan, scanReport, setClientOrder } from "./clients";
import { NOTICES, APP_VERSION, SERVER, autostart, connView, langView, menubar, noticeMode, tested, themeView, updateView } from "./app";
import { P } from "./params";
import { DAY, clone, msg } from "./util";
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 All @@ -75,6 +76,7 @@ interface Commands {
gateway_base: [void, string];
// 这台机器上的客户端、MCP、扫描
list_clients: [void, ClientsResponse];
set_client_order: [{ order: string[] }, void];
plan_adopt: [{ id: string; env?: string }, PlanView];
plan_restore: [{ id: string; env?: string }, PlanView];
mcp_targets: [void, McpTargetView[]];
Expand Down Expand Up @@ -123,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 Expand Up @@ -168,6 +174,7 @@ const COMMANDS: Table = {
gateway_base: () => `http://${gatewayAddr()}`,

list_clients: clientsResponse,
set_client_order: (a) => setClientOrder(need("set_client_order", a, "order").order),
plan_adopt: (a) => plan(need("plan_adopt", a, "id").id, false),
plan_restore: (a) => plan(need("plan_restore", a, "id").id, true),
mcp_targets: mcpTargets,
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";
22 changes: 18 additions & 4 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,13 +123,25 @@ 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())!;
const last = (await models.last().locator(":scope > span").first().boundingBox())!;
const x = last.x + last.width / 2;
await page.mouse.move(x, last.y + last.height / 2);
await page.mouse.down();
await page.mouse.move(x, first.y + first.height / 4, { steps: 10 });
await expect(page.locator(".row-reorder-overlay")).toBeVisible();
await page.mouse.up();
await expect(rule.getByRole("textbox", { name: "上游模型 ID" }).first()).toHaveValue("manual-only");
await rule.getByRole("button", { name: "添加", exact: true }).click();
await route.getByRole("button", { name: "保存", exact: true }).click();
await expect.poll(() => page.evaluate(() => (window as unknown as { savedRoute?: RouteSave }).savedRoute?.route.rules.find((r) => r.name === "pin")?.to)).toEqual([
{ provider: "anthropic", model: "claude-opus-5" }, { provider: "relay", model: "claude-sonnet-5" },
{ provider: "deepseek", model: "manual-only" },
{ provider: "deepseek", model: "manual-only" }, { provider: "anthropic", model: "claude-opus-5" },
{ provider: "relay", model: "claude-sonnet-5" },
]);
});
139 changes: 139 additions & 0 deletions scripts/ui/row-reorder.pw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { expect, test, type Locator, type Page } from "@playwright/test";
import type { GroupSave, PluginOrder, PluginView, RouteSave } from "@/types";
import type {} from "../shots/drive";

async function open(page: Page, scene: string) {
await page.goto(`/scripts/shots/index.html?scene=${scene}&lang=zh`);
await page.waitForFunction(() => window.__shot?.state === "ready");
}

async function drag(page: Page, handle: Locator, destination: Locator, position: "before" | "after") {
await handle.scrollIntoViewIfNeeded();
await destination.scrollIntoViewIfNeeded();
const from = (await handle.boundingBox())!;
const to = (await destination.boundingBox())!;
const x = from.x + from.width / 2;
await page.mouse.move(x, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(x, to.y + to.height * (position === "before" ? 0.2 : 0.8), { steps: 12 });
await expect(page.locator(".row-reorder-overlay")).toBeVisible();
await page.mouse.up();
await expect(page.locator(".row-reorder-overlay")).toHaveCount(0);
}

test("client rows reorder within their table and persist across reload", async ({ page }) => {
await open(page, "clients");
const rows = page.locator("table").filter({ has: page.locator("tr[data-reorder-row]") }).first().locator("tr[data-reorder-row]");
const ids = () => rows.evaluateAll((items) => items.map((row) => row.getAttribute("data-row")));
const initial = await ids();
expect(initial.length).toBeGreaterThan(1);
await drag(page, rows.first().locator("td").first().locator(".font-medium"), rows.nth(1), "after");
const expected = [initial[1], initial[0], ...initial.slice(2)];
await expect.poll(ids).toEqual(expected);
await expect(page.getByRole("dialog")).toHaveCount(0);
await page.reload();
await expect.poll(ids).toEqual(expected);
});

test("route rule and group member drops update their drafts before saving", async ({ page }) => {
await open(page, "routing");
await page.evaluate(() => {
const ctx = window as unknown as {
__TAURI_INTERNALS__: { invoke(cmd: string, args?: Record<string, unknown>): Promise<unknown> };
writes: unknown[];
};
ctx.writes = [];
const invoke = ctx.__TAURI_INTERNALS__.invoke;
ctx.__TAURI_INTERNALS__.invoke = async (cmd, args) => {
if (cmd === "call" && (args?.endpoint === "UpdateRoute" || args?.endpoint === "UpdateGroup")) {
ctx.writes.push(args.req);
return { version: "updated" };
}
return invoke(cmd, args);
};
});
const writes = () => page.evaluate(() => (window as unknown as { writes: [RouteSave?, GroupSave?] }).writes);
await page.getByRole("row", { name: /^default / }).click();
const route = page.getByRole("dialog", { name: "编辑路由「default」" });
const rules = route.locator("tr[data-reorder-row]");
await drag(page, rules.first().getByText("Opus 直连", { exact: true }), rules.nth(1), "after");
await expect(rules.first()).toContainText("DeepSeek 模型");
expect(await writes()).toEqual([]);
await route.getByRole("button", { name: "保存", exact: true }).click();
await expect.poll(async () => (await writes())[0]?.route.rules.slice(0, 2).map((rule) => rule.name))
.toEqual(["DeepSeek 模型", "Opus 直连"]);

await page.getByRole("tab", { name: "策略组" }).click();
await page.getByRole("row", { name: /^主力 / }).click();
const group = page.getByRole("dialog", { name: "编辑策略组「主力」" });
const members = group.locator("tr[data-reorder-row]");
const initial = await members.evaluateAll((rows) => rows.slice(0, 2).map((row) =>
row.querySelector("label .truncate")?.textContent));
await expect(members.nth(1).getByRole("checkbox")).toBeChecked();
await drag(page, members.first().locator("label .truncate"), members.nth(1), "after");
await expect(members.first().locator("label .truncate")).toHaveText(initial[1]!);
await expect(members.nth(1).getByRole("checkbox")).toBeChecked();
expect(await writes()).toHaveLength(1);
await group.getByRole("button", { name: "保存", exact: true }).click();
await expect.poll(async () => (await writes())[1]?.group.providers.slice(0, 2)).toEqual([initial[1], initial[0]]);
});

test("plugin ordering works in the main list and writes only on save", async ({ page }) => {
await open(page, "overview");
await page.evaluate(() => {
const ctx = window as unknown as {
__TAURI_INTERNALS__: { invoke(cmd: string, args?: Record<string, unknown>): Promise<unknown> };
pluginOrders: PluginOrder[];
};
let plugins: PluginView[] = ["one", "two", "three"].map((id) => ({
id, name: id, description: id === "one" ? "First plugin with a description" : null,
enabled: false, on_error: "skip", permissions: [], requests: ["conversation"],
scope: { clients: [], models: [], upstreams: [] }, reply_mode: "block", settings_schema: [],
sha256: "", status: { kind: "disabled" },
stats: { calls: 0, changed: 0, rejected: 0, errors: 0, avg_cpu_us: 0, last_error: null },
}));
ctx.pluginOrders = [];
const invoke = ctx.__TAURI_INTERNALS__.invoke;
ctx.__TAURI_INTERNALS__.invoke = async (cmd, args) => {
if (cmd === "call" && args?.endpoint === "Plugins") return plugins;
if (cmd === "call" && args?.endpoint === "ReorderPlugins") {
const req = args.req as PluginOrder;
ctx.pluginOrders.push(req);
plugins = req.ids.map((id) => plugins.find((p) => p.id === id)!);
return { version: "updated" };
}
return invoke(cmd, args);
};
});
const writes = () => page.evaluate(() => (window as unknown as { pluginOrders: PluginOrder[] }).pluginOrders);
await page.getByRole("button", { name: "插件", exact: true }).click();
const rows = page.locator("li[data-plugin]");
const ids = () => rows.evaluateAll((items) => items.map((row) => row.getAttribute("data-plugin")));
for (const action of ["取消", "保存"]) {
await page.getByRole("button", { name: "调整顺序" }).click();
await expect(page.getByRole("dialog")).toHaveCount(0);
await drag(page, rows.first().getByText("one", { exact: true }), rows.last(), "after");
await expect.poll(ids).toEqual(["two", "three", "one"]);
expect(await writes()).toEqual([]);
await page.getByRole("button", { name: action, exact: true }).click();
await expect.poll(ids).toEqual(action === "取消" ? ["one", "two", "three"] : ["two", "three", "one"]);
}
expect(await writes()).toEqual([{ ids: ["two", "three", "one"], base_version: expect.any(String) }]);
});

test("column settings allow drag within a pin group and reject cross-group drops", async ({ page }) => {
await open(page, "traffic");
await page.getByRole("button", { name: "列设置" }).click();
const settings = page.locator("[data-slot=popover-content]");
const order = () => settings.getByRole("combobox").evaluateAll((list) => list.map((control) => control.getAttribute("aria-label")));
const initial = await order();
const row = (name: string) => settings.locator("[data-reorder-row]").filter({ has: page.getByRole("combobox", { name: `${name}列的固定位置` }) });
await drag(page, row("费用").getByText("费用", { exact: true }), row("时间"), "before");
await expect.poll(order).toEqual(initial);
await drag(page, row("费用").getByText("费用", { exact: true }), row("token"), "before");
const expected = [...initial.slice(0, -2), initial.at(-1), initial.at(-2)];
await expect.poll(order).toEqual(expected);
await page.reload();
await page.getByRole("button", { name: "列设置" }).click();
await expect.poll(order).toEqual(expected);
});
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);
});
Loading
Loading