From e7d346a6f3cb0aad9a316121782c3ad78313ce38 Mon Sep 17 00:00:00 2001 From: blankll Date: Fri, 20 Nov 2026 01:32:09 +0800 Subject: [PATCH 1/3] feat(tray): show Data Studio Bridge and MCP server status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tray carries two disabled status lines plus a Copy Bridge URL action: 'Data Studio Bridge · Running (port N) / Stopped (subscription required)' and '{App} MCP Server · N session(s) — clients' - McpSessionRegistry tracks live Data Studio MCP sessions from X-Data-Studio-Session/Client headers on /tools and /invoke (30s TTL, capped at 50; anonymous traffic keeps a last-seen fallback for older npm releases) - BridgeStopStatus records why the bridge went down so the tray can say more than 'Stopped' when the entitlement gate shuts it down - adds the clipboard manager plugin (dep + registration + capability) to back Copy Bridge URL - settings page and all locales rename the component from 'MCP Bridge' to 'Data Studio Bridge' --- src-tauri/Cargo.lock | 320 +++++++++++++++++++++++++++- src-tauri/Cargo.toml | 1 + src-tauri/capabilities/default.json | 3 +- src-tauri/src/desktop.rs | 311 ++++++++++++++++++++++++--- src-tauri/src/lib.rs | 5 + src-tauri/src/mcp_bridge.rs | 220 ++++++++++++++++++- src/lang/enUS.ts | 2 +- src/lang/esES.ts | 14 +- src/lang/jaJP.ts | 14 +- src/lang/koKR.ts | 14 +- src/lang/ptBR.ts | 14 +- src/lang/zhCN.ts | 12 +- src/lang/zhTW.ts | 14 +- 13 files changed, 869 insertions(+), 75 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 7a06b656..e454be3d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -158,6 +158,27 @@ dependencies = [ "derive_arbitrary", ] +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + [[package]] name = "argon2" version = "0.5.3" @@ -808,6 +829,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.0" @@ -960,7 +987,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" dependencies = [ - "nom", + "nom 7.1.3", ] [[package]] @@ -1064,6 +1091,15 @@ dependencies = [ "libloading 0.8.9", ] +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + [[package]] name = "cmake" version = "0.1.58" @@ -1847,6 +1883,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "dpi" version = "0.1.2" @@ -2063,6 +2105,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "event-listener" version = "5.4.1" @@ -2091,7 +2139,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" dependencies = [ "futures-core", - "nom", + "nom 7.1.3", "pin-project-lite", ] @@ -2145,6 +2193,12 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -2186,6 +2240,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + [[package]] name = "flagset" version = "0.4.7" @@ -2795,6 +2855,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -3170,6 +3241,20 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -3797,6 +3882,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "muda" version = "0.19.3" @@ -3942,6 +4037,15 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -4055,6 +4159,7 @@ dependencies = [ "block2", "objc2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation", ] @@ -4339,6 +4444,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "osakit" version = "0.3.1" @@ -4539,6 +4654,17 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap 2.14.0", +] + [[package]] name = "phf" version = "0.13.1" @@ -4980,6 +5106,18 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.30.0" @@ -4999,6 +5137,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + [[package]] name = "quinn" version = "0.11.9" @@ -5353,7 +5500,7 @@ dependencies = [ "futures-core", "futures-timer", "mime", - "nom", + "nom 7.1.3", "pin-project-lite", "reqwest 0.12.28", "thiserror 1.0.69", @@ -6498,6 +6645,7 @@ dependencies = [ "tar", "tauri", "tauri-build", + "tauri-plugin-clipboard-manager", "tauri-plugin-deep-link", "tauri-plugin-dialog", "tauri-plugin-opener", @@ -6952,6 +7100,21 @@ dependencies = [ "walkdir", ] +[[package]] +name = "tauri-plugin-clipboard-manager" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4136fb69d967753d000423d7e5f863f89bf949efbdfbecb43a580426a01a0194" +dependencies = [ + "arboard", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", +] + [[package]] name = "tauri-plugin-deep-link" version = "2.4.9" @@ -7345,6 +7508,20 @@ dependencies = [ "uuid", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "tiktoken-rs" version = "0.7.0" @@ -7779,6 +7956,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom 8.0.0", + "petgraph", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -8152,6 +8340,76 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.0", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.0", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml 0.41.0", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + [[package]] name = "web-sys" version = "0.3.102" @@ -8301,6 +8559,12 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "whoami" version = "2.1.2" @@ -8873,6 +9137,24 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "writeable" version = "0.6.3" @@ -8953,6 +9235,23 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + [[package]] name = "x509-cert" version = "0.2.5" @@ -9262,6 +9561,21 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "5.12.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7a1cb517..dd5e1301 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -29,6 +29,7 @@ tauri = { version = "2", features = [ tauri-plugin-opener = "2" tauri-plugin-process = "2" tauri-plugin-updater = "2" +tauri-plugin-clipboard-manager = "2" serde = { version = "1", features = [ "derive" ] } serde_json = "1" async-trait = "0.1" diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 039ea6c0..e5804f09 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -20,6 +20,7 @@ "dialog:default", "dialog:allow-save", "updater:default", - "deep-link:default" + "deep-link:default", + "clipboard-manager:allow-write-text" ] } diff --git a/src-tauri/src/desktop.rs b/src-tauri/src/desktop.rs index f4914ec7..fdee0127 100644 --- a/src-tauri/src/desktop.rs +++ b/src-tauri/src/desktop.rs @@ -1,26 +1,189 @@ +use std::sync::Mutex; +use std::time::Duration; + use tauri::menu::{MenuBuilder, MenuItem}; -use tauri::tray::TrayIconBuilder; -use tauri::{App, AppHandle, Manager, WindowEvent}; +use tauri::tray::{TrayIcon, TrayIconBuilder}; +use tauri::{App, AppHandle, Manager, WindowEvent, Wry}; +use tauri_plugin_clipboard_manager::ClipboardExt; + +use crate::mcp_bridge::{BridgeStopReason, McpSessionRegistry}; const MAIN_WINDOW: &str = "main"; const SHOW_WINDOW: &str = "tray-show-window"; +const COPY_BRIDGE_URL: &str = "tray-copy-bridge-url"; const QUIT: &str = "tray-quit"; +const STATUS_REFRESH: Duration = Duration::from_secs(5); +/// Client names rendered on one tray line; the rest collapses into "+N". +const MAX_CLIENTS_DISPLAYED: usize = 3; + +/// Localized tray copy. Product nouns ("Data Studio Bridge", backend client +/// names) stay untranslated; only the status phrasing is localized. +struct TrayLabels { + show_window: &'static str, + quit: &'static str, + copy_url: &'static str, + /// "{}" → port + bridge_running: &'static str, + bridge_stopped: &'static str, + bridge_stopped_gate: &'static str, + /// "{count}" → session count, "{clients}" → client names + server_sessions: &'static str, + /// "{}" → seconds since last anonymous request + server_anonymous: &'static str, + server_none: &'static str, +} + +impl TrayLabels { + fn bridge_running_line(&self, port: u16) -> String { + self.bridge_running.replace("{}", &port.to_string()) + } + + fn server_sessions_line(&self, count: usize, clients: &str) -> String { + self.server_sessions + .replace("{count}", &count.to_string()) + .replace("{clients}", clients) + } + + fn server_anonymous_line(&self, secs: u64) -> String { + self.server_anonymous.replace("{}", &secs.to_string()) + } +} + +fn tray_labels(locale: &str) -> TrayLabels { + let normalized = locale.to_ascii_lowercase(); + let mut locale_parts = normalized.split(['-', '_']); + match locale_parts.next() { + Some("zh") if locale_parts.any(|part| matches!(part, "hant" | "tw" | "hk" | "mo")) => { + TrayLabels { + show_window: "顯示視窗", + quit: "結束", + copy_url: "複製 Bridge 地址", + bridge_running: "運行中(連接埠 {})", + bridge_stopped: "已停止", + bridge_stopped_gate: "已停止(需要訂閱)", + server_sessions: "{count} 個會話 — {clients}", + server_anonymous: "活躍({} 秒前有活動)", + server_none: "無活躍會話", + } + } + Some("zh") => TrayLabels { + show_window: "显示窗口", + quit: "退出", + copy_url: "复制 Bridge 地址", + bridge_running: "运行中(端口 {})", + bridge_stopped: "已停止", + bridge_stopped_gate: "已停止(需要订阅)", + server_sessions: "{count} 个会话 — {clients}", + server_anonymous: "活跃({} 秒前有活动)", + server_none: "无活跃会话", + }, + Some("pt") => TrayLabels { + show_window: "Mostrar janela", + quit: "Sair", + copy_url: "Copiar URL do Bridge", + bridge_running: "Em execução (porta {})", + bridge_stopped: "Parado", + bridge_stopped_gate: "Parado (assinatura necessária)", + server_sessions: "{count} sessão(ões) — {clients}", + server_anonymous: "ativo (visto há {}s)", + server_none: "sem sessões ativas", + }, + Some("ja") => TrayLabels { + show_window: "ウィンドウを表示", + quit: "終了", + copy_url: "Bridge URL をコピー", + bridge_running: "実行中(ポート {})", + bridge_stopped: "停止中", + bridge_stopped_gate: "停止中(サブスクリプションが必要)", + server_sessions: "{count} セッション — {clients}", + server_anonymous: "アクティブ({} 秒前に活動)", + server_none: "アクティブなセッションなし", + }, + Some("ko") => TrayLabels { + show_window: "창 표시", + quit: "종료", + copy_url: "Bridge URL 복사", + bridge_running: "실행 중 (포트 {})", + bridge_stopped: "중지됨", + bridge_stopped_gate: "중지됨 (구독 필요)", + server_sessions: "{count}개 세션 — {clients}", + server_anonymous: "활성 ({}초 전 활동)", + server_none: "활성 세션 없음", + }, + Some("es") => TrayLabels { + show_window: "Mostrar ventana", + quit: "Salir", + copy_url: "Copiar URL del Bridge", + bridge_running: "En ejecución (puerto {})", + bridge_stopped: "Detenido", + bridge_stopped_gate: "Detenido (se requiere suscripción)", + server_sessions: "{count} sesión(es) — {clients}", + server_anonymous: "activo (visto hace {}s)", + server_none: "sin sesiones activas", + }, + _ => TrayLabels { + show_window: "Show Window", + quit: "Quit", + copy_url: "Copy Bridge URL", + bridge_running: "Running (port {})", + bridge_stopped: "Stopped", + bridge_stopped_gate: "Stopped (subscription required)", + server_sessions: "{count} session(s) — {clients}", + server_anonymous: "active (last seen {}s ago)", + server_none: "no active sessions", + }, + } +} + +/// Tray widgets the refresh loop and the copy handler share. Managed as Tauri +/// state so the menu event handler can reach the last known port without +/// touching the filesystem. +struct TrayStatusItems { + tray: TrayIcon, + bridge_line: MenuItem, + server_line: MenuItem, + copy_url: MenuItem, + labels: TrayLabels, + app_name: String, + /// Last seen bridge port, kept fresh by the refresh loop. + port: Mutex>, +} pub(crate) fn setup(app: &App) { - let tray_ready = match create_tray(app) { - Ok(()) => true, + let tray = match create_tray(app) { + Ok(items) => { + app.manage(items); + true + } Err(error) => { eprintln!("Could not create the system tray: {error}"); false } }; + if tray { + let app_handle = app.handle().clone(); + if let Some(items) = app_handle.try_state::() { + // Paint the first status lines synchronously; the loop only has to + // keep them fresh afterwards. + refresh_status_lines(&app_handle, &items); + tauri::async_runtime::spawn(async move { + loop { + tokio::time::sleep(STATUS_REFRESH).await; + if let Some(items) = app_handle.try_state::() { + refresh_status_lines(&app_handle, &items); + } + } + }); + } + } + if let Some(window) = app.get_webview_window(MAIN_WINDOW) { let main_window = window.clone(); window.on_window_event(move |event| { if let WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); - if tray_ready && main_window.hide().is_ok() { + if tray && main_window.hide().is_ok() { return; } if let Err(error) = main_window.minimize() { @@ -43,46 +206,142 @@ pub(crate) fn show_main_window(app: &AppHandle) { } } -fn create_tray(app: &App) -> tauri::Result<()> { +fn create_tray(app: &App) -> Result> { #[cfg(target_os = "macos")] let icon = tauri::include_image!("icons/tray-template.png"); #[cfg(not(target_os = "macos"))] let icon = tauri::include_image!("icons/tray.png"); - let locale = tauri_plugin_os::locale() - .unwrap_or_default() - .to_ascii_lowercase(); - let mut locale_parts = locale.split(['-', '_']); - let (show_label, quit_label) = match locale_parts.next() { - Some("zh") if locale_parts.any(|part| matches!(part, "hant" | "tw" | "hk" | "mo")) => { - ("顯示視窗", "結束") - } - Some("zh") => ("显示窗口", "退出"), - Some("pt") => ("Mostrar janela", "Sair"), - Some("ja") => ("ウィンドウを表示", "終了"), - Some("ko") => ("창 표시", "종료"), - Some("es") => ("Mostrar ventana", "Salir"), - _ => ("Show Window", "Quit"), - }; + let locale = tauri_plugin_os::locale().unwrap_or_default(); + let labels = tray_labels(&locale); + let app_name = app.package_info().name.clone(); - let show = MenuItem::with_id(app, SHOW_WINDOW, show_label, true, None::<&str>)?; - let quit = MenuItem::with_id(app, QUIT, quit_label, true, None::<&str>)?; + let bridge_line = MenuItem::with_id(app, "tray-bridge-status", "", false, None::<&str>)?; + let server_line = MenuItem::with_id(app, "tray-server-status", "", false, None::<&str>)?; + let copy_url = MenuItem::with_id(app, COPY_BRIDGE_URL, labels.copy_url, true, None::<&str>)?; + let show = MenuItem::with_id(app, SHOW_WINDOW, labels.show_window, true, None::<&str>)?; + let quit = MenuItem::with_id(app, QUIT, labels.quit, true, None::<&str>)?; let menu = MenuBuilder::new(app) + .item(&bridge_line) + .item(&server_line) + .item(©_url) + .separator() .item(&show) .separator() .item(&quit) .build()?; - TrayIconBuilder::with_id(app.config().identifier.as_str()) + + let tray = TrayIconBuilder::with_id(app.config().identifier.as_str()) .icon(icon) .icon_as_template(cfg!(target_os = "macos")) - .tooltip(&app.package_info().name) + .tooltip(&app_name) .menu(&menu) .show_menu_on_left_click(true) .on_menu_event(|app, event| match event.id().as_ref() { SHOW_WINDOW => show_main_window(app), + COPY_BRIDGE_URL => copy_bridge_url(app), QUIT => app.exit(0), _ => {} }) .build(app)?; - Ok(()) + + Ok(TrayStatusItems { + tray, + bridge_line, + server_line, + copy_url, + labels, + app_name, + port: Mutex::new(None), + }) +} + +fn refresh_status_lines(app: &AppHandle, items: &TrayStatusItems) { + let Ok(app_data_dir) = app.path().app_data_dir() else { + return; + }; + let running_port = crate::mcp_bridge::get_actual_port(&app_data_dir); + *items.port.lock().unwrap() = running_port; + + let bridge_text = match running_port { + Some(port) => items.labels.bridge_running_line(port), + None => { + let gated = app + .try_state::() + .is_some_and(|status| { + *status.reason.lock().unwrap() == Some(BridgeStopReason::SubscriptionRequired) + }); + if gated { + items.labels.bridge_stopped_gate.to_string() + } else { + items.labels.bridge_stopped.to_string() + } + } + }; + + let server_text = app + .try_state::() + .map(|registry| server_line(®istry, &items.labels)) + .unwrap_or_else(|| items.labels.server_none.to_string()); + + let _ = items.bridge_line.set_text(&bridge_text); + let _ = items.server_line.set_text(&server_text); + let _ = items.copy_url.set_enabled(running_port.is_some()); + let tooltip = match running_port { + Some(port) => format!("{} — Data Studio Bridge on :{port}", items.app_name), + None => items.app_name.clone(), + }; + let _ = items.tray.set_tooltip(Some(tooltip)); +} + +fn server_line(registry: &McpSessionRegistry, labels: &TrayLabels) -> String { + let sessions = registry.live_sessions(); + if sessions.is_empty() { + return registry + .anonymous_age_secs() + .map(|secs| labels.server_anonymous_line(secs)) + .unwrap_or_else(|| labels.server_none.to_string()); + } + + let names: Vec = sessions + .iter() + .map(|entry| { + entry + .client + .clone() + .or_else(|| { + entry + .version + .clone() + .map(|v| format!("data-studio-mcp/{v}")) + }) + .unwrap_or_else(|| "data-studio-mcp".to_string()) + }) + .collect(); + let shown = &names[..names.len().min(MAX_CLIENTS_DISPLAYED)]; + let clients = if names.len() > MAX_CLIENTS_DISPLAYED { + format!( + "{} +{}", + shown.join(", "), + names.len() - MAX_CLIENTS_DISPLAYED + ) + } else { + shown.join(", ") + }; + labels.server_sessions_line(names.len(), &clients) +} + +fn copy_bridge_url(app: &AppHandle) { + let Some(items) = app.try_state::() else { + return; + }; + let Some(port) = *items.port.lock().unwrap() else { + return; + }; + if let Err(error) = app + .clipboard() + .write_text(format!("http://127.0.0.1:{port}")) + { + eprintln!("Could not copy the bridge URL: {error}"); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3f7fe4ed..cc3858ad 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -147,6 +147,7 @@ pub fn run() { .plugin(tauri_plugin_deep_link::init()) .plugin(tauri_plugin_os::init()) .plugin(tauri_plugin_window_state::Builder::default().build()) + .plugin(tauri_plugin_clipboard_manager::init()) .manage(AppState::new()) .manage(store.clone()) .setup(move |app| { @@ -167,6 +168,10 @@ pub fn run() { store.set_app_handle(handle.clone()).await; }); menu::create_menu(app)?; + // Tray-visible MCP state must exist before desktop::setup spawns + // the status refresh loop. + app.manage(crate::mcp_bridge::McpSessionRegistry::default()); + app.manage(crate::mcp_bridge::BridgeStopStatus::default()); #[cfg(desktop)] desktop::setup(app); diff --git a/src-tauri/src/mcp_bridge.rs b/src-tauri/src/mcp_bridge.rs index d0ee9c76..b7886b1d 100644 --- a/src-tauri/src/mcp_bridge.rs +++ b/src-tauri/src/mcp_bridge.rs @@ -1,12 +1,14 @@ +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::Mutex; +use std::time::{Duration, Instant}; use crate::ai_permissions::{ load_permission_policy, read_permission_config, AiPolicy, AI_POLICY_LOCK, }; use axum::extract::State; -use axum::http::StatusCode; +use axum::http::{HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::Json; @@ -37,6 +39,142 @@ impl McpServerHandle { } } +// --------------------------------------------------------------------------- +// Session registry — tray visibility into Data Studio MCP server traffic +// --------------------------------------------------------------------------- + +/// data-studio-mcp polls every ~10s, so three missed polls drop a session. +const SESSION_TTL: Duration = Duration::from_secs(30); +/// Upper bound so a misbehaving client cannot grow the map without limit. +const MAX_SESSIONS: usize = 50; +const SESSION_HEADER: &str = "x-data-studio-session"; +const CLIENT_HEADER: &str = "x-data-studio-client"; + +#[derive(Debug, Clone)] +pub struct SessionEntry { + pub client: Option, + pub version: Option, + pub last_seen: Instant, +} + +#[derive(Default)] +pub struct McpSessionRegistry { + sessions: Mutex>, + anonymous_last_seen: Mutex>, +} + +/// Why the bridge is not running, when the reason is a gate rather than the +/// user turning `auto_start` off (which shows as a plain "Stopped"). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BridgeStopReason { + SubscriptionRequired, +} + +#[derive(Default)] +pub struct BridgeStopStatus { + pub reason: Mutex>, +} + +impl McpSessionRegistry { + fn prune(sessions: &mut HashMap) { + sessions.retain(|_, entry| entry.last_seen.elapsed() < SESSION_TTL); + } + + /// Record a request from the Data Studio MCP server. Requests without the + /// identity headers (older npm releases) still count, as anonymous traffic. + pub fn note_activity( + &self, + session_id: Option, + client: Option, + version: Option, + ) { + let now = Instant::now(); + match session_id { + Some(id) if !id.is_empty() => { + let mut sessions = self.sessions.lock().unwrap(); + Self::prune(&mut sessions); + if sessions.len() >= MAX_SESSIONS && !sessions.contains_key(&id) { + return; + } + sessions.insert( + id, + SessionEntry { + client, + version, + last_seen: now, + }, + ); + } + _ => { + *self.anonymous_last_seen.lock().unwrap() = Some(now); + } + } + } + + /// Sessions seen within the TTL, ordered by last activity. + pub fn live_sessions(&self) -> Vec { + let mut sessions = self.sessions.lock().unwrap(); + Self::prune(&mut sessions); + let mut entries: Vec = sessions.values().cloned().collect(); + entries.sort_by_key(|entry| entry.last_seen); + entries + } + + /// Seconds since the last header-less request, when within the TTL. + pub fn anonymous_age_secs(&self) -> Option { + let last = *self.anonymous_last_seen.lock().unwrap(); + last.map(|seen| seen.elapsed().as_secs()) + .filter(|age| *age < SESSION_TTL.as_secs()) + } +} + +/// Strip control characters and cap the length for tray rendering — the +/// header comes from an external process. +fn sanitize_label(raw: &str, max: usize) -> String { + raw.chars() + .filter(|c| !c.is_control()) + .collect::() + .trim() + .chars() + .take(max) + .collect() +} + +/// `data-studio-mcp/0.1.12 (ZCode)` → `(version, client)`. +fn parse_client_header(raw: &str) -> (Option, Option) { + let cleaned = sanitize_label(raw, 96); + let mut parts = cleaned.splitn(2, ' '); + let product = parts.next().unwrap_or_default(); + let version = product + .split_once('/') + .map(|(_, v)| sanitize_label(v, 24)) + .filter(|v| !v.is_empty()); + let client = parts + .next() + .map(str::trim) + .and_then(|rest| rest.strip_prefix('(')) + .and_then(|rest| rest.strip_suffix(')')) + .map(|name| sanitize_label(name, 48)) + .filter(|name| !name.is_empty()); + (version, client) +} + +fn note_bridge_traffic(handle: &AppHandle, headers: &HeaderMap) { + let session_id = headers + .get(SESSION_HEADER) + .and_then(|value| value.to_str().ok()) + .map(|value| sanitize_label(value, 64)) + .filter(|value| !value.is_empty()); + let (client, version) = headers + .get(CLIENT_HEADER) + .and_then(|value| value.to_str().ok()) + .map(parse_client_header) + .unwrap_or((None, None)); + if let Some(registry) = handle.try_state::() { + registry.note_activity(session_id, client, version); + } +} + // --------------------------------------------------------------------------- // Config // --------------------------------------------------------------------------- @@ -193,7 +331,8 @@ fn entitlement_denied(state: &BridgeState) -> Option { None } -async fn handle_tools(State(state): State>) -> Response { +async fn handle_tools(State(state): State>, headers: HeaderMap) -> Response { + note_bridge_traffic(&state.handle, &headers); if let Some(reason) = entitlement_denied(&state) { return ( StatusCode::FORBIDDEN, @@ -337,8 +476,10 @@ fn allowlist_missing_connection_reason( async fn handle_invoke( State(state): State>, + headers: HeaderMap, Json(payload): Json, ) -> Json { + note_bridge_traffic(&state.handle, &headers); if let Some(reason) = entitlement_denied(&state) { return Json(InvokeResponse::error(403, reason)); } @@ -435,7 +576,7 @@ fn get_default_port() -> u16 { 9121 } -fn get_actual_port(app_data_dir: &Path) -> Option { +pub(crate) fn get_actual_port(app_data_dir: &Path) -> Option { let path = app_data_dir.join("mcp-port"); let port = std::fs::read_to_string(&path) .ok() @@ -501,6 +642,10 @@ pub fn sync_with_entitlement(handle: &AppHandle) { } let handle = handle.clone(); tauri::async_runtime::spawn(async move { + // Record why the bridge went away so the tray can say more than "Stopped". + if let Some(status) = handle.try_state::() { + *status.reason.lock().unwrap() = Some(BridgeStopReason::SubscriptionRequired); + } shutdown_if_running(&handle).await; }); } @@ -641,6 +786,11 @@ pub async fn start( } }; + // A successful start supersedes whatever gate previously blocked the bridge. + if let Some(status) = handle.try_state::() { + *status.reason.lock().unwrap() = None; + } + port } @@ -1281,4 +1431,68 @@ mod tests { ); assert_eq!(filter_ai_connections(filtered, &policy), json!([])); } + + #[test] + fn sanitize_label_strips_control_chars_and_caps_length() { + assert_eq!(sanitize_label("ZCode\u{7}x", 48), "ZCodex"); + assert_eq!(sanitize_label("abcdefghij", 4), "abcd"); + assert_eq!(sanitize_label(" spaced ", 48), "spaced"); + } + + #[test] + fn parse_client_header_extracts_version_and_client() { + let (version, client) = parse_client_header("data-studio-mcp/0.1.12 (ZCode)"); + assert_eq!(version.as_deref(), Some("0.1.12")); + assert_eq!(client.as_deref(), Some("ZCode")); + } + + #[test] + fn parse_client_header_allows_missing_client() { + let (version, client) = parse_client_header("data-studio-mcp/0.1.12"); + assert_eq!(version.as_deref(), Some("0.1.12")); + assert_eq!(client, None); + } + + #[test] + fn parse_client_header_tolerates_garbage() { + let (version, client) = parse_client_header("\u{1}not-a-product"); + assert_eq!(version, None); + assert_eq!(client, None); + } + + #[test] + fn registry_tracks_sessions_and_anonymous_traffic() { + let registry = McpSessionRegistry::default(); + assert!(registry.live_sessions().is_empty()); + assert_eq!(registry.anonymous_age_secs(), None); + + registry.note_activity( + Some("session-a".to_string()), + Some("ZCode".to_string()), + Some("0.1.12".to_string()), + ); + registry.note_activity(None, None, None); + + let sessions = registry.live_sessions(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].client.as_deref(), Some("ZCode")); + assert!(registry.anonymous_age_secs().is_some()); + + // Re-activity refreshes the entry instead of duplicating it. + registry.note_activity( + Some("session-a".to_string()), + Some("ZCode".to_string()), + Some("0.1.12".to_string()), + ); + assert_eq!(registry.live_sessions().len(), 1); + } + + #[test] + fn registry_caps_tracked_sessions() { + let registry = McpSessionRegistry::default(); + for i in 0..(MAX_SESSIONS + 10) { + registry.note_activity(Some(format!("session-{i}")), None, None); + } + assert_eq!(registry.live_sessions().len(), MAX_SESSIONS); + } } diff --git a/src/lang/enUS.ts b/src/lang/enUS.ts index 3e2ef07e..a7912a9b 100644 --- a/src/lang/enUS.ts +++ b/src/lang/enUS.ts @@ -601,7 +601,7 @@ export const enUS = { }, }, mcp: { - title: 'MCP Bridge', + title: 'Data Studio Bridge', status: 'Status', running: 'Running on port {port}', stopped: 'Stopped', diff --git a/src/lang/esES.ts b/src/lang/esES.ts index 97ba1ea7..16513025 100644 --- a/src/lang/esES.ts +++ b/src/lang/esES.ts @@ -129,7 +129,7 @@ export const esES = { er_diagram: 'Diagramas ER', transfer: 'Importación / exportación masiva y migración', ssh: 'Túnel SSH', - mcp: 'Puente MCP', + mcp: 'Data Studio Bridge', versionLock: 'Bloqueo de versión', }, upgrade: { @@ -601,21 +601,21 @@ export const esES = { }, }, mcp: { - title: 'Puente MCP', + title: 'Data Studio Bridge', status: 'Estado', running: 'Ejecutándose en el puerto {port}', stopped: 'Detenido', port: 'Puerto', - portDesc: 'Puerto del servidor del puente MCP (déjalo vacío para automático)', + portDesc: 'Puerto del servidor del Data Studio Bridge (déjalo vacío para automático)', restart: 'Reiniciar puente', - restartSuccess: 'Puente MCP reiniciado correctamente', + restartSuccess: 'Data Studio Bridge reiniciado correctamente', restartFailed: 'No se pudo reiniciar', - restartFailedDetail: 'No se pudo reiniciar el puente MCP', - restartTimeout: 'El puente MCP no se inició en 60 segundos', + restartFailedDetail: 'No se pudo reiniciar el Data Studio Bridge', + restartTimeout: 'El Data Studio Bridge no se inició en 60 segundos', shuttingDown: 'Apagando...', starting: 'Iniciando...', autoStart: 'Inicio automático', - autoStartDesc: 'Iniciar el puente MCP automáticamente al abrir la aplicación', + autoStartDesc: 'Iniciar el Data Studio Bridge automáticamente al abrir la aplicación', saveFailed: 'No se pudo guardar la configuración de MCP', }, about: { diff --git a/src/lang/jaJP.ts b/src/lang/jaJP.ts index 80ad6611..62a1acd2 100644 --- a/src/lang/jaJP.ts +++ b/src/lang/jaJP.ts @@ -128,7 +128,7 @@ export const jaJP = { er_diagram: 'ER 図', transfer: '一括インポート / エクスポート & 移行', ssh: 'SSH トンネル', - mcp: 'MCP ブリッジ', + mcp: 'Data Studio Bridge', versionLock: 'バージョンロック', }, upgrade: { @@ -600,21 +600,21 @@ export const jaJP = { }, }, mcp: { - title: 'MCP ブリッジ', + title: 'Data Studio Bridge', status: 'ステータス', running: 'ポート {port} で実行中', stopped: '停止中', port: 'ポート', - portDesc: 'MCP ブリッジサーバーのポート (空欄の場合は自動)', + portDesc: 'Data Studio Bridgeサーバーのポート (空欄の場合は自動)', restart: 'ブリッジを再起動', - restartSuccess: 'MCP ブリッジを正常に再起動しました', + restartSuccess: 'Data Studio Bridgeを正常に再起動しました', restartFailed: '再起動に失敗しました', - restartFailedDetail: 'MCP ブリッジの再起動に失敗しました', - restartTimeout: 'MCP ブリッジが 60 秒以内に起動しませんでした', + restartFailedDetail: 'Data Studio Bridgeの再起動に失敗しました', + restartTimeout: 'Data Studio Bridgeが 60 秒以内に起動しませんでした', shuttingDown: 'シャットダウン中...', starting: '起動中...', autoStart: '自動起動', - autoStartDesc: 'アプリの起動時に MCP ブリッジを自動的に開始します', + autoStartDesc: 'アプリの起動時に Data Studio Bridgeを自動的に開始します', saveFailed: 'MCP 設定の保存に失敗しました', }, about: { diff --git a/src/lang/koKR.ts b/src/lang/koKR.ts index 8b224d9e..4277ece5 100644 --- a/src/lang/koKR.ts +++ b/src/lang/koKR.ts @@ -129,7 +129,7 @@ export const koKR = { er_diagram: 'ER 다이어그램', transfer: '대량 가져오기 / 내보내기 및 마이그레이션', ssh: 'SSH 터널', - mcp: 'MCP 브리지', + mcp: 'Data Studio Bridge', versionLock: '버전 잠금', }, upgrade: { @@ -601,21 +601,21 @@ export const koKR = { }, }, mcp: { - title: 'MCP 브리지', + title: 'Data Studio Bridge', status: '상태', running: '포트 {port}에서 실행 중', stopped: '중지됨', port: '포트', - portDesc: 'MCP 브리지 서버 포트 (비워두면 자동)', + portDesc: 'Data Studio Bridge 서버 포트 (비워두면 자동)', restart: '브리지 재시작', - restartSuccess: 'MCP 브리지가 성공적으로 재시작되었습니다', + restartSuccess: 'Data Studio Bridge가 성공적으로 재시작되었습니다', restartFailed: '재시작에 실패했습니다', - restartFailedDetail: 'MCP 브리지를 재시작하지 못했습니다', - restartTimeout: 'MCP 브리지가 60초 안에 시작하지 못했습니다', + restartFailedDetail: 'Data Studio Bridge를 재시작하지 못했습니다', + restartTimeout: 'Data Studio Bridge가 60초 안에 시작하지 못했습니다', shuttingDown: '종료하는 중...', starting: '시작하는 중...', autoStart: '자동 시작', - autoStartDesc: '앱 실행 시 MCP 브리지를 자동으로 시작합니다', + autoStartDesc: '앱 실행 시 Data Studio Bridge를 자동으로 시작합니다', saveFailed: 'MCP 설정을 저장하지 못했습니다', }, about: { diff --git a/src/lang/ptBR.ts b/src/lang/ptBR.ts index c40689cf..d22553ba 100644 --- a/src/lang/ptBR.ts +++ b/src/lang/ptBR.ts @@ -129,7 +129,7 @@ export const ptBR = { er_diagram: 'Diagramas ER', transfer: 'Importação/exportação em massa e migração', ssh: 'Túnel SSH', - mcp: 'Ponte MCP', + mcp: 'Data Studio Bridge', versionLock: 'Bloqueio de versão', }, upgrade: { @@ -601,21 +601,21 @@ export const ptBR = { }, }, mcp: { - title: 'Ponte MCP', + title: 'Data Studio Bridge', status: 'Status', running: 'Em execução na porta {port}', stopped: 'Parado', port: 'Porta', - portDesc: 'Porta do servidor da ponte MCP (deixe vazio para automática)', + portDesc: 'Porta do servidor da Data Studio Bridge (deixe vazio para automática)', restart: 'Reiniciar ponte', - restartSuccess: 'Ponte MCP reiniciada com sucesso', + restartSuccess: 'Data Studio Bridge reiniciada com sucesso', restartFailed: 'Falha ao reiniciar', - restartFailedDetail: 'Falha ao reiniciar a ponte MCP', - restartTimeout: 'A ponte MCP não iniciou em 60 segundos', + restartFailedDetail: 'Falha ao reiniciar a Data Studio Bridge', + restartTimeout: 'A Data Studio Bridge não iniciou em 60 segundos', shuttingDown: 'Desligando...', starting: 'Iniciando...', autoStart: 'Início automático', - autoStartDesc: 'Inicia a ponte MCP automaticamente ao abrir o aplicativo', + autoStartDesc: 'Inicia a Data Studio Bridge automaticamente ao abrir o aplicativo', saveFailed: 'Falha ao salvar as configurações de MCP', }, about: { diff --git a/src/lang/zhCN.ts b/src/lang/zhCN.ts index 6b8fea6b..2ffd33fe 100644 --- a/src/lang/zhCN.ts +++ b/src/lang/zhCN.ts @@ -601,21 +601,21 @@ export const zhCN = { }, }, mcp: { - title: 'MCP 桥接', + title: 'Data Studio Bridge', status: '状态', running: '运行中(端口 {port})', stopped: '已停止', port: '端口', - portDesc: 'MCP 桥接服务器端口(留空自动选择)', + portDesc: 'Data Studio Bridge 服务器端口(留空自动选择)', restart: '重启桥接', - restartSuccess: 'MCP 桥接重启成功', + restartSuccess: 'Data Studio Bridge 重启成功', restartFailed: '重启失败', - restartFailedDetail: 'MCP 桥接重启失败', - restartTimeout: 'MCP 桥接 60 秒内未能启动', + restartFailedDetail: 'Data Studio Bridge 重启失败', + restartTimeout: 'Data Studio Bridge 60 秒内未能启动', shuttingDown: '正在关闭...', starting: '正在启动...', autoStart: '自动启动', - autoStartDesc: '应用启动时自动启动 MCP 桥接', + autoStartDesc: '应用启动时自动启动 Data Studio Bridge', saveFailed: '保存 MCP 设置失败', }, about: { diff --git a/src/lang/zhTW.ts b/src/lang/zhTW.ts index 8f5499ce..d4103e80 100644 --- a/src/lang/zhTW.ts +++ b/src/lang/zhTW.ts @@ -128,7 +128,7 @@ export const zhTW = { er_diagram: 'ER 圖', transfer: '大量匯入 / 匯出與移轉', ssh: 'SSH 通道', - mcp: 'MCP Bridge', + mcp: 'Data Studio Bridge', versionLock: '版本鎖定', }, upgrade: { @@ -600,21 +600,21 @@ export const zhTW = { }, }, mcp: { - title: 'MCP Bridge', + title: 'Data Studio Bridge', status: '狀態', running: '正在連接埠 {port} 上執行', stopped: '已停止', port: '連接埠', - portDesc: 'MCP Bridge 伺服器使用的連接埠(留空則自動指定)', + portDesc: 'Data Studio Bridge 伺服器使用的連接埠(留空則自動指定)', restart: '重新啟動 Bridge', - restartSuccess: 'MCP Bridge 已成功重新啟動', + restartSuccess: 'Data Studio Bridge 已成功重新啟動', restartFailed: '重新啟動失敗', - restartFailedDetail: '無法重新啟動 MCP Bridge', - restartTimeout: 'MCP Bridge 未能在 60 秒內啟動', + restartFailedDetail: '無法重新啟動 Data Studio Bridge', + restartTimeout: 'Data Studio Bridge 未能在 60 秒內啟動', shuttingDown: '正在關閉...', starting: '正在啟動...', autoStart: '自動啟動', - autoStartDesc: '應用程式啟動時自動啟動 MCP Bridge', + autoStartDesc: '應用程式啟動時自動啟動 Data Studio Bridge', saveFailed: '無法儲存 MCP 設定', }, about: { From b36901524f3b276631999b97ffe66ff52f326b16 Mon Sep 17 00:00:00 2001 From: blankll Date: Fri, 20 Nov 2026 16:10:11 +0800 Subject: [PATCH 2/3] feat(settings+tray): MCP Bridge status surface, unlock shortcut, settings revamp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tray: - status lines carry product names: "MCP Bridge: Running (port N)" / "Stopped" / "Stopped (subscription required)"; server session line removed (single port — session info lives in settings) - new "Unlock MCP Bridge…" action item (gated-stop state only) opens the subscription dialog via mcp-bridge://subscription → App.vue listener - get_mcp_status now reports stopReason + live MCP sessions Settings (MCP tab): - two-card layout: MCP Bridge card (status + Copy/Restart icon buttons with tooltips + port + auto-start, outside the paywall) and SqlKit MCP Server card (sessions + "Connect an AI client" install guide with brand tabs, docs link, gated); DefaultPermissionEditor and all setting rows span full width, aligning text left / controls right - sessionsEmpty copy simplified + link to the product docs page UI polish: - Auto-compact messages uses a Switch - provider rows show monochrome brand icons - PaidGate provider chip: Claude Desktop → Claude Code - McpPoster refreshed: real port (9121), current npx config and tools Locales: keep the original "MCP Bridge" naming across tray, settings and all 7 languages; simplify sessionsEmpty; add docsLink. Verification: cargo test 615 passed; cargo fmt/clippy clean; eslint/vue-tsc clean. --- src-tauri/src/desktop.rs | 158 ++++------ src-tauri/src/mcp_bridge.rs | 24 ++ src/App.vue | 4 + .../DefaultPermissionEditor.vue | 2 +- .../upgrade/FeaturePoster/McpPoster.vue | 27 +- src/components/upgrade/PaidGate.vue | 2 +- src/lang/enUS.ts | 42 ++- src/lang/esES.ts | 44 ++- src/lang/jaJP.ts | 44 ++- src/lang/koKR.ts | 44 ++- src/lang/ptBR.ts | 44 ++- src/lang/zhCN.ts | 42 ++- src/lang/zhTW.ts | 44 ++- src/pages/SettingsPage.vue | 18 +- src/views/setting/ai-settings.vue | 4 +- src/views/setting/bridge-status.vue | 269 ++++++++++++++++++ src/views/setting/code-copy-block.vue | 49 ++++ src/views/setting/mcp-bridge.vue | 207 +++++++++----- src/views/setting/provider-list.vue | 26 +- 19 files changed, 837 insertions(+), 257 deletions(-) create mode 100644 src/views/setting/bridge-status.vue create mode 100644 src/views/setting/code-copy-block.vue diff --git a/src-tauri/src/desktop.rs b/src-tauri/src/desktop.rs index fdee0127..572f5070 100644 --- a/src-tauri/src/desktop.rs +++ b/src-tauri/src/desktop.rs @@ -6,17 +6,16 @@ use tauri::tray::{TrayIcon, TrayIconBuilder}; use tauri::{App, AppHandle, Manager, WindowEvent, Wry}; use tauri_plugin_clipboard_manager::ClipboardExt; -use crate::mcp_bridge::{BridgeStopReason, McpSessionRegistry}; +use crate::mcp_bridge::BridgeStopReason; const MAIN_WINDOW: &str = "main"; const SHOW_WINDOW: &str = "tray-show-window"; +const UNLOCK_BRIDGE: &str = "tray-unlock-bridge"; const COPY_BRIDGE_URL: &str = "tray-copy-bridge-url"; const QUIT: &str = "tray-quit"; const STATUS_REFRESH: Duration = Duration::from_secs(5); -/// Client names rendered on one tray line; the rest collapses into "+N". -const MAX_CLIENTS_DISPLAYED: usize = 3; -/// Localized tray copy. Product nouns ("Data Studio Bridge", backend client +/// Localized tray copy. Product nouns ("MCP Bridge", backend client /// names) stay untranslated; only the status phrasing is localized. struct TrayLabels { show_window: &'static str, @@ -26,27 +25,14 @@ struct TrayLabels { bridge_running: &'static str, bridge_stopped: &'static str, bridge_stopped_gate: &'static str, - /// "{count}" → session count, "{clients}" → client names - server_sessions: &'static str, - /// "{}" → seconds since last anonymous request - server_anonymous: &'static str, - server_none: &'static str, + /// Action item shown under the gated-stop status; "…" = opens a dialog. + unlock: &'static str, } impl TrayLabels { fn bridge_running_line(&self, port: u16) -> String { self.bridge_running.replace("{}", &port.to_string()) } - - fn server_sessions_line(&self, count: usize, clients: &str) -> String { - self.server_sessions - .replace("{count}", &count.to_string()) - .replace("{clients}", clients) - } - - fn server_anonymous_line(&self, secs: u64) -> String { - self.server_anonymous.replace("{}", &secs.to_string()) - } } fn tray_labels(locale: &str) -> TrayLabels { @@ -58,79 +44,65 @@ fn tray_labels(locale: &str) -> TrayLabels { show_window: "顯示視窗", quit: "結束", copy_url: "複製 Bridge 地址", - bridge_running: "運行中(連接埠 {})", - bridge_stopped: "已停止", - bridge_stopped_gate: "已停止(需要訂閱)", - server_sessions: "{count} 個會話 — {clients}", - server_anonymous: "活躍({} 秒前有活動)", - server_none: "無活躍會話", + bridge_running: "MCP Bridge:運行中(連接埠 {})", + bridge_stopped: "MCP Bridge:已停止", + bridge_stopped_gate: "MCP Bridge:已停止(需要訂閱)", + unlock: "解鎖 MCP Bridge…", } } Some("zh") => TrayLabels { show_window: "显示窗口", quit: "退出", copy_url: "复制 Bridge 地址", - bridge_running: "运行中(端口 {})", - bridge_stopped: "已停止", - bridge_stopped_gate: "已停止(需要订阅)", - server_sessions: "{count} 个会话 — {clients}", - server_anonymous: "活跃({} 秒前有活动)", - server_none: "无活跃会话", + bridge_running: "MCP 桥接:运行中(端口 {})", + bridge_stopped: "MCP 桥接:已停止", + bridge_stopped_gate: "MCP 桥接:已停止(需要订阅)", + unlock: "解锁 MCP 桥接…", }, Some("pt") => TrayLabels { show_window: "Mostrar janela", quit: "Sair", copy_url: "Copiar URL do Bridge", - bridge_running: "Em execução (porta {})", - bridge_stopped: "Parado", - bridge_stopped_gate: "Parado (assinatura necessária)", - server_sessions: "{count} sessão(ões) — {clients}", - server_anonymous: "ativo (visto há {}s)", - server_none: "sem sessões ativas", + bridge_running: "Ponte MCP: em execução (porta {})", + bridge_stopped: "Ponte MCP: parado", + bridge_stopped_gate: "Ponte MCP: parado (assinatura necessária)", + unlock: "Desbloquear Ponte MCP…", }, Some("ja") => TrayLabels { show_window: "ウィンドウを表示", quit: "終了", copy_url: "Bridge URL をコピー", - bridge_running: "実行中(ポート {})", - bridge_stopped: "停止中", - bridge_stopped_gate: "停止中(サブスクリプションが必要)", - server_sessions: "{count} セッション — {clients}", - server_anonymous: "アクティブ({} 秒前に活動)", - server_none: "アクティブなセッションなし", + bridge_running: "MCPブリッジ:実行中(ポート {})", + bridge_stopped: "MCPブリッジ:停止中", + bridge_stopped_gate: "MCPブリッジ:停止中(サブスクリプションが必要)", + unlock: "MCPブリッジを解錠…", }, Some("ko") => TrayLabels { show_window: "창 표시", quit: "종료", copy_url: "Bridge URL 복사", - bridge_running: "실행 중 (포트 {})", - bridge_stopped: "중지됨", - bridge_stopped_gate: "중지됨 (구독 필요)", - server_sessions: "{count}개 세션 — {clients}", - server_anonymous: "활성 ({}초 전 활동)", - server_none: "활성 세션 없음", + bridge_running: "MCP 브리지: 실행 중 (포트 {})", + bridge_stopped: "MCP 브리지: 중지됨", + bridge_stopped_gate: "MCP 브리지: 중지됨 (구독 필요)", + unlock: "MCP 브리지 잠금 해제…", }, Some("es") => TrayLabels { show_window: "Mostrar ventana", quit: "Salir", copy_url: "Copiar URL del Bridge", - bridge_running: "En ejecución (puerto {})", - bridge_stopped: "Detenido", - bridge_stopped_gate: "Detenido (se requiere suscripción)", - server_sessions: "{count} sesión(es) — {clients}", - server_anonymous: "activo (visto hace {}s)", - server_none: "sin sesiones activas", + bridge_running: "Puente MCP: en ejecución (puerto {})", + bridge_stopped: "Puente MCP: detenido", + bridge_stopped_gate: "Puente MCP: detenido (se requiere suscripción)", + unlock: "Desbloquear Puente MCP…", }, _ => TrayLabels { show_window: "Show Window", quit: "Quit", copy_url: "Copy Bridge URL", - bridge_running: "Running (port {})", - bridge_stopped: "Stopped", - bridge_stopped_gate: "Stopped (subscription required)", - server_sessions: "{count} session(s) — {clients}", - server_anonymous: "active (last seen {}s ago)", - server_none: "no active sessions", + bridge_running: "MCP Bridge: Running (port {})", + bridge_stopped: "MCP Bridge: Stopped", + bridge_stopped_gate: "MCP Bridge: Stopped (subscription required)", + unlock: "Unlock MCP Bridge…", }, } } @@ -141,7 +113,7 @@ fn tray_labels(locale: &str) -> TrayLabels { struct TrayStatusItems { tray: TrayIcon, bridge_line: MenuItem, - server_line: MenuItem, + unlock_line: MenuItem, copy_url: MenuItem, labels: TrayLabels, app_name: String, @@ -216,14 +188,15 @@ fn create_tray(app: &App) -> Result> let labels = tray_labels(&locale); let app_name = app.package_info().name.clone(); + // Inert status line — its id is never matched; the unlock item below carries the click. let bridge_line = MenuItem::with_id(app, "tray-bridge-status", "", false, None::<&str>)?; - let server_line = MenuItem::with_id(app, "tray-server-status", "", false, None::<&str>)?; + let unlock_line = MenuItem::with_id(app, UNLOCK_BRIDGE, labels.unlock, false, None::<&str>)?; let copy_url = MenuItem::with_id(app, COPY_BRIDGE_URL, labels.copy_url, true, None::<&str>)?; let show = MenuItem::with_id(app, SHOW_WINDOW, labels.show_window, true, None::<&str>)?; let quit = MenuItem::with_id(app, QUIT, labels.quit, true, None::<&str>)?; let menu = MenuBuilder::new(app) .item(&bridge_line) - .item(&server_line) + .item(&unlock_line) .item(©_url) .separator() .item(&show) @@ -239,6 +212,11 @@ fn create_tray(app: &App) -> Result> .show_menu_on_left_click(true) .on_menu_event(|app, event| match event.id().as_ref() { SHOW_WINDOW => show_main_window(app), + UNLOCK_BRIDGE => { + show_main_window(app); + use tauri::Emitter; + let _ = app.emit("mcp-bridge://subscription", ()); + } COPY_BRIDGE_URL => copy_bridge_url(app), QUIT => app.exit(0), _ => {} @@ -248,7 +226,7 @@ fn create_tray(app: &App) -> Result> Ok(TrayStatusItems { tray, bridge_line, - server_line, + unlock_line, copy_url, labels, app_name, @@ -278,59 +256,19 @@ fn refresh_status_lines(app: &AppHandle, items: &TrayStatusItems) { } } }; - - let server_text = app - .try_state::() - .map(|registry| server_line(®istry, &items.labels)) - .unwrap_or_else(|| items.labels.server_none.to_string()); - + // The "Unlock …" action item appears only under the gated-stop status — + // the status line itself stays inert; the action item carries the click. + let gated_stop = running_port.is_none() && bridge_text == items.labels.bridge_stopped_gate; let _ = items.bridge_line.set_text(&bridge_text); - let _ = items.server_line.set_text(&server_text); + let _ = items.unlock_line.set_enabled(gated_stop); let _ = items.copy_url.set_enabled(running_port.is_some()); let tooltip = match running_port { - Some(port) => format!("{} — Data Studio Bridge on :{port}", items.app_name), + Some(port) => format!("{} — MCP Bridge on :{port}", items.app_name), None => items.app_name.clone(), }; let _ = items.tray.set_tooltip(Some(tooltip)); } -fn server_line(registry: &McpSessionRegistry, labels: &TrayLabels) -> String { - let sessions = registry.live_sessions(); - if sessions.is_empty() { - return registry - .anonymous_age_secs() - .map(|secs| labels.server_anonymous_line(secs)) - .unwrap_or_else(|| labels.server_none.to_string()); - } - - let names: Vec = sessions - .iter() - .map(|entry| { - entry - .client - .clone() - .or_else(|| { - entry - .version - .clone() - .map(|v| format!("data-studio-mcp/{v}")) - }) - .unwrap_or_else(|| "data-studio-mcp".to_string()) - }) - .collect(); - let shown = &names[..names.len().min(MAX_CLIENTS_DISPLAYED)]; - let clients = if names.len() > MAX_CLIENTS_DISPLAYED { - format!( - "{} +{}", - shown.join(", "), - names.len() - MAX_CLIENTS_DISPLAYED - ) - } else { - shown.join(", ") - }; - labels.server_sessions_line(names.len(), &clients) -} - fn copy_bridge_url(app: &AppHandle) { let Some(items) = app.try_state::() else { return; diff --git a/src-tauri/src/mcp_bridge.rs b/src-tauri/src/mcp_bridge.rs index b7886b1d..4a4e906b 100644 --- a/src-tauri/src/mcp_bridge.rs +++ b/src-tauri/src/mcp_bridge.rs @@ -819,11 +819,35 @@ pub async fn get_mcp_status(app: AppHandle) -> Result { let config = read_permission_config(&app_data_dir)?; let running_port = get_actual_port(&app_data_dir); + let stop_reason = app.try_state::().and_then(|status| { + (*status.reason.lock().unwrap()).map(|reason| match reason { + BridgeStopReason::SubscriptionRequired => "subscriptionRequired", + }) + }); + let sessions: Vec = app + .try_state::() + .map(|registry| { + registry + .live_sessions() + .iter() + .map(|entry| { + json!({ + "client": entry.client, + "version": entry.version, + "lastSeenSecs": entry.last_seen.elapsed().as_secs(), + }) + }) + .collect() + }) + .unwrap_or_default(); + let status = json!({ "running": running_port.is_some(), "port": running_port, "configuredPort": config.port, "autoStart": config.auto_start, + "stopReason": stop_reason, + "sessions": sessions, "policy": serde_json::to_value(&config.policy).map_err(|e| e.to_string())?, }); diff --git a/src/App.vue b/src/App.vue index 97391a9c..d53806cf 100644 --- a/src/App.vue +++ b/src/App.vue @@ -9,6 +9,7 @@ import DeviceReplaceDialog from '@/components/DeviceReplaceDialog.vue' import AppNotifications from '@/components/ui/notification/AppNotifications.vue' import UpdateNotification from '@/components/UpdateNotification.vue' import UpgradeDialog from '@/components/upgrade/UpgradeDialog.vue' +import { openUpgradeDialog } from '@/components/upgrade/upgradeDialogService' import { useAppUpdater } from '@/composables/useAppUpdater' import { toast } from '@/composables/useNotifications' import { useAccountStore } from '@/store/accountStore' @@ -57,6 +58,9 @@ const sessionLifecycle = createSessionLifecycle({ onMounted(async () => { checkForUpdates(false) + // Tray → "Stopped (subscription required)" opens the upgrade dialog. + listen('mcp-bridge://subscription', () => openUpgradeDialog('mcp_bridge')).catch(() => {}) + await pushUiLocale() await sessionLifecycle.start() }) diff --git a/src/components/ai-permissions/DefaultPermissionEditor.vue b/src/components/ai-permissions/DefaultPermissionEditor.vue index 7d7f18c7..ff83a42a 100644 --- a/src/components/ai-permissions/DefaultPermissionEditor.vue +++ b/src/components/ai-permissions/DefaultPermissionEditor.vue @@ -91,7 +91,7 @@ const selectPreset = (value: string) => { {{ t('aiPermissions.retry') }} -
+
diff --git a/src/components/upgrade/FeaturePoster/McpPoster.vue b/src/components/upgrade/FeaturePoster/McpPoster.vue index 22dc9124..416e5990 100644 --- a/src/components/upgrade/FeaturePoster/McpPoster.vue +++ b/src/components/upgrade/FeaturePoster/McpPoster.vue @@ -3,14 +3,14 @@ import { Lock, Wrench } from 'lucide-vue-next' import { ProgressiveBlur } from '../effects' const tools = [ - 'search', - 'count', - 'indexDoc', - 'getDoc', - 'bulk', - 'catIndices', - 'catHealth', - 'clusterHealth', + 'execute_query', + 'explain_query', + 'describe_table', + 'list_tables', + 'list_databases', + 'list_connections', + 'get_schema', + 'get_slow_queries', ] as const @@ -23,7 +23,7 @@ const tools = [ MCP - {{ $t('pages.settings.mcp.running', { port: 7878 }) }} + {{ $t('pages.settings.mcp.running', { port: 9121 }) }}
@@ -33,7 +33,7 @@ const tools = [
{{ $t('pages.settings.mcp.port') }}
- 7878 + 9121 {{ $t('pages.settings.mcp.restart') }}
@@ -45,7 +45,7 @@ const tools = [
{{ $t('plan.poster.mcp.clients') }}
- Claude Desktop + Claude Code Cursor Any MCP client
@@ -58,8 +58,9 @@ const tools = [
 {
   "mcpServers": {
-    "dockit": {
-      "url": "http://localhost:7878/mcp"
+    "data-studio": {
+      "command": "npx",
+      "args": ["-y", "@geek-fun/data-studio-mcp"]
     }
   }
 }
diff --git a/src/components/upgrade/PaidGate.vue b/src/components/upgrade/PaidGate.vue index 5ce6de8c..ca94fdc8 100644 --- a/src/components/upgrade/PaidGate.vue +++ b/src/components/upgrade/PaidGate.vue @@ -89,7 +89,7 @@ const providerGroups = computed(() => { { labelKey: 'plan.gate.groups.clients', items: [ - { label: 'Claude Desktop', icon: 'i-simple-icons-claude' }, + { label: 'Claude Code', icon: 'i-simple-icons-claude' }, { label: 'Cursor', icon: 'i-simple-icons-cursor' }, { label: 'Windsurf', icon: 'i-simple-icons-windsurf' }, { label: 'Any MCP client', icon: 'i-lucide-plug' }, diff --git a/src/lang/enUS.ts b/src/lang/enUS.ts index a7912a9b..4c222d05 100644 --- a/src/lang/enUS.ts +++ b/src/lang/enUS.ts @@ -601,22 +601,52 @@ export const enUS = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'MCP Bridge', status: 'Status', running: 'Running on port {port}', stopped: 'Stopped', port: 'Port', - portDesc: 'Port for the MCP bridge server (leave empty for auto)', + portDesc: 'Port for the MCP Bridge server (leave empty for auto)', restart: 'Restart Bridge', - restartSuccess: 'MCP bridge restarted successfully', + restartSuccess: 'MCP Bridge restarted successfully', restartFailed: 'Restart failed', - restartFailedDetail: 'Failed to restart the MCP bridge', - restartTimeout: 'MCP bridge failed to start within 60 seconds', + restartFailedDetail: 'Failed to restart the MCP Bridge', + restartTimeout: 'MCP Bridge failed to start within 60 seconds', shuttingDown: 'Shutting down...', starting: 'Starting...', autoStart: 'Auto-start', - autoStartDesc: 'Start the MCP bridge automatically when app launches', + autoStartDesc: 'Start the MCP Bridge automatically when app launches', saveFailed: 'Failed to save MCP settings', + statusLoadFailed: 'Failed to load bridge status', + copyUrl: 'Copy Bridge URL', + portFallback: 'Port {configured} is busy — the bridge is serving on {actual} instead.', + sessions: '{count} session — {clients} | {count} sessions — {clients}', + sessionsEmpty: 'Add Data Studio MCP to your AI tool with the guide below.', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'The MCP tool catalog SqlKit exposes to AI clients.', + serverStopped: 'Not served — the MCP Bridge is stopped.', + serverIdle: 'no active sessions', + stoppedReason: 'The MCP Bridge is stopped because your subscription is inactive. AI clients cannot reach your databases through SqlKit right now.', + stoppedReasonTransient: 'The MCP Bridge restarts automatically once your plan refreshes. If it stays stopped, check your subscription.', + unlockBelow: 'Unlock the MCP Bridge below to bring it back online.', + unlockAction: 'Unlock MCP Bridge', + configTitle: 'Configuration', + install: { + title: 'Connect an AI client', + desc: 'Register the Data Studio MCP server with any MCP-capable AI tool to work with your databases in plain language.', + serverCommand: 'MCP server command', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: 'Other clients', + cursorDesc: 'Create .cursor/mcp.json (project) or ~/.cursor/mcp.json (global):', + genericDesc: 'Register a stdio MCP server — command npx, args ["-y", "@geek-fun/data-studio-mcp"] — in your client\'s MCP settings.', + copy: 'Copy', + copied: 'Copied', + docsLink: 'View full documentation', + + portEnvNote: 'Ports are discovered automatically. To pin one, set SQLKIT_MCP_PORT (and DOCKIT_MCP_PORT for DocKit) in the client environment.', + }, }, about: { title: 'About', diff --git a/src/lang/esES.ts b/src/lang/esES.ts index 16513025..fbd74933 100644 --- a/src/lang/esES.ts +++ b/src/lang/esES.ts @@ -129,7 +129,7 @@ export const esES = { er_diagram: 'Diagramas ER', transfer: 'Importación / exportación masiva y migración', ssh: 'Túnel SSH', - mcp: 'Data Studio Bridge', + mcp: 'Puente MCP', versionLock: 'Bloqueo de versión', }, upgrade: { @@ -601,22 +601,52 @@ export const esES = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'Puente MCP', status: 'Estado', running: 'Ejecutándose en el puerto {port}', stopped: 'Detenido', port: 'Puerto', - portDesc: 'Puerto del servidor del Data Studio Bridge (déjalo vacío para automático)', + portDesc: 'Puerto del servidor del Puente MCP (déjalo vacío para automático)', restart: 'Reiniciar puente', - restartSuccess: 'Data Studio Bridge reiniciado correctamente', + restartSuccess: 'Puente MCP reiniciado correctamente', restartFailed: 'No se pudo reiniciar', - restartFailedDetail: 'No se pudo reiniciar el Data Studio Bridge', - restartTimeout: 'El Data Studio Bridge no se inició en 60 segundos', + restartFailedDetail: 'No se pudo reiniciar el Puente MCP', + restartTimeout: 'El Puente MCP no se inició en 60 segundos', shuttingDown: 'Apagando...', starting: 'Iniciando...', autoStart: 'Inicio automático', - autoStartDesc: 'Iniciar el Data Studio Bridge automáticamente al abrir la aplicación', + autoStartDesc: 'Iniciar el Puente MCP automáticamente al abrir la aplicación', saveFailed: 'No se pudo guardar la configuración de MCP', + statusLoadFailed: 'No se pudo cargar el estado del Bridge', + copyUrl: 'Copiar URL del Bridge', + portFallback: 'El puerto {configured} está ocupado — el Puente MCP está sirviendo en el {actual}.', + sessions: '{count} sesión — {clients} | {count} sesiones — {clients}', + sessionsEmpty: 'Añade Data Studio MCP a tu herramienta de IA con la guía de abajo.', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'El catálogo de herramientas MCP que SqlKit expone a los clientes de IA.', + serverStopped: 'No servido — el Puente MCP está detenido.', + serverIdle: 'sin sesiones activas', + stoppedReason: 'El Puente MCP está detenido porque tu suscripción está inactiva. Los clientes de IA no pueden acceder a tus bases de datos a través de SqlKit en este momento.', + stoppedReasonTransient: 'El Puente MCP se reanuda automáticamente cuando se actualiza el estado de la suscripción. Si sigue detenido, revisa tu suscripción.', + unlockBelow: 'Desbloquea abajo para volver a poner el Puente MCP en marcha.', + unlockAction: 'Desbloquear Puente MCP', + configTitle: 'Configuración', + install: { + title: 'Conectar un cliente de IA', + desc: 'Registra el servidor MCP de Data Studio en cualquier herramienta de IA compatible con MCP para trabajar con tus bases de datos en lenguaje natural.', + serverCommand: 'Comando del servidor MCP', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: 'Otros clientes', + cursorDesc: 'Crea .cursor/mcp.json (proyecto) o ~/.cursor/mcp.json (global):', + genericDesc: 'Registra un servidor MCP stdio — comando npx, argumentos ["-y", "@geek-fun/data-studio-mcp"] — en la configuración MCP del cliente.', + copy: 'Copiar', + copied: 'Copiado', + docsLink: 'Ver documentación completa', + + portEnvNote: 'Los puertos se detectan automáticamente. Para fijar uno, define SQLKIT_MCP_PORT (y DOCKIT_MCP_PORT para DocKit) en el entorno del cliente.', + }, }, about: { title: 'Acerca de', diff --git a/src/lang/jaJP.ts b/src/lang/jaJP.ts index 62a1acd2..10ac907f 100644 --- a/src/lang/jaJP.ts +++ b/src/lang/jaJP.ts @@ -128,7 +128,7 @@ export const jaJP = { er_diagram: 'ER 図', transfer: '一括インポート / エクスポート & 移行', ssh: 'SSH トンネル', - mcp: 'Data Studio Bridge', + mcp: 'MCPブリッジ', versionLock: 'バージョンロック', }, upgrade: { @@ -600,22 +600,52 @@ export const jaJP = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'MCPブリッジ', status: 'ステータス', running: 'ポート {port} で実行中', stopped: '停止中', port: 'ポート', - portDesc: 'Data Studio Bridgeサーバーのポート (空欄の場合は自動)', + portDesc: 'MCPブリッジサーバーのポート (空欄の場合は自動)', restart: 'ブリッジを再起動', - restartSuccess: 'Data Studio Bridgeを正常に再起動しました', + restartSuccess: 'MCPブリッジを正常に再起動しました', restartFailed: '再起動に失敗しました', - restartFailedDetail: 'Data Studio Bridgeの再起動に失敗しました', - restartTimeout: 'Data Studio Bridgeが 60 秒以内に起動しませんでした', + restartFailedDetail: 'MCPブリッジの再起動に失敗しました', + restartTimeout: 'MCPブリッジが 60 秒以内に起動しませんでした', shuttingDown: 'シャットダウン中...', starting: '起動中...', autoStart: '自動起動', - autoStartDesc: 'アプリの起動時に Data Studio Bridgeを自動的に開始します', + autoStartDesc: 'アプリの起動時に MCPブリッジを自動的に開始します', saveFailed: 'MCP 設定の保存に失敗しました', + statusLoadFailed: 'Bridge の状態を読み込めませんでした', + copyUrl: 'Bridge URL をコピー', + portFallback: 'ポート {configured} は使用中のため、MCPブリッジは {actual} で待ち受けています。', + sessions: '{count} セッション — {clients}', + sessionsEmpty: 'Data Studio MCP を AI ツールに追加してください。以下のガイドを参照。', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'SqlKit が AI クライアントに公開する MCP ツールカタログ。', + serverStopped: '提供されていません——MCPブリッジ が停止しています。', + serverIdle: 'アクティブなセッションなし', + stoppedReason: 'サブスクリプションが無効なため、MCPブリッジ は停止しています。現在 AI クライアントから SqlKit のデータベースにアクセスできません。', + stoppedReasonTransient: 'サブスクリプションの状態が更新されると MCPブリッジは自動的に再開します。再開しない場合はサブスクリプションを確認してください。', + unlockBelow: '下で解錠すると、MCPブリッジは自動的に再開します。', + unlockAction: 'MCPブリッジ を解錠', + configTitle: '設定', + install: { + title: 'AI クライアントを接続', + desc: 'MCP 対応の AI ツールに Data Studio MCP サーバーを登録すれば、自然言語でデータベースを操作できます。', + serverCommand: 'MCP サーバーコマンド', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: 'その他のクライアント', + cursorDesc: '.cursor/mcp.json(プロジェクト)または ~/.cursor/mcp.json(グローバル)を作成:', + genericDesc: 'クライアントの MCP 設定に stdio サーバーを登録:コマンド npx、引数 ["-y", "@geek-fun/data-studio-mcp"]。', + copy: 'コピー', + copied: 'コピーしました', + docsLink: 'ドキュメントを見る', + + portEnvNote: 'ポートは自動検出されます。固定する場合は、クライアントの環境変数に SQLKIT_MCP_PORT(DocKit は DOCKIT_MCP_PORT)を設定してください。', + }, }, about: { title: '情報', diff --git a/src/lang/koKR.ts b/src/lang/koKR.ts index 4277ece5..79e98089 100644 --- a/src/lang/koKR.ts +++ b/src/lang/koKR.ts @@ -129,7 +129,7 @@ export const koKR = { er_diagram: 'ER 다이어그램', transfer: '대량 가져오기 / 내보내기 및 마이그레이션', ssh: 'SSH 터널', - mcp: 'Data Studio Bridge', + mcp: 'MCP 브리지', versionLock: '버전 잠금', }, upgrade: { @@ -601,22 +601,52 @@ export const koKR = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'MCP 브리지', status: '상태', running: '포트 {port}에서 실행 중', stopped: '중지됨', port: '포트', - portDesc: 'Data Studio Bridge 서버 포트 (비워두면 자동)', + portDesc: 'MCP 브리지 서버 포트 (비워두면 자동)', restart: '브리지 재시작', - restartSuccess: 'Data Studio Bridge가 성공적으로 재시작되었습니다', + restartSuccess: 'MCP 브리지가 성공적으로 재시작되었습니다', restartFailed: '재시작에 실패했습니다', - restartFailedDetail: 'Data Studio Bridge를 재시작하지 못했습니다', - restartTimeout: 'Data Studio Bridge가 60초 안에 시작하지 못했습니다', + restartFailedDetail: 'MCP 브리지를 재시작하지 못했습니다', + restartTimeout: 'MCP 브리지가 60초 안에 시작하지 못했습니다', shuttingDown: '종료하는 중...', starting: '시작하는 중...', autoStart: '자동 시작', - autoStartDesc: '앱 실행 시 Data Studio Bridge를 자동으로 시작합니다', + autoStartDesc: '앱 실행 시 MCP 브리지를 자동으로 시작합니다', saveFailed: 'MCP 설정을 저장하지 못했습니다', + statusLoadFailed: 'Bridge 상태를 불러오지 못했습니다', + copyUrl: 'Bridge URL 복사', + portFallback: '포트 {configured}가 사용 중이어서 MCP 브리지가 {actual}에서 대신 실행 중입니다.', + sessions: '{count}개 세션 — {clients}', + sessionsEmpty: 'Data Studio MCP를 AI 도구에 추가세요. 아래 가이드를 참조하세요.', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'SqlKit이 AI 클라이언트에 노출하는 MCP 도구 카탈로그.', + serverStopped: '제공되지 않음 — MCP 브리지가 중지되었습니다.', + serverIdle: '활성 세션 없음', + stoppedReason: '구독이 비활성화되어 MCP 브리지가 중지되었습니다. 현재 AI 클라이언트는 SqlKit을 통해 데이터베이스에 접근할 수 없습니다.', + stoppedReasonTransient: '구독 상태가 갱신되면 MCP 브리지가 자동으로 재시작합니다. 재시작되지 않으면 구독 상태를 확인하세요.', + unlockBelow: '아래에서 잠금 해제하면 MCP 브리지가 자동으로 재시작됩니다.', + unlockAction: 'MCP 브리지 잠금 해제', + configTitle: '설정', + install: { + title: 'AI 클라이언트 연결', + desc: 'MCP를 지원하는 AI 도구에 Data Studio MCP 서버를 등록하면 자연어로 데이터베이스를 다룰 수 있습니다.', + serverCommand: 'MCP 서버 명령', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: '기타 클라이언트', + cursorDesc: '.cursor/mcp.json(프로젝트) 또는 ~/.cursor/mcp.json(전역) 생성:', + genericDesc: '클라이언트의 MCP 설정에 stdio 서버를 등록하세요: 명령 npx, 인수 ["-y", "@geek-fun/data-studio-mcp"].', + copy: '복사', + copied: '복사됨', + docsLink: '전체 문서 보기', + + portEnvNote: '포트는 자동으로 검색됩니다. 고정하려면 클라이언트 환경 변수에 SQLKIT_MCP_PORT(DocKit은 DOCKIT_MCP_PORT)를 설정하세요.', + }, }, about: { title: '정보', diff --git a/src/lang/ptBR.ts b/src/lang/ptBR.ts index d22553ba..7a0d60c2 100644 --- a/src/lang/ptBR.ts +++ b/src/lang/ptBR.ts @@ -129,7 +129,7 @@ export const ptBR = { er_diagram: 'Diagramas ER', transfer: 'Importação/exportação em massa e migração', ssh: 'Túnel SSH', - mcp: 'Data Studio Bridge', + mcp: 'Ponte MCP', versionLock: 'Bloqueio de versão', }, upgrade: { @@ -601,22 +601,52 @@ export const ptBR = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'Ponte MCP', status: 'Status', running: 'Em execução na porta {port}', stopped: 'Parado', port: 'Porta', - portDesc: 'Porta do servidor da Data Studio Bridge (deixe vazio para automática)', + portDesc: 'Porta do servidor da Ponte MCP (deixe vazio para automática)', restart: 'Reiniciar ponte', - restartSuccess: 'Data Studio Bridge reiniciada com sucesso', + restartSuccess: 'Ponte MCP reiniciada com sucesso', restartFailed: 'Falha ao reiniciar', - restartFailedDetail: 'Falha ao reiniciar a Data Studio Bridge', - restartTimeout: 'A Data Studio Bridge não iniciou em 60 segundos', + restartFailedDetail: 'Falha ao reiniciar a Ponte MCP', + restartTimeout: 'A Ponte MCP não iniciou em 60 segundos', shuttingDown: 'Desligando...', starting: 'Iniciando...', autoStart: 'Início automático', - autoStartDesc: 'Inicia a Data Studio Bridge automaticamente ao abrir o aplicativo', + autoStartDesc: 'Inicia a Ponte MCP automaticamente ao abrir o aplicativo', saveFailed: 'Falha ao salvar as configurações de MCP', + statusLoadFailed: 'Falha ao carregar o status do Bridge', + copyUrl: 'Copiar URL do Bridge', + portFallback: 'A porta {configured} está em uso — a Ponte MCP está servindo na {actual}.', + sessions: '{count} sessão — {clients} | {count} sessões — {clients}', + sessionsEmpty: 'Adicione o Data Studio MCP à sua ferramenta de IA com o guia abaixo.', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'O catálogo de ferramentas MCP que o SqlKit expõe aos clientes de IA.', + serverStopped: 'Não servido — a Ponte MCP está parada.', + serverIdle: 'sem sessões ativas', + stoppedReason: 'A Ponte MCP está parada porque sua assinatura está inativa. Os clientes de IA não conseguem acessar seus bancos de dados pelo SqlKit neste momento.', + stoppedReasonTransient: 'A Ponte MCP reinicia automaticamente quando o estado da assinatura é atualizado. Se permanecer parado, verifique sua assinatura.', + unlockBelow: 'Desbloqueie abaixo para colocar a Ponte MCP de volta no ar.', + unlockAction: 'Desbloquear Ponte MCP', + configTitle: 'Configuração', + install: { + title: 'Conectar um cliente de IA', + desc: 'Registre o servidor MCP do Data Studio em qualquer ferramenta de IA compatível com MCP para trabalhar com seus bancos de dados em linguagem natural.', + serverCommand: 'Comando do servidor MCP', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: 'Outros clientes', + cursorDesc: 'Crie .cursor/mcp.json (projeto) ou ~/.cursor/mcp.json (global):', + genericDesc: 'Registre um servidor MCP stdio — comando npx, argumentos ["-y", "@geek-fun/data-studio-mcp"] — nas configurações de MCP do cliente.', + copy: 'Copiar', + copied: 'Copiado', + docsLink: 'Ver documentação completa', + + portEnvNote: 'As portas são descobertas automaticamente. Para fixar uma, defina SQLKIT_MCP_PORT (e DOCKIT_MCP_PORT para o DocKit) no ambiente do cliente.', + }, }, about: { title: 'Sobre', diff --git a/src/lang/zhCN.ts b/src/lang/zhCN.ts index 2ffd33fe..471c9aa9 100644 --- a/src/lang/zhCN.ts +++ b/src/lang/zhCN.ts @@ -601,22 +601,52 @@ export const zhCN = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'MCP 桥接', status: '状态', running: '运行中(端口 {port})', stopped: '已停止', port: '端口', - portDesc: 'Data Studio Bridge 服务器端口(留空自动选择)', + portDesc: 'MCP 桥接服务器端口(留空自动选择)', restart: '重启桥接', - restartSuccess: 'Data Studio Bridge 重启成功', + restartSuccess: 'MCP 桥接重启成功', restartFailed: '重启失败', - restartFailedDetail: 'Data Studio Bridge 重启失败', - restartTimeout: 'Data Studio Bridge 60 秒内未能启动', + restartFailedDetail: 'MCP 桥接重启失败', + restartTimeout: 'MCP 桥接 60 秒内未能启动', shuttingDown: '正在关闭...', starting: '正在启动...', autoStart: '自动启动', - autoStartDesc: '应用启动时自动启动 Data Studio Bridge', + autoStartDesc: '应用启动时自动启动 MCP 桥接', saveFailed: '保存 MCP 设置失败', + statusLoadFailed: 'MCP 桥接状态加载失败', + copyUrl: '复制 MCP 桥接地址', + portFallback: '端口 {configured} 被占用,MCP 桥接已改用 {actual}。', + sessions: '{count} 个会话 — {clients}', + sessionsEmpty: '把 Data Studio MCP 添加到你的 AI 工具(见下方指引)。', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'SqlKit 暴露给 AI 客户端的 MCP 工具目录。', + serverStopped: '未提供服务——MCP 桥接已停止。', + serverIdle: '无活跃会话', + stoppedReason: '订阅未激活,MCP 桥接已停止——AI 客户端暂时无法通过 SqlKit 访问数据库。', + stoppedReasonTransient: '订阅状态刷新后 MCP 桥接会自动恢复;若仍未恢复,请检查订阅状态。', + unlockBelow: '在下方解锁后,MCP 桥接会自动恢复运行。', + unlockAction: '解锁 MCP 桥接', + configTitle: '配置', + install: { + title: '连接 AI 客户端', + desc: '把 Data Studio MCP 注册到任何支持 MCP 的 AI 工具,即可用自然语言查询和操作数据库。', + serverCommand: 'MCP 服务器命令', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: '其他客户端', + cursorDesc: '创建 .cursor/mcp.json(项目)或 ~/.cursor/mcp.json(全局):', + genericDesc: '在客户端的 MCP 设置里注册 stdio server:命令 npx,参数 ["-y", "@geek-fun/data-studio-mcp"]。', + copy: '复制', + copied: '已复制', + docsLink: '查看完整文档', + + portEnvNote: '端口默认自动发现;如需固定,在客户端环境变量中设置 SQLKIT_MCP_PORT(DocKit 对应 DOCKIT_MCP_PORT)。', + }, }, about: { title: '关于', diff --git a/src/lang/zhTW.ts b/src/lang/zhTW.ts index d4103e80..1f5dc224 100644 --- a/src/lang/zhTW.ts +++ b/src/lang/zhTW.ts @@ -128,7 +128,7 @@ export const zhTW = { er_diagram: 'ER 圖', transfer: '大量匯入 / 匯出與移轉', ssh: 'SSH 通道', - mcp: 'Data Studio Bridge', + mcp: 'MCP Bridge', versionLock: '版本鎖定', }, upgrade: { @@ -600,22 +600,52 @@ export const zhTW = { }, }, mcp: { - title: 'Data Studio Bridge', + title: 'MCP Bridge', status: '狀態', running: '正在連接埠 {port} 上執行', stopped: '已停止', port: '連接埠', - portDesc: 'Data Studio Bridge 伺服器使用的連接埠(留空則自動指定)', + portDesc: 'MCP Bridge 伺服器使用的連接埠(留空則自動指定)', restart: '重新啟動 Bridge', - restartSuccess: 'Data Studio Bridge 已成功重新啟動', + restartSuccess: 'MCP Bridge 已成功重新啟動', restartFailed: '重新啟動失敗', - restartFailedDetail: '無法重新啟動 Data Studio Bridge', - restartTimeout: 'Data Studio Bridge 未能在 60 秒內啟動', + restartFailedDetail: '無法重新啟動 MCP Bridge', + restartTimeout: 'MCP Bridge 未能在 60 秒內啟動', shuttingDown: '正在關閉...', starting: '正在啟動...', autoStart: '自動啟動', - autoStartDesc: '應用程式啟動時自動啟動 Data Studio Bridge', + autoStartDesc: '應用程式啟動時自動啟動 MCP Bridge', saveFailed: '無法儲存 MCP 設定', + statusLoadFailed: '無法載入 Bridge 狀態', + copyUrl: '複製 Bridge 地址', + portFallback: '連接埠 {configured} 被佔用,Bridge 已改用 {actual}。', + sessions: '{count} 個會話 — {clients}', + sessionsEmpty: '將 Data Studio MCP 加入你的 AI 工具(見下方指引)。', + serverTitle: 'SqlKit MCP Server', + serverDesc: 'SqlKit 暴露給 AI 用戶端的 MCP 工具目錄。', + serverStopped: '未提供服務——MCP Bridge 已停止。', + serverIdle: '無活躍會話', + stoppedReason: '訂閱未啟用,MCP Bridge 已停止——AI 用戶端暫時無法透過 SqlKit 存取資料庫。', + stoppedReasonTransient: '訂閱狀態重新整理後 Bridge 會自動恢復;若仍未恢復,請檢查訂閱狀態。', + unlockBelow: '在下方解鎖後,Bridge 會自動恢復執行。', + unlockAction: '解鎖 MCP Bridge', + configTitle: '設定', + install: { + title: '連接 AI 用戶端', + desc: '將 Data Studio MCP 註冊到任何支援 MCP 的 AI 工具,即可用自然語言查詢與操作資料庫。', + serverCommand: 'MCP 伺服器命令', + tabClaude: 'Claude Code', + tabCodex: 'Codex', + tabCursor: 'Cursor', + tabGeneric: '其他用戶端', + cursorDesc: '建立 .cursor/mcp.json(專案)或 ~/.cursor/mcp.json(全域):', + genericDesc: '在用戶端的 MCP 設定中註冊 stdio server:命令 npx,參數 ["-y", "@geek-fun/data-studio-mcp"]。', + copy: '複製', + copied: '已複製', + docsLink: '查看完整文件', + + portEnvNote: '連接埠預設自動探索;如需固定,請在用戶端環境變數中設定 SQLKIT_MCP_PORT(DocKit 對應 DOCKIT_MCP_PORT)。', + }, }, about: { title: '關於', diff --git a/src/pages/SettingsPage.vue b/src/pages/SettingsPage.vue index 528acebb..965e7124 100644 --- a/src/pages/SettingsPage.vue +++ b/src/pages/SettingsPage.vue @@ -13,6 +13,7 @@ import { PaidGate, ProBadge } from '@/components/upgrade' import { LanguageType, ThemeType, useAppStore } from '@/store/appStore' import { useEntitlementStore } from '@/store/entitlementStore' import AiSettings from '@/views/setting/ai-settings.vue' +import BridgeStatus from '@/views/setting/bridge-status.vue' import JreDriverSection from '@/views/setting/jre-driver-section.vue' import McpBridge from '@/views/setting/mcp-bridge.vue' import PlanSection from '@/views/setting/plan-section.vue' @@ -314,7 +315,7 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave -
+

@@ -337,7 +338,7 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave

-
+

@@ -360,7 +361,7 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave

-
+

@@ -383,7 +384,7 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave

-
+

@@ -483,7 +484,7 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave -

+

@@ -506,7 +507,7 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave

-
+

@@ -561,7 +562,10 @@ const toggleAutoSave = () => appStore.setAutoSave(!appStore.queryConfig.autoSave - + + + diff --git a/src/views/setting/ai-settings.vue b/src/views/setting/ai-settings.vue index 641ab8d5..6685a54f 100644 --- a/src/views/setting/ai-settings.vue +++ b/src/views/setting/ai-settings.vue @@ -8,8 +8,8 @@ import { UPGRADE_URL } from '@/common' import { SettingsFeedback } from '@/components/settings' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' -import { Checkbox } from '@/components/ui/checkbox' import { Input } from '@/components/ui/input' +import { Switch } from '@/components/ui/switch' import { ProBadge } from '@/components/upgrade' import { useAppStore } from '@/store/appStore' import { useEntitlementStore } from '@/store/entitlementStore' @@ -208,7 +208,7 @@ function handleCloseDialog() { {{ t('pages.settings.ai.chat.autoCompactDescription') }}

- +import { invoke } from '@tauri-apps/api/core' +import { computed, onBeforeUnmount, onMounted, ref } from 'vue' +import { useI18n } from 'vue-i18n' +import { Button } from '@/components/ui/button' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Switch } from '@/components/ui/switch' +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' +import { openUpgradeDialog } from '@/components/upgrade/upgradeDialogService' +import { useEntitlementStore } from '../../store' + +type BridgeSession = { + client: string | null + version: string | null + lastSeenSecs: number +} + +type BridgeStatus = { + running: boolean + port: number | null + configuredPort: number | null + autoStart: boolean + stopReason: string | null + sessions: BridgeSession[] +} + +const { t } = useI18n() +const entitlementStore = useEntitlementStore() + +const status = ref(null) +const loading = ref(true) +const saving = ref(false) +const loaded = ref(false) +const copied = ref(false) +const port = ref() +const autoStart = ref(true) +const saveError = ref('') +const feedback = ref('') + +const statusText = computed(() => { + if (!status.value) + return loading.value ? t('aiPermissions.loading') : t('aiPermissions.unavailable') + return status.value.running + ? t('pages.settings.mcp.running', { port: status.value.port }) + : t('pages.settings.mcp.stopped') +}) + +const portFallback = computed(() => + status.value?.running + && Boolean(status.value.configuredPort) + && status.value.port !== status.value.configuredPort) + +let inFlight = false +const load = async () => { + if (inFlight) + return + inFlight = true + try { + const data = JSON.parse(await invoke('get_mcp_status')) as BridgeStatus & { configuredPort: number | null } + status.value = data + // Only sync the editable fields when the user is not mid-edit. + if (!saving.value) { + port.value = data.configuredPort ?? undefined + autoStart.value = data.autoStart + loaded.value = true + } + } + catch { + // Keep the last known good status; a transient failure is refreshed on the next tick. + } + finally { + inFlight = false + loading.value = false + } +} + +const saveConfig = async (restart = false, start = autoStart.value) => { + if (saving.value || !loaded.value) + return + saving.value = true + saveError.value = '' + feedback.value = '' + const previous = autoStart.value + try { + await invoke('save_mcp_config', { port: port.value ?? null, autoStart: start, restart }) + autoStart.value = start + feedback.value = t(restart ? 'pages.settings.mcp.restartSuccess' : 'pages.settings.feedback.saved') + await load() + } + catch (e) { + autoStart.value = previous + saveError.value = String(e) + } + finally { + saving.value = false + } +} + +const copyUrl = async () => { + if (!status.value?.port) + return + const url = `http://127.0.0.1:${status.value.port}` + try { + await navigator.clipboard.writeText(url) + } + catch { + const ta = document.createElement('textarea') + ta.value = url + document.body.appendChild(ta) + ta.select() + document.execCommand('copy') + document.body.removeChild(ta) + } + copied.value = true + setTimeout(() => (copied.value = false), 2000) +} + +let poll: ReturnType | undefined +onMounted(() => { + load() + poll = setInterval(load, 5000) +}) +onBeforeUnmount(() => clearInterval(poll)) + + + diff --git a/src/views/setting/code-copy-block.vue b/src/views/setting/code-copy-block.vue new file mode 100644 index 00000000..eb7ce5a0 --- /dev/null +++ b/src/views/setting/code-copy-block.vue @@ -0,0 +1,49 @@ + + + diff --git a/src/views/setting/mcp-bridge.vue b/src/views/setting/mcp-bridge.vue index 5f25a21b..d6e859bd 100644 --- a/src/views/setting/mcp-bridge.vue +++ b/src/views/setting/mcp-bridge.vue @@ -1,56 +1,75 @@