From 95cb212cdd0616950f068a2ee0aee45c15b0f219 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:10:04 +0800 Subject: [PATCH] feat(upstreams): prepare Lite 2026.12.2 (#473) Reorder upstreams by dragging rows and configure extra outbound JSON per upstream. Bundle Core 0.101.0. --- package.json | 2 +- release-notes/2026.12.2.md | 3 + scripts/ui/upstreams.pw.ts | 41 +++++ src-tauri/Cargo.lock | 165 ++++++++++--------- src-tauri/Cargo.toml | 14 +- src-tauri/tauri.conf.json | 2 +- src-tauri/tests/control_plane.rs | 4 + src/clients/ClientsTable.tsx | 90 +--------- src/generated/tw-api.ts | 8 +- src/i18n/core.zh-Hant.json | 1 + src/i18n/core.zh.json | 1 + src/index.css | 41 +++++ src/routing/rowDragCursor.ts | 41 +++++ src/routing/rowDragPreview.ts | 184 +++++++++++++++++++++ src/routing/useReorder.ts | 210 ++++++++++++++++++++---- src/upstreams/ConnectionSection.i18n.ts | 35 ++++ src/upstreams/ConnectionSection.tsx | 47 +++++- src/upstreams/UpstreamTable.tsx | 34 +++- src/upstreams/UpstreamsPage.tsx | 44 ++++- src/upstreams/upstreamForm.i18n.ts | 5 + src/upstreams/upstreamForm.ts | 24 +++ src/upstreams/upstreamOrder.i18n.ts | 36 ++++ src/upstreams/upstreamOrder.ts | 15 ++ 23 files changed, 833 insertions(+), 214 deletions(-) create mode 100644 release-notes/2026.12.2.md create mode 100644 scripts/ui/upstreams.pw.ts create mode 100644 src/routing/rowDragCursor.ts create mode 100644 src/routing/rowDragPreview.ts create mode 100644 src/upstreams/upstreamOrder.i18n.ts create mode 100644 src/upstreams/upstreamOrder.ts diff --git a/package.json b/package.json index ff5c7ce3..b79b0028 100644 --- a/package.json +++ b/package.json @@ -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.11.25", + "version": "2026.12.2", "type": "module", "packageManager": "pnpm@11.13.1", "scripts": { diff --git a/release-notes/2026.12.2.md b/release-notes/2026.12.2.md new file mode 100644 index 00000000..ef7f9779 --- /dev/null +++ b/release-notes/2026.12.2.md @@ -0,0 +1,3 @@ +- Drag any upstream row to reorder the list. Keep dragging below the last row to move it to the end, or hold near a window edge to scroll a longer list. Lite remembers the display order for each connection. +- Add JSON fields to a provider's outgoing generation requests under **Connection → Advanced settings → Extra request body**. To preserve a client-provided prompt cache key across protocol conversion, enable **Reuse the client's prompt cache key**. +- Bundles ThinkWatch Core 0.101.0, including a control-channel security update. diff --git a/scripts/ui/upstreams.pw.ts b/scripts/ui/upstreams.pw.ts new file mode 100644 index 00000000..9c2e29e2 --- /dev/null +++ b/scripts/ui/upstreams.pw.ts @@ -0,0 +1,41 @@ +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 }) => { + 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]"); + const names = () => rows.evaluateAll((list) => list.map((row) => row.getAttribute("data-row"))); + await expect.poll(() => rows.count()).toBeGreaterThan(1); + const initial = await names(); + const checkbox = rows.first().getByRole("checkbox"); + await checkbox.click(); + await expect(checkbox).toBeChecked(); + + const cell = rows.first().locator("td").nth(1); + await cell.click(); + const editor = page.getByRole("dialog", { name: "编辑上游" }); + await expect(editor).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(editor).toBeHidden(); + + const from = (await cell.boundingBox())!; + const x = from.x + from.width / 2; + const y = from.y + from.height / 2; + const bottom = page.viewportSize()!.height - 4; + await page.mouse.move(x, y); + await page.mouse.down(); + await page.mouse.move(x, bottom, { steps: 12 }); + const preview = page.locator(".row-reorder-overlay"); + await expect(preview).toBeVisible(); + await expect(rows.last()).toHaveClass(/shadow-\[inset_0_-2px/); + await page.mouse.up(); + + const reordered = [...initial.slice(1), initial[0]]; + await expect.poll(names).toEqual(reordered); + await expect(editor).toBeHidden(); + await expect(preview).toHaveCount(0); + await page.reload(); + await page.waitForFunction(() => window.__shot?.state === "ready"); + await expect.poll(names).toEqual(reordered); +}); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 15dbf62f..e9ee34fd 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -10,12 +10,12 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aead" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ - "crypto-common 0.1.7", - "generic-array", + "crypto-common 0.2.2", + "inout", ] [[package]] @@ -73,7 +73,7 @@ dependencies = [ "objc2-foundation", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] @@ -326,11 +326,11 @@ dependencies = [ [[package]] name = "blake2" -version = "0.10.6" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" dependencies = [ - "digest 0.10.7", + "digest 0.11.3", ] [[package]] @@ -553,17 +553,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" -[[package]] -name = "chacha20" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - [[package]] name = "chacha20" version = "0.10.2" @@ -571,21 +560,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", + "cipher", "cpufeatures 0.3.1", "rand_core 0.10.1", ] [[package]] name = "chacha20poly1305" -version = "0.10.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" dependencies = [ "aead", - "chacha20 0.9.1", + "chacha20", "cipher", "poly1305", - "zeroize", ] [[package]] @@ -602,13 +591,13 @@ dependencies = [ [[package]] name = "cipher" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common 0.1.7", + "block-buffer 0.12.1", + "crypto-common 0.2.2", "inout", - "zeroize", ] [[package]] @@ -620,6 +609,12 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "combine" version = "4.6.8" @@ -830,6 +825,15 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -839,12 +843,26 @@ dependencies = [ "cfg-if", "cpufeatures 0.2.17", "curve25519-dalek-derive", - "fiat-crypto", + "fiat-crypto 0.2.9", "rustc_version", "subtle", "zeroize", ] +[[package]] +name = "curve25519-dalek" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "fiat-crypto 0.3.0", + "rustc_version", + "subtle", +] + [[package]] name = "curve25519-dalek-derive" version = "0.1.1" @@ -959,7 +977,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", - "subtle", ] [[package]] @@ -971,6 +988,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1011,7 +1029,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.3", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1197,7 +1215,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -1253,6 +1271,12 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "field-offset" version = "0.3.6" @@ -2157,11 +2181,11 @@ dependencies = [ [[package]] name = "inout" -version = "0.1.4" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -2745,7 +2769,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3025,12 +3049,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "open" version = "5.4.4" @@ -3306,12 +3324,11 @@ dependencies = [ [[package]] name = "poly1305" -version = "0.8.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" dependencies = [ - "cpufeatures 0.2.17", - "opaque-debug", + "cpufeatures 0.3.1", "universal-hash", ] @@ -3489,7 +3506,7 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20 0.10.2", + "chacha20", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -3716,7 +3733,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3772,7 +3789,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -4202,14 +4219,14 @@ checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" [[package]] name = "snow" -version = "0.10.0" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "599b506ccc4aff8cf7844bc42cf783009a434c1e26c964432560fb6d6ad02d82" +checksum = "9cdc2f454d9ede9afabf52b058a4b871c856df58efb1ffa8ea1e67e32c40c42f" dependencies = [ "blake2", "chacha20poly1305", - "curve25519-dalek", - "getrandom 0.3.4", + "curve25519-dalek 5.1.0", + "getrandom 0.4.3", "rustc_version", "subtle", ] @@ -4927,7 +4944,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -4950,7 +4967,7 @@ dependencies = [ [[package]] name = "thinkwatch-lite" -version = "2026.11.25" +version = "2026.12.2" dependencies = [ "anyhow", "base64 0.22.1", @@ -5459,8 +5476,8 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "serde", "serde_json", @@ -5471,8 +5488,8 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "memchr", "serde", @@ -5481,14 +5498,14 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "aho-corasick", "base64 0.22.1", "bech32", "bytes", - "curve25519-dalek", + "curve25519-dalek 4.1.3", "memchr", "regex", "regex-syntax", @@ -5503,8 +5520,8 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "serde", "serde_json", @@ -5530,8 +5547,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "serde", "ts-rs", @@ -5539,8 +5556,8 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "libc", "notify", @@ -5550,8 +5567,8 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.100.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.100.0#a0c209d33961103fddf9417a912d2422755eb411" +version = "0.101.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.101.0#95d86ca3e075b06792f1572ff4a4a14fe1e6443b" dependencies = [ "saphyr-parser", "thiserror 2.0.21", @@ -5601,12 +5618,12 @@ checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "universal-hash" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" dependencies = [ - "crypto-common 0.1.7", - "subtle", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -6021,7 +6038,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4fc33ec1..fabbc3d9 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "thinkwatch-lite" -version = "2026.11.25" +version = "2026.12.2" edition = "2024" # **这个数决定依赖能升到哪一版。**edition 2024 的解析器只挑声明的 Rust # 版本编得动的依赖:写 1.85 的时候,`cargo update` 一直停在旧的 time 和 @@ -26,12 +26,12 @@ license = "MIT" # twcore 二进制必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是 # 从 tw-api 锁到的 tag 去取二进制的(见 scripts/fetch-core.sh)。 [workspace.dependencies] -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.100.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.100.0" } -tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.100.0" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.100.0" } -tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.100.0" } -tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.100.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.101.0" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.101.0" } +tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.101.0" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.101.0" } +tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.101.0" } +tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.101.0" } [lib] name = "thinkwatch_lite_lib" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d4ab81e2..ce08ba67 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "ThinkWatch Lite", - "version": "2026.11.25", + "version": "2026.12.2", "identifier": "app.thinkwatch.lite", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src-tauri/tests/control_plane.rs b/src-tauri/tests/control_plane.rs index dfdf7311..f3f40ccd 100644 --- a/src-tauri/tests/control_plane.rs +++ b/src-tauri/tests/control_plane.rs @@ -443,6 +443,8 @@ async fn a_streaming_request_can_be_followed_live_until_it_ends() { aws: None, protocol: Some(Protocol::Anthropic), forward_client_identity: false, + extra_body: None, + use_client_prompt_cache_key: None, proxy: "direct".into(), on_proxy_fail: OnProxyFail::Fail, models: vec!["claude-test".into()], @@ -677,6 +679,8 @@ async fn a_bedrock_upstream_is_saved_the_way_the_dialog_sends_it() { aws, protocol: None, forward_client_identity: false, + extra_body: None, + use_client_prompt_cache_key: None, proxy: "direct".into(), on_proxy_fail: OnProxyFail::Fail, models: vec![], diff --git a/src/clients/ClientsTable.tsx b/src/clients/ClientsTable.tsx index 4adf7142..be3347a1 100644 --- a/src/clients/ClientsTable.tsx +++ b/src/clients/ClientsTable.tsx @@ -1,4 +1,4 @@ -import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; +import { useEffect, useState, type ReactNode } from "react"; import { ChevronRightIcon, GripVerticalIcon } from "lucide-react"; import { Button, DISCLOSURE } from "@/ui/button"; import { Count } from "@/ui/count"; @@ -17,8 +17,7 @@ import { ClientMark, UsageCell } from "@/keys/parts"; import { clientsText } from "./clients.i18n"; import { SILENCE_MS, hostOf, manualStatusOf, statusOf, type Status, type WslPlace } from "./status"; import { ClientStatus, reasonText } from "./ClientStatus"; -import { moved } from "./order"; -import { useReorder } from "@/routing/useReorder"; +import { sortKeys, sortRow, useSortable, type RowSort } from "@/routing/useReorder"; export interface RowActions { details: (c: DetectedClient) => void; @@ -55,91 +54,6 @@ export interface RowContext { reorder?: (ids: string[]) => void; } -/** 能排序的表里的一行:第几个、共几个,拖动把手,上移下移 */ -interface RowSort { - index: number; - count: number; - /** 行上标的:`useReorder` 按它认是哪一行、是不是这一张表的 */ - attrs: { "data-reorder-row": number; "data-reorder-scope": string }; - handle: ReturnType["handle"]>; - mark: "before" | "after" | null; - dragging: boolean; - move: (d: -1 | 1) => void; -} - -/** - * 一张能排序的表:拖动把手、行菜单的上移下移、在行上按 Alt+↑/↓。`onReorder` 没给就不能排。 - * - * **拖动中画的是按下把手那一刻的列表。**这一页跟着请求刷新,拖到一半来了新数据(新装了 - * 一个、有一个不见了)的话,行的进出场动画会把行挤来挤去,放下时的下标也对不上;放下 - * 之后才换成新的。 - * - * 用键盘挪的那一行重新排过之后可能丢了焦点(React 挪的是它所在的那个节点):焦点丢了 - * 就还给它 - */ -function useSortable(items: T[], idOf: (item: T) => string, onReorder: ((ids: string[]) => void) | undefined) { - const scope = useId(); - const table = useRef(null); - const [frozen, setFrozen] = useState(null); - const latest = useRef([]); - const commit = (ids: string[], focus?: string) => { - onReorder?.(ids); - if (focus === undefined) return; - requestAnimationFrame(() => { - const a = document.activeElement; - if (a && a !== document.body && a.isConnected) return; - table.current?.querySelector(`tr[data-row="${CSS.escape(focus)}"]`)?.focus(); - }); - }; - const reorder = useReorder((from, to) => commit(moved(latest.current, from, to)), scope); - const dragging = reorder.dragging !== null; - if (dragging && frozen === null) setFrozen(items); - else if (!dragging && frozen !== null) setFrozen(null); - const list = (dragging ? frozen : null) ?? items; - const ids = list.map(idOf); - latest.current = ids; - const sortOf = (id: string): RowSort | undefined => { - if (!onReorder) return undefined; - const i = ids.indexOf(id); - // 正在淡出的那一行已经不在列表里:不能再拖、再挪 - if (i < 0) return undefined; - return { - index: i, - count: ids.length, - attrs: { "data-reorder-row": i, "data-reorder-scope": scope }, - handle: reorder.handle(i), - mark: reorder.marker(i, ids.length), - dragging: reorder.dragging === i, - move: (d) => { - const j = i + d; - if (j < 0 || j >= ids.length) return; - commit(moved(ids, i, j), id); - }, - }; - }; - return { list, table, sortOf }; -} - -/** 拖动中:被拖的那一行淡下去,放下的位置画一条线(和路由规则一样) */ -const sortRow = (sort: RowSort | undefined) => - sort && [ - sort.dragging && "opacity-50", - sort.mark === "before" && "shadow-[inset_0_2px_0_var(--color-foreground)]", - sort.mark === "after" && "shadow-[inset_0_-2px_0_var(--color-foreground)]", - ]; - -/** 行上的按键:Alt+↑/↓ 上移下移,其余照 `openable` */ -function sortKeys(sort: RowSort | undefined, onKeyDown: (e: KeyboardEvent) => void) { - return (e: KeyboardEvent) => { - if (sort && e.target === e.currentTarget && e.altKey && (e.key === "ArrowUp" || e.key === "ArrowDown")) { - e.preventDefault(); - sort.move(e.key === "ArrowUp" ? -1 : 1); - return; - } - onKeyDown(e); - }; -} - /** 行菜单里的上移、下移。到顶、到底时置灰 */ function moveItems(sort: RowSort | undefined, t: typeof clientsText.zh): MenuItems { if (!sort) return []; diff --git a/src/generated/tw-api.ts b/src/generated/tw-api.ts index f144a0cf..1729a0d6 100644 --- a/src/generated/tw-api.ts +++ b/src/generated/tw-api.ts @@ -3340,7 +3340,7 @@ export type Overview = { /** * Routing changes take effect on the next request, including manual selection. */ -hard_route_switch?: boolean, +hard_route_switch?: boolean, provider_request_extras?: boolean, /** * 配置文件现在的版本号。和 `GET /config` 的 `version`、改配置时带的 * `base_version` 是同一个。 @@ -3914,7 +3914,7 @@ export type Protocol = "anthropic" | "openai-chat" | "openai-responses" | "gemin * 那一方不知道引号规则,一个带 `#` 的值就能写坏整份配置。 * * **整份定义就是保存之后的样子**:视图给的是原样的设置,界面回填、改完整份交回来。 - * 只有 OAuth 能「保持原样」,见 [`OAuthChange::Keep`]。 + * OAuth 可选保持原样。旧客户端省略额外请求体设置时,也保留已配置的值。 */ export type ProviderInput = { name: string, base_url: string, /** @@ -3924,7 +3924,7 @@ key?: string | null, /** * 请求头,按顺序。没列出来的行被删掉 */ -headers?: Array, +headers?: Array, extra_body?: Record, use_client_prompt_cache_key?: boolean, /** * OAuth。修改时默认保持原样 */ @@ -4109,7 +4109,7 @@ auth_header: string, /** * 其余请求头,按配置里的顺序,值原样 */ -headers?: Array, oauth?: OAuthView | null, +headers?: Array, extra_body?: Record, use_client_prompt_cache_key?: boolean, oauth?: OAuthView | null, /** * Bedrock 的 AWS 访问密钥,配置里写的原样。用 API Key 的、别的协议的都是空 */ diff --git a/src/i18n/core.zh-Hant.json b/src/i18n/core.zh-Hant.json index e2dab397..c5966de8 100644 --- a/src/i18n/core.zh-Hant.json +++ b/src/i18n/core.zh-Hant.json @@ -588,6 +588,7 @@ "config.empty_key": "閘道器金鑰「{key}」的值為空。", "config.base_url_backslash": "上游「{upstream}」的介面地址含有反斜槓:{url}。地址中請只使用正斜槓。", "config.base_url_userinfo": "上游「{upstream}」的介面地址在主機前帶有使用者名稱或密碼。憑據請改寫在 key 或 headers 中。", + "config.extra_body_managed_field": "上游「{upstream}」的額外請求主體無法設定由閘道器管理的欄位 {field}。", "config.zero_concurrency": "閘道器金鑰「{key}」的 max_concurrent 為 0,使用它的請求會一直等待。不限制併發時請刪除 max_concurrent。", "config.min_speed_range": "上游「{upstream}」的 min_speed.{field} 為 {value},須在 {min} 到 {max} 之間。", "config.provider_concurrency_range": "上游「{upstream}」的 max_concurrent 為 {value},須在 1 到 {max} 之間。不限制併發時請刪除 max_concurrent。", diff --git a/src/i18n/core.zh.json b/src/i18n/core.zh.json index 19837582..f4a6996c 100644 --- a/src/i18n/core.zh.json +++ b/src/i18n/core.zh.json @@ -651,6 +651,7 @@ "config.empty_key": "网关密钥「{key}」的值为空。", "config.base_url_backslash": "上游「{upstream}」的接口地址含有反斜杠:{url}。地址中请只使用正斜杠。", "config.base_url_userinfo": "上游「{upstream}」的接口地址在主机前带有用户名或密码。凭据请改写在 key 或 headers 中。", + "config.extra_body_managed_field": "上游「{upstream}」的额外请求体不能设置由网关管理的字段 {field}。", "config.zero_concurrency": "网关密钥「{key}」的 max_concurrent 为 0,使用它的请求会一直等待。不限制并发时请删除 max_concurrent。", "config.min_speed_range": "上游「{upstream}」的 min_speed.{field} 为 {value},须在 {min} 到 {max} 之间。", "config.provider_concurrency_range": "上游「{upstream}」的 max_concurrent 为 {value},须在 1 到 {max} 之间。不限制并发时请删除 max_concurrent。", diff --git a/src/index.css b/src/index.css index fdf43f07..158b2ed5 100644 --- a/src/index.css +++ b/src/index.css @@ -501,6 +501,47 @@ animation: tw-row-flash 900ms var(--motion-ease); } } +/* 源行留在表格里维持尺寸,悬浮的副本在表格外跟手。 */ +@utility motion-reorder-row { + &[data-reorder-row] { + user-select: none; + } + &[data-reorder-preview="neighbor"] { + translate: 0 var(--reorder-y, 0px); + transition: translate var(--motion-fast) var(--motion-ease); + } + &[data-reorder-preview="source"] { + opacity: 0; + } + @media (prefers-reduced-motion: reduce) { + &[data-reorder-preview="neighbor"] { + transition: none; + } + } +} +/* 拖动中的光标也覆盖表格下方的空白落点。 */ +body:has(> .row-reorder-overlay), +body:has(> .row-reorder-overlay) * { + cursor: grabbing; +} +body[data-row-reorder-open-hand], +body[data-row-reorder-open-hand] * { + cursor: grab; +} +.row-reorder-overlay { + position: fixed; + z-index: 60; + top: 0; + pointer-events: none; + container: page / inline-size; + background: var(--color-surface); + box-shadow: inset 0 1px var(--color-border), inset 0 -1px var(--color-border), 0 3px 8px rgb(0 0 0 / 0.12); + will-change: transform; + > table { + width: 100%; + table-layout: fixed; + } +} /* 要消失的一行:淡出,期间不再接受点击(usePresentList 给 exit 状态) */ @utility motion-row-out { animation: tw-fade-out var(--motion-fast) var(--motion-ease) forwards; diff --git a/src/routing/rowDragCursor.ts b/src/routing/rowDragCursor.ts new file mode 100644 index 00000000..2daa57fe --- /dev/null +++ b/src/routing/rowDragCursor.ts @@ -0,0 +1,41 @@ +import { prefersReducedMotion } from "@/ui/motion"; + +const BEFORE_GRASP_MS = 70; +const AFTER_RELEASE_MS = 95; +const OPEN_HAND_ATTRIBUTE = "data-row-reorder-open-hand"; + +let disposeCurrent: (() => void) | undefined; + +export function startDragCursor() { + disposeCurrent?.(); + if (prefersReducedMotion()) return null; + + const body = document.body; + const listeners = new AbortController(); + let timer: number | undefined; + + function showOpenHand(duration: number, onEnd: () => void) { + window.clearTimeout(timer); + body.setAttribute(OPEN_HAND_ATTRIBUTE, ""); + timer = window.setTimeout(onEnd, duration); + } + + function dispose() { + window.clearTimeout(timer); + body.removeAttribute(OPEN_HAND_ATTRIBUTE); + listeners.abort(); + if (disposeCurrent === dispose) disposeCurrent = undefined; + } + + function release() { + if (listeners.signal.aborted) return; + window.addEventListener("pointerdown", dispose, { capture: true, signal: listeners.signal }); + showOpenHand(AFTER_RELEASE_MS, dispose); + } + + disposeCurrent = dispose; + window.addEventListener("blur", dispose, { signal: listeners.signal }); + // While the overlay is present, removing the override shows the native closed hand. + showOpenHand(BEFORE_GRASP_MS, () => body.removeAttribute(OPEN_HAND_ATTRIBUTE)); + return { release, dispose }; +} diff --git a/src/routing/rowDragPreview.ts b/src/routing/rowDragPreview.ts new file mode 100644 index 00000000..24deaef3 --- /dev/null +++ b/src/routing/rowDragPreview.ts @@ -0,0 +1,184 @@ +import { prefersReducedMotion } from "@/ui/motion"; +import { startDragCursor } from "./rowDragCursor"; + +const SETTLE_ANIMATION = "tw-row-reorder"; +const SCROLL_EDGE = 48; + +function floatingRow(source: HTMLTableRowElement, table: HTMLTableElement, bounds: DOMRect) { + // The table's scroll wrapper clips its rows. Keep the drag preview in viewport coordinates. + const overlay = document.createElement("div"); + overlay.className = "row-reorder-overlay"; + overlay.setAttribute("aria-hidden", "true"); + overlay.inert = true; + overlay.style.left = `${bounds.left}px`; + overlay.style.width = `${bounds.width}px`; + + const shell = table.cloneNode(false) as HTMLTableElement; + const columns = document.createElement("colgroup"); + shell.append(columns); + for (const cell of source.cells) { + const col = document.createElement("col"); + col.style.width = `${cell.getBoundingClientRect().width}px`; + columns.append(col); + } + const copy = source.cloneNode(true) as HTMLTableRowElement; + delete copy.dataset.reorderRow; + delete copy.dataset.reorderScope; + delete copy.dataset.row; + copy.classList.remove("motion-row-in", "motion-row-out"); + for (const node of copy.querySelectorAll("[id]")) node.removeAttribute("id"); + shell.createTBody().append(copy); + overlay.append(shell); + document.body.append(overlay); + return overlay; +} + +function scrollParent(element: HTMLElement): Element | null { + for (let parent = element.parentElement; parent; parent = parent.parentElement) { + const scrollable = parent.scrollHeight > parent.clientHeight; + if (scrollable && /^(auto|scroll)$/.test(getComputedStyle(parent).overflowY)) return parent; + } + const viewport = document.scrollingElement; + return viewport && viewport.scrollHeight > viewport.clientHeight ? viewport : null; +} + +export function startRowDragPreview( + handle: HTMLElement, + selector: string, + start: number, + pointerY: number, + onTarget: (slot: number | null) => void, +) { + const source = handle.closest(selector); + const body = source?.parentElement; + const table = source?.closest("table"); + if (!source || !body || !table) return null; + const group = body; + const wrapper = table.parentElement ?? table; + const scroller = scrollParent(wrapper); + const rows = [...group.children].filter((row): row is HTMLElement => + row instanceof HTMLElement && row.matches(selector), + ); + for (const row of rows) { + for (const animation of row.getAnimations()) { + if (animation.id === SETTLE_ANIMATION) animation.cancel(); + } + } + + const initialTop = group.getBoundingClientRect().top; + const sourceBounds = source.getBoundingClientRect(); + const { height } = sourceBounds; + const gripOffset = pointerY - sourceBounds.top; + // Hit testing stays on the unshifted layout as the neighbors move and the page scrolls. + const slots = rows.map((row) => { + const bounds = row.getBoundingClientRect(); + return { + row, + index: Number(row.dataset.reorderRow), + midpoint: bounds.top - initialTop + bounds.height / 2, + }; + }); + const overlay = floatingRow(source, table, sourceBounds); + const cursor = startDragCursor(); + let overlayTop = sourceBounds.top; + overlay.style.transform = `translateY(${overlayTop}px)`; + for (const row of rows) row.dataset.reorderPreview = row === source ? "source" : "neighbor"; + + let previous: number | null = null; + let pointer: { x: number; y: number } | null = null; + let scrollFrame: number | null = null; + + function insideColumn(x: number) { + const bounds = wrapper.getBoundingClientRect(); + return x >= Math.max(0, bounds.left) && x <= Math.min(window.innerWidth, bounds.right); + } + + function update(x: number, y: number) { + const localY = y - group.getBoundingClientRect().top; + overlayTop = Math.max(0, Math.min(window.innerHeight - height, y - gripOffset)); + overlay.style.transform = `translateY(${overlayTop}px)`; + + // Blank space below the last row is the final drop slot, down to the window edge. + const inside = insideColumn(x) && y >= 0 && y <= window.innerHeight && localY >= 0; + const slot = inside ? (slots.find((item) => localY < item.midpoint)?.index ?? slots.length) : null; + if (slot === previous) return slot; + previous = slot; + for (const { row, index } of slots) { + if (row === source) continue; + let offset = 0; + if (slot !== null) { + if (index > start && index < slot) offset = -height; + if (index < start && index >= slot) offset = height; + } + row.style.setProperty("--reorder-y", `${offset}px`); + } + onTarget(slot); + return slot; + } + + function scroll() { + scrollFrame = null; + if (!pointer || !scroller || !group.isConnected || !insideColumn(pointer.x)) return; + const isViewport = scroller === document.scrollingElement; + const bounds = scroller.getBoundingClientRect(); + const top = isViewport ? 0 : Math.max(0, bounds.top); + const bottom = isViewport ? window.innerHeight : Math.min(window.innerHeight, bounds.bottom); + const { x, y } = pointer; + if (y < top || y > bottom) return; + const edge = Math.min(SCROLL_EDGE, (bottom - top) / 2); + const upwards = Math.max(0, top + edge - y); + const downwards = Math.max(0, y - bottom + edge); + if (!upwards && !downwards) return; + const before = scroller.scrollTop; + const speed = Math.ceil(18 * (upwards || downwards) / edge); + scroller.scrollTop += upwards ? -speed : speed; + if (scroller.scrollTop === before) return; + update(x, y); + scrollFrame = requestAnimationFrame(scroll); + } + + function move(x: number, y: number) { + pointer = { x, y }; + const slot = update(x, y); + if (scroller && scrollFrame === null) scrollFrame = requestAnimationFrame(scroll); + return slot; + } + + function clearRows() { + if (scrollFrame !== null) cancelAnimationFrame(scrollFrame); + overlay.remove(); + for (const row of rows) { + delete row.dataset.reorderPreview; + row.style.removeProperty("--reorder-y"); + } + } + + function dispose() { + clearRows(); + cursor?.dispose(); + } + + function finish() { + const before = prefersReducedMotion() ? [] : rows.map((row) => + row === source ? overlayTop : row.getBoundingClientRect().top, + ); + clearRows(); + cursor?.release(); + if (before.length === 0) return; + requestAnimationFrame(() => { + // React has committed the order. Ease from the position the user just saw. + for (const [index, row] of rows.entries()) { + if (!row.isConnected || row.dataset.reorderPreview) continue; + const offset = before[index]! - row.getBoundingClientRect().top; + if (Math.abs(offset) < 1) continue; + const animation = row.animate( + { translate: [`0 ${offset}px`, "0 0px"] }, + { duration: 160, easing: "ease-out" }, + ); + animation.id = SETTLE_ANIMATION; + } + }); + } + + return { move, finish, dispose }; +} diff --git a/src/routing/useReorder.ts b/src/routing/useReorder.ts index d8c76b83..bcbeee80 100644 --- a/src/routing/useReorder.ts +++ b/src/routing/useReorder.ts @@ -1,4 +1,21 @@ -import { useRef, useState, type PointerEvent } from "react"; +import { useEffect, useId, useRef, useState, type KeyboardEvent, type MouseEvent, type PointerEvent } from "react"; +import { move } from "./model"; +import { startRowDragPreview } from "./rowDragPreview"; + +const ROW_DRAG_THRESHOLD = 6; +const ROW_CONTROLS = [ + "button", "input", "select", "textarea", "a[href]", "summary", + "[role=button]", "[role=checkbox]", "[role=switch]", "[role=combobox]", + "[contenteditable=true]", "[data-no-reorder]", +].join(","); + +interface DragGesture { + pointerId: number; + x: number; + y: number; + index: number; + active: boolean; +} /** * 拖动把手调整一张列表的顺序。 @@ -10,58 +27,103 @@ import { useRef, useState, type PointerEvent } from "react"; * `scope`:一页上有好几张能各自排序的表时,各给一个名字,行上再标 * `data-reorder-scope={scope}`。只认同一张表里的行:拖到别的表上等于没放下。 */ -export function useReorder(onMove: (from: number, to: number) => void, scope?: string) { - const from = useRef(null); +export function useReorder(onMove: (from: number, to: number) => void, scope?: string, wholeRow = false) { + const rowSelector = () => scope === undefined + ? "[data-reorder-row]" + : `[data-reorder-row][data-reorder-scope="${CSS.escape(scope)}"]`; + const gesture = useRef(null); + const suppressClick = useRef(false); + const preview = useRef>(null); const [dragging, setDragging] = useState(null); /** 放下时会落到哪个位置之前(等于长度时是末尾) */ const [target, setTarget] = useState(null); + useEffect(() => () => preview.current?.dispose(), []); + function locate(e: PointerEvent): number | null { - const row = scope === undefined ? "[data-reorder-row]" : `[data-reorder-row][data-reorder-scope="${CSS.escape(scope)}"]`; - const el = document.elementFromPoint(e.clientX, e.clientY)?.closest(row); + if (preview.current) return preview.current.move(e.clientX, e.clientY); + const el = document.elementFromPoint(e.clientX, e.clientY)?.closest(rowSelector()); if (!el) return null; const i = Number(el.dataset.reorderRow); const r = el.getBoundingClientRect(); return e.clientY < r.top + r.height / 2 ? i : i + 1; } + function clear() { + preview.current?.finish(); + preview.current = null; + gesture.current = null; + setDragging(null); + setTarget(null); + } + + function activate(e: PointerEvent, drag: DragGesture, index: number) { + e.preventDefault(); + drag.active = true; + drag.index = index; + if (wholeRow) preview.current = startRowDragPreview(e.currentTarget, rowSelector(), index, drag.y, setTarget); + setDragging(index); + } + + function cancel(e: PointerEvent) { + if (gesture.current?.pointerId === e.pointerId) clear(); + } + function handle(i: number) { return { onPointerDown: (e: PointerEvent) => { - if (e.button !== 0) return; - e.preventDefault(); + if (e.button !== 0 || !e.isPrimary || gesture.current) return; + suppressClick.current = false; + const target = e.target instanceof Element ? e.target : e.currentTarget; + if (wholeRow && ( + e.pointerType === "touch" || + !e.currentTarget.contains(target) || + target.closest(ROW_CONTROLS) + )) return; + + const drag = { pointerId: e.pointerId, index: i, x: e.clientX, y: e.clientY, active: false }; + gesture.current = drag; try { - // 把后续的移动都交给把手,指针离开它也不丢 - e.currentTarget.setPointerCapture(e.pointerId); + // Preserve the original hit target for clicks that never become drags. + (wholeRow ? target : e.currentTarget).setPointerCapture(e.pointerId); } catch { - // 指针已经不在了(比如刚按下就被系统取消):照常开始,松开时会结束 + // A pointer canceled by the system may no longer be capturable. } - from.current = i; - setDragging(i); - setTarget(null); + if (!wholeRow) activate(e, drag, i); }, onPointerMove: (e: PointerEvent) => { - if (from.current == null) return; + const drag = gesture.current; + if (!drag || drag.pointerId !== e.pointerId) return; + if (!drag.active) { + if (Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < ROW_DRAG_THRESHOLD) return; + activate(e, drag, i); + } setTarget(locate(e)); }, onPointerUp: (e: PointerEvent) => { - const start = from.current; - from.current = null; - setDragging(null); - setTarget(null); - if (start == null) return; + const drag = gesture.current; + if (!drag || drag.pointerId !== e.pointerId) return; + if (!drag.active) { + gesture.current = null; + return; + } const to = locate(e); - if (to == null) return; - // 落在自己前后等于没动;往后挪时,拿走自己之后下标要减一 - const dest = to > start ? to - 1 : to; - if (dest !== start) onMove(start, dest); - }, - onPointerCancel: () => { - from.current = null; - setDragging(null); - setTarget(null); + suppressClick.current = wholeRow; + clear(); + if (to === null) return; + // 往后挪时,拿走自己之后下标要减一。 + const dest = to > drag.index ? to - 1 : to; + if (dest !== drag.index) onMove(drag.index, dest); }, - style: { cursor: dragging === i ? "grabbing" : "grab", touchAction: "none" as const }, + onPointerCancel: cancel, + onLostPointerCapture: cancel, + onClickCapture: wholeRow ? (e: MouseEvent) => { + if (!suppressClick.current || e.detail === 0) return; + suppressClick.current = false; + e.preventDefault(); + e.stopPropagation(); + } : undefined, + style: wholeRow ? undefined : { cursor: dragging === i ? "grabbing" : "grab", touchAction: "none" as const }, }; } @@ -76,3 +138,93 @@ export function useReorder(onMove: (from: number, to: number) => void, scope?: s return { handle, dragging, marker }; } + +/** 能排序的表里的一行:第几个、共几个,拖动把手,上移下移 */ +export interface RowSort { + index: number; + count: number; + /** 行上标的:`useReorder` 按它认是哪一行、是不是这一张表的 */ + attrs: { "data-reorder-row": number; "data-reorder-scope": string }; + handle: ReturnType["handle"]>; + mark: "before" | "after" | null; + dragging: boolean; + move: (d: -1 | 1) => void; +} + +/** + * 一张能排序的表:拖动把手、行菜单的上移下移、在行上按 Alt+↑/↓。`onReorder` 没给就不能排。 + * + * **拖动中画的是按下把手那一刻的列表。**这一页跟着请求刷新,拖到一半来了新数据(新装了 + * 一个、有一个不见了)的话,行的进出场动画会把行挤来挤去,放下时的下标也对不上;放下 + * 之后才换成新的。 + * + * 用键盘挪的那一行重新排过之后可能丢了焦点(React 挪的是它所在的那个节点):焦点丢了 + * 就还给它 + */ +export function useSortable( + items: T[], + idOf: (item: T) => string, + onReorder: ((ids: string[]) => void) | undefined, + { wholeRow = false }: { wholeRow?: boolean } = {}, +) { + const scope = useId(); + const table = useRef(null); + const [frozen, setFrozen] = useState(null); + const latest = useRef([]); + const commit = (ids: string[], focus?: string) => { + onReorder?.(ids); + if (focus === undefined) return; + requestAnimationFrame(() => { + const a = document.activeElement; + if (a && a !== document.body && a.isConnected) return; + table.current?.querySelector(`tr[data-row="${CSS.escape(focus)}"]`)?.focus(); + }); + }; + const reorder = useReorder((from, to) => commit(move(latest.current, from, to)), scope, wholeRow); + const dragging = reorder.dragging !== null; + if (dragging && frozen === null) setFrozen(items); + else if (!dragging && frozen !== null) setFrozen(null); + const list = (dragging ? frozen : null) ?? items; + const ids = list.map(idOf); + latest.current = ids; + const sortOf = (id: string): RowSort | undefined => { + if (!onReorder) return undefined; + const i = ids.indexOf(id); + // 正在淡出的那一行已经不在列表里:不能再拖、再挪 + if (i < 0) return undefined; + return { + index: i, + count: ids.length, + attrs: { "data-reorder-row": i, "data-reorder-scope": scope }, + handle: reorder.handle(i), + mark: reorder.marker(i, ids.length), + dragging: reorder.dragging === i, + move: (d) => { + const j = i + d; + if (j < 0 || j >= ids.length) return; + commit(move(ids, i, j), id); + }, + }; + }; + return { list, table, sortOf }; +} + +/** 拖动中:被拖的那一行淡下去,放下的位置画一条线(和路由规则一样) */ +export const sortRow = (sort: RowSort | undefined) => + sort && [ + sort.dragging && "opacity-50", + sort.mark === "before" && "shadow-[inset_0_2px_0_var(--color-foreground)]", + sort.mark === "after" && "shadow-[inset_0_-2px_0_var(--color-foreground)]", + ]; + +/** 行上的按键:Alt+↑/↓ 上移下移,其余照 `openable` */ +export function sortKeys(sort: RowSort | undefined, onKeyDown: (e: KeyboardEvent) => void) { + return (e: KeyboardEvent) => { + if (sort && e.target === e.currentTarget && e.altKey && (e.key === "ArrowUp" || e.key === "ArrowDown")) { + e.preventDefault(); + sort.move(e.key === "ArrowUp" ? -1 : 1); + return; + } + onKeyDown(e); + }; +} diff --git a/src/upstreams/ConnectionSection.i18n.ts b/src/upstreams/ConnectionSection.i18n.ts index fbd0da19..ecd6d094 100644 --- a/src/upstreams/ConnectionSection.i18n.ts +++ b/src/upstreams/ConnectionSection.i18n.ts @@ -293,3 +293,38 @@ export const connectionSectionText = messages( }, }, ); + +export const extraBodyText = messages( + { + label: "额外请求体", + hint: "为此上游的生成请求补充 JSON 字段。对象逐层合并。", + cache: "沿用客户端会话缓存键", + cacheHint: "协议转换后缺少 prompt_cache_key 时,使用客户端提交的值。", + }, + { + label: "Extra request body", + hint: "Add JSON fields to generation requests for this upstream. Nested objects are merged.", + cache: "Reuse the client’s prompt cache key", + cacheHint: "Use the client’s prompt_cache_key when it is missing after protocol conversion.", + }, + { + "zh-Hant": { + label: "額外請求主體", + hint: "為此上游的生成請求補充 JSON 欄位。物件逐層合併。", + cache: "沿用用戶端工作階段快取鍵", + cacheHint: "協定轉換後缺少 prompt_cache_key 時,使用用戶端提交的值。", + }, + ko: { + label: "추가 요청 본문", + hint: "이 업스트림의 생성 요청에 JSON 필드를 추가합니다. 중첩 객체는 병합됩니다.", + cache: "클라이언트 프롬프트 캐시 키 재사용", + cacheHint: "프로토콜 변환 후 prompt_cache_key가 없으면 클라이언트가 보낸 값을 사용합니다.", + }, + es: { + label: "Cuerpo adicional de la solicitud", + hint: "Añade campos JSON a las solicitudes de generación de este proveedor. Los objetos anidados se combinan.", + cache: "Reutilizar la clave de caché del cliente", + cacheHint: "Usa el valor de prompt_cache_key del cliente si falta tras la conversión del protocolo.", + }, + }, +); diff --git a/src/upstreams/ConnectionSection.tsx b/src/upstreams/ConnectionSection.tsx index 72e584a8..59629f6f 100644 --- a/src/upstreams/ConnectionSection.tsx +++ b/src/upstreams/ConnectionSection.tsx @@ -3,6 +3,7 @@ import { useState, type ReactNode } from "react"; import { ChevronRightIcon, CircleAlertIcon, CircleCheckIcon, PlugIcon } from "lucide-react"; import { Button, DISCLOSURE } from "@/ui/button"; import { Input } from "@/ui/input"; +import { Textarea } from "@/ui/textarea"; import { SelectField, SelectOption } from "@/ui/select-field"; import { SecretInput } from "@/ui/secret-input"; import { Segmented } from "@/ui/segmented"; @@ -21,7 +22,7 @@ import type { ZaiFamily, } from "@/types"; import { AccountKeyPanel } from "./AccountPanel"; -import { connectionSectionText } from "./ConnectionSection.i18n"; +import { connectionSectionText, extraBodyText } from "./ConnectionSection.i18n"; import { balanceBrief, sourceLabel } from "./balance"; import { useSystemProxyLabel } from "@/connection/Remote"; import { useRemote } from "@/connection/useRemote"; @@ -53,6 +54,7 @@ import { freeName, isBedrock, oauthKept, + parseExtraBody, type FieldRules, type UpstreamForm, } from "./upstreamForm"; @@ -293,6 +295,7 @@ export function ConnectionSection({ form={form} set={set} rules={rules} + showExtraBody={ov.provider_request_extras === true} limits={} > {/* 连着远程 core 时 `${变量名}` 读的是服务器上的环境 */} @@ -307,6 +310,7 @@ export function ConnectionSection({ })} /> + {ov.provider_request_extras && } {check && } @@ -315,6 +319,43 @@ export function ConnectionSection({ } /** 「余额来源」能选的:自动识别、不读取,然后是认得的几种来源 */ + +function ExtraBodyEditor({ + form, + set, +}: { + form: UpstreamForm; + set: (patch: Partial) => void; +}) { + const t = useText(extraBodyText); + return ( + <> + +