xiaozhi-client 2.2.0 → 2.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/dist/backend/WebServer.js +10 -32
  3. package/dist/backend/WebServer.js.map +1 -1
  4. package/dist/backend/WebServerLauncher.js +10 -32
  5. package/dist/backend/WebServerLauncher.js.map +1 -1
  6. package/dist/backend/package.json +52 -8
  7. package/dist/frontend/assets/form-utils-n2_wJnKb.js +41 -0
  8. package/dist/frontend/assets/form-utils-n2_wJnKb.js.map +1 -0
  9. package/dist/frontend/assets/index-C3xvW3AQ.js +81 -0
  10. package/dist/frontend/assets/index-C3xvW3AQ.js.map +1 -0
  11. package/dist/frontend/assets/index-CLIN00a1.css +1 -0
  12. package/dist/frontend/assets/radix-ui-B9D1KdKb.js +2 -0
  13. package/dist/frontend/assets/radix-ui-B9D1KdKb.js.map +1 -0
  14. package/dist/frontend/assets/react-vendor-CmWLnLSk.js +67 -0
  15. package/dist/frontend/assets/react-vendor-CmWLnLSk.js.map +1 -0
  16. package/dist/frontend/assets/rolldown-runtime-Dw2cE7zH.js +1 -0
  17. package/dist/frontend/assets/utils-UasCLNM3.js +2 -0
  18. package/dist/frontend/assets/utils-UasCLNM3.js.map +1 -0
  19. package/dist/frontend/index.html +7 -6
  20. package/package.json +25 -11
  21. package/dist/frontend/assets/form-utils-Bskf0D3l.js +0 -41
  22. package/dist/frontend/assets/form-utils-Bskf0D3l.js.map +0 -1
  23. package/dist/frontend/assets/index-BAV6nu4X.js +0 -81
  24. package/dist/frontend/assets/index-BAV6nu4X.js.map +0 -1
  25. package/dist/frontend/assets/index-HDlbxheg.css +0 -1
  26. package/dist/frontend/assets/radix-ui-BQCqNqg0.js +0 -2
  27. package/dist/frontend/assets/radix-ui-BQCqNqg0.js.map +0 -1
  28. package/dist/frontend/assets/react-vendor-BPQojLhf.js +0 -67
  29. package/dist/frontend/assets/react-vendor-BPQojLhf.js.map +0 -1
  30. package/dist/frontend/assets/utils-BWIWSmq9.js +0 -2
  31. package/dist/frontend/assets/utils-BWIWSmq9.js.map +0 -1
@@ -1,81 +0,0 @@
1
- import{c as As,d as Ds,r as l,t as O,j as e,S as fn,O as hn,P as $a,C as pn,a as xn,D as gn,A as vn,b as jn,R as Pa,e as Oa,f as bn,g as La,h as Sn,i as wn,X as Nn,k as yn,l as Cn,m as Aa,n as Da,u as pt,o as Ze,L as fe,W as ar,p as or,q as xt,s as En,B as Ma,v as Qe,w as Rn,x as qa,F as Fa,y as Fe,E as Ee,G as Re,H as Tn,I as za,J as gt,K as kn,M as Ms,N as In,Q as Ua,U as $n,V as Va,Y as Pn,Z as On,_ as _a,$ as vt,a0 as Wa,a1 as Ln,a2 as Ba,a3 as Ga,a4 as Ha,a5 as An,a6 as Dn,a7 as Mn,a8 as Ja,a9 as Xa,aa as Ka,ab as Ya,ac as Za,ad as qn,ae as Qa,af as Fn,ag as Ke,ah as eo,ai as qs,aj as ir,ak as Fs,al as Is,am as cr,an as zn,ao as Un,ap as to,aq as so,ar as ro,as as Vn,at as no,au as ao,av as oo,aw as io,ax as zs,ay as _n,az as co,aA as lo,aB as Wn,aC as uo,aD as mo,aE as lr,aF as fo,aG as ho,aH as po,aI as xo,aJ as qt,aK as dr,aL as go,aM as vo,aN as jo}from"./react-vendor-BPQojLhf.js";import{t as bo,c as Bn,a as Ae,T as So}from"./utils-BWIWSmq9.js";import{z as _,s as Oe,o as et,l as Us,d as wo,b as at,r as No,c as ur,e as yo,_ as Co,n as Eo}from"./form-utils-Bskf0D3l.js";import"./radix-ui-BQCqNqg0.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function s(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=s(a);fetch(a.href,o)}})();class Ro{baseUrl;constructor(t){if(t)this.baseUrl=t;else{const s=window.location.protocol,n=window.location.hostname,a=window.location.port;this.baseUrl=`${s}//${n}${a?`:${a}`:""}`}}async request(t,s={}){const n=`${this.baseUrl}${t}`,a={headers:{"Content-Type":"application/json",...s.headers}},o=await fetch(n,{...a,...s});if(!o.ok){let i=`HTTP ${o.status}: ${o.statusText}`;try{i=(await o.json()).error?.message||i}catch{}throw new Error(i)}return o.json()}async getConfig(){const t=await this.request("/api/config");if(!t.success||!t.data)throw new Error("获取配置失败");return t.data}async updateConfig(t){const s=await this.request("/api/config",{method:"PUT",body:JSON.stringify(t)});if(!s.success)throw new Error(s.error?.message||"配置更新失败")}async getMcpEndpoint(){const t=await this.request("/api/config/mcp-endpoint");if(!t.success||!t.data)throw new Error("获取 MCP 端点失败");return t.data.endpoint}async getMcpEndpoints(){const t=await this.request("/api/config/mcp-endpoints");if(!t.success||!t.data)throw new Error("获取 MCP 端点列表失败");return t.data.endpoints}async getMcpServers(){const t=await this.request("/api/config/mcp-servers");if(!t.success||!t.data)throw new Error("获取 MCP 服务配置失败");return t.data.servers}async getConnectionConfig(){const t=await this.request("/api/config/connection");if(!t.success||!t.data)throw new Error("获取连接配置失败");return t.data.connection}async reloadConfig(){const t=await this.request("/api/config/reload",{method:"POST"});if(!t.success||!t.data)throw new Error("重新加载配置失败");return t.data}async getConfigPath(){const t=await this.request("/api/config/path");if(!t.success||!t.data)throw new Error("获取配置文件路径失败");return t.data.path}async checkConfigExists(){const t=await this.request("/api/config/exists");if(!t.success||t.data?.exists===void 0)throw new Error("检查配置是否存在失败");return t.data.exists}async getPromptFiles(){const t=await this.request("/api/config/prompts");if(!t.success||!t.data)throw new Error("获取提示词文件列表失败");return t.data.prompts}async getPromptFileContent(t){const s=await this.request(`/api/config/prompts/content?path=${encodeURIComponent(t)}`);if(!s.success||!s.data)throw new Error(s.error?.message||"获取提示词文件内容失败");return s.data}async updatePromptFileContent(t,s){const n=await this.request("/api/config/prompts/content",{method:"PUT",body:JSON.stringify({path:t,content:s})});if(!n.success||!n.data)throw new Error(n.error?.message||"更新提示词文件内容失败");return n.data}async createPromptFile(t,s){const n=await this.request("/api/config/prompts/content",{method:"POST",body:JSON.stringify({fileName:t,content:s})});if(!n.success||!n.data)throw new Error(n.error?.message||"创建提示词文件失败");return n.data}async deletePromptFile(t){const s=await this.request(`/api/config/prompts/content?path=${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success)throw new Error(s.error?.message||"删除提示词文件失败")}async getStatus(){const t=await this.request("/api/status");if(!t.success||!t.data)throw new Error("获取状态失败");return t.data}async getClientStatus(){const t=await this.request("/api/status/client");if(!t.success||!t.data)throw new Error("获取客户端状态失败");return t.data}async getRestartStatus(){const t=await this.request("/api/status/restart");if(!t.success)throw new Error("获取重启状态失败");return t.data||null}async checkClientConnected(){const t=await this.request("/api/status/connected");if(!t.success||t.data?.connected===void 0)throw new Error("检查客户端连接失败");return t.data.connected}async getLastHeartbeat(){const t=await this.request("/api/status/heartbeat");if(!t.success)throw new Error("获取最后心跳时间失败");return t.data?.lastHeartbeat||null}async getActiveMCPServers(){const t=await this.request("/api/status/mcp-servers");if(!t.success||!t.data)throw new Error("获取活跃 MCP 服务器失败");return t.data.servers}async updateClientStatus(t){const s=await this.request("/api/status/client",{method:"PUT",body:JSON.stringify(t)});if(!s.success)throw new Error(s.error?.message||"更新客户端状态失败")}async setActiveMCPServers(t){const s=await this.request("/api/status/mcp-servers",{method:"PUT",body:JSON.stringify({servers:t})});if(!s.success)throw new Error(s.error?.message||"设置活跃 MCP 服务器失败")}async resetStatus(){const t=await this.request("/api/status/reset",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"重置状态失败")}async addCustomTool(t,s,n,a){if(typeof t=="object"&&"type"in t&&"data"in t){const d=await this.request("/api/tools/custom",{method:"POST",body:JSON.stringify(t)});if(!d.success||!d.data)throw new Error(d.error?.message||"添加自定义工具失败");return d.data.tool}const o=t,i=await this.request("/api/tools/custom",{method:"POST",body:JSON.stringify({workflow:o,customName:s,customDescription:n,parameterConfig:a})});if(!i.success||!i.data)throw new Error(i.error?.message||"添加自定义工具失败");return i.data.tool}async updateCustomTool(t,s){const n=await this.request(`/api/tools/custom/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(s)});if(!n.success||!n.data)throw new Error(n.error?.message||"更新自定义工具失败");return n.data.tool}async removeCustomTool(t){const s=await this.request(`/api/tools/custom/${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success)throw new Error(s.error?.message||"删除自定义工具失败")}async getCustomTools(){const t=await this.request("/api/tools/custom");if(!t.success||!t.data)throw new Error("获取自定义工具列表失败");return t.data.tools}async getToolsList(t="all",s){const n=new URLSearchParams;t!=="all"&&n.append("status",t),s&&n.append("sortBy",s.field);const a=`/api/tools/list${n.toString()?`?${n.toString()}`:""}`,o=await this.request(a);if(!o.success||!o.data)throw new Error("获取工具列表失败");return o.data.list}async restartService(){const t=await this.request("/api/services/restart",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"重启服务失败")}async stopService(){const t=await this.request("/api/services/stop",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"停止服务失败")}async startService(){const t=await this.request("/api/services/start",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"启动服务失败")}async getServiceStatus(){const t=await this.request("/api/services/status");if(!t.success||!t.data)throw new Error("获取服务状态失败");return t.data}async getServiceHealth(){const t=await this.request("/api/services/health");if(!t.success||!t.data)throw new Error("获取服务健康状态失败");return t.data}async getTTSVoices(){const t=await this.request("/api/tts/voices");if(!t.success||!t.data)throw new Error("获取音色列表失败");return t.data}async getVersion(){const t=await this.request("/api/version");if(!t.success||!t.data)throw new Error("获取版本信息失败");return t.data}async getVersionSimple(){const t=await this.request("/api/version/simple");if(!t.success||!t.data)throw new Error("获取版本号失败");return t.data}async getAvailableVersions(t="stable"){const s=new URLSearchParams;t!=="stable"&&s.append("type",t);const n=`/api/version/available${s.toString()?`?${s.toString()}`:""}`,a=await this.request(n);if(!a.success||!a.data)throw new Error("获取可用版本列表失败");return a.data}async getLatestVersion(){const t=await this.request("/api/version/latest");if(!t.success||!t.data)throw new Error("检查最新版本失败");return t.data}async clearVersionCache(){const t=await this.request("/api/version/cache/clear",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"清除版本缓存失败")}async updateVersion(t){const s=await this.request("/api/update",{method:"POST",body:JSON.stringify({version:t})});if(!s.success)throw new Error(s.error?.message||"版本更新失败");return s.data}async getEndpointStatus(t){const s=await this.request("/api/endpoint/status",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success||!s.data)throw new Error("获取接入点状态失败");return s.data}async connectEndpoint(t){const s=await this.request("/api/endpoint/connect",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"连接接入点失败")}async disconnectEndpoint(t){const s=await this.request("/api/endpoint/disconnect",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"断开接入点失败")}async reconnectEndpoint(t){const s=await this.request("/api/endpoint/reconnect",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"重连接入点失败")}async addEndpoint(t){const s=await this.request("/api/endpoint/add",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success||!s.data)throw new Error(s.error?.message||"添加接入点失败");return s.data}async removeEndpoint(t){const s=await this.request("/api/endpoint/remove",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"移除接入点失败")}async addMCPServer(t,s){const n={name:t,config:s},a=await this.request("/api/mcp-servers",{method:"POST",body:JSON.stringify(n)});if(!a.success||!a.data)throw new Error(a.error?.message||"添加 MCP 服务器失败");return a.data}async removeMCPServer(t){const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success||!s.data)throw new Error(s.error?.message||"删除 MCP 服务器失败");return s.data}async getMCPServerStatus(t){const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}/status`);if(!s.success||!s.data)throw new Error(s.error?.message||"获取 MCP 服务器状态失败");return s.data}async listMCPServers(){const t=await this.request("/api/mcp-servers");if(!t.success||!t.data)throw new Error(t.error?.message||"获取 MCP 服务器列表失败");return t.data}async checkMCPServerExists(t){try{const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}/exists`);return s.success&&s.data?.exists||!1}catch(s){if(s instanceof Error&&s.message.includes("404"))return!1;throw s}}async updateMCPServer(t,s){const n=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({config:s})});if(!n.success||!n.data)throw new Error(n.error?.message||"更新 MCP 服务器配置失败");return n.data}async callTool(t,s,n={}){const a=await this.request("/api/tools/call",{method:"POST",body:JSON.stringify({serviceName:t,toolName:s,args:n})});if(!a.success)throw new Error(a.error?.message||"调用工具失败");return a.data}async restartMCPServer(t){const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}/restart`,{method:"POST"});if(!s.success||!s.data)throw new Error(s.error?.message||"重启 MCP 服务器失败");return s.data}async manageMCPTool(t){const s=await this.request("/api/tools/mcp/manage",{method:"POST",body:JSON.stringify(t)});if(!s.success||!s.data)throw new Error(s.error?.message||"MCP 工具管理操作失败");return s.data}async listMCPTools(t){const s=await this.request("/api/tools/mcp/list",{method:"POST",body:JSON.stringify(t||{})});if(!s.success||!s.data)throw new Error(s.error?.message||"获取 MCP 工具列表失败");return s.data}}const z=new Ro,Gn=1e3;var ce=(r=>(r.DISCONNECTED="disconnected",r.CONNECTING="connecting",r.CONNECTED="connected",r.RECONNECTING="reconnecting",r))(ce||{});class To{listeners=new Map;on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{this.off(t,s)}}off(t,s){const n=this.listeners.get(t);n&&(n.delete(s),n.size===0&&this.listeners.delete(t))}emit(t,s){const n=this.listeners.get(t);if(n)for(const a of n)try{a(s)}catch(o){console.error(`[EventBus] 事件监听器执行失败 (${t}):`,o)}}clear(){this.listeners.clear()}getListenerCount(t){return t?this.listeners.get(t)?.size||0:Array.from(this.listeners.values()).reduce((s,n)=>s+n.size,0)}}class ie{static instance=null;static isCreating=!1;ws=null;url;state="disconnected";eventBus=new To;reconnectAttempts=0;maxReconnectAttempts;reconnectInterval;reconnectTimer;heartbeatTimer;heartbeatInterval;heartbeatTimeout;lastHeartbeat=0;constructor(t={}){this.url=t.url||this.getDefaultWebSocketUrl(),this.maxReconnectAttempts=t.maxReconnectAttempts||5,this.reconnectInterval=t.reconnectInterval||3e3,this.heartbeatInterval=t.heartbeatInterval||3e4,this.heartbeatTimeout=t.heartbeatTimeout||35e3}static getInstance(t){if(ie.instance)return ie.instance;if(ie.isCreating)throw new Error("[WebSocketManager] 检测到循环创建,请检查代码逻辑");ie.isCreating=!0;try{return ie.instance=new ie(t),console.log("[WebSocketManager] 单例实例已创建"),ie.instance}finally{ie.isCreating=!1}}static resetInstance(){ie.instance&&(ie.instance.disconnect(),ie.instance.eventBus.clear(),ie.instance=null,console.log("[WebSocketManager] 单例实例已重置"))}getDefaultWebSocketUrl(){const t=localStorage.getItem("xiaozhi-ws-url");if(t)return t;const s=window.location.protocol==="https:"?"wss:":"ws:",n=window.location.hostname;return`${s}//${n}:9999`}connect(){if(!(this.state==="connected"||this.state==="connecting")){this.state="connecting",console.log(`[WebSocket] 连接到: ${this.url}`),this.eventBus.emit("connection:connecting",void 0);try{this.ws=new WebSocket(this.url),this.setupEventHandlers()}catch(t){console.error("[WebSocket] 连接失败:",t),this.handleConnectionError(t)}}}disconnect(){console.log("[WebSocket] 主动断开连接"),this.clearTimers(),this.state="disconnected",this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}subscribe(t,s){return this.eventBus.on(t,s)}unsubscribe(t,s){this.eventBus.off(t,s)}getEventBus(){return this.eventBus}getState(){return this.state}isConnected(){return this.state==="connected"&&this.ws?.readyState===WebSocket.OPEN}setUrl(t){this.url!==t&&(this.url=t,localStorage.setItem("xiaozhi-ws-url",t),this.isConnected()&&(this.disconnect(),setTimeout(()=>this.connect(),Gn)))}send(t){if(!this.isConnected())return console.warn("[WebSocket] 连接未建立,无法发送消息"),!1;try{const s=typeof t=="string"?t:JSON.stringify(t);return this.ws.send(s),!0}catch(s){return console.error("[WebSocket] 发送消息失败:",s),this.eventBus.emit("connection:error",{error:s,context:"send_message"}),!1}}getUrl(){return this.url}getConnectionStats(){return{state:this.state,url:this.url,reconnectAttempts:this.reconnectAttempts,maxReconnectAttempts:this.maxReconnectAttempts,lastHeartbeat:this.lastHeartbeat,eventListenerCount:this.eventBus.getListenerCount()}}setupEventHandlers(){this.ws&&(this.ws.onopen=()=>{console.log("[WebSocket] 连接已建立"),this.state="connected",this.reconnectAttempts=0,this.startHeartbeat(),this.eventBus.emit("connection:connected",void 0)},this.ws.onmessage=t=>{try{const s=JSON.parse(t.data);this.handleMessage(s)}catch(s){console.error("[WebSocket] 消息解析失败:",s)}},this.ws.onclose=t=>{console.log(`[WebSocket] 连接已关闭 (code: ${t.code})`),this.handleConnectionClose()},this.ws.onerror=t=>{console.error("[WebSocket] 连接错误:",t),this.handleConnectionError(new Error("WebSocket 连接错误"))})}handleMessage(t){console.log("[WebSocket] 收到消息:",t.type),this.eventBus.emit("system:message",t);try{switch(t.type){case"configUpdate":case"config":t.data&&this.eventBus.emit("data:configUpdate",t.data);break;case"statusUpdate":case"status":t.data&&this.eventBus.emit("data:statusUpdate",t.data);break;case"restartStatus":t.data&&this.eventBus.emit("data:restartStatus",t.data);break;case"endpoint_status_changed":t.data&&this.eventBus.emit("data:endpointStatusChanged",t.data);break;case"npm:install:started":t.data&&this.eventBus.emit("data:npmInstallStarted",t.data);break;case"npm:install:log":t.data&&this.eventBus.emit("data:npmInstallLog",t.data);break;case"npm:install:completed":t.data&&this.eventBus.emit("data:npmInstallCompleted",t.data);break;case"npm:install:failed":t.data&&this.eventBus.emit("data:npmInstallFailed",t.data);break;case"heartbeatResponse":this.lastHeartbeat=Date.now(),this.eventBus.emit("system:heartbeat",{timestamp:this.lastHeartbeat});break;case"error":{const s=new Error(t.error?.message||"服务器错误");console.error("[WebSocket] 服务器错误:",t.error),this.eventBus.emit("system:error",{error:s,message:t}),this.eventBus.emit("connection:error",{error:s,context:"server_error"});break}default:console.log("[WebSocket] 未处理的消息类型:",t.type)}}catch(s){console.error("[WebSocket] 消息处理失败:",s),this.eventBus.emit("system:error",{error:s,message:t})}}handleConnectionClose(){this.state="disconnected",this.clearTimers(),this.eventBus.emit("connection:disconnected",void 0),this.reconnectAttempts<this.maxReconnectAttempts?this.scheduleReconnect():(console.error("[WebSocket] 达到最大重连次数,停止重连"),this.eventBus.emit("connection:error",{error:new Error("达到最大重连次数"),context:"max_reconnect_attempts"}))}handleConnectionError(t){this.state="disconnected",this.clearTimers(),this.eventBus.emit("connection:error",{error:t,context:"connection_error"}),this.reconnectAttempts<this.maxReconnectAttempts?this.scheduleReconnect():console.error("[WebSocket] 达到最大重连次数,停止重连")}scheduleReconnect(){this.reconnectAttempts++,this.state="reconnecting",console.log(`[WebSocket] 安排重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts}) 在 ${this.reconnectInterval}ms 后`),this.eventBus.emit("connection:reconnecting",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),this.reconnectTimer=setTimeout(()=>{this.connect()},this.reconnectInterval)}startHeartbeat(){this.lastHeartbeat=Date.now(),this.heartbeatTimer=setInterval(()=>{this.isConnected()&&(this.sendHeartbeat(),Date.now()-this.lastHeartbeat>this.heartbeatTimeout&&(console.warn("[WebSocket] 心跳超时,重新连接"),this.disconnect(),this.connect()))},this.heartbeatInterval)}sendHeartbeat(){if(this.isConnected()){const t={type:"clientStatus",data:{status:"connected",timestamp:Date.now()}};this.ws?.send(JSON.stringify(t))}}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}}const B=ie.getInstance(),mr={clientStatus:null,restartStatus:null,serviceStatus:null,serviceHealth:null,fullStatus:null,loading:{isLoading:!1,isRefreshing:!1,isRestarting:!1,lastUpdated:null,lastError:null},polling:{enabled:!1,interval:3e4,maxRetries:3,currentRetries:0},restartPolling:{enabled:!1,interval:1e3,maxAttempts:60,currentAttempts:0,timeout:6e4,startTime:null},lastSource:null};let ot=null,it=null;const Ce=As()(Ds((r,t)=>({...mr,setClientStatus:(s,n="http")=>{console.log(`[StatusStore] 设置客户端状态,来源: ${n}`),r(a=>({clientStatus:s,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setClientStatus")},setRestartStatus:(s,n="http")=>{console.log(`[StatusStore] 设置重启状态,来源: ${n}`),r(a=>({restartStatus:s,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setRestartStatus")},setServiceStatus:s=>{console.log("[StatusStore] 设置服务状态"),r({serviceStatus:s},!1,"setServiceStatus")},setServiceHealth:s=>{console.log("[StatusStore] 设置服务健康状态"),r({serviceHealth:s},!1,"setServiceHealth")},setFullStatus:(s,n="http")=>{console.log(`[StatusStore] 设置完整状态,来源: ${n}`),r(a=>({fullStatus:s,clientStatus:s.client,restartStatus:s.restart||null,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setFullStatus")},setLoading:s=>{r(n=>({loading:{...n.loading,...s}}),!1,"setLoading")},setError:s=>{r(n=>({loading:{...n.loading,lastError:s}}),!1,"setError")},getStatus:async()=>{const{fullStatus:s,loading:n}=t();return s&&n.lastUpdated&&Date.now()-n.lastUpdated<30*1e3?s:t().refreshStatus()},refreshStatus:async()=>{const{setLoading:s,setFullStatus:n,setError:a,polling:o}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[StatusStore] 开始刷新状态");const i=await z.getStatus();return n(i,"http"),o.enabled&&t().setPollingConfig({currentRetries:0}),console.log("[StatusStore] 状态刷新成功"),i}catch(i){const d=i instanceof Error?i:new Error("状态刷新失败");if(console.error("[StatusStore] 状态刷新失败:",d),a(d),o.enabled){const u=o.currentRetries+1;t().setPollingConfig({currentRetries:u}),u>=o.maxRetries&&(console.warn("[StatusStore] 达到最大重试次数,停止轮询"),t().stopPolling())}throw d}finally{s({isRefreshing:!1})}},restartService:async()=>{const{setLoading:s,setRestartStatus:n,setError:a,startRestartPolling:o}=t();try{s({isRestarting:!0,lastError:null}),console.log("[StatusStore] 开始重启服务"),n({status:"restarting",timestamp:Date.now()},"http"),await z.restartService(),console.log("[StatusStore] 服务重启请求已发送,开始重连检查"),o()}catch(i){const d=i instanceof Error?i:new Error("服务重启失败");throw console.error("[StatusStore] 服务重启失败:",d),n({status:"failed",error:d.message,timestamp:Date.now()},"http"),a(d),s({isRestarting:!1}),d}},getServiceStatus:async()=>{try{console.log("[StatusStore] 获取服务状态");const s=await z.getServiceStatus();return t().setServiceStatus(s),s}catch(s){const n=s instanceof Error?s:new Error("获取服务状态失败");throw console.error("[StatusStore] 获取服务状态失败:",n),t().setError(n),n}},getServiceHealth:async()=>{try{console.log("[StatusStore] 获取服务健康状态");const s=await z.getServiceHealth();return t().setServiceHealth(s),s}catch(s){const n=s instanceof Error?s:new Error("获取服务健康状态失败");throw console.error("[StatusStore] 获取服务健康状态失败:",n),t().setError(n),n}},startPolling:(s=3e4)=>{const{polling:n,refreshStatus:a}=t();if(n.enabled){console.log("[StatusStore] 轮询已启用,跳过启动");return}console.log(`[StatusStore] 启动状态轮询,间隔: ${s}ms`),r(o=>({polling:{...o.polling,enabled:!0,interval:s,currentRetries:0}}),!1,"startPolling"),a().catch(o=>{console.error("[StatusStore] 轮询初始刷新失败:",o)}),ot=setInterval(()=>{t().polling.enabled&&a().catch(i=>{console.error("[StatusStore] 轮询刷新失败:",i)})},s)},stopPolling:()=>{console.log("[StatusStore] 停止状态轮询"),r(s=>({polling:{...s.polling,enabled:!1,currentRetries:0}}),!1,"stopPolling"),ot&&(clearInterval(ot),ot=null)},setPollingConfig:s=>{r(n=>({polling:{...n.polling,...s}}),!1,"setPollingConfig")},startRestartPolling:()=>{const{restartPolling:s,refreshStatus:n,setRestartStatus:a,setLoading:o}=t();if(s.enabled){console.log("[StatusStore] 重启轮询已启用,跳过启动");return}console.log("[StatusStore] 启动重启后重连检查轮询");const i=Date.now();r(d=>({restartPolling:{...d.restartPolling,enabled:!0,currentAttempts:0,startTime:i}}),!1,"startRestartPolling"),it=setInterval(async()=>{const d=t(),{restartPolling:u}=d;if(!u.enabled)return;const m=Date.now()-(u.startTime||0),c=u.currentAttempts+1;console.log(`[StatusStore] 重启重连检查 (第 ${c} 次,已用时 ${Math.round(m/1e3)}s)`);try{if((await n()).client?.status==="connected"){console.log("[StatusStore] 服务重连成功,停止重启轮询"),a({status:"completed",timestamp:Date.now()},"polling"),d.stopRestartPolling(),o({isRestarting:!1});return}d.setRestartPollingConfig({currentAttempts:c}),(m>=u.timeout||c>=u.maxAttempts)&&(console.warn("[StatusStore] 重启重连检查超时或达到最大尝试次数"),a({status:"failed",error:"重连超时,服务可能未成功重启",timestamp:Date.now()},"polling"),d.stopRestartPolling(),o({isRestarting:!1}))}catch(p){console.log(`[StatusStore] 重启重连检查失败 (第 ${c} 次):`,p),d.setRestartPollingConfig({currentAttempts:c}),(m>=u.timeout||c>=u.maxAttempts)&&(console.error("[StatusStore] 重启重连检查超时或达到最大尝试次数"),a({status:"failed",error:"重连超时,服务可能未成功重启",timestamp:Date.now()},"polling"),d.stopRestartPolling(),o({isRestarting:!1}))}},s.interval)},stopRestartPolling:()=>{console.log("[StatusStore] 停止重启轮询"),r(s=>({restartPolling:{...s.restartPolling,enabled:!1,currentAttempts:0,startTime:null}}),!1,"stopRestartPolling"),it&&(clearInterval(it),it=null)},setRestartPollingConfig:s=>{r(n=>({restartPolling:{...n.restartPolling,...s}}),!1,"setRestartPollingConfig")},reset:()=>{console.log("[StatusStore] 重置状态"),t().stopPolling(),t().stopRestartPolling(),r(mr,!1,"reset")},initialize:async()=>{const{setLoading:s,refreshStatus:n}=t();try{s({isLoading:!0}),console.log("[StatusStore] 初始化状态 Store"),B.subscribe("data:statusUpdate",a=>{console.log("[StatusStore] 收到 WebSocket 状态更新"),t().setClientStatus(a,"websocket")}),B.subscribe("data:restartStatus",a=>{console.log("[StatusStore] 收到 WebSocket 重启状态更新"),t().setRestartStatus(a,"websocket")}),await n(),console.log("[StatusStore] 状态 Store 初始化完成")}catch(a){throw console.error("[StatusStore] 状态 Store 初始化失败:",a),a}finally{s({isLoading:!1})}}}),{name:"status-store"})),ko=()=>Ce(r=>r.restartStatus),Hn=()=>Ce(r=>r.restartPolling);function Io(){const r=ko(),t=Hn(),s=l.useRef(null),n=l.useRef(null);l.useEffect(()=>{if(!r)return;const{status:a,timestamp:o,error:i}=r;if(!(s.current===a&&n.current===o))switch(s.current=a,n.current=o,a){case"restarting":O.info("正在重启服务...",{id:"restart-status-progress",description:"请耐心等待",duration:0});break;case"completed":{const d=t.enabled?`服务重启成功!重连检查完成 (${t.currentAttempts}次检查)`:"服务重启成功!";O.dismiss("restart-status-progress"),O.success(d,{id:"restart-status-success",description:"服务已恢复正常运行"});break}case"failed":{const d=i||"服务重启失败",u=t.enabled?`重连检查超时 (${t.currentAttempts}/${t.maxAttempts}次)`:"请检查服务状态或稍后重试";O.dismiss("restart-status-progress"),O.error(d,{id:"restart-status-failed",description:u});break}}},[r,t]),l.useEffect(()=>()=>{s.current=null,n.current=null},[])}function $o(){return Io(),null}function tt({showValue:r=!0,value:t=0,maxValue:s=100,size:n=60,activeColor:a="#3b82f6",inactiveColor:o="#e5e7eb",symbol:i="%",ariaLabel:d}){const u=(n-6)/2,m=u*2*Math.PI,c=m,p=s===0?m:m-t/s*m;return e.jsxs("div",{className:"relative inline-flex items-center justify-center",role:"progressbar",tabIndex:0,"aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":s,"aria-label":d||`进度:${t}/${s}`,children:[e.jsxs("svg",{width:n,height:n,className:"transform -rotate-90",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:u,stroke:o,strokeWidth:6,fill:"none"}),e.jsx("circle",{cx:n/2,cy:n/2,r:u,stroke:a,strokeWidth:6,fill:"none",strokeDasharray:c,strokeDashoffset:p,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]}),r&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-xs font-medium",children:[t,i]})})]})}function I(...r){return bo(Bn(r))}const Po=Ae("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function pe({className:r,variant:t,...s}){return e.jsx("div",{className:I(Po({variant:t}),r),...s})}const jt=Ae("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),A=l.forwardRef(({className:r,variant:t,size:s,asChild:n=!1,...a},o)=>{const i=n?fn:"button";return e.jsx(i,{className:I(jt({variant:t,size:s,className:r})),ref:o,...a})});A.displayName="Button";const Vs=Pa,Oo=Oa,Lo=$a,Jn=l.forwardRef(({className:r,...t},s)=>e.jsx(hn,{className:I("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...t,ref:s}));Jn.displayName=hn.displayName;const bt=l.forwardRef(({className:r,...t},s)=>e.jsxs(Lo,{children:[e.jsx(Jn,{}),e.jsx(pn,{ref:s,className:I("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...t})]}));bt.displayName=pn.displayName;const St=({className:r,...t})=>e.jsx("div",{className:I("flex flex-col space-y-2 text-center sm:text-left",r),...t});St.displayName="AlertDialogHeader";const wt=({className:r,...t})=>e.jsx("div",{className:I("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...t});wt.displayName="AlertDialogFooter";const Nt=l.forwardRef(({className:r,...t},s)=>e.jsx(xn,{ref:s,className:I("text-lg font-semibold",r),...t}));Nt.displayName=xn.displayName;const yt=l.forwardRef(({className:r,...t},s)=>e.jsx(gn,{ref:s,className:I("text-sm text-muted-foreground",r),...t}));yt.displayName=gn.displayName;const Ct=l.forwardRef(({className:r,...t},s)=>e.jsx(vn,{ref:s,className:I(jt(),r),...t}));Ct.displayName=vn.displayName;const Et=l.forwardRef(({className:r,...t},s)=>e.jsx(jn,{ref:s,className:I(jt({variant:"outline"}),"mt-2 sm:mt-0",r),...t}));Et.displayName=jn.displayName;const me=Aa,Te=Da,Ao=La,$e=wn,Xn=l.forwardRef(({className:r,...t},s)=>e.jsx(bn,{ref:s,className:I("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...t}));Xn.displayName=bn.displayName;const le=l.forwardRef(({className:r,children:t,...s},n)=>e.jsxs(Ao,{children:[e.jsx(Xn,{}),e.jsxs(Sn,{ref:n,className:I("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...s,children:[t,e.jsxs(wn,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));le.displayName=Sn.displayName;const de=({className:r,...t})=>e.jsx("div",{className:I("flex flex-col space-y-1.5 text-center sm:text-left",r),...t});de.displayName="DialogHeader";const ke=({className:r,...t})=>e.jsx("div",{className:I("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...t});ke.displayName="DialogFooter";const ue=l.forwardRef(({className:r,...t},s)=>e.jsx(yn,{ref:s,className:I("text-lg font-semibold leading-none tracking-tight",r),...t}));ue.displayName=yn.displayName;const we=l.forwardRef(({className:r,...t},s)=>e.jsx(Cn,{ref:s,className:I("text-sm text-muted-foreground",r),...t}));we.displayName=Cn.displayName;const te=l.forwardRef(({className:r,type:t,...s},n)=>e.jsx("input",{type:t,className:I("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",r),ref:n,"data-1p-ignore":!0,...s}));te.displayName="Input";const fr={config:null,loading:{isLoading:!1,isUpdating:!1,isRefreshing:!1,lastUpdated:null,lastError:null},lastSource:null,mcpServerStatuses:[],mcpServerStatusLoading:!1,mcpServerStatusLastUpdate:null},he=As()(Ds((r,t)=>({...fr,setConfig:(s,n="http")=>{console.log(`[ConfigStore] 设置配置数据,来源: ${n}`),r(a=>({config:s,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setConfig")},setLoading:s=>{r(n=>({loading:{...n.loading,...s}}),!1,"setLoading")},setError:s=>{r(n=>({loading:{...n.loading,lastError:s}}),!1,"setError")},getConfig:async()=>{const{config:s,loading:n}=t();return s&&n.lastUpdated&&Date.now()-n.lastUpdated<300*1e3?s:t().refreshConfig()},updateConfig:async s=>{const{setLoading:n,setConfig:a,setError:o}=t();try{n({isUpdating:!0,lastError:null}),console.log("[ConfigStore] 开始更新配置"),await z.updateConfig(s),a(s,"http"),console.log("[ConfigStore] 配置更新成功")}catch(i){const d=i instanceof Error?i:new Error("配置更新失败");throw console.error("[ConfigStore] 配置更新失败:",d),o(d),d}finally{n({isUpdating:!1})}},refreshConfig:async()=>{const{setLoading:s,setConfig:n,setError:a}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[ConfigStore] 开始刷新配置");const o=await z.getConfig();return n(o,"http"),console.log("[ConfigStore] 配置刷新成功"),o}catch(o){const i=o instanceof Error?o:new Error("配置刷新失败");throw console.error("[ConfigStore] 配置刷新失败:",i),a(i),i}finally{s({isRefreshing:!1})}},reloadConfig:async()=>{const{setLoading:s,setConfig:n,setError:a}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[ConfigStore] 开始重新加载配置");const o=await z.reloadConfig();return n(o,"http"),console.log("[ConfigStore] 配置重新加载成功"),o}catch(o){const i=o instanceof Error?o:new Error("配置重新加载失败");throw console.error("[ConfigStore] 配置重新加载失败:",i),a(i),i}finally{s({isRefreshing:!1})}},updateMcpEndpoint:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 MCP 端点");const o={...n,mcpEndpoint:s};await a(o)},updateMcpServers:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 MCP 服务");const o={...n,mcpServers:s};await a(o)},updateConnectionConfig:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新连接配置");const o={...n,connection:s};await a(o)},updateModelScopeConfig:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 ModelScope 配置");const o={...n,modelscope:s};await a(o)},updateWebUIConfig:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 Web UI 配置");const o={...n,webUI:s};await a(o)},reset:()=>{console.log("[ConfigStore] 重置状态"),r(fr,!1,"reset")},initialize:async()=>{const{setLoading:s,refreshConfig:n}=t();try{s({isLoading:!0}),console.log("[ConfigStore] 初始化配置 Store"),B.subscribe("data:configUpdate",a=>{console.log("[ConfigStore] 收到 WebSocket 配置更新"),t().setConfig(a,"websocket")}),await n(),console.log("[ConfigStore] 配置 Store 初始化完成")}catch(a){throw console.error("[ConfigStore] 配置 Store 初始化失败:",a),a}finally{s({isLoading:!1})}},setMcpServerStatuses:s=>{r(()=>({mcpServerStatuses:s,mcpServerStatusLastUpdate:Date.now()}),!1,"setMcpServerStatuses")},setMcpServerStatusLoading:s=>{r(()=>({mcpServerStatusLoading:s}),!1,"setMcpServerStatusLoading")},refreshMcpServerStatuses:async()=>{const s=t(),{setMcpServerStatuses:n,setMcpServerStatusLoading:a,setConfig:o}=s;try{a(!0),console.log("[ConfigStore] 开始刷新 MCP 服务器状态");const i=await z.listMCPServers();if(n(i.servers),s.config){const d={};for(const u of i.servers)d[u.name]=u.config;o({...s.config,mcpServers:d},"http")}return console.log(`[ConfigStore] MCP 服务器状态刷新成功,共 ${i.servers.length} 个服务器`),i.servers}catch(i){const d=i instanceof Error?i:new Error("MCP 服务器状态刷新失败");throw console.error("[ConfigStore] MCP 服务器状态刷新失败:",d),n([]),d}finally{a(!1)}},getMcpServerStatus:s=>t().mcpServerStatuses.find(n=>n.name===s)}),{name:"config-store"})),We=()=>he(r=>r.config),Kn=()=>he(r=>r.config?.mcpEndpoint),Do=()=>he(pt(r=>({asr:r.config?.asr,llm:r.config?.llm,tts:r.config?.tts}))),Mo=()=>he(pt(r=>({getConfig:r.getConfig,updateConfig:r.updateConfig,refreshConfig:r.refreshConfig,reloadConfig:r.reloadConfig,updateMcpEndpoint:r.updateMcpEndpoint,updateMcpServers:r.updateMcpServers,updateConnectionConfig:r.updateConnectionConfig,updateModelScopeConfig:r.updateModelScopeConfig,updateWebUIConfig:r.updateWebUIConfig,reset:r.reset,initialize:r.initialize}))),Yn=()=>he(pt(r=>({servers:r.mcpServerStatuses,loading:r.mcpServerStatusLoading,refresh:r.refreshMcpServerStatuses,lastUpdate:r.mcpServerStatusLastUpdate}))),hr=r=>`${r.slice(0,30)}...${r.slice(-10)}`,qo=r=>{if(!r.trim())return"请输入接入点地址";if(!r.startsWith("ws://")&&!r.startsWith("wss://"))return"接入点格式无效,请输入正确的WebSocket URL (ws:// 或 wss://)";try{new URL(r)}catch{return"接入点格式无效,请输入正确的URL格式"}return null};function Fo(){const[r,t]=l.useState(!1),[s,n]=l.useState(!1),[a,o]=l.useState(""),[i,d]=l.useState(!1),[u,m]=l.useState(!1),[c,p]=l.useState(""),[h,x]=l.useState(!1),[v,g]=l.useState(""),[N,k]=l.useState({}),j=We(),y=Kn(),{refreshConfig:T}=Mo(),E=l.useCallback(async f=>{try{return await z.getEndpointStatus(f)}catch(S){return console.error(`获取接入点状态失败: ${f}`,S),{endpoint:f,connected:!1,initialized:!1,isReconnecting:!1,reconnectAttempts:0,reconnectDelay:0}}},[]),$=l.useCallback((f,S)=>{k(C=>({...C,[f]:{...C[f],...S}}))},[]),M=l.useCallback(async f=>{const S={};for(const C of f)try{const P=await E(C);S[C]={connected:P.connected,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}}catch{S[C]={connected:!1,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}}k(S)},[E]),D=async f=>{$(f,{isOperating:!0});try{await z.connectEndpoint(f),$(f,{connected:!0,isOperating:!1,lastOperation:{type:"connect",success:!0,message:"连接成功",timestamp:Date.now()}}),O.success("接入点连接成功")}catch(S){$(f,{isOperating:!1,lastOperation:{type:"connect",success:!1,message:S instanceof Error?S.message:"连接失败",timestamp:Date.now()}}),O.error(S instanceof Error?S.message:"接入点连接失败")}},W=async f=>{$(f,{isOperating:!0});try{await z.disconnectEndpoint(f),$(f,{connected:!1,isOperating:!1,lastOperation:{type:"disconnect",success:!0,message:"断开成功",timestamp:Date.now()}}),O.success("接入点断开成功")}catch(S){$(f,{isOperating:!1,lastOperation:{type:"disconnect",success:!1,message:S instanceof Error?S.message:"断开失败",timestamp:Date.now()}}),O.error(S instanceof Error?S.message:"接入点断开失败")}},U=async f=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(f),O.success("接入点地址已复制到剪贴板");else{const S=document.createElement("textarea");S.value=f,S.style.position="fixed",S.style.opacity="0",document.body.appendChild(S),S.select();const C=document.execCommand("copy");if(document.body.removeChild(S),C)O.success("接入点地址已复制到剪贴板");else throw new Error("复制命令执行失败")}}catch(S){console.error("复制失败:",S),O.error("复制失败,请手动复制")}},X=async()=>{d(!0);try{await z.removeEndpoint(a),await T(),k(f=>{const S={...f};return delete S[a],S}),O.success("接入点已删除"),n(!1),o("")}catch(f){console.error("删除接入点失败:",f),O.error(f instanceof Error?f.message:"删除接入点失败")}finally{d(!1)}},L=async()=>{const f=qo(c);if(f){g(f);return}if((Array.isArray(y)?y:[y]).includes(c)){g("该接入点已存在");return}if(!j){O.error("配置数据未加载,请稍后重试");return}x(!0);try{const C=await z.addEndpoint(c);await T(),k(P=>({...P,[c]:{connected:C.connected,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}})),O.success("接入点添加成功"),m(!1),p(""),g("")}catch(C){console.error("添加接入点失败:",C),O.error(C instanceof Error?C.message:"添加接入点失败")}finally{x(!1)}},F=()=>{p(""),g(""),m(!0)},b=f=>{p(f),v&&g("")},w=f=>{o(f),n(!0)},R=l.useMemo(()=>{let f=[];return Array.isArray(y)&&(f=y),typeof y=="string"&&y.length&&f.push(y),f},[y]);return l.useEffect(()=>{r&&R.length>0&&M(R)},[r,R,M]),l.useEffect(()=>{if(!r||R.length===0)return;const f=R.map(S=>B.subscribe("data:endpointStatusChanged",P=>{P.endpoint===S&&(console.log(`[McpEndpointSettingButton] 接收到端点 ${S} 状态变更:`,P),$(S,{connected:P.connected,isOperating:!1,lastOperation:{type:P.operation,success:P.success,message:P.message||(P.connected?"连接成功":"断开成功"),timestamp:P.timestamp}}),P.success?O.success(`端点 ${P.operation==="connect"?"连接":P.operation==="disconnect"?"断开":"重连"}成功`):O.error(`端点 ${P.operation==="connect"?"连接":P.operation==="disconnect"?"断开":"重连"}失败: ${P.message||"未知错误"}`))}));return()=>{for(const S of f)S()}},[r,R,$]),e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ze,{className:"size-4"})})}),e.jsxs(le,{className:"min-w-[600px] max-w-[800px] max-h-[80vh] overflow-y-auto",children:[e.jsxs(de,{className:"mb-4",children:[e.jsx(ue,{children:"配置小智服务端接入点"}),e.jsx(we,{children:"点击保存后,需要重启服务才会生效。"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[R.map(f=>{const S=N[f],C=S?.connected||!1,P=S?.isOperating||!1;return e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-slate-50 rounded-md font-mono gap-3 transition-all duration-200 hover:bg-slate-100",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("span",{className:"flex-1 text-ellipsis overflow-hidden whitespace-nowrap text-sm sm:text-base",children:hr(f)}),e.jsxs(pe,{className:`flex items-center gap-1 transition-all duration-200 text-xs sm:text-sm ${C?"bg-green-100 text-green-800 border-green-200 hover:text-green-800 hover:border-green-200 hover:bg-green-100":"bg-gray-100 text-gray-600 border-gray-200 hover:bg-gray-100 hover:text-gray-600 hover:border-gray-200"}`,children:[P?e.jsx(fe,{className:"size-3 animate-spin"}):C?e.jsx(ar,{className:"size-3"}):e.jsx(or,{className:"size-3"}),P?"操作中":C?"已连接":"未连接"]})]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-end",children:[e.jsx(A,{variant:"outline",size:"icon",onClick:()=>U(f),title:"复制完整地址",className:"transition-all duration-200 hover:scale-105",children:e.jsx(xt,{className:"size-4"})}),C?e.jsx(A,{variant:"outline",size:"icon",onClick:()=>W(f),title:"断开连接",disabled:P,className:"text-red-600 hover:text-red-700 hover:bg-red-50 transition-all duration-200 hover:scale-105 disabled:scale-100 disabled:opacity-50",children:P?e.jsx(fe,{className:"size-4 animate-spin"}):e.jsx(or,{className:"size-4"})}):e.jsx(A,{variant:"outline",size:"icon",onClick:()=>D(f),title:"连接",disabled:P,className:"text-green-600 hover:text-green-700 hover:bg-green-50 transition-all duration-200 hover:scale-105 disabled:scale-100 disabled:opacity-50",children:P?e.jsx(fe,{className:"size-4 animate-spin"}):e.jsx(ar,{className:"size-4"})}),e.jsx(A,{variant:"outline",size:"icon",onClick:()=>w(f),title:"删除此接入点",className:"transition-all duration-200 hover:scale-105 hover:text-red-600",children:e.jsx(En,{className:"size-4 text-red-500"})})]})]},f)}),R.length===0&&e.jsxs("div",{className:"flex flex-col items-center flex-1 text-sm text-muted-foreground text-center justify-center gap-2",children:[e.jsx(Ma,{}),e.jsx("span",{children:"暂无接入点,请添加"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-2 mt-4",children:[e.jsxs(A,{className:"flex-1 flex items-center gap-2",onClick:F,children:[e.jsx(Qe,{className:"size-4"}),e.jsx("span",{className:"text-sm sm:text-base",children:"添加小智服务端接入点"})]}),e.jsx(A,{variant:"outline",className:"flex-1 flex items-center gap-2",onClick:()=>window.open("https://xiaozhi.me/console/agents","_blank"),children:e.jsx("span",{className:"text-sm sm:text-base",children:"打开小智服务端"})})]})]})]}),e.jsx(Vs,{open:s,onOpenChange:n,children:e.jsxs(bt,{children:[e.jsxs(St,{children:[e.jsx(Nt,{children:"确认删除接入点"}),e.jsxs(yt,{children:['确定要删除接入点 "',hr(a),'" 吗?此操作无法撤销。']})]}),e.jsxs(wt,{children:[e.jsx(Et,{disabled:i,children:"取消"}),e.jsx(Ct,{onClick:X,disabled:i,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:i?"删除中...":"确定删除"})]})]})}),e.jsx(me,{open:u,onOpenChange:m,children:e.jsxs(le,{className:"sm:max-w-[500px]",children:[e.jsxs(de,{children:[e.jsx(ue,{children:"添加新的接入点"}),e.jsx(we,{children:"请输入小智服务端接入点地址"})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{placeholder:"请输入接入点地址,例如:wss://api.xiaozhi.me/mcp/?token=... 或 ws(s)://<hostname>:<port>",value:c,onChange:f=>b(f.target.value),disabled:h,className:"font-mono text-sm"}),v&&e.jsx("p",{className:"text-sm text-red-500",children:v})]})}),e.jsxs(ke,{children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:h,children:"取消"})}),e.jsx(A,{onClick:L,disabled:h||!c.trim(),children:h?"添加中...":"确定"})]})]})})]})}const Pe=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("rounded-lg border bg-card text-card-foreground shadow-sm",r),...t}));Pe.displayName="Card";const De=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("flex flex-col space-y-1.5 p-6",r),...t}));De.displayName="CardHeader";const Me=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("text-2xl font-semibold leading-none tracking-tight",r),...t}));Me.displayName="CardTitle";const Be=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("text-sm text-muted-foreground",r),...t}));Be.displayName="CardDescription";const Zn=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("p-6 pt-0",r),...t}));Zn.displayName="CardContent";const Ge=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("flex items-center p-6 pt-0",r),...t}));Ge.displayName="CardFooter";function zo(){const r=Kn(),t=Array.isArray(r)?r.length:r?1:0;return e.jsxs(Pe,{className:"@container/card",children:[e.jsxs(De,{className:"relative",children:[e.jsx(Be,{children:"小智接入点"}),e.jsx(Me,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:t}),e.jsx("div",{className:"absolute right-4 top-4 flex flex-col items-center",children:e.jsx(tt,{showValue:!1,value:t,maxValue:Math.max(t,1),activeColor:"#16a34a",inactiveColor:"#f87171",size:30,symbol:""})})]}),e.jsx(Ge,{className:"flex-col items-end gap-1 text-sm",children:e.jsx(Fo,{})})]})}const Uo=Ae("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ft=l.forwardRef(({className:r,...t},s)=>e.jsx(Rn,{ref:s,className:I(Uo(),r),...t}));ft.displayName=Rn.displayName;const qe=Fa,Qn=l.createContext({}),K=({...r})=>e.jsx(Qn.Provider,{value:{name:r.name},children:e.jsx(Fe,{...r})}),Rt=()=>{const r=l.useContext(Qn),t=l.useContext(ea),{getFieldState:s,formState:n}=qa(),a=s(r.name,n);if(!r)throw new Error("useFormField should be used within <FormField>");const{id:o}=t;return{id:o,name:r.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...a}},ea=l.createContext({}),J=l.forwardRef(({className:r,...t},s)=>{const n=l.useId();return e.jsx(ea.Provider,{value:{id:n},children:e.jsx("div",{ref:s,className:I("space-y-2",r),...t})})});J.displayName="FormItem";const ee=l.forwardRef(({className:r,...t},s)=>{const{error:n,formItemId:a}=Rt();return e.jsx(ft,{ref:s,className:I(n&&"text-destructive",r),htmlFor:a,...t})});ee.displayName="FormLabel";const H=l.forwardRef(({...r},t)=>{const{error:s,formItemId:n,formDescriptionId:a,formMessageId:o}=Rt();return e.jsx(fn,{ref:t,id:n,"aria-describedby":s?`${a} ${o}`:`${a}`,"aria-invalid":!!s,...r})});H.displayName="FormControl";const Ue=l.forwardRef(({className:r,...t},s)=>{const{formDescriptionId:n}=Rt();return e.jsx("p",{ref:s,id:n,className:I("text-sm text-muted-foreground",r),...t})});Ue.displayName="FormDescription";const Y=l.forwardRef(({className:r,children:t,...s},n)=>{const{error:a,formMessageId:o}=Rt(),i=a?String(a?.message??""):t;return i?e.jsx("p",{ref:n,id:o,className:I("text-sm font-medium text-destructive",r),...s,children:i}):null});Y.displayName="FormMessage";class Vo{apiClient;webSocketManager;initialized=!1;constructor(){this.apiClient=z,this.webSocketManager=B}async initialize(){this.initialized||(console.log("[NetworkService] 初始化网络服务"),this.webSocketManager.connect(),this.initialized=!0,console.log("[NetworkService] 网络服务初始化完成"))}destroy(){console.log("[NetworkService] 销毁网络服务"),this.webSocketManager.disconnect(),this.initialized=!1}async getConfig(){return this.apiClient.getConfig()}async updateConfig(t){return this.apiClient.updateConfig(t)}async getStatus(){return this.apiClient.getStatus()}async getClientStatus(){return this.apiClient.getClientStatus()}async restartService(){return this.apiClient.restartService()}async stopService(){return this.apiClient.stopService()}async startService(){return this.apiClient.startService()}async getServiceStatus(){return this.apiClient.getServiceStatus()}async getServiceHealth(){return this.apiClient.getServiceHealth()}async getMcpEndpoint(){return this.apiClient.getMcpEndpoint()}async getMcpEndpoints(){return this.apiClient.getMcpEndpoints()}async getMcpServers(){return this.apiClient.getMcpServers()}async getConnectionConfig(){return this.apiClient.getConnectionConfig()}async reloadConfig(){return this.apiClient.reloadConfig()}async getConfigPath(){return this.apiClient.getConfigPath()}async checkConfigExists(){return this.apiClient.checkConfigExists()}async getRestartStatus(){return this.apiClient.getRestartStatus()}async checkClientConnected(){return this.apiClient.checkClientConnected()}async getLastHeartbeat(){return this.apiClient.getLastHeartbeat()}async getActiveMCPServers(){return this.apiClient.getActiveMCPServers()}async updateClientStatus(t){return this.apiClient.updateClientStatus(t)}async setActiveMCPServers(t){return this.apiClient.setActiveMCPServers(t)}async resetStatus(){return this.apiClient.resetStatus()}getWebSocketState(){return this.webSocketManager.getState()}isWebSocketConnected(){return this.webSocketManager.isConnected()}setWebSocketUrl(t){this.webSocketManager.setUrl(t)}onWebSocketEvent(t,s){return this.webSocketManager.subscribe(t,s)}reconnectWebSocket(){this.webSocketManager.disconnect(),setTimeout(()=>{this.webSocketManager.connect()},1e3)}send(t){return this.webSocketManager.send(t)}async getFullAppState(){const[t,s]=await Promise.all([this.getConfig(),this.getStatus()]);return{config:t,status:s,webSocketConnected:this.isWebSocketConnected()}}async updateConfigWithNotification(t,s=5e3){return new Promise((n,a)=>{const o=this.webSocketManager.subscribe("data:configUpdate",()=>{clearTimeout(i),o(),n()}),i=setTimeout(()=>{o(),a(new Error("等待配置更新通知超时"))},s);this.updateConfig(t).catch(d=>{clearTimeout(i),o?.(),a(d)})})}async restartServiceWithNotification(t=3e4){return new Promise((s,n)=>{const a=this.webSocketManager.subscribe("data:restartStatus",i=>{i.status==="completed"?(clearTimeout(o),a(),s()):i.status==="failed"&&(clearTimeout(o),a(),n(new Error(i.error||"服务重启失败")))}),o=setTimeout(()=>{a(),n(new Error("等待重启状态通知超时"))},t);this.restartService().catch(i=>{clearTimeout(o),a?.(),n(i)})})}}const Q=new Vo,pr={connectionState:ce.DISCONNECTED,wsUrl:"",connectionStats:{reconnectAttempts:0,maxReconnectAttempts:5,lastHeartbeat:0,eventListenerCount:0},portChangeStatus:void 0,lastError:null,connectedAt:null,disconnectedAt:null},st=As()(Ds((r,t)=>({...pr,setConnectionState:s=>{console.log("[WebSocketStore] 更新连接状态:",s);const n=Date.now(),a={connectionState:s};s===ce.CONNECTED?(a.connectedAt=n,a.lastError=null):s===ce.DISCONNECTED&&(a.disconnectedAt=n),r(a,!1,"setConnectionState");const o=B.getConnectionStats();t().setConnectionStats(o)},setWsUrl:s=>{console.log("[WebSocketStore] 更新 WebSocket URL:",s),r({wsUrl:s},!1,"setWsUrl")},setConnectionStats:s=>{r({connectionStats:s},!1,"setConnectionStats")},setLastError:s=>{console.log("[WebSocketStore] 更新连接错误:",s?.message),r({lastError:s},!1,"setLastError")},setPortChangeStatus:s=>{console.log("[WebSocketStore] 更新端口变更状态:",s?.status),r({portChangeStatus:s},!1,"setPortChangeStatus")},connect:async()=>{try{console.log("[WebSocketStore] 开始连接 WebSocket"),B.connect()}catch(s){const n=s instanceof Error?s:new Error("连接失败");throw console.error("[WebSocketStore] 连接失败:",n),t().setLastError(n),n}},disconnect:()=>{console.log("[WebSocketStore] 断开 WebSocket 连接"),B.disconnect()},reconnect:async()=>{try{console.log("[WebSocketStore] 重新连接 WebSocket"),B.disconnect(),await new Promise(s=>setTimeout(s,Gn)),B.connect()}catch(s){const n=s instanceof Error?s:new Error("重连失败");throw console.error("[WebSocketStore] 重连失败:",n),t().setLastError(n),n}},send:s=>{try{return B.send(s)}catch(n){const a=n instanceof Error?n:new Error("发送消息失败");return console.error("[WebSocketStore] 发送消息失败:",a),t().setLastError(a),!1}},updateUrl:s=>{console.log("[WebSocketStore] 更新 WebSocket URL:",s),B.setUrl(s),t().setWsUrl(s)},getConnectionInfo:()=>{const s=t();return{state:s.connectionState,url:s.wsUrl,stats:s.connectionStats,isConnected:s.connectionState===ce.CONNECTED}},reset:()=>{console.log("[WebSocketStore] 重置状态"),r(pr,!1,"reset")},initialize:()=>{console.log("[WebSocketStore] 初始化 WebSocket Store"),B.subscribe("connection:connecting",()=>{t().setConnectionState(ce.CONNECTING)}),B.subscribe("connection:connected",()=>{t().setConnectionState(ce.CONNECTED)}),B.subscribe("connection:disconnected",()=>{t().setConnectionState(ce.DISCONNECTED)}),B.subscribe("connection:reconnecting",()=>{t().setConnectionState(ce.RECONNECTING);const n=B.getConnectionStats();t().setConnectionStats(n)}),B.subscribe("connection:error",({error:n})=>{t().setLastError(n)}),B.subscribe("system:heartbeat",()=>{const n=B.getConnectionStats();t().setConnectionStats(n)});const s=B.getConnectionStats();t().setConnectionStats(s),t().setWsUrl(B.getUrl()),console.log("[WebSocketStore] WebSocket Store 初始化完成")},setConnected:s=>{console.warn("[WebSocketStore] setConnected 方法已废弃,请使用 setConnectionState");const n=s?ce.CONNECTED:ce.DISCONNECTED;t().setConnectionState(n)}}),{name:"websocket-store"})),ta=()=>st(r=>r.connectionState===ce.CONNECTED),_o=()=>st(r=>r.wsUrl),Wo=()=>st(r=>r.portChangeStatus),Bo=()=>st(pt(r=>({setConnectionState:r.setConnectionState,setWsUrl:r.setWsUrl,setConnectionStats:r.setConnectionStats,setLastError:r.setLastError,setPortChangeStatus:r.setPortChangeStatus,connect:r.connect,disconnect:r.disconnect,reconnect:r.reconnect,send:r.send,updateUrl:r.updateUrl,reset:r.reset,initialize:r.initialize,getConnectionInfo:r.getConnectionInfo,setConnected:r.setConnected})));function Go(){const r=Bo(),t=l.useRef(!1);l.useEffect(()=>{if(t.current)return;console.log("[NetworkService] 初始化网络服务"),t.current=!0,Q.initialize().catch(v=>{console.error("[NetworkService] 初始化失败:",v)});const x=[Q.onWebSocketEvent("connection:connected",()=>{console.log("[NetworkService] WebSocket 已连接"),r.setConnectionState(ce.CONNECTED),s()}),Q.onWebSocketEvent("connection:disconnected",()=>{console.log("[NetworkService] WebSocket 已断开"),r.setConnectionState(ce.DISCONNECTED)}),Q.onWebSocketEvent("data:configUpdate",v=>{console.log("[NetworkService] 收到配置更新通知"),he.getState().setConfig(v,"websocket")}),Q.onWebSocketEvent("data:statusUpdate",v=>{console.log("[NetworkService] 收到状态更新通知"),Ce.getState().setClientStatus(v,"websocket")}),Q.onWebSocketEvent("data:restartStatus",v=>{console.log("[NetworkService] 收到重启状态通知:",v),Ce.getState().setRestartStatus(v,"websocket")}),Q.onWebSocketEvent("system:error",({error:v})=>{console.error("[NetworkService] WebSocket 错误:",v);const g=`WebSocket 连接错误: ${v.message}`;Ce.getState().setError(new Error(g)),v.message.includes("ECONNREFUSED")||v.message.includes("连接被拒绝")?console.warn("[NetworkService] 连接被拒绝,可能是服务未启动"):v.message.includes("timeout")||v.message.includes("超时")?console.warn("[NetworkService] 连接超时,请检查网络连接"):console.warn("[NetworkService] 未知的 WebSocket 错误:",v)})];return()=>{console.log("[NetworkService] 清理网络服务");for(const v of x)try{v?.()}catch(g){console.error("[NetworkService] 清理事件监听器失败:",g)}Q.destroy(),t.current=!1}},[r]);const s=l.useCallback(async()=>{try{console.log("[NetworkService] 加载初始数据");const[x,v]=await Promise.all([Q.getConfig(),Q.getClientStatus()]);console.log("[NetworkService] 初始数据加载成功"),he.getState().setConfig(x,"http"),Ce.getState().setClientStatus(v,"http")}catch(x){console.error("[NetworkService] 加载初始数据失败:",x)}},[]),n=l.useCallback(async()=>{try{const x=await Q.getConfig();return he.getState().setConfig(x,"http"),x}catch(x){throw console.error("[NetworkService] 获取配置失败:",x),x}},[]),a=l.useCallback(async x=>{try{console.log("[NetworkService] 更新配置"),await Q.updateConfig(x),he.getState().setConfig(x,"http"),console.log("[NetworkService] 配置更新成功")}catch(v){throw console.error("[NetworkService] 配置更新失败:",v),v}},[]),o=l.useCallback(async()=>{try{const x=await Q.getStatus();return Ce.getState().setClientStatus(x.client,"http"),x}catch(x){throw console.error("[NetworkService] 获取状态失败:",x),x}},[]),i=l.useCallback(async()=>{try{await o()}catch(x){console.error("[NetworkService] 刷新状态失败:",x)}},[o]),d=l.useCallback(async()=>{try{console.log("[NetworkService] 重启服务"),await Q.restartService(),console.log("[NetworkService] 重启请求已发送")}catch(x){throw console.error("[NetworkService] 重启服务失败:",x),x}},[]),u=l.useCallback(async(x=3e4)=>{try{console.log("[NetworkService] 重启服务并等待通知"),await Q.restartServiceWithNotification(x),console.log("[NetworkService] 服务重启完成")}catch(v){throw console.error("[NetworkService] 重启服务失败:",v),v}},[]),m=l.useCallback(async(x,v=5e3)=>{try{console.log("[NetworkService] 更新配置并等待通知"),await Q.updateConfigWithNotification(x,v),console.log("[NetworkService] 配置更新完成")}catch(g){throw console.error("[NetworkService] 配置更新失败:",g),g}},[]),c=l.useCallback(x=>{console.log("[NetworkService] 设置自定义 WebSocket URL:",x),Q.setWebSocketUrl(x),r.setWsUrl(x)},[r]),p=l.useCallback(async x=>{try{console.log(`[NetworkService] 切换到端口 ${x}`),r.setPortChangeStatus({status:"checking",targetPort:x,timestamp:Date.now()});const v=window.location.protocol==="https:"?"wss:":"ws:",g=window.location.hostname,N=`${v}//${g}:${x}`;await d(),await new Promise(k=>setTimeout(k,5e3)),c(N),window.location.reload()}catch(v){throw console.error("[NetworkService] 端口切换失败:",v),r.setPortChangeStatus({status:"failed",targetPort:x,error:v instanceof Error?v.message:"端口切换失败",timestamp:Date.now()}),v}},[r,d,c]),h=l.useCallback(()=>{const x=localStorage.getItem("xiaozhi-ws-url");if(x)return x;const v=window.location.protocol==="https:"?"wss:":"ws:",g=window.location.hostname,N=window.location.port;return`${v}//${g}${N?`:${N}`:""}`},[]);return{getConfig:n,updateConfig:a,getStatus:o,refreshStatus:i,restartService:d,updateConfigWithNotification:m,restartServiceWithNotification:u,setCustomWsUrl:c,getWebSocketUrl:h,changePort:p,loadInitialData:s,isWebSocketConnected:()=>Q.isWebSocketConnected(),getWebSocketState:()=>Q.getWebSocketState()}}async function Ho(){console.log("[Stores] 开始初始化所有 stores");try{console.log("[Stores] 初始化 WebSocket store"),st.getState().initialize(),console.log("[Stores] 初始化配置 store"),await he.getState().initialize(),console.log("[Stores] 初始化 MCP 服务器状态"),await he.getState().refreshMcpServerStatuses(),console.log("[Stores] 初始化状态 store"),await Ce.getState().initialize(),console.log("[Stores] 所有 stores 初始化完成")}catch(r){throw console.error("[Stores] Stores 初始化失败:",r),r}}const sa=l.createContext(null);function Jo({children:r}){const t=Go(),[s,n]=l.useState(!1);return l.useEffect(()=>{let a=!0;return(async()=>{try{console.log("[WebSocketProvider] 开始初始化 stores"),await Ho(),a&&(n(!0),console.log("[WebSocketProvider] Stores 初始化完成"))}catch(i){console.error("[WebSocketProvider] Stores 初始化失败:",i),a&&n(!0)}})(),()=>{a=!1}},[]),s?e.jsx(sa.Provider,{value:t,children:r}):e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"正在初始化应用..."})]})})}function _s(){const r=l.useContext(sa);if(!r)throw new Error("useNetworkServiceActions must be used within a NetworkServiceProvider");return r}const Xo=Jo,ra=_s,Ko=_.object({port:_.string().min(1,{message:"端口号不能为空"}).refine(r=>!Number.isNaN(Number(r)),{message:"请输入有效的数字"}).refine(r=>Number(r)>=1&&Number(r)<=65535,{message:"端口号必须在 1-65535 之间"}).refine(r=>Number.isInteger(Number(r)),{message:"端口号必须是整数"})});function Yo(){const[r,t]=l.useState(!1),[s,n]=l.useState(!1),a=We(),o=ta(),i=Wo(),{changePort:d}=_s(),u=Ee({resolver:Re(Ko),defaultValues:{port:"9999"}});l.useEffect(()=>{a?.webUI?.port&&u.reset({port:a.webUI.port.toString()})},[a,u]);const m=()=>{if(s)return"处理中...";if(i?.status==="checking")return"检测端口...";if(i?.status==="polling"){const{currentAttempt:p,maxAttempts:h}=i;return`等待服务重启 (${p||0}/${h||45})`}return i?.status==="connecting"?"连接中...":o?"保存并重启":"保存并连接"};async function c(p){const h=Number(p.port),x=a?.webUI?.port;if(h===x){t(!1);return}console.log(`[WebUrlSettingButton] 开始端口切换: ${x} -> ${h}`),n(!0);try{O.info(o?`正在将端口从 ${x} 切换到 ${h}...`:`正在连接到端口 ${h}...`),await d(h),O.success(o?`端口已成功切换到 ${h},页面即将刷新...`:`已成功连接到端口 ${h},页面即将刷新...`),t(!1)}catch(v){console.error("端口切换失败:",v);const g=v instanceof Error?v.message:"端口切换失败";O.error(`端口切换失败: ${g}`)}finally{n(!1)}}return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ze,{className:"h-4 w-4"})})}),e.jsx(le,{className:"sm:max-w-[250px]",children:e.jsx(qe,{...u,children:e.jsxs("form",{onSubmit:u.handleSubmit(c),children:[e.jsxs(de,{className:"mb-4",children:[e.jsx(ue,{children:"配置服务端端口"}),e.jsx(we,{children:o?"修改端口后将自动重启服务并重新连接。":"请输入服务端端口号,系统将尝试连接。"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{children:["ws://",window.location.hostname,":"]}),e.jsx("div",{className:"w-[100px]",children:e.jsx(K,{control:u.control,name:"port",render:({field:p})=>e.jsxs(J,{children:[e.jsx(H,{children:e.jsx(te,{placeholder:"服务端端口,默认9999",className:"font-mono text-sm",disabled:s,type:"number",...p})}),e.jsx(Y,{})]})})})]}),e.jsxs(ke,{className:"mt-4",children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s||i?.status==="polling",children:m()})]})]})})})]})}function Zo(){const r=ta(),t=_o();return e.jsxs(Pe,{className:"@container/card",children:[e.jsxs(De,{className:"relative",children:[e.jsx(Be,{children:"Xiaozhi Client"}),e.jsx(Me,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:r?"已连接":"未连接"}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(tt,{showValue:!1,value:1,maxValue:1,activeColor:r?"#16a34a":"#f87171",inactiveColor:r?"#16a34a":"#f87171",size:30,symbol:""})})]}),e.jsxs(Ge,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:t}),e.jsx(Yo,{})]})]})}const Ne=Ba,Qo=Ha,ye=Ga,xe=l.forwardRef(({className:r,children:t,...s},n)=>e.jsxs(Tn,{ref:n,className:I("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",r),...s,children:[t,e.jsx(za,{asChild:!0,children:e.jsx(gt,{className:"h-4 w-4 opacity-50"})})]}));xe.displayName=Tn.displayName;const na=l.forwardRef(({className:r,...t},s)=>e.jsx(kn,{ref:s,className:I("flex cursor-default items-center justify-center py-1",r),...t,children:e.jsx(Ms,{className:"h-4 w-4"})}));na.displayName=kn.displayName;const aa=l.forwardRef(({className:r,...t},s)=>e.jsx(In,{ref:s,className:I("flex cursor-default items-center justify-center py-1",r),...t,children:e.jsx(gt,{className:"h-4 w-4"})}));aa.displayName=In.displayName;const ge=l.forwardRef(({className:r,children:t,position:s="popper",...n},a)=>e.jsx(Ua,{children:e.jsxs($n,{ref:a,className:I("relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:s,...n,children:[e.jsx(na,{}),e.jsx(Va,{className:I("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(aa,{})]})}));ge.displayName=$n.displayName;const oa=l.forwardRef(({className:r,...t},s)=>e.jsx(Pn,{ref:s,className:I("py-1.5 pl-8 pr-2 text-sm font-semibold",r),...t}));oa.displayName=Pn.displayName;const ne=l.forwardRef(({className:r,children:t,...s},n)=>e.jsxs(On,{ref:n,className:I("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(_a,{children:e.jsx(vt,{className:"h-4 w-4"})})}),e.jsx(Wa,{children:t})]}));ne.displayName=On.displayName;const ei=l.forwardRef(({className:r,...t},s)=>e.jsx(Ln,{ref:s,className:I("-mx-1 my-1 h-px bg-muted",r),...t}));ei.displayName=Ln.displayName;const He=l.forwardRef(({className:r,...t},s)=>e.jsx("textarea",{className:I("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",r),ref:s,...t}));He.displayName="Textarea";function ia(r,t,s){const{name:n,type:a,label:o,required:i,placeholder:d,description:u,condition:m,options:c,inputType:p}=r;if(m&&!m(t))return null;const h=s??r.disabled,x=v=>{switch(a){case"text":return e.jsx(te,{...v,type:p,placeholder:d,disabled:h,className:r.className});case"textarea":return e.jsx(He,{...v,placeholder:d,className:r.className,rows:r.rows,disabled:h});case"select":return e.jsxs(Ne,{value:v.value,onValueChange:v.onChange,disabled:h,children:[e.jsx(xe,{children:e.jsx(ye,{placeholder:d})}),e.jsx(ge,{children:c?.map(g=>e.jsx(ne,{value:g.value,children:g.label},g.value))})]});default:return null}};return e.jsx(K,{control:t.control,name:String(n),render:({field:v})=>e.jsxs(J,{children:[e.jsxs(ee,{children:[i&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),o]}),e.jsx(H,{children:x(v)}),typeof u=="function"?e.jsx(Ue,{children:u(t)}):u?e.jsx(Ue,{children:u}):null,e.jsx(Y,{})]})},String(n))}function ti(r,t,s,n){const{name:a,type:o,label:i,required:d,placeholder:u,description:m,options:c}=r;return o!=="select"?(console.warn("renderSelectFieldWithHandler 只能用于 select 类型字段"),ia(r,t,n)):e.jsx(K,{control:t.control,name:String(a),render:({field:p})=>e.jsxs(J,{children:[e.jsxs(ee,{children:[d&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),i]}),e.jsx(H,{children:e.jsxs(Ne,{value:p.value,onValueChange:s,disabled:n??r.disabled,children:[e.jsx(xe,{children:e.jsx(ye,{placeholder:u})}),e.jsx(ge,{children:c?.map(h=>e.jsx(ne,{value:h.value,children:h.label},h.value))})]})}),typeof m=="function"?e.jsx(Ue,{children:m(t)}):m?e.jsx(Ue,{children:m}):null,e.jsx(Y,{})]})},String(a))}const si=[{name:"type",type:"select",label:"MCP 类型",required:!0,placeholder:"选择 MCP 类型",description:r=>{const t=r.watch("type");return t==="stdio"?"本地通过命令行启动的 MCP 服务":t==="http"?"通过 HTTP 协议访问的远程 MCP 服务":t==="sse"?"通过 SSE 协议访问的远程 MCP 服务":""},options:[{value:"stdio",label:"本地进程 (stdio)"},{value:"http",label:"远程服务 (HTTP)"},{value:"sse",label:"服务器推送 (SSE)"}]},{name:"name",type:"text",label:"MCP 名称",required:!0,placeholder:"例如: xxx-mcp",description:"服务的唯一标识符,建议使用小写字母和连字符"},{name:"command",type:"text",label:"启动命令",required:!0,placeholder:"例如: npx -y xxx",description:"完整的启动命令,空格分隔命令和参数",condition:r=>r.watch("type")==="stdio"},{name:"env",type:"textarea",label:"环境变量 (可选)",placeholder:`KEY1=value1
2
- KEY2=value2`,description:"每行一个环境变量,支持 KEY=value 或 KEY: value 格式",className:"min-h-[100px] font-mono text-sm",condition:r=>r.watch("type")==="stdio"},{name:"url",type:"text",label:"服务地址",required:!0,inputType:"url",placeholder:"https://example.com/mcp",description:"MCP 服务的完整 URL 地址",condition:r=>{const t=r.watch("type");return t==="http"||t==="sse"}},{name:"headers",type:"textarea",label:"请求头 (可选)",placeholder:`Authorization: Bearer your-key
3
- Content-Type: application/json`,description:"每行一个请求头,格式: Header-Name: value",className:"min-h-[100px] font-mono text-sm",condition:r=>{const t=r.watch("type");return t==="http"||t==="sse"}}],Ws=Oe().trim(),Bs=Oe().min(1,"MCP 名称不能为空").regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,"MCP 名称只能包含小写字母、数字和连字符,且必须以字母或数字开头和结尾"),ri=et({type:Us("stdio"),name:Bs,command:Oe().min(1,"启动命令不能为空"),env:Ws}),ni=et({type:Us("http"),name:Bs,url:Oe().url("请输入有效的 URL 地址"),headers:Ws}),ai=et({type:Us("sse"),name:Bs,url:Oe().url("请输入有效的 URL 地址"),headers:Ws}),Gs=wo("type",[ri,ni,ai]);function ca({form:r,defaultValues:t,onSubmit:s,disabled:n=!1,submitText:a="保存配置"}){const o=r||Ee({resolver:Re(Gs),defaultValues:t||{type:"stdio",name:"",command:"",env:""}}),i=d=>{o.setValue("type",d);const u=o;d==="stdio"?(u.setValue("url",""),u.setValue("headers","")):(u.setValue("command",""),u.setValue("env",""))};return e.jsx(qe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(s),className:"space-y-4 py-2",children:[si.map(d=>d.name==="type"?ti(d,o,i,n):ia(d,o,n)),e.jsx(A,{type:"submit",className:"w-full",disabled:n,children:a})]})})}const Ye=Ja,rt=l.forwardRef(({className:r,...t},s)=>e.jsx(An,{ref:s,className:I("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",r),...t}));rt.displayName=An.displayName;const be=l.forwardRef(({className:r,...t},s)=>e.jsx(Dn,{ref:s,className:I("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",r),...t}));be.displayName=Dn.displayName;const Se=l.forwardRef(({className:r,...t},s)=>e.jsx(Mn,{ref:s,className:I("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",r),...t}));Se.displayName=Mn.displayName;function oi(r){const t=r.trim();if(!t)throw new Error("命令不能为空");const s=[];let n="",a=!1,o="";for(let i=0;i<t.length;i++){const d=t[i];(d==='"'||d==="'")&&(i===0||t[i-1]!=="\\")?a&&d===o?(a=!1,o=""):a?n+=d:(a=!0,o=d):d===" "&&!a?n&&(s.push(n),n=""):n+=d}if(n&&s.push(n),s.length===0)throw new Error("命令不能为空");return{command:s[0],args:s.slice(1)}}function xr(r){if(r.length>=2){const t=r[0],s=r[r.length-1];if(t==='"'&&s==='"'||t==="'"&&s==="'")return r.slice(1,-1)}return r}function Hs(r){const t={};for(const s of r.split(`
4
- `)){const n=s.trim();if(!n||n.startsWith("#"))continue;const a=n.indexOf("=");if(a>0){const i=n.slice(0,a).trim();let d=n.slice(a+1).trim();d=xr(d),t[i]=d;continue}const o=n.indexOf(":");if(o>0){const i=n.slice(0,o).trim();let d=n.slice(o+1).trim();d=xr(d),t[i]=d}}return t}function ii(r){const{command:t,args:s}=oi(r.command),n=Hs(r.env),a={command:t,args:s};return Object.keys(n).length>0&&(a.env=n),a}function ci(r){const t=Hs(r.headers),s={type:"streamable-http",url:r.url};return Object.keys(t).length>0&&(s.headers=t),s}function li(r){const t=Hs(r.headers),s={type:"sse",url:r.url};return Object.keys(t).length>0&&(s.headers=t),s}function Js(r){const{name:t,type:s}=r;let n;switch(s){case"stdio":n=ii(r);break;case"http":n=ci(r);break;case"sse":n=li(r);break;default:throw new Error("不支持的 MCP 类型")}return{name:t,config:n}}function di(r){return"command"in r?"stdio":"type"in r&&r.type==="sse"?"sse":"http"}function ui(r){const t=[r.command];return r.args&&r.args.length>0&&t.push(...r.args),t.join(" ")}function Xs(r){return!r||Object.keys(r).length===0?"":Object.entries(r).map(([t,s])=>`${t}: ${s}`).join(`
5
- `)}function mi(r,t){const s=t;return{type:"stdio",name:r,command:ui(s),env:Xs(s.env)}}function fi(r,t){const s=t;return{type:"http",name:r,url:s.url,headers:Xs(s.headers)}}function hi(r,t){const s=t;return{type:"sse",name:r,url:s.url,headers:Xs(s.headers)}}function $s(r,t){switch(di(t)){case"stdio":return mi(r,t);case"http":return fi(r,t);case"sse":return hi(r,t);default:throw new Error("无法识别的 MCP 类型")}}function la(r){try{const t=JSON.parse(r);if(t.mcpServers&&typeof t.mcpServers=="object"){const s=Object.entries(t.mcpServers);if(s.length===0)return null;const[n,a]=s[0];return $s(n,a)}if(typeof t=="object"&&t!==null&&("command"in t||"type"in t||"url"in t)){let s;return"command"in t&&t.command?s=t.command.split("/").pop()||"mcp-server":"type"in t&&t.type==="sse"?s="sse-server":s="http-server",$s(s,t)}return null}catch{return null}}function da(r){const{name:t,config:s}=Js(r);return JSON.stringify({mcpServers:{[t]:s}},null,2)}function pi(r,t){if(!t||typeof t!="object")return{valid:!1,error:`服务 "${r}" 的配置必须是一个对象`};const s=t,n="command"in s,a="type"in s,o="url"in s;if(n){if(!s.command||typeof s.command!="string")return{valid:!1,error:`服务 "${r}" 缺少必需的 command 字段或字段类型不正确`};if(!Array.isArray(s.args))return{valid:!1,error:`服务 "${r}" 的 args 字段必须是数组`}}else if(a&&s.type==="sse"){if(!s.url||typeof s.url!="string")return{valid:!1,error:`服务 "${r}" 缺少必需的 url 字段或字段类型不正确`}}else if(o){if(!s.url||typeof s.url!="string")return{valid:!1,error:`服务 "${r}" 缺少必需的 url 字段或字段类型不正确`}}else return{valid:!1,error:`服务 "${r}" 的配置无效: 必须包含 command 字段(stdio)、type: 'sse' 字段(sse)或 url 字段(streamable-http)`};return{valid:!0}}function ua(r){try{const t=r.trim();if(!t)return{success:!1,error:"配置不能为空"};const s=JSON.parse(t);let n;if(s.mcpServers&&typeof s.mcpServers=="object")n=s.mcpServers;else if(typeof s=="object"&&!Array.isArray(s)){const a="command"in s,o="type"in s,i="url"in s;if(a||o||i)n={[a?String(s.command).split("/").pop()||"mcp-server":o&&s.type==="sse"?"sse-server":"http-server"]:s};else return{success:!1,error:"配置格式错误: 必须是对象格式"}}else return{success:!1,error:"配置格式错误: 必须是对象格式"};for(const[a,o]of Object.entries(n)){const i=pi(a,o);if(!i.valid)return{success:!1,error:i.error}}return{success:!0,data:n}}catch(t){return{success:!1,error:`JSON 格式错误: ${t instanceof Error?t.message:"无法解析 JSON"}`}}}const xi=_.object({config:_.string().min(2,{message:"配置不能为空"})});function gi(){const[r,t]=l.useState(!1),[s,n]=l.useState(!1),[a,o]=l.useState("form"),[i,d]=l.useState(""),u=Ee({resolver:Re(Gs),defaultValues:{type:"stdio",name:"",command:"",env:""}}),m=Ee({resolver:Re(xi),defaultValues:{config:""}}),c=l.useCallback(v=>{v||(u.reset(),m.reset(),d(""),o("form")),t(v)},[u,m]),p=l.useCallback(v=>{if(!(v!=="form"&&v!=="json")){if(v==="json"&&a==="form"){const g=u.getValues();try{d(da(g))}catch{d("")}}else if(v==="form"&&a==="json"){const g=la(i);g&&u.reset(g)}o(v)}},[a,u,i]),h=l.useCallback(async v=>{n(!0);try{const{name:g,config:N}=Js(v);if((await z.listMCPServers()).servers.some(y=>y.name===g)){O.error(`服务名称 "${g}" 已存在`);return}if(!await z.addMCPServer(g,N))throw new Error("添加服务器失败");O.success(`已添加 MCP 服务 "${g}"`),u.reset(),t(!1)}catch(g){console.error("更新配置失败:",g),O.error(g instanceof Error?g.message:"更新配置失败")}finally{n(!1)}},[u]),x=l.useCallback(async v=>{n(!0);try{const g=ua(v.config);if(!g.success){O.error(g.error||"配置验证失败");return}const N=g.data,k=await z.listMCPServers(),j=Object.keys(N).filter(T=>k.servers.some(E=>E.name===T));if(j.length>0){O.error(`服务名称冲突: 以下服务已存在: ${j.join(", ")}`);return}for(const[T,E]of Object.entries(N))if(!await z.addMCPServer(T,E))throw new Error("添加服务器失败");const y=Object.keys(N).length;O.success(y===1?`已添加 MCP 服务 "${Object.keys(N)[0]}"`:`已添加 ${y} 个 MCP 服务`),m.reset(),t(!1)}catch(g){console.error("更新配置失败:",g),O.error(g instanceof Error?g.message:"更新配置失败")}finally{n(!1)}},[m]);return e.jsxs(me,{open:r,onOpenChange:c,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8","aria-label":"添加MCP服务",title:"添加MCP服务",children:e.jsx(Qe,{className:"size-4"})})}),e.jsxs(le,{className:"sm:max-w-[600px]",children:[e.jsxs(de,{className:"mb-4",children:[e.jsx(ue,{children:"添加MCP服务"}),e.jsx(we,{children:"添加后,需要重启服务才会生效。"})]}),e.jsxs(Ye,{value:a,onValueChange:p,children:[e.jsxs(rt,{className:"grid w-full grid-cols-2",children:[e.jsx(be,{value:"form",children:"表单模式"}),e.jsx(be,{value:"json",children:"高级模式"})]}),e.jsx(Se,{value:"form",className:"mt-4",children:e.jsx(ca,{form:u,onSubmit:h,disabled:s,submitText:s?"保存中...":"保存配置"})}),e.jsx(Se,{value:"json",className:"mt-4",children:e.jsx(qe,{...m,children:e.jsxs("form",{onSubmit:m.handleSubmit(x),children:[e.jsx("div",{className:"grid gap-4",children:e.jsx(K,{control:m.control,name:"config",render:({field:v})=>e.jsxs(J,{children:[e.jsx(H,{children:e.jsx(He,{className:"resize-none h-[300px] font-mono text-sm",disabled:s,placeholder:`支持三种通信方式:
6
-
7
- 1. 本地进程 (stdio):
8
- {
9
- "mcpServers": {
10
- "local-server": {
11
- "command": "npx",
12
- "args": ["-y", "@example/mcp-server"]
13
- }
14
- }
15
- }
16
-
17
- 2. 服务器推送 (SSE):
18
- {
19
- "mcpServers": {
20
- "sse-server": {
21
- "type": "sse",
22
- "url": "https://example.com/sse"
23
- }
24
- }
25
- }
26
-
27
- 3. 流式 HTTP:
28
- {
29
- "mcpServers": {
30
- "http-server": {
31
- "url": "https://example.com/mcp"
32
- }
33
- }
34
- }`,...v,onChange:g=>{v.onChange(g),d(g.target.value)}})}),e.jsx(Y,{})]})})}),e.jsxs(ke,{className:"mt-4",children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s,children:s?"保存中...":"保存"})]})]})})})]})]})]})}const Ks=l.createContext({size:"default"}),vi=Ae("w-full caption-bottom text-sm",{variants:{size:{default:"text-sm",compact:"text-xs"}},defaultVariants:{size:"default"}}),ji=Ae("text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",{variants:{size:{default:"h-12 px-4",compact:"h-10 p-4"}},defaultVariants:{size:"default"}}),bi=Ae("align-middle [&:has([role=checkbox])]:pr-0",{variants:{size:{default:"p-4",compact:"py-2 px-4"}},defaultVariants:{size:"default"}}),Tt=l.forwardRef(({className:r,size:t,children:s,...n},a)=>{const o=t??"default";return e.jsx(Ks.Provider,{value:{size:o},children:e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:a,className:I(vi({size:o,className:r})),...n,children:s})})})});Tt.displayName="Table";const kt=l.forwardRef(({className:r,...t},s)=>e.jsx("thead",{ref:s,className:I("[&_tr]:border-b",r),...t}));kt.displayName="TableHeader";const It=l.forwardRef(({className:r,...t},s)=>e.jsx("tbody",{ref:s,className:I("[&_tr:last-child]:border-0",r),...t}));It.displayName="TableBody";const Si=l.forwardRef(({className:r,...t},s)=>e.jsx("tfoot",{ref:s,className:I("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",r),...t}));Si.displayName="TableFooter";const Le=l.forwardRef(({className:r,...t},s)=>e.jsx("tr",{ref:s,className:I("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",r),...t}));Le.displayName="TableRow";const se=l.forwardRef(({className:r,...t},s)=>{const{size:n}=l.useContext(Ks);return e.jsx("th",{ref:s,className:I(ji({size:n,className:r})),...t})});se.displayName="TableHead";const re=l.forwardRef(({className:r,...t},s)=>{const{size:n}=l.useContext(Ks);return e.jsx("td",{ref:s,className:I(bi({size:n,className:r})),...t})});re.displayName="TableCell";const wi=l.forwardRef(({className:r,...t},s)=>e.jsx("caption",{ref:s,className:I("mt-4 text-sm text-muted-foreground",r),...t}));wi.displayName="TableCaption";const Ni={stdio:"本地进程",sse:"服务器推送","streamable-http":"流式 HTTP"};function yi(r){return Ni[r]}function Ci(r){const[t,s]=l.useState(""),n=Array.isArray(r)?r:[],a=l.useMemo(()=>{if(!t.trim())return n;const i=t.toLowerCase();return n.filter(d=>{const u=(d?.name?.toLowerCase()||"").includes(i),m=(d?.communicationType?.toLowerCase()||"").includes(i),c=d?.communicationType?yi(d.communicationType).toLowerCase().includes(i):!1;return u||m||c})},[n,t]),o=l.useCallback(()=>{s("")},[]);return{searchValue:t,setSearchValue:s,filteredServers:a,clearSearch:o}}function ma(r){const{storageKey:t,defaultConfig:s,validFields:n,loggerName:a}=r,[o,i]=l.useState(()=>{if(typeof window<"u")try{const d=localStorage.getItem(t);if(d){const u=JSON.parse(d);if(u&&n.includes(u.field))return u;console.warn(`[${a}] 无效的排序字段,使用默认配置`)}}catch(d){console.warn(`[${a}] 读取排序配置失败:`,d)}return s});return l.useEffect(()=>{if(typeof window<"u")try{localStorage.setItem(t,JSON.stringify(o))}catch(d){console.warn(`[${a}] 保存排序配置失败:`,d)}},[o,t]),{sortConfig:o,setSortConfig:i}}const Ei=["name","communicationType","toolCount"];function Ri(){return ma({storageKey:"mcp-server-sort-config",defaultConfig:{field:"name"},validFields:Ei,loggerName:"useServerSortPersistence"})}function fa(r,t=10){const[s,n]=l.useState(1),[a,o]=l.useState(t),i=Array.isArray(r)?r:[],d=l.useMemo(()=>Math.ceil(i.length/a)||1,[i.length,a]),u=l.useMemo(()=>{const h=(s-1)*a,x=h+a;return i.slice(h,x)},[i,s,a]),m=l.useCallback(h=>{n(Math.max(1,Math.min(h,d)))},[d]),c=l.useCallback(h=>{o(h),n(1)},[]),p=l.useCallback(()=>{n(1)},[]);return{currentPage:s,pageSize:a,totalPages:d,paginatedTools:u,setPage:m,setPageSize:c,resetPage:p}}const Ti=_.object({config:_.string().min(2,{message:"配置不能为空"})});function ki({mcpServer:r,mcpServerName:t}){const[s,n]=l.useState(!1),[a,o]=l.useState(!1),[i,d]=l.useState("form"),[u,m]=l.useState(""),c=We(),{updateConfig:p}=_s(),h=$s(t,r),x=Ee({resolver:Re(Gs),defaultValues:h}),v=Ee({resolver:Re(Ti),defaultValues:{config:JSON.stringify({mcpServers:{[t]:r}},null,2)}}),g=l.useCallback(y=>{y||(x.reset(h),v.reset(),m(""),d("form")),n(y)},[x,v,h]),N=l.useCallback(y=>{if(!(y!=="form"&&y!=="json")){if(y==="json"&&i==="form"){const T=x.getValues();try{m(da(T))}catch{m("")}}else if(y==="form"&&i==="json"){const T=la(u);T&&x.reset(T)}d(y)}},[i,x,u]),k=l.useCallback(async y=>{if(!c){O.error("配置数据未加载,请稍后重试");return}o(!0);try{const{name:T,config:E}=Js(y);let $={...c};if(T!==t){const{[t]:D,...W}=$.mcpServers;$.mcpServers=W}$={...$,mcpServers:{...$.mcpServers,[T]:E}},await p($);const M=T!==t;O.success(M?`MCP 服务 "${t}" 已重命名为 "${T}"`:`MCP 服务 "${T}" 配置已更新`),n(!1)}catch(T){console.error("更新配置失败:",T),O.error(T instanceof Error?T.message:"更新配置失败")}finally{o(!1)}},[c,t,p]),j=l.useCallback(async y=>{if(!c){O.error("配置数据未加载,请稍后重试");return}o(!0);try{const T=ua(y.config);if(!T.success){O.error(T.error||"配置验证失败");return}const E=T.data,$=Object.entries(E);if($.length!==1){O.error("编辑模式只能修改单个 MCP 服务配置");return}const[M,D]=$[0];let W={...c};if(M!==t){const{[t]:X,...L}=W.mcpServers;W.mcpServers=L}W={...W,mcpServers:{...W.mcpServers,[M]:D}},await p(W);const U=M!==t;O.success(U?`MCP 服务 "${t}" 已重命名为 "${M}"`:`MCP 服务 "${M}" 配置已更新`),n(!1)}catch(T){console.error("更新配置失败:",T),O.error(T instanceof Error?T.message:"更新配置失败")}finally{o(!1)}},[c,t,p]);return e.jsxs(me,{open:s,onOpenChange:g,children:[e.jsx(Te,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 hover:cursor-pointer hover:text-primary transition-all duration-100",children:[e.jsx(Ze,{size:14}),e.jsx("span",{children:"配置"})]})}),e.jsxs(le,{className:"sm:max-w-[600px]",children:[e.jsxs(de,{className:"mb-4",children:[e.jsxs(ue,{children:["配置 ",t," MCP"]}),e.jsx(we,{children:"点击保存后,需要重启服务才会生效。"})]}),e.jsxs(Ye,{value:i,onValueChange:N,children:[e.jsxs(rt,{className:"grid w-full grid-cols-2",children:[e.jsx(be,{value:"form",children:"表单模式"}),e.jsx(be,{value:"json",children:"高级模式 (JSON)"})]}),e.jsx(Se,{value:"form",className:"mt-4",children:e.jsx(ca,{form:x,defaultValues:h,onSubmit:k,disabled:a,submitText:a?"保存中...":"保存"})}),e.jsx(Se,{value:"json",className:"mt-4",children:e.jsx(qe,{...v,children:e.jsxs("form",{onSubmit:v.handleSubmit(j),children:[e.jsx("div",{className:"grid gap-4",children:e.jsx(K,{control:v.control,name:"config",render:({field:y})=>e.jsxs(J,{children:[e.jsx(H,{children:e.jsx(He,{className:"resize-none h-[300px] font-mono text-sm",disabled:a,placeholder:`支持三种通信方式:
35
-
36
- 1. 本地进程 (stdio):
37
- {
38
- "mcpServers": {
39
- "local-server": {
40
- "command": "npx",
41
- "args": ["-y", "@example/mcp-server"]
42
- }
43
- }
44
- }
45
-
46
- 2. 服务器推送 (SSE):
47
- {
48
- "mcpServers": {
49
- "sse-server": {
50
- "type": "sse",
51
- "url": "https://example.com/sse"
52
- }
53
- }
54
- }
55
-
56
- 3. 流式 HTTP:
57
- {
58
- "mcpServers": {
59
- "http-server": {
60
- "url": "https://example.com/mcp"
61
- }
62
- }
63
- }`,...y,onChange:T=>{y.onChange(T),m(T.target.value)}})}),e.jsx(Y,{})]})})}),e.jsxs(ke,{className:"mt-4",children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:a,children:"取消"})}),e.jsx(A,{type:"submit",disabled:a,children:a?"保存中...":"保存"})]})]})})})]})]})]})}function Ii({mcpServerName:r,onRemoveSuccess:t,disabled:s=!1}){const[n,a]=l.useState(!1),o=async()=>{try{if(a(!0),!await z.removeMCPServer(r))throw new Error("删除服务器失败");O.success(`MCP 服务 "${r}" 已删除`),t&&await t()}catch(i){console.error("删除 MCP 服务失败:",i),O.error(`删除 MCP 服务失败: ${i instanceof Error?i.message:"未知错误"}`)}finally{a(!1)}};return e.jsxs(Vs,{children:[e.jsx(Oo,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:s||n,className:I("flex items-center gap-1 hover:cursor-pointer text-destructive hover:text-red-700 transition-all duration-100",(s||n)&&"opacity-50 cursor-not-allowed"),children:[e.jsx(En,{size:14}),e.jsx("span",{children:"卸载"})]})}),e.jsxs(bt,{children:[e.jsxs(St,{children:[e.jsxs(Nt,{children:["确定要删除这个(",r,")MCP服务吗?"]}),e.jsx(yt,{children:"删除后,对应的工具列表也会移除。"})]}),e.jsxs(wt,{children:[e.jsx(Et,{children:"取消"}),e.jsx(Ct,{onClick:o,disabled:s||n,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:n?"删除中...":"确定"})]})]})]})}const ha=({className:r,...t})=>e.jsx("nav",{"aria-label":"pagination",className:I("mx-auto flex w-full justify-center",r),...t});ha.displayName="Pagination";const pa=l.forwardRef(({className:r,...t},s)=>e.jsx("ul",{ref:s,className:I("flex flex-row items-center gap-1",r),...t}));pa.displayName="PaginationContent";const ze=l.forwardRef(({className:r,...t},s)=>e.jsx("li",{ref:s,className:I("",r),...t}));ze.displayName="PaginationItem";const $t=({className:r,isActive:t,size:s="icon",...n})=>e.jsx("a",{"aria-current":t?"page":void 0,className:I(jt({variant:t?"outline":"ghost",size:s}),r),...n});$t.displayName="PaginationLink";const xa=({className:r,...t})=>e.jsxs($t,{"aria-label":"Go to previous page",size:"default",className:I("gap-1 pl-2.5",r),...t,children:[e.jsx(Xa,{className:"h-4 w-4"}),e.jsx("span",{children:"上一页"})]});xa.displayName="PaginationPrevious";const ga=({className:r,...t})=>e.jsxs($t,{"aria-label":"Go to next page",size:"default",className:I("gap-1 pr-2.5",r),...t,children:[e.jsx("span",{children:"下一页"}),e.jsx(Ya,{className:"h-4 w-4"})]});ga.displayName="PaginationNext";const Ps=({className:r,...t})=>e.jsxs("span",{"aria-hidden":!0,className:I("flex h-9 w-9 items-center justify-center",r),...t,children:[e.jsx(Ka,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"更多页"})]});Ps.displayName="PaginationEllipsis";function $i(r,t){const s=[];if(t<=7)for(let a=1;a<=t;a++)s.push(a);else if(r<=4){for(let a=1;a<=5;a++)s.push(a);s.push(-2,t)}else if(r>=t-3){s.push(1,-1);for(let a=t-3;a<=t;a++)s.push(a)}else s.push(1,-1,r-1,r,r+1,-2,t);return s}function va({currentPage:r,totalPages:t,setPage:s}){const n=l.useMemo(()=>$i(r,t),[r,t]);return t>1?e.jsx("div",{className:"flex items-end justify-start py-4",children:e.jsx(ha,{children:e.jsxs(pa,{children:[e.jsx(ze,{children:e.jsx(xa,{onClick:()=>s(r-1),className:I("cursor-pointer",r===1&&"pointer-events-none opacity-50")})}),n.map(o=>o===-1?e.jsx(ze,{children:e.jsx(Ps,{})},"ellipsis-start"):o===-2?e.jsx(ze,{children:e.jsx(Ps,{})},"ellipsis-end"):e.jsx(ze,{children:e.jsx($t,{onClick:()=>s(o),isActive:r===o,className:"cursor-pointer",children:o})},`page-${o}`)),e.jsx(ze,{children:e.jsx(ga,{onClick:()=>s(r+1),className:I("cursor-pointer",r===t&&"pointer-events-none opacity-50")})})]})})}):null}function ja({value:r,onChange:t,placeholder:s="搜索服务名、工具名、描述...",className:n}){const a=l.useRef(null),o=d=>{t(d.target.value)},i=()=>{t(""),a.current?.focus()};return e.jsx("div",{className:I("relative",n),children:e.jsxs("div",{className:"relative flex items-center",children:[e.jsx(Za,{className:"absolute left-3 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(te,{ref:a,type:"text",value:r,onChange:o,placeholder:s,className:"pl-9 pr-9 w-64","aria-label":"搜索工具"}),r&&e.jsx("button",{type:"button",onClick:i,className:"absolute right-3 text-muted-foreground hover:text-foreground transition-colors","aria-label":"清除搜索",children:e.jsx(Nn,{className:"h-4 w-4"})})]})})}const Pi=[{value:"name",label:"按名称排序"},{value:"communicationType",label:"按通信类型排序"},{value:"toolCount",label:"按工具数量排序"}];function Oi({value:r,onChange:t}){return e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ne,{value:r.field,onValueChange:s=>t({field:s}),children:[e.jsx(xe,{id:"server-sort-field",className:"w-40",children:e.jsx(ye,{})}),e.jsx(ge,{children:Pi.map(s=>e.jsx(ne,{value:s.value,children:s.label},s.value))})]})})}function Li({status:r}){const t={connected:"bg-green-500",disconnected:"bg-red-500",connecting:"bg-yellow-500",error:"bg-gray-500"},s={connected:"已连接",disconnected:"未连接",connecting:"连接中",error:"错误"};return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:I("flex size-2 rounded-full",t[r]),title:s[r]}),s[r]]})}function Ai(r,t,s,n,a){return{name:r,config:t,communicationType:s,toolCount:n,status:a}}function Di(r){return"command"in r&&typeof r.command=="string"?"stdio":"type"in r&&r.type==="sse"?"sse":"streamable-http"}const Mi={stdio:"stdio",sse:"sse","streamable-http":"http"};function qi({className:r}){const{servers:t,loading:s,refresh:n}=Yn(),{sortConfig:a,setSortConfig:o}=Ri();l.useEffect(()=>{n()},[n]);const i=l.useMemo(()=>t.map(j=>Ai(j.name,j.config,Di(j.config),j.tools.length,j.status)),[t]),d=l.useMemo(()=>{const j=[...i],{field:y}=a;return j.sort((T,E)=>{switch(y){case"name":return T.name.localeCompare(E.name,"zh-CN");case"communicationType":return T.communicationType.localeCompare(E.communicationType);case"toolCount":return(E.toolCount??0)-(T.toolCount??0);default:return 0}}),j},[i,a]),{searchValue:u,setSearchValue:m,filteredServers:c,clearSearch:p}=Ci(d),{currentPage:h,totalPages:x,paginatedTools:v,setPage:g}=fa(c,10),N=v,k=l.useCallback(async()=>{try{await n(),O.success("刷新成功")}catch{O.error("刷新失败")}},[n]);return l.useEffect(()=>{g(1)},[u,g]),e.jsxs("div",{className:I("flex flex-col gap-4 w-full",r),children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(Oi,{value:a,onChange:o}),e.jsx(ja,{value:u,onChange:m,placeholder:"搜索服务器名称、通信类型..."})]}),u&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["找到 ",c.length," 个结果",c.length>0&&e.jsx("button",{type:"button",onClick:p,className:"ml-2 text-primary hover:underline",children:"清除搜索"})]}),e.jsx("div",{className:"rounded-md border",children:N.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx(qn,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:u?"没有找到匹配的服务器":"暂无可用服务器"}),u&&e.jsx(A,{variant:"outline",size:"sm",onClick:p,children:"清除搜索"})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Tt,{size:"compact",children:[e.jsx(kt,{children:e.jsxs(Le,{children:[e.jsx(se,{children:"服务器名称"}),e.jsx(se,{className:"w-[100px]",children:"状态"}),e.jsx(se,{className:"w-[120px]",children:"通信类型"}),e.jsx(se,{className:"w-[100px] text-right",children:"工具数量"}),e.jsx(se,{className:"w-[220px] text-right",children:"操作"})]})}),e.jsx(It,{children:N.map(j=>e.jsxs(Le,{children:[e.jsx(re,{className:"font-medium",children:j.name}),e.jsx(re,{children:j.status?e.jsx(Li,{status:j.status}):"-"}),e.jsx(re,{children:e.jsx(pe,{variant:"secondary",className:"rounded-md",children:Mi[j.communicationType]})}),e.jsx(re,{className:"text-right text-muted-foreground",children:j.toolCount??"-"}),e.jsx(re,{children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(ki,{mcpServerName:j.name,mcpServer:j.config}),e.jsx(Ii,{mcpServerName:j.name,onRemoveSuccess:k,disabled:s})]})})]},j.name))})]}),e.jsx(va,{currentPage:h,totalPages:x,setPage:g})]})})]})}function Fi(){const[r,t]=l.useState(!1);return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8","aria-label":"MCP服务列表",title:"MCP服务列表",children:e.jsx(Qa,{className:"size-4"})})}),e.jsxs(le,{className:"max-w-5xl max-h-[85vh]",children:[e.jsx(de,{children:e.jsx(ue,{children:"MCP 服务器列表"})}),e.jsx(qi,{})]})]})}const Ie=l.forwardRef(({className:r,children:t,...s},n)=>e.jsx("div",{ref:n,className:I("relative overflow-auto",r),...s,children:t}));Ie.displayName="ScrollArea";const zi=l.forwardRef(({className:r,orientation:t="vertical",...s},n)=>e.jsx("div",{ref:n,className:I("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 w-full border-t border-t-transparent p-[1px]",r),...s,children:e.jsx("div",{className:"relative flex-1 rounded-full bg-border"})}));zi.displayName="ScrollBar";const ht=l.forwardRef(({className:r,orientation:t="horizontal",decorative:s=!0,...n},a)=>e.jsx(Fn,{ref:a,decorative:s,orientation:t,className:I("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",r),...n}));ht.displayName=Fn.displayName;const ba=r=>r?new Date(r).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):"未知时间",Sa=r=>r?r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`:"-",Ui=(r,t)=>{const s=r.timestamp||Date.now();return`${r.toolName}-${s}-${t}`},ct=r=>{if(!r)return null;try{return JSON.stringify(r,null,2)}catch{return String(r)}};function Vi(){const[r,t]=l.useState(!1),[s,n]=l.useState([]),[a,o]=l.useState(!1),[i,d]=l.useState(!1),[u,m]=l.useState(null),[c,p]=l.useState(null),[h,x]=l.useState(null),[v]=l.useState(50),[g,N]=l.useState(0),k=l.useCallback(async(E=!1)=>{E?d(!0):o(!0),m(null);try{const M=await(await fetch(`/api/tool-calls/logs?limit=${v}`)).json();M.success&&M.data?(n(M.data.records),N(M.data.total)):m(M.error?.message||"获取日志失败")}catch($){m("网络请求失败"),console.error("获取工具调用日志失败:",$)}finally{E?d(!1):o(!1)}},[v]);l.useEffect(()=>{r?k():(p(null),x(null))},[r,k]);const j=(E,$)=>{h!==$&&(p(E),x($))},y=()=>{},T=()=>{p(null),x(null)};return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8","aria-label":"MCP工具调用日志",title:"MCP工具调用日志",children:e.jsx(Ke,{className:"size-4"})})}),e.jsxs(le,{className:"max-w-6xl max-h-[80vh]",onMouseLeave:T,children:[e.jsx(de,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ke,{className:"h-5 w-5"}),"MCP 工具调用日志",g>0&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground ml-2",children:["(共 ",g," 条记录)"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>k(!0),disabled:i,children:[e.jsx(eo,{className:`h-4 w-4 ${i?"animate-spin":""}`}),"刷新"]})]})})}),e.jsxs("div",{className:"flex-1 flex gap-4",children:[e.jsx("div",{className:"flex-1",children:a?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fe,{className:"h-8 w-8 animate-spin text-muted-foreground"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(Ke,{className:"h-4 w-4 text-muted-foreground/50"})})]}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-muted-foreground font-medium",children:"正在加载日志数据"}),e.jsx("p",{className:"text-muted-foreground/70 text-sm mt-1",children:"请稍候片刻..."})]})]}):u?e.jsx("div",{className:"text-center py-8",children:e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-6 max-w-md mx-auto",children:[e.jsx(qs,{className:"h-12 w-12 text-destructive mx-auto mb-4"}),e.jsx("h3",{className:"text-destructive font-semibold text-lg mb-2",children:"加载失败"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4 leading-relaxed",children:u}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(A,{onClick:()=>k(),variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),"重试加载"]}),e.jsx(A,{onClick:()=>k(!0),variant:"ghost",size:"sm",className:"text-xs",children:"强制刷新"})]})]})}):s.length===0?e.jsx("div",{className:"text-center py-8",children:e.jsxs("div",{className:"bg-muted/30 border border-muted rounded-lg p-6 max-w-md mx-auto",children:[e.jsx(Ke,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"font-medium text-lg mb-2",children:"暂无工具调用记录"}),e.jsx("p",{className:"text-muted-foreground text-sm leading-relaxed mb-4",children:"当前还没有任何工具调用记录。当您开始使用工具时,相关的调用信息会在这里显示。"}),e.jsxs(A,{onClick:()=>k(!0),variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),"检查更新"]})]})}):e.jsx(Ie,{className:"h-[60vh]",children:e.jsxs(Tt,{children:[e.jsx(kt,{children:e.jsxs(Le,{children:[e.jsx(se,{children:"工具名称"}),e.jsx(se,{children:"服务器"}),e.jsx(se,{children:"状态"}),e.jsx(se,{children:"耗时"}),e.jsx(se,{children:"时间"})]})}),e.jsx(It,{children:s.map((E,$)=>e.jsxs(Le,{className:`cursor-pointer transition-colors ${h===$?"bg-muted/50":"hover:bg-muted/30"}`,onMouseEnter:()=>j(E,$),children:[e.jsx(re,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("div",{children:E.toolName}),E.originalToolName&&E.originalToolName!==E.toolName&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["原始: ",E.originalToolName]})]})}),e.jsx(re,{children:E.serverName||e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(re,{children:e.jsx(pe,{variant:E.success?void 0:"destructive",className:`gap-1 w-[50px] text-center ${E.success?"bg-green-600 hover:bg-green-600":"bg-red-600 hover:bg-red-600"}`,children:E.success?"成功":"失败"})}),e.jsx(re,{children:Sa(E.duration)}),e.jsx(re,{className:"text-muted-foreground text-sm",children:ba(E.timestamp)})]},Ui(E,$)))})]})})}),c&&e.jsx("div",{className:"w-96 border-l pl-4",onMouseEnter:y,children:e.jsx(_i,{log:c})})]})]})]})}function lt({size:r="sm",copyContent:t,className:s=""}){const[n,a]=l.useState(!1),o=l.useRef(null),i=async()=>{try{await navigator.clipboard.writeText(t),a(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a(!1)},3e3)}catch(d){console.error("复制失败:",d)}};return l.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]),e.jsx(A,{variant:"ghost",size:r,className:`${s} ${n?"text-green-600 hover:text-green-700":""}`,onClick:i,children:n?e.jsx(vt,{}):e.jsx(xt,{})})}function _i({log:r}){const t=s=>{try{return JSON.stringify(s,null,2)}catch{return String(s)}};return e.jsx(Pe,{className:"h-[60vh]",children:e.jsxs("div",{className:"p-4 h-full flex flex-col",children:[e.jsxs(Ye,{defaultValue:"arguments",className:"flex-1 flex flex-col min-h-0",children:[e.jsxs(rt,{className:"grid w-full grid-cols-3 flex-shrink-0",children:[e.jsx(be,{value:"arguments",children:"入参"}),e.jsx(be,{value:"result",children:"出参"}),e.jsx(be,{value:"raw",children:"原始数据"})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx(Se,{value:"arguments",className:"h-full data-[state=active]:flex data-[state=active]:flex-col",children:e.jsx(Ie,{className:"h-full",children:r.arguments?e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto text-wrap break-words",children:ct(r.arguments)}),e.jsx(lt,{copyContent:ct(r.arguments)||"",className:"absolute top-2 right-2 hover:bg-slate-200 w-[30px] h-[30px]"})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-8",children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"无入参"})]})})}),e.jsx(Se,{value:"result",className:"h-full data-[state=active]:flex data-[state=active]:flex-col",children:e.jsx(Ie,{className:"h-full",children:r.success?r.result?e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto text-wrap break-words",children:ct(r.result)}),e.jsx(lt,{copyContent:ct(r.result)||"",className:"absolute top-2 right-2 hover:bg-slate-200 w-[30px] h-[30px]"})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-8",children:[e.jsx(Is,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"无出参"})]}):e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 p-3 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qs,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"font-medium text-destructive",children:"调用失败"})]}),r.error&&e.jsx("pre",{className:"text-xs text-destructive/80 whitespace-pre-wrap",children:r.error})]}),r.error&&e.jsx(lt,{copyContent:r.error||"",className:"absolute top-2 right-2"})]})})}),e.jsx(Se,{value:"raw",className:"h-full data-[state=active]:flex data-[state=active]:flex-col",children:e.jsx(Ie,{className:"h-full",children:e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto text-wrap break-words",children:t(r)}),e.jsx(lt,{copyContent:t(r),className:"absolute top-2 right-2 hover:bg-slate-200 w-[30px] h-[30px]"})]})})})]})]}),e.jsx(ht,{className:"my-4 flex-shrink-0"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex justify-between flex-shrink-0",children:[e.jsxs("span",{children:["耗时: ",Sa(r.duration)]}),e.jsx("span",{children:ba(r.timestamp)})]})]})})}function Wi(){const{servers:r}=Yn(),t=r.length,s=r.filter(n=>n.connected).length;return e.jsxs(Pe,{className:"@container/card",children:[e.jsxs(De,{className:"relative",children:[e.jsx(Be,{children:"MCP服务"}),e.jsxs(Me,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:[s,"/",t]}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(tt,{showValue:!1,value:s,maxValue:Math.max(t,1),activeColor:"#16a34a",inactiveColor:"#f87171",size:30,symbol:""})})]}),e.jsxs(Ge,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsxs("div",{className:"text-muted-foreground",children:["已连接 ",s," 个,共 ",t," 个服务"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(gi,{}),e.jsx(Fi,{}),e.jsx(Vi,{})]})]})]})}function Bi({disabled:r=!1,variant:t="outline",className:s="",restartingText:n="重启中...",defaultText:a="重启服务",iconMode:o=!1}){const{loading:{isRestarting:i},restartService:d}=Ce(),u=Hn(),m=async()=>{try{await d()}catch(p){console.error("[RestartButton] 重启失败:",p)}},c=()=>i?u.enabled&&u.startTime?"重连中...":n:a;return o?e.jsx(A,{type:"button",onClick:m,variant:"secondary",size:"icon",className:"size-8",disabled:i||r,"aria-label":"重启服务",title:"重启服务",children:i?e.jsx(fe,{className:"size-4 animate-spin"}):e.jsx(cr,{className:"size-4"})}):e.jsxs(A,{type:"button",onClick:m,variant:t,disabled:i||r,className:Bn("flex items-center gap-2 w-[120px]",s),children:[i?e.jsx(fe,{className:"size-4 animate-spin"}):e.jsx(cr,{className:"size-4"}),c()]})}const Gi=_.object({modelscope:_.object({apiKey:_.string().optional()}),platforms:_.object({coze:_.object({token:_.string().optional()})}),connection:_.object({heartbeatInterval:_.number().min(1e3,{message:"心跳间隔不能小于1000毫秒"}),heartbeatTimeout:_.number().min(1e3,{message:"心跳超时不能小于1000毫秒"}),reconnectInterval:_.number().min(1e3,{message:"重连间隔不能小于1000毫秒"})})});function Hi(){const[r,t]=l.useState(!1),[s,n]=l.useState(!1),a=We(),{updateConfig:o}=ra(),i=Ee({resolver:Re(Gi),defaultValues:{platforms:{coze:{token:a?.platforms?.coze?.token||""}},modelscope:{apiKey:a?.modelscope?.apiKey||""},connection:{heartbeatInterval:a?.connection?.heartbeatInterval||3e4,heartbeatTimeout:a?.connection?.heartbeatTimeout||1e4,reconnectInterval:a?.connection?.reconnectInterval||5e3}}});l.useEffect(()=>{i.reset({modelscope:{apiKey:a?.modelscope?.apiKey||""},connection:{heartbeatInterval:a?.connection?.heartbeatInterval||3e4,heartbeatTimeout:a?.connection?.heartbeatTimeout||1e4,reconnectInterval:a?.connection?.reconnectInterval||5e3}})},[a,i]);async function d(u){if(!a){O.error("配置数据未加载,请稍后重试");return}n(!0);try{const m={...a,modelscope:{apiKey:u.modelscope.apiKey},connection:{heartbeatInterval:u.connection.heartbeatInterval,heartbeatTimeout:u.connection.heartbeatTimeout,reconnectInterval:u.connection.reconnectInterval},platforms:{...a?.platforms??{},coze:{...a?.platforms?.coze??{},token:u.platforms.coze.token}}};await o(m),O.success("配置已更新"),t(!1)}catch(m){console.error("更新配置失败:",m),O.error(m instanceof Error?m.message:"更新配置失败")}finally{n(!1)}}return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ze,{className:"size-4"})})}),e.jsxs(le,{className:"sm:max-w-[600px]",children:[e.jsxs(de,{children:[e.jsx(ue,{children:"系统设置"}),e.jsx(we,{children:"配置平台认证和连接参数"})]}),e.jsx(qe,{...i,children:e.jsxs("form",{onSubmit:i.handleSubmit(d),children:[e.jsxs("div",{className:"grid gap-4 max-h-[60vh] overflow-y-auto",children:[e.jsx(K,{control:i.control,name:"modelscope.apiKey",render:({field:u})=>e.jsxs(J,{children:[e.jsx(ee,{children:"魔搭社区 API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{children:e.jsx(te,{placeholder:"魔搭社区 API Key",className:"font-mono text-sm",type:"password",disabled:s,autoComplete:"off","data-1p-ignore":!0,...u})}),e.jsx(A,{variant:"outline",type:"button",onClick:()=>{window.open("https://www.modelscope.cn/my/myaccesstoken","_blank")},children:"打开魔搭社区"})]}),e.jsx(Y,{})]})}),e.jsx(K,{control:i.control,name:"platforms.coze.token",render:({field:u})=>e.jsxs(J,{children:[e.jsx(ee,{children:"扣子身份凭证"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{children:e.jsx(te,{placeholder:"扣子身份凭证",className:"font-mono text-sm",type:"password",autoComplete:"off","data-1p-ignore":!0,disabled:s,...u})}),e.jsx(A,{variant:"outline",type:"button",onClick:()=>{window.open("https://www.coze.cn/open/oauth/sats","_blank")},children:"打开扣子平台"})]}),e.jsx(Y,{})]})}),e.jsx(K,{control:i.control,name:"connection.heartbeatInterval",render:({field:u})=>e.jsxs(J,{children:[e.jsx(ee,{children:"心跳间隔(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(H,{children:e.jsx(te,{placeholder:"心跳间隔(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...u,value:u.value||"",onChange:m=>{const c=m.target.value;u.onChange(c===""?"":Number(c))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(Y,{})]})}),e.jsx(K,{control:i.control,name:"connection.heartbeatTimeout",render:({field:u})=>e.jsxs(J,{children:[e.jsx(ee,{children:"心跳超时(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(H,{children:e.jsx(te,{placeholder:"心跳超时(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...u,value:u.value||"",onChange:m=>{const c=m.target.value;u.onChange(c===""?"":Number(c))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(Y,{})]})}),e.jsx(K,{control:i.control,name:"connection.reconnectInterval",render:({field:u})=>e.jsxs(J,{children:[e.jsx(ee,{children:"重连间隔(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(H,{children:e.jsx(te,{placeholder:"重连间隔(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...u,value:u.value||"",onChange:m=>{const c=m.target.value;u.onChange(c===""?"":Number(c))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(Y,{})]})})]}),e.jsxs(ke,{className:"mt-4",children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s,children:s?"保存中...":"保存"})]})]})})]})]})}const dt=5;function Ji(){const r=We(),t=l.useMemo(()=>{if(!r)return 0;let n=0;return r.modelscope?.apiKey&&n++,r.platforms?.coze?.token&&n++,r.connection?.heartbeatInterval&&n++,r.connection?.heartbeatTimeout&&n++,r.connection?.reconnectInterval&&n++,n},[r]),s=t/dt;return e.jsxs(Pe,{className:"@container/card",children:[e.jsxs(De,{className:"relative",children:[e.jsx(Be,{children:"系统设置"}),e.jsxs(Me,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:["已配置 ",t,"/",dt]}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(tt,{showValue:!0,value:t,maxValue:dt,activeColor:s>=.8?"#16a34a":s>=.5?"#f59e0b":"#f87171",inactiveColor:"#e5e7eb",size:30,symbol:""})})]}),e.jsxs(Ge,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:s===1?"配置已完成":s>=.6?`还差 ${dt-t} 项配置`:"请完善系统配置"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Bi,{iconMode:!0}),e.jsx(Hi,{})]})]})]})}const Xi=Ae("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Ve=l.forwardRef(({className:r,variant:t,...s},n)=>e.jsx("div",{ref:n,role:"alert",className:I(Xi({variant:t}),r),...s}));Ve.displayName="Alert";const wa=l.forwardRef(({className:r,...t},s)=>e.jsx("h5",{ref:s,className:I("mb-1 font-medium leading-none tracking-tight",r),...t}));wa.displayName="AlertTitle";const _e=l.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:I("text-sm [&_p]:leading-relaxed",r),...t}));_e.displayName="AlertDescription";function Ki({open:r,onOpenChange:t,selectedPath:s,onPromptUpdated:n,onPromptCreated:a,onPromptDeleted:o}){const[i,d]=l.useState("view"),[u,m]=l.useState(!1),[c,p]=l.useState(!1),[h,x]=l.useState(""),[v,g]=l.useState(""),[N,k]=l.useState(""),[j,y]=l.useState(null),T=l.useCallback(async U=>{m(!0),y(null);try{const X=await z.getPromptFileContent(U);x(X.content),g(X.content),k(X.fileName)}catch(X){y(X instanceof Error?X.message:"加载提示词文件失败")}finally{m(!1)}},[]);l.useEffect(()=>{r&&(i==="create"?(x(""),g(""),k(""),y(null)):s?T(s):(d("create"),x(""),g(""),k(""),y(null)))},[r,s,i,T]),l.useEffect(()=>{r||d("view")},[r]);const E=async()=>{if(i==="create"){if(!N.trim()){y("请输入文件名");return}if(!N.endsWith(".md")){y("文件名必须以 .md 结尾");return}}p(!0),y(null);try{if(i==="create"){const U=await z.createPromptFile(N,h);O.success("提示词文件创建成功"),a?.(U.relativePath),t(!1)}else s&&(await z.updatePromptFileContent(s,h),O.success("提示词文件保存成功"),g(h),n?.(),d("view"))}catch(U){y(U instanceof Error?U.message:"保存失败")}finally{p(!1)}},$=async()=>{if(s&&window.confirm(`确定要删除文件 "${N}" 吗?此操作无法撤销。`)){p(!0),y(null);try{await z.deletePromptFile(s),O.success("提示词文件删除成功"),o?.(),t(!1)}catch(U){y(U instanceof Error?U.message:"删除失败")}finally{p(!1)}}},M=h!==v,D=()=>{switch(i){case"create":return"新建提示词文件";case"edit":return"编辑提示词";default:return"查看提示词"}},W=()=>i==="create"?"创建一个新的系统提示词文件":s||"提示词文件";return e.jsx(me,{open:r,onOpenChange:t,children:e.jsxs(le,{className:"sm:max-w-[700px]",children:[e.jsxs(de,{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(Ke,{className:"size-5"}),D()]}),e.jsx(we,{children:W()})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[j&&e.jsxs(Ve,{variant:"destructive",children:[e.jsx(zn,{className:"size-4"}),e.jsx(_e,{children:j})]}),i==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ft,{htmlFor:"fileName",children:"文件名"}),e.jsx(te,{id:"fileName",placeholder:"例如:custom-prompt.md",value:N,onChange:U=>k(U.target.value),disabled:c})]}),u?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(fe,{className:"size-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"加载中..."})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ft,{htmlFor:"content",children:"提示词内容"}),e.jsx(He,{id:"content",placeholder:"请输入系统提示词内容...",className:"min-h-[300px] font-mono text-sm",value:h,onChange:U=>x(U.target.value),disabled:c||i==="view"&&!c})]})]}),e.jsxs(ke,{className:"gap-2 sm:gap-0",children:[i==="view"&&s&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{variant:"destructive",size:"sm",onClick:$,disabled:c,className:"mr-auto",children:[e.jsx(Un,{className:"size-4 mr-1"}),"删除"]}),e.jsx(A,{variant:"outline",onClick:()=>d("edit"),disabled:c,children:"编辑"}),e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"secondary",children:"关闭"})})]}),i==="edit"&&e.jsxs(e.Fragment,{children:[e.jsx(A,{variant:"outline",onClick:()=>{d("view"),x(v),y(null)},disabled:c,children:"取消"}),e.jsx(A,{onClick:E,disabled:c||!M,children:c?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"size-4 mr-1 animate-spin"}),"保存中..."]}):"保存"})]}),i==="create"&&e.jsxs(e.Fragment,{children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:c,children:"取消"})}),e.jsx(A,{onClick:E,disabled:c||!h.trim()||!N.trim(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"size-4 mr-1 animate-spin"}),"创建中..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"size-4 mr-1"}),"创建"]})})]})]})]})})}const mt=l.forwardRef(({className:r,showPassword:t,onShowPasswordChange:s,...n},a)=>{const[o,i]=l.useState(!1),d=t!==void 0,u=d?t:o,m=()=>{d&&s?s(!t):i(!o)};return e.jsxs("div",{className:"relative",children:[e.jsx(te,{type:u?"text":"password",className:I("pr-10",r),ref:a,...n}),e.jsxs(A,{type:"button",variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full px-3 hover:bg-transparent",onClick:m,"aria-label":u?"隐藏密码":"显示密码","aria-pressed":u,children:[u?e.jsx(to,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}):e.jsx(so,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:u?"隐藏密码":"显示密码"})]})]})});mt.displayName="PasswordInput";const Yi=_.object({asr:_.object({appid:_.string().optional(),accessToken:_.string().optional()}),llm:_.object({model:_.string().min(1,{message:"模型名称不能为空"}),apiKey:_.string().min(1,{message:"API 密钥不能为空"}),baseURL:_.string().url({message:"请输入有效的 URL"}),prompt:_.string().optional()}),tts:_.object({appid:_.string().optional(),accessToken:_.string().optional(),voice_type:_.string().optional()})});function Zi(){const[r,t]=l.useState(!1),[s,n]=l.useState(!1),[a,o]=l.useState([]),[i,d]=l.useState(!1),[u,m]=l.useState(!1),[c,p]=l.useState(void 0),[h,x]=l.useState([]),[v,g]=l.useState(!1),N=We(),{updateConfig:k}=ra(),j=Ee({resolver:Re(Yi),defaultValues:{asr:{appid:N?.asr?.appid||"",accessToken:N?.asr?.accessToken||""},llm:{model:N?.llm?.model||"",apiKey:N?.llm?.apiKey||"",baseURL:N?.llm?.baseURL||"",prompt:N?.llm?.prompt||""},tts:{appid:N?.tts?.appid||"",accessToken:N?.tts?.accessToken||"",voice_type:N?.tts?.voice_type||""}}}),y=l.useRef(!1);l.useEffect(()=>{r&&!y.current&&N&&(j.reset({asr:{appid:N.asr?.appid||"",accessToken:N.asr?.accessToken||""},llm:{model:N.llm?.model||"",apiKey:N.llm?.apiKey||"",baseURL:N.llm?.baseURL||"",prompt:N.llm?.prompt||""},tts:{appid:N.tts?.appid||"",accessToken:N.tts?.accessToken||"",voice_type:N.tts?.voice_type||""}}),y.current=!0),r||(y.current=!1,j.reset())},[r,N,j]);const T=l.useCallback(async()=>{d(!0);try{const L=await z.getPromptFiles();o(L)}catch(L){console.error("加载提示词文件列表失败:",L),o([])}finally{d(!1)}},[]),E=l.useCallback(async()=>{g(!0);try{const L=await z.getTTSVoices();x(L.voices)}catch(L){console.error("加载音色列表失败:",L),x([])}finally{g(!1)}},[]);l.useEffect(()=>{r&&(T(),E())},[r,T,E]);const $=l.useCallback(()=>{const L=j.getValues("llm.prompt");p(L&&L!=="__none__"?L:void 0),m(!0)},[j]),M=l.useCallback(()=>{p(void 0),m(!0)},[]),D=l.useCallback(()=>{T()},[T]),W=l.useCallback(L=>{T(),j.setValue("llm.prompt",L)},[T,j]),U=l.useCallback(()=>{T(),j.setValue("llm.prompt","")},[T,j]);async function X(L){if(!N){O.error("配置数据未加载,请稍后重试");return}n(!0);try{const F=L.asr.appid||L.asr.accessToken?{appid:L.asr.appid||void 0,accessToken:L.asr.accessToken||void 0}:{},b={model:L.llm.model,apiKey:L.llm.apiKey,baseURL:L.llm.baseURL,prompt:L.llm.prompt||void 0},w=L.tts.appid||L.tts.accessToken||L.tts.voice_type?{appid:L.tts.appid||void 0,accessToken:L.tts.accessToken||void 0,voice_type:L.tts.voice_type||void 0}:{},R={...N,asr:F,llm:b,tts:w};await k(R),O.success("语音交互配置已更新"),t(!1)}catch(F){console.error("更新语音交互配置失败:",F),O.error(F instanceof Error?F.message:"更新配置失败")}finally{n(!1)}}return e.jsxs(e.Fragment,{children:[e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(Te,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ze,{className:"size-4"})})}),e.jsxs(le,{className:"sm:max-w-[600px]",children:[e.jsxs(de,{children:[e.jsx(ue,{children:"语音交互设置"}),e.jsx(we,{children:"配置 ASR(语音识别)、LLM(大语言模型)、TTS(语音合成)服务"})]}),e.jsx(qe,{...j,children:e.jsxs("form",{onSubmit:j.handleSubmit(X),children:[e.jsxs("div",{className:"max-h-[60vh] overflow-y-auto pr-2",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground mb-3",children:"ASR 配置"}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(K,{control:j.control,name:"asr.appid",render:({field:L})=>e.jsxs(J,{children:[e.jsx(ee,{children:"应用 ID"}),e.jsx(H,{children:e.jsx(te,{placeholder:"请输入火山引擎语音识别应用 ID",className:"font-mono text-sm",disabled:s,...L})}),e.jsx(Y,{})]})}),e.jsx(K,{control:j.control,name:"asr.accessToken",render:({field:L})=>e.jsxs(J,{children:[e.jsx(ee,{children:"访问令牌"}),e.jsx(H,{children:e.jsx(mt,{placeholder:"请输入访问令牌",className:"font-mono text-sm",disabled:s,autoComplete:"off",...L})}),e.jsx(Y,{})]})})]})]}),e.jsx(ht,{className:"my-4"}),e.jsxs("div",{className:"mb-4",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground mb-3",children:"LLM 配置"}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(K,{control:j.control,name:"llm.model",render:({field:L})=>e.jsxs(J,{children:[e.jsxs(ee,{children:["模型名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(H,{children:e.jsx(te,{placeholder:"如:gpt-4、deepseek-chat",className:"font-mono text-sm",disabled:s,...L})}),e.jsx(Y,{})]})}),e.jsx(K,{control:j.control,name:"llm.apiKey",render:({field:L})=>e.jsxs(J,{children:[e.jsxs(ee,{children:["API 密钥 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(H,{children:e.jsx(mt,{placeholder:"请输入 API 密钥",className:"font-mono text-sm",disabled:s,autoComplete:"off",...L})}),e.jsx(Y,{})]})}),e.jsx(K,{control:j.control,name:"llm.baseURL",render:({field:L})=>e.jsxs(J,{children:[e.jsxs(ee,{children:["API 基础地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(H,{children:e.jsx(te,{placeholder:"如:https://api.openai.com/v1",className:"font-mono text-sm",disabled:s,...L})}),e.jsx(Y,{})]})}),e.jsx(K,{control:j.control,name:"llm.prompt",render:({field:L})=>e.jsxs(J,{children:[e.jsx(ee,{children:"系统提示词文件"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{children:e.jsxs(Ne,{disabled:s||i,value:L.value||"__none__",onValueChange:F=>{L.onChange(F==="__none__"?"":F)},children:[e.jsx(xe,{className:"font-mono text-sm flex-1",children:e.jsx(ye,{placeholder:"选择提示词文件(可选)"})}),e.jsxs(ge,{children:[e.jsx(ne,{value:"__none__",children:"不使用提示词文件"}),a.map(F=>e.jsx(ne,{value:F.relativePath,children:F.fileName},F.relativePath))]})]})}),e.jsx(A,{type:"button",variant:"outline",size:"icon",onClick:$,disabled:s||i||!j.watch("llm.prompt")||j.watch("llm.prompt")==="__none__",title:"编辑选中的提示词文件",children:e.jsx(ro,{className:"size-4"})}),e.jsx(A,{type:"button",variant:"outline",size:"icon",onClick:M,disabled:s||i,title:"新建提示词文件",children:e.jsx(Qe,{className:"size-4"})})]}),e.jsx(Y,{})]})})]})]}),e.jsx(ht,{className:"my-4"}),e.jsxs("div",{className:"mb-4",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground mb-3",children:"TTS 配置"}),e.jsxs("div",{className:"grid gap-4",children:[e.jsx(K,{control:j.control,name:"tts.appid",render:({field:L})=>e.jsxs(J,{children:[e.jsx(ee,{children:"应用 ID"}),e.jsx(H,{children:e.jsx(te,{placeholder:"请输入火山引擎语音合成应用 ID",className:"font-mono text-sm",disabled:s,...L})}),e.jsx(Y,{})]})}),e.jsx(K,{control:j.control,name:"tts.accessToken",render:({field:L})=>e.jsxs(J,{children:[e.jsx(ee,{children:"访问令牌"}),e.jsx(H,{children:e.jsx(mt,{placeholder:"请输入访问令牌",className:"font-mono text-sm",disabled:s,autoComplete:"off",...L})}),e.jsx(Y,{})]})}),e.jsx(K,{control:j.control,name:"tts.voice_type",render:({field:L})=>e.jsxs(J,{children:[e.jsx(ee,{children:"声音类型"}),e.jsx(H,{children:e.jsxs(Ne,{disabled:s||v,value:L.value||"__none__",onValueChange:F=>{L.onChange(F==="__none__"?"":F)},children:[e.jsx(xe,{className:"font-mono text-sm",children:e.jsx(ye,{placeholder:"选择音色(可选)"})}),e.jsxs(ge,{children:[e.jsx(ne,{value:"__none__",children:"不指定音色"}),L.value&&L.value!=="__none__"&&!h.some(F=>F.voiceType===L.value)&&e.jsxs(ne,{value:L.value,children:[L.value," (自定义音色)"]}),Object.entries(h.reduce((F,b)=>(F[b.scene]||(F[b.scene]=[]),F[b.scene].push(b),F),{})).map(([F,b])=>e.jsxs(Qo,{children:[e.jsx(oa,{children:F}),b.map(w=>e.jsx(ne,{value:w.voiceType,children:w.name},w.voiceType))]},F))]})]})}),e.jsx(Y,{})]})})]})]})]}),e.jsxs(ke,{className:"mt-4",children:[e.jsx($e,{asChild:!0,children:e.jsx(A,{type:"button",variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s,children:s?"保存中...":"保存"})]})]})})]})]}),e.jsx(Ki,{open:u,onOpenChange:m,selectedPath:c,onPromptUpdated:D,onPromptCreated:W,onPromptDeleted:U})]})}function gr(r){return!!(r?.appid&&r?.accessToken)}function vr(r){return!!(r?.model&&r?.apiKey&&r?.baseURL)}function jr(r){return!!(r?.appid&&r?.accessToken&&r?.voice_type)}function Qi(){const{asr:r,llm:t,tts:s}=Do(),n=l.useMemo(()=>{let d=0;return gr(r)&&d++,vr(t)&&d++,jr(s)&&d++,d},[r,t,s]),a=3,o=n/a,i=[];return gr(r)&&i.push("ASR"),vr(t)&&i.push("LLM"),jr(s)&&i.push("TTS"),e.jsxs(Pe,{className:"@container/card",children:[e.jsxs(De,{className:"relative",children:[e.jsx(Be,{children:"实时语音"}),e.jsxs(Me,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:[n,"/",a," 就绪"]}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(tt,{showValue:!0,value:n,maxValue:a,activeColor:o>=1?"#16a34a":o>=.66?"#f59e0b":"#f87171",inactiveColor:"#e5e7eb",size:30,symbol:""})})]}),e.jsxs(Ge,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:o===1?"语音交互已就绪":i.length>0?`${i.join("、")} 已配置`:"请配置语音服务"}),e.jsx(Zi,{})]})]})}function ec(){return e.jsxs("div",{className:"*:data-[slot=card]:shadow-xs @xl/main:grid-cols-2 @5xl/main:grid-cols-5 grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card lg:px-6",children:[e.jsx(zo,{}),e.jsx(Zo,{}),e.jsx(Wi,{}),e.jsx(Qi,{}),e.jsx(Ji,{})]})}function tc({text:r,maxLength:t=100,storageKey:s,className:n,textSize:a="text-sm"}){const o=()=>{if(!s)return!1;try{return localStorage.getItem(s)==="true"}catch{return!1}},[i,d]=l.useState(o);l.useEffect(()=>{if(s)try{localStorage.setItem(s,String(i))}catch(p){console.warn("无法写入 localStorage:",p)}},[i,s]),l.useEffect(()=>{if(s){const p=localStorage.getItem(s);d(p==="true")}},[s]);const u=()=>{d(p=>!p)},m=r||"-",c=m.length>t;return e.jsxs("div",{className:I("flex flex-col gap-1",n),children:[i||!c?e.jsx("p",{className:I("break-words",a),children:m}):e.jsxs("p",{className:I("break-words",a),children:[m.slice(0,t),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),c&&e.jsx("button",{type:"button",onClick:u,className:I("text-primary hover:underline flex items-center gap-1 w-fit",a),children:i?e.jsxs(e.Fragment,{children:["收起 ",e.jsx(Ms,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["展开 ",e.jsx(gt,{className:"h-4 w-4"})]})})]})}const Na=oo,Ys=no,Zs=ao,Pt=l.forwardRef(({className:r,sideOffset:t=4,...s},n)=>e.jsx(Vn,{ref:n,sideOffset:t,className:I("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",r),...s}));Pt.displayName=Vn.displayName;function Os(r){if(!r||typeof r!="object")return at();switch(r.type){case"string":{if(r.enum)return Co(r.enum);let t=Oe();return r.minLength&&(t=t.min(r.minLength)),r.maxLength&&(t=t.max(r.maxLength)),r.pattern&&(t=t.regex(new RegExp(r.pattern))),t}case"number":case"integer":{let t=Eo();return r.type==="integer"&&(t=t.int()),typeof r.minimum=="number"&&(t=t.min(r.minimum)),typeof r.maximum=="number"&&(t=t.max(r.maximum)),typeof r.multipleOf=="number"&&(t=t.multipleOf(r.multipleOf)),t}case"boolean":return yo();case"array":if(r.items){const t=Os(r.items);let s=ur(t);return typeof r.minItems=="number"&&(s=s.min(r.minItems)),typeof r.maxItems=="number"&&(s=s.max(r.maxItems)),s}return ur(at());case"object":if(r.properties&&Object.keys(r.properties).length>0){const t={},s=r.required||[];for(const[n,a]of Object.entries(r.properties)){let o=Os(a);s.includes(n)||(o=o.optional()),t[n]=o}return et(t)}return No(Oe(),at());default:return at()}}function Ls(r){if(r)switch(r.type){case"string":return r.enum?r.enum[0]:"";case"number":case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":if(r.properties){const t={};for(const[s,n]of Object.entries(r.properties))t[s]=Ls(n);return t}return{};default:return}}function sc(r){if(!r||!r.properties)return{};const t={},s=r.required||[];for(const[n,a]of Object.entries(r.properties))if(s.includes(n))t[n]=Ls(a);else{const o=Ls(a);o!==void 0&&o!==""&&(t[n]=o)}return t}const rc=l.memo(function({name:t,schema:s,form:n,renderFormField:a}){const{fields:o,append:i,remove:d}=io({control:n.control,name:t}),u=()=>{const m=s.items;let c;switch(m.type){case"string":c=m.enum?m.enum[0]:"";break;case"number":case"integer":c=0;break;case"boolean":c=!1;break;case"array":c=[];break;case"object":c={};break;default:c=""}i(c)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium",children:["数组项目 (",s.items?.type||"unknown",")"]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",onClick:u,className:"h-8 px-2",children:[e.jsx(Qe,{className:"h-3 w-3 mr-1"}),"添加"]})]}),o.length===0?e.jsx("div",{className:"text-center py-4 border border-dashed rounded-md",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:"暂无数组项目"})}):e.jsx("div",{className:"space-y-3",children:o.map((m,c)=>e.jsxs("div",{className:"relative p-3 border rounded-md bg-muted/20",children:[e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(c),className:"h-6 w-6 p-0 text-red-500 hover:text-red-700",children:e.jsx(Un,{className:"h-3 w-3"})})}),e.jsxs("div",{className:"pr-8",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground mb-2 block",children:["项目 ",c+1]}),e.jsx(K,{control:n.control,name:`${t}.${c}`,render:()=>e.jsx(J,{children:s.items?.type==="object"||s.items?.type==="array"?e.jsx("div",{className:"ml-6 border-l-2 border-muted pl-4",children:a(`${t}.${c}`,s.items)}):a(`${t}.${c}`,s.items)})})]})]},m.id))})]})}),nc=l.memo(function({name:t,schema:s,form:n,renderFormField:a,getTypeBadge:o}){return!s.properties||Object.keys(s.properties).length===0?e.jsx("div",{className:"text-center py-4 border border-dashed rounded-md",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:"对象无定义字段"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("span",{className:"text-sm font-medium",children:"对象字段"}),Object.entries(s.properties).map(([i,d])=>e.jsx("div",{className:"ml-6 border-l-2 border-muted pl-4",children:e.jsx(K,{control:n.control,name:`${t}.${i}`,render:()=>e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ee,{children:[s.required?.includes(i)&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),i]}),e.jsx(pe,{variant:"secondary",className:`text-xs ${o(d.type)}`,children:d.type}),d.description&&e.jsxs(Ys,{children:[e.jsx(Zs,{children:e.jsx(zs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Pt,{children:e.jsx("p",{className:"max-w-xs whitespace-pre-wrap",children:d.description})})]})]}),a(`${t}.${i}`,d),d.description&&e.jsx(Ue,{children:d.description}),e.jsx(Y,{})]})})},`${t}-${i}`))]})}),ac=l.memo(function(){return e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center space-y-4 max-w-sm mx-auto p-6",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center",children:e.jsx(vt,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"无需输入参数"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'点击"调用工具"按钮执行,无需输入任何参数。'})]})]})})}),oc=l.memo(function({tool:t,form:s,renderFormField:n}){return t?.inputSchema?.properties?e.jsx(qe,{...s,children:e.jsx(Ie,{className:"h-full",children:e.jsx("div",{className:"space-y-4 p-2",children:Object.entries(t.inputSchema.properties).map(([a,o])=>e.jsx(K,{control:s.control,name:a,render:()=>e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ee,{children:[t.inputSchema.required?.includes(a)&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),a]}),e.jsx(pe,{variant:"secondary",className:`text-xs ${o.type==="string"?"bg-blue-100 text-blue-800":o.type==="number"||o.type==="integer"?"bg-green-100 text-green-800":o.type==="boolean"?"bg-purple-100 text-purple-800":o.type==="array"?"bg-orange-100 text-orange-800":(o.type==="object","bg-gray-100 text-gray-800")}`,children:o.type}),o.description&&e.jsxs(Ys,{children:[e.jsx(Zs,{children:e.jsx(zs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Pt,{children:e.jsx("p",{className:"max-w-xs whitespace-pre-wrap",children:o.description})})]})]}),n(a,o),e.jsx(Y,{})]})},`${t.name}-${a}`))})})}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-muted-foreground",children:"该工具无参数定义"})]})});function ic({open:r,onOpenChange:t,tool:s}){const[n,a]=l.useState("form"),[o,i]=l.useState(`{
64
-
65
- }`),[d,u]=l.useState(null),[m,c]=l.useState(!1),[p,h]=l.useState(null),[x,v]=l.useState(!1),g=l.useRef(null),N=l.useMemo(()=>s?.inputSchema?Os(s.inputSchema):et({}),[s?.inputSchema]),k=l.useMemo(()=>s?.inputSchema?sc(s.inputSchema):{},[s?.inputSchema]),j=Ee({resolver:Re(N),defaultValues:k,mode:"onChange"});l.useEffect(()=>{if(s?.inputSchema){j.reset(k);try{i(JSON.stringify(k,null,2))}catch{i(`{
66
-
67
- }`)}}else j.reset({}),i(`{
68
-
69
- }`)},[s?.inputSchema,k,j]),l.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const y=l.useCallback(()=>{a("form"),i(`{
70
-
71
- }`),u(null),h(null),v(!1),s?.inputSchema&&j.reset(k)},[s?.inputSchema,k,j]),T=l.useCallback(b=>{if(b==="json"&&n==="form"){const w=j.getValues();try{i(JSON.stringify(w,null,2))}catch{i(`{
72
-
73
- }`)}}else if(b==="form"&&n==="json")try{const w=JSON.parse(o);for(const R of Object.keys(w))j.setValue(R,w[R])}catch{}a(b)},[n,o,j]),E=l.useCallback(b=>{b||y(),t(b)},[t,y]),$=l.useCallback(b=>{try{return JSON.parse(b),!0}catch{return!1}},[]),M=l.useCallback(async()=>{if(!s)return;let b;if(!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0)b={};else if(n==="form"){const R=j.getValues();if(!await j.trigger()){O.error("请检查表单中的错误");return}b=R}else{if(!$(o)){O.error("输入参数不是有效的JSON格式");return}b=JSON.parse(o)}c(!0),h(null),u(null);try{const R=await z.callTool(s.serverName,s.toolName,b);u(R),O.success("工具调用成功")}catch(R){const f=R instanceof Error?R.message:"调用工具失败";h(f),O.error(f)}finally{c(!1)}},[s,n,j,o,$]),D=l.useCallback(async()=>{const b=d?JSON.stringify(d,null,2):p||"";try{await navigator.clipboard.writeText(b),v(!0),O.success("已复制到剪贴板"),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>v(!1),2e3)}catch{O.error("复制失败")}},[d,p]),W=l.useCallback(()=>{if(u(null),h(null),n==="form"&&s?.inputSchema){j.reset(k);try{i(JSON.stringify(k,null,2))}catch{i(`{
74
-
75
- }`)}}else i(`{
76
-
77
- }`),s?.inputSchema?j.reset(k):j.reset({})},[n,s?.inputSchema,k,j]),U=l.useMemo(()=>{const b=w=>({string:"bg-blue-100 text-blue-800",number:"bg-green-100 text-green-800",integer:"bg-green-100 text-green-800",boolean:"bg-purple-100 text-purple-800",array:"bg-orange-100 text-orange-800",object:"bg-gray-100 text-gray-800"})[w]||"bg-gray-100 text-gray-800";return(w,R)=>{switch(R.type){case"string":return R.enum?e.jsx(Fe,{name:w,control:j.control,render:({field:f})=>e.jsxs(Ne,{value:f.value,onValueChange:f.onChange,children:[e.jsx(H,{children:e.jsx(xe,{children:e.jsx(ye,{placeholder:`选择${w}`})})}),e.jsx(ge,{children:R.enum.map(S=>e.jsx(ne,{value:S,children:S},S))})]})}):e.jsx(Fe,{name:w,control:j.control,render:({field:f})=>e.jsx(H,{children:e.jsx(te,{...f,placeholder:`输入${w}`,type:R.format==="password"?"password":"text"})})});case"number":case"integer":return e.jsx(Fe,{name:w,control:j.control,render:({field:f})=>e.jsx(H,{children:e.jsx(te,{...f,type:"number",placeholder:`输入${w}`,step:R.type==="integer"?"1":"0.1",onChange:S=>{const C=S.target.value;f.onChange(C===""?"":Number(C))}})})});case"boolean":return e.jsx(Fe,{name:w,control:j.control,render:({field:f})=>e.jsxs(Ne,{value:f.value?.toString(),onValueChange:S=>f.onChange(S==="true"),children:[e.jsx(H,{children:e.jsx(xe,{children:e.jsx(ye,{placeholder:`选择${w}`})})}),e.jsxs(ge,{children:[e.jsx(ne,{value:"true",children:"true"}),e.jsx(ne,{value:"false",children:"false"})]})]})});case"array":return e.jsx(rc,{name:w,schema:R,form:j,renderFormField:U});case"object":return e.jsx(nc,{name:w,schema:R,form:j,renderFormField:U,getTypeBadge:b});default:return e.jsx(Fe,{name:w,control:j.control,render:({field:f})=>e.jsx(H,{children:e.jsx(te,{...f,placeholder:`输入${w}`})})})}}},[j]),X=l.useCallback(b=>{try{return JSON.stringify(b,null,2)}catch{return String(b)}},[]),L=l.useCallback(()=>typeof window>"u"||/Mac|iPhone|iPad|iPod/.test(navigator.platform)?"⌘+Enter":"Ctrl+Enter",[]),F=l.useCallback(async b=>{if((/Mac|iPhone|iPad|iPod/.test(navigator.platform)?b.metaKey&&b.key==="Enter":b.ctrlKey&&b.key==="Enter")&&r&&!m){if(b.preventDefault(),!(!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0)&&n==="json"&&!$(o)){O.error("输入参数不是有效的JSON格式");return}await M()}},[r,m,n,o,$,M,s?.inputSchema?.properties]);return l.useEffect(()=>{if(r)return window.addEventListener("keydown",F),()=>{window.removeEventListener("keydown",F)}},[r,F]),e.jsx(me,{open:r,onOpenChange:E,children:e.jsx(Na,{children:e.jsxs(le,{className:"max-w-4xl max-h-[90vh] flex flex-col",children:[e.jsx(de,{children:e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5"}),"工具调试"]})}),s&&e.jsxs("div",{className:"flex flex-col gap-4 h-[80vh]",children:[e.jsxs(Pe,{children:[e.jsx(De,{className:"pb-0",children:e.jsxs(Me,{className:"text-base flex items-center gap-2",children:[e.jsx(pe,{variant:"secondary",children:s.serverName}),s.toolName]})}),e.jsx(Zn,{children:s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})})]}),e.jsxs("div",{className:"flex-1 flex min-h-0 w-full overflow-hidden",children:[e.jsxs("div",{className:"w-1/2 flex flex-col gap-2 flex-shrink-0 overflow-hidden pr-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between h-[40px]",children:[e.jsx("h3",{className:"text-sm font-medium",children:"输入参数"}),s?.inputSchema?.properties&&Object.keys(s.inputSchema.properties).length>0&&e.jsx(Ye,{value:n,onValueChange:b=>T(b),children:e.jsxs(rt,{className:"grid w-full grid-cols-2",children:[e.jsx(be,{value:"form",className:"text-xs",children:"表单模式"}),e.jsx(be,{value:"json",className:"text-xs",children:"高级模式"})]})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:s?.inputSchema?.properties&&Object.keys(s.inputSchema.properties).length>0?e.jsxs(Ye,{value:n,onValueChange:b=>T(b),className:"h-full flex flex-col",children:[e.jsx(Se,{value:"form",className:"flex-1 data-[state=active]:flex data-[state=active]:flex-col mt-0",children:e.jsx(oc,{tool:s,form:j,renderFormField:U})}),e.jsx(Se,{value:"json",className:"flex-1 data-[state=active]:flex data-[state=active]:flex-col mt-0",children:e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsx(He,{value:o,onChange:b=>i(b.target.value),placeholder:"请输入JSON格式的参数...",className:"flex-1 font-mono text-sm resize-none min-h-[200px]",disabled:m}),!$(o)&&o.trim()!==`{
78
-
79
- }`&&e.jsxs(Ve,{className:"mt-2",children:[e.jsx(zn,{className:"h-4 w-4"}),e.jsx(_e,{children:"JSON格式错误,请检查输入"})]})]})})]}):e.jsx(ac,{})})]}),e.jsxs("div",{className:"w-1/2 flex flex-col gap-2 flex-shrink-0 overflow-hidden pl-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between h-[40px]",children:[e.jsx("h3",{className:"text-sm font-medium",children:"调用结果"}),(d||p)&&e.jsx(A,{variant:"outline",size:"sm",onClick:D,className:"gap-0",children:x?e.jsxs(e.Fragment,{children:[e.jsx(vt,{className:"h-4 w-4 mr-1"}),"已复制"]}):e.jsxs(e.Fragment,{children:[e.jsx(xt,{className:"h-4 w-4 mr-1"}),"复制结果"]})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:m?e.jsx("div",{className:"h-full flex items-center justify-center border rounded-md",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(fe,{className:"h-8 w-8 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"正在调用工具..."})]})}):p?e.jsx("div",{className:"h-full",children:e.jsx(Ve,{variant:"destructive",className:"h-full",children:e.jsx(_e,{className:"font-mono text-sm whitespace-pre-wrap break-words",children:p})})}):d?e.jsx(Ie,{className:"h-full border rounded-md",children:e.jsx("pre",{className:"p-3 text-sm font-mono whitespace-pre-wrap break-words min-w-0",children:X(d)})}):e.jsx("div",{className:"h-full flex items-center justify-center border rounded-md",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"等待调用工具..."})]})})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsxs(A,{variant:"outline",onClick:W,disabled:m,children:[e.jsx(co,{className:"h-4 w-4"}),"清空"]}),e.jsx(A,{onClick:M,disabled:m||!(!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0)&&n==="json"&&!$(o),children:m?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-4 w-4 mr-2 animate-spin"}),"调用中..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lo,{className:"h-4 w-4"}),!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0?"直接调用":"调用工具"," (",L(),")"]})})]})]})]})})})}const ya=l.forwardRef(({className:r,...t},s)=>e.jsx(Wn,{className:I("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",r),...t,ref:s,children:e.jsx(uo,{className:I("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));ya.displayName=Wn.displayName;function cc(r){const[t,s]=l.useState(""),n=Array.isArray(r)?r:[],a=l.useMemo(()=>{if(!t.trim())return n;const i=t.toLowerCase();return n.filter(d=>(d?.serverName?.toLowerCase()||"").includes(i)||(d?.toolName?.toLowerCase()||"").includes(i)||(d?.description?.toLowerCase()||"").includes(i))},[n,t]),o=l.useCallback(()=>{s("")},[]);return{searchValue:t,setSearchValue:s,filteredTools:a,clearSearch:o}}const lc=["name","enabled","usageCount","lastUsedTime"];function dc(){return ma({storageKey:"mcp-tool-sort-config",defaultConfig:{field:"name"},validFields:lc,loggerName:"useToolSortPersistence"})}const uc=[{value:"name",label:"按名称排序"},{value:"enabled",label:"按状态排序"},{value:"usageCount",label:"按使用次数排序"},{value:"lastUsedTime",label:"按最近使用排序"}];function mc({value:r,onChange:t}){return e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ne,{value:r.field,onValueChange:s=>t({field:s}),children:[e.jsx(xe,{id:"sort-field",className:"w-40",children:e.jsx(ye,{})}),e.jsx(ge,{children:uc.map(s=>e.jsx(ne,{value:s.value,children:s.label},s.value))})]})})}const Ft="未知服务",fc="自定义服务";function hc(r){if(!r)return"-";try{const t=new Date(r),n=new Date().getTime()-t.getTime(),a=Math.floor(n/6e4);return a<1?"刚刚":a<60?`${a}分钟前`:a<1440?`${Math.floor(a/60)}小时前`:`${Math.floor(a/1440)}天前`}catch{return r}}function pc({initialStatus:r="all",className:t}){const{sortConfig:s,setSortConfig:n}=dc(),[a,o]=l.useState([]),{searchValue:i,setSearchValue:d,filteredTools:u,clearSearch:m}=cc(a),{currentPage:c,totalPages:p,paginatedTools:h,setPage:x,resetPage:v}=fa(u,10),[g,N]=l.useState(!0),[k,j]=l.useState(null),[,y]=l.useState(!1),[T,E]=l.useState(null),[$,M]=l.useState({open:!1}),D=l.useCallback((f,S)=>{const{serviceName:C,toolName:P}=!f||!f.handler?{serviceName:Ft,toolName:f?.name||Ft}:f.handler.type==="mcp"?{serviceName:f.handler.config?.serviceName||Ft,toolName:f.handler.config?.toolName||f.name}:f.handler.type==="proxy"&&f.handler.platform==="coze"?{serviceName:"customMCP",toolName:f.name}:{serviceName:fc,toolName:f.name};return{name:f.name,serverName:C,toolName:P,description:f.description||"",enabled:S,usageCount:f.usageCount||0,lastUsedTime:f.lastUsedTime||"",inputSchema:f.inputSchema}},[]),W=l.useCallback(async()=>{const S=(await z.getToolsList(r,s)).map(C=>D(C,C.enabled??!1));o(S)},[r,s,D]),U=l.useCallback(async()=>{N(!0),j(null);try{await W()}catch(f){console.error("获取工具列表失败:",f),j(f instanceof Error?f.message:"获取工具列表失败"),O.error("获取工具列表失败")}finally{N(!1)}},[W]),X=l.useCallback(async()=>{try{await W()}catch(f){console.error("刷新工具列表失败:",f),O.error("刷新工具列表失败")}},[W]),L=l.useCallback(async()=>{y(!0);try{await U(),O.success("刷新成功")}catch{O.error("刷新失败")}finally{y(!1)}},[U]),F=l.useCallback(async(f,S)=>{try{const C=a.find(P=>P.name===f);if(!C){O.error("找不到对应的工具信息");return}if(C.serverName==="customMCP"){if(S){E(f);return}await z.addCustomTool({workflow_id:"",workflow_name:f,description:C.description||"",icon_url:"",app_id:""},f,C.description||""),O.success(`添加工具 ${f} 成功`)}else{const P=S?"disable":"enable";await z.manageMCPTool({action:P,serverName:C.serverName,toolName:C.toolName,description:C.description}),O.success(`${S?"禁用":"启用"}工具 ${f} 成功`)}await X()}catch(C){console.error("切换工具状态失败:",C),O.error(C instanceof Error?C.message:"切换工具状态失败")}},[a,X]),b=l.useCallback(async()=>{if(T)try{await z.removeCustomTool(T),O.success(`删除工具 ${T} 成功`),await X()}catch(f){console.error("删除 Coze 工具失败:",f),O.error(f instanceof Error?f.message:"删除 Coze 工具失败")}finally{E(null)}},[T,X]),w=l.useCallback(()=>{E(null)},[]),R=l.useCallback(f=>{M({open:!0,tool:{name:f.name,serverName:f.serverName,toolName:f.toolName,description:f.description,inputSchema:f.inputSchema}})},[]);return l.useEffect(()=>{U()},[U]),l.useEffect(()=>{v()},[i,v]),e.jsxs("div",{className:I("flex flex-col gap-4",t),children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(mc,{value:s,onChange:n}),e.jsx(ja,{value:i,onChange:d,placeholder:"搜索服务名、工具名..."})]}),i&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["找到 ",u.length," 个结果",u.length>0&&e.jsx("button",{type:"button",onClick:m,className:"ml-2 text-primary hover:underline",children:"清除搜索"})]}),e.jsx("div",{className:"rounded-md border",children:g?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(fe,{className:"h-8 w-8 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"加载工具列表中..."})]})}):k?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx("div",{className:"text-red-500 text-sm",children:k}),e.jsx(A,{variant:"outline",size:"sm",onClick:L,children:"重试"})]}):u.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx(qn,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i?"没有找到匹配的工具":r==="enabled"?"没有已启用的工具":r==="disabled"?"没有已禁用的工具":"暂无可用工具"}),i&&e.jsx(A,{variant:"outline",size:"sm",onClick:m,children:"清除搜索"})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Tt,{size:"compact",children:[e.jsx(kt,{children:e.jsxs(Le,{children:[e.jsx(se,{children:"服务名"}),e.jsx(se,{children:"工具名"}),e.jsx(se,{children:"描述"}),e.jsx(se,{children:"使用次数"}),e.jsx(se,{children:"最近使用"}),e.jsx(se,{children:"状态"}),e.jsx(se,{children:"操作"})]})}),e.jsx(It,{children:h.map(f=>e.jsxs(Le,{children:[e.jsx(re,{children:e.jsx(pe,{variant:"secondary",className:"rounded-md",children:f.serverName})}),e.jsx(re,{className:"font-medium",children:f.toolName}),e.jsx(re,{className:"text-muted-foreground max-w-[300px]",children:e.jsx(tc,{text:f.description,maxLength:100,textSize:"text-xs",storageKey:`mcp-tool-desc-${f.name}`})}),e.jsx(re,{className:"text-right",children:f.usageCount}),e.jsx(re,{className:"text-right text-muted-foreground",children:hc(f.lastUsedTime)}),e.jsx(re,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx(ya,{checked:f.enabled,onCheckedChange:S=>F(f.name,!S)})})}),e.jsx(re,{children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 hover:cursor-pointer hover:text-primary transition-all duration-100",onClick:()=>R(f),title:"调试工具",children:[e.jsx(_n,{size:14}),e.jsx("span",{children:"调试"})]})})})]},f.name))})]}),e.jsx(va,{currentPage:c,totalPages:p,setPage:x})]})}),e.jsx(Vs,{open:T!==null,onOpenChange:f=>!f&&E(null),children:e.jsxs(bt,{children:[e.jsxs(St,{children:[e.jsx(Nt,{children:"确认移除 Coze 工作流工具"}),e.jsxs(yt,{children:['移除后需要通过【工作流集成】重新添加并配置入参,确定要移除工具 "',T,'" 吗?']})]}),e.jsxs(wt,{children:[e.jsx(Et,{onClick:w,children:"取消"}),e.jsx(Ct,{onClick:b,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"确认移除"})]})]})}),e.jsx(ic,{open:$.open,onOpenChange:f=>M(S=>({...S,open:f})),tool:$.tool||null})]})}const xc=({size:r=24,color:t="currentColor",...s})=>e.jsx("svg",{width:r,height:r,viewBox:"0 0 1024 1024",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...s,children:e.jsx("path",{d:"M980.79827 694.105946c-21.144216-122.796973-109.844757-203.250162-109.844757-203.250162 12.647784-111.477622-33.792-131.26573-33.792-131.26573C827.392 14.668108 530.985514 20.67373 524.730811 20.839784 518.476108 20.67373 222.01427 14.668108 212.300108 359.590054c0 0-46.467459 19.788108-33.819676 131.26573 0 0-88.700541 80.453189-109.817081 203.250162 0 0-11.291676 207.484541 101.403676 25.40627 0 0 25.350919 69.161514 71.790703 131.26573 0 0-83.082378 28.256865-75.997405 101.625081 0 0-2.87827 81.836973 177.401081 76.218811 0 0 126.699243-9.852541 164.753297-63.515676l16.605405 0 0.276757 0 16.633081 0c38.026378 53.635459 164.725622 63.515676 164.725622 63.515676 180.224 5.618162 177.401081-76.218811 177.401081-76.218811 7.029622-73.368216-75.997405-101.625081-75.997405-101.625081 46.439784-62.104216 71.790703-131.26573 71.790703-131.26573C992.034595 901.590486 980.79827 694.105946 980.79827 694.105946z"})}),gc=({size:r=24,color:t="currentColor",...s})=>e.jsx("svg",{width:r,height:r,viewBox:"0 0 1024 1024",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...s,children:e.jsx("path",{d:"M0 524.992q0 166.016 95.488 298.496t247.488 185.504q6.016 0.992 10.016 0.992t6.496-1.504 4-3.008 2.016-4.992 0.512-4.992v-100.512q-36.992 4-66.016-0.512t-45.504-14.016-28.992-23.488-16.992-25.504-8.992-24-5.504-14.496q-8.992-15.008-27.008-27.488t-27.008-20-2.016-14.496q50.016-26.016 112.992 66.016 34.016 51.008 119.008 30.016 10.016-40.992 40-70.016Q293.984 736 237.984 670.976t-56-158.016q0-87.008 55.008-151.008-22.016-64.992 6.016-136.992 28.992-2.016 64.992 11.488t50.496 23.008 25.504 17.504q56.992-16 128.512-16t129.504 16q12.992-8.992 28.992-19.008t48.992-21.504 60.992-9.504q27.008 71.008 7.008 135.008 56 64 56 151.008 0 92.992-56.992 158.496t-172 85.504q43.008 43.008 43.008 104v128.992q0 0.992 0.992 3.008 0 6.016 0.512 8.992t4.512 6.016 12 3.008q152.992-52 250.496-185.504t97.504-300.512q0-104-40.512-199.008t-108.992-163.488-163.488-108.992T512.032 12.96 313.024 53.472 149.536 162.464t-108.992 163.488-40.512 199.008z","p-id":"4674"})});function Ca(){const[r,t]=l.useState({status:"idle",logs:[]});l.useEffect(()=>{const u=B.subscribe("data:npmInstallStarted",h=>{console.log("[useNPMInstall] 安装开始:",h),t({status:"installing",version:h.version,installId:h.installId,logs:[]})}),m=B.subscribe("data:npmInstallLog",h=>{console.log("[useNPMInstall] 收到日志:",h),t(x=>x.installId===h.installId?{...x,logs:[...x.logs,{type:h.type,message:h.message,timestamp:h.timestamp}]}:x)}),c=B.subscribe("data:npmInstallCompleted",h=>{console.log("[useNPMInstall] 安装完成:",h),t(x=>x.installId===h.installId?{...x,status:"completed",duration:h.duration}:x)}),p=B.subscribe("data:npmInstallFailed",h=>{console.log("[useNPMInstall] 安装失败:",h),t(x=>x.installId===h.installId?{...x,status:"failed",error:h.error,duration:h.duration}:x)});return()=>{u(),m(),c(),p()}},[]);const s=l.useCallback(async u=>{try{console.log("[useNPMInstall] 开始安装版本:",u);const c=await(await fetch("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:u})})).json();if(!c.success)throw new Error(c.error?.message||"安装请求失败");return console.log("[useNPMInstall] 安装请求已接受:",c),c}catch(m){throw console.error("[useNPMInstall] 安装请求失败:",m),t(c=>({...c,status:"failed",error:m instanceof Error?m.message:"未知错误"})),m}},[]),n=l.useCallback(()=>{console.log("[useNPMInstall] 清除安装状态"),t({status:"idle",logs:[]})},[]),a=l.useCallback(()=>{switch(r.status){case"installing":return`正在安装 xiaozhi-client@${r.version}...`;case"completed":return"安装完成!";case"failed":return`安装失败: ${r.error}`;default:return""}},[r]),o=l.useCallback(()=>{switch(r.status){case"installing":return"text-blue-600";case"completed":return"text-green-600";case"failed":return"text-red-600";default:return"text-gray-600"}},[r]),i=l.useCallback(()=>r.status==="installing",[r.status]),d=l.useCallback(()=>r.status!=="installing",[r.status]);return{installStatus:r,startInstall:s,clearStatus:n,getStatusText:a,getStatusColor:o,isInstalling:i,canCloseDialog:d}}var ut={exports:{}},zt,br;function Ot(){if(br)return zt;br=1;const r="2.0.0",t=256,s=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=t-6;return zt={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:s,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},zt}var Ut,Sr;function Lt(){if(Sr)return Ut;Sr=1;var r={};return Ut=typeof process=="object"&&r&&r.NODE_DEBUG&&/\bsemver\b/i.test(r.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{},Ut}var wr;function nt(){return wr||(wr=1,(function(r,t){const{MAX_SAFE_COMPONENT_LENGTH:s,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=Ot(),o=Lt();t=r.exports={};const i=t.re=[],d=t.safeRe=[],u=t.src=[],m=t.safeSrc=[],c=t.t={};let p=0;const h="[a-zA-Z0-9-]",x=[["\\s",1],["\\d",a],[h,n]],v=N=>{for(const[k,j]of x)N=N.split(`${k}*`).join(`${k}{0,${j}}`).split(`${k}+`).join(`${k}{1,${j}}`);return N},g=(N,k,j)=>{const y=v(k),T=p++;o(N,T,k),c[N]=T,u[T]=k,m[T]=y,i[T]=new RegExp(k,j?"g":void 0),d[T]=new RegExp(y,j?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),g("MAINVERSION",`(${u[c.NUMERICIDENTIFIER]})\\.(${u[c.NUMERICIDENTIFIER]})\\.(${u[c.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${u[c.NUMERICIDENTIFIERLOOSE]})\\.(${u[c.NUMERICIDENTIFIERLOOSE]})\\.(${u[c.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${u[c.NONNUMERICIDENTIFIER]}|${u[c.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${u[c.NONNUMERICIDENTIFIER]}|${u[c.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${u[c.PRERELEASEIDENTIFIER]}(?:\\.${u[c.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${u[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[c.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${h}+`),g("BUILD",`(?:\\+(${u[c.BUILDIDENTIFIER]}(?:\\.${u[c.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${u[c.MAINVERSION]}${u[c.PRERELEASE]}?${u[c.BUILD]}?`),g("FULL",`^${u[c.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${u[c.MAINVERSIONLOOSE]}${u[c.PRERELEASELOOSE]}?${u[c.BUILD]}?`),g("LOOSE",`^${u[c.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${u[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${u[c.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${u[c.XRANGEIDENTIFIER]})(?:\\.(${u[c.XRANGEIDENTIFIER]})(?:\\.(${u[c.XRANGEIDENTIFIER]})(?:${u[c.PRERELEASE]})?${u[c.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${u[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[c.XRANGEIDENTIFIERLOOSE]})(?:${u[c.PRERELEASELOOSE]})?${u[c.BUILD]}?)?)?`),g("XRANGE",`^${u[c.GTLT]}\\s*${u[c.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${u[c.GTLT]}\\s*${u[c.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${s}})(?:\\.(\\d{1,${s}}))?(?:\\.(\\d{1,${s}}))?`),g("COERCE",`${u[c.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",u[c.COERCEPLAIN]+`(?:${u[c.PRERELEASE]})?(?:${u[c.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",u[c.COERCE],!0),g("COERCERTLFULL",u[c.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${u[c.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",g("TILDE",`^${u[c.LONETILDE]}${u[c.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${u[c.LONETILDE]}${u[c.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${u[c.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",g("CARET",`^${u[c.LONECARET]}${u[c.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${u[c.LONECARET]}${u[c.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${u[c.GTLT]}\\s*(${u[c.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${u[c.GTLT]}\\s*(${u[c.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${u[c.GTLT]}\\s*(${u[c.LOOSEPLAIN]}|${u[c.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${u[c.XRANGEPLAIN]})\\s+-\\s+(${u[c.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${u[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[c.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(ut,ut.exports)),ut.exports}var Vt,Nr;function Qs(){if(Nr)return Vt;Nr=1;const r=Object.freeze({loose:!0}),t=Object.freeze({});return Vt=n=>n?typeof n!="object"?r:n:t,Vt}var _t,yr;function Ea(){if(yr)return _t;yr=1;const r=/^[0-9]+$/,t=(n,a)=>{if(typeof n=="number"&&typeof a=="number")return n===a?0:n<a?-1:1;const o=r.test(n),i=r.test(a);return o&&i&&(n=+n,a=+a),n===a?0:o&&!i?-1:i&&!o?1:n<a?-1:1};return _t={compareIdentifiers:t,rcompareIdentifiers:(n,a)=>t(a,n)},_t}var Wt,Cr;function oe(){if(Cr)return Wt;Cr=1;const r=Lt(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:s}=Ot(),{safeRe:n,t:a}=nt(),o=Qs(),{compareIdentifiers:i}=Ea();class d{constructor(m,c){if(c=o(c),m instanceof d){if(m.loose===!!c.loose&&m.includePrerelease===!!c.includePrerelease)return m;m=m.version}else if(typeof m!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof m}".`);if(m.length>t)throw new TypeError(`version is longer than ${t} characters`);r("SemVer",m,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const p=m.trim().match(c.loose?n[a.LOOSE]:n[a.FULL]);if(!p)throw new TypeError(`Invalid Version: ${m}`);if(this.raw=m,this.major=+p[1],this.minor=+p[2],this.patch=+p[3],this.major>s||this.major<0)throw new TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw new TypeError("Invalid patch version");p[4]?this.prerelease=p[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const x=+h;if(x>=0&&x<s)return x}return h}):this.prerelease=[],this.build=p[5]?p[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(m){if(r("SemVer.compare",this.version,this.options,m),!(m instanceof d)){if(typeof m=="string"&&m===this.version)return 0;m=new d(m,this.options)}return m.version===this.version?0:this.compareMain(m)||this.comparePre(m)}compareMain(m){return m instanceof d||(m=new d(m,this.options)),this.major<m.major?-1:this.major>m.major?1:this.minor<m.minor?-1:this.minor>m.minor?1:this.patch<m.patch?-1:this.patch>m.patch?1:0}comparePre(m){if(m instanceof d||(m=new d(m,this.options)),this.prerelease.length&&!m.prerelease.length)return-1;if(!this.prerelease.length&&m.prerelease.length)return 1;if(!this.prerelease.length&&!m.prerelease.length)return 0;let c=0;do{const p=this.prerelease[c],h=m.prerelease[c];if(r("prerelease compare",c,p,h),p===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(p===void 0)return-1;if(p===h)continue;return i(p,h)}while(++c)}compareBuild(m){m instanceof d||(m=new d(m,this.options));let c=0;do{const p=this.build[c],h=m.build[c];if(r("build compare",c,p,h),p===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(p===void 0)return-1;if(p===h)continue;return i(p,h)}while(++c)}inc(m,c,p){if(m.startsWith("pre")){if(!c&&p===!1)throw new Error("invalid increment argument: identifier is empty");if(c){const h=`-${c}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!h||h[1]!==c)throw new Error(`invalid identifier: ${c}`)}}switch(m){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",c,p);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",c,p);break;case"prepatch":this.prerelease.length=0,this.inc("patch",c,p),this.inc("pre",c,p);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",c,p),this.inc("pre",c,p);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(p)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let x=this.prerelease.length;for(;--x>=0;)typeof this.prerelease[x]=="number"&&(this.prerelease[x]++,x=-2);if(x===-1){if(c===this.prerelease.join(".")&&p===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(c){let x=[c,h];p===!1&&(x=[c]),i(this.prerelease[0],c)===0?isNaN(this.prerelease[1])&&(this.prerelease=x):this.prerelease=x}break}default:throw new Error(`invalid increment argument: ${m}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Wt=d,Wt}var Bt,Er;function Je(){if(Er)return Bt;Er=1;const r=oe();return Bt=(s,n,a=!1)=>{if(s instanceof r)return s;try{return new r(s,n)}catch(o){if(!a)return null;throw o}},Bt}var Gt,Rr;function vc(){if(Rr)return Gt;Rr=1;const r=Je();return Gt=(s,n)=>{const a=r(s,n);return a?a.version:null},Gt}var Ht,Tr;function jc(){if(Tr)return Ht;Tr=1;const r=Je();return Ht=(s,n)=>{const a=r(s.trim().replace(/^[=v]+/,""),n);return a?a.version:null},Ht}var Jt,kr;function bc(){if(kr)return Jt;kr=1;const r=oe();return Jt=(s,n,a,o,i)=>{typeof a=="string"&&(i=o,o=a,a=void 0);try{return new r(s instanceof r?s.version:s,a).inc(n,o,i).version}catch{return null}},Jt}var Xt,Ir;function Sc(){if(Ir)return Xt;Ir=1;const r=Je();return Xt=(s,n)=>{const a=r(s,null,!0),o=r(n,null,!0),i=a.compare(o);if(i===0)return null;const d=i>0,u=d?a:o,m=d?o:a,c=!!u.prerelease.length;if(!!m.prerelease.length&&!c){if(!m.patch&&!m.minor)return"major";if(m.compareMain(u)===0)return m.minor&&!m.patch?"minor":"patch"}const h=c?"pre":"";return a.major!==o.major?h+"major":a.minor!==o.minor?h+"minor":a.patch!==o.patch?h+"patch":"prerelease"},Xt}var Kt,$r;function wc(){if($r)return Kt;$r=1;const r=oe();return Kt=(s,n)=>new r(s,n).major,Kt}var Yt,Pr;function Nc(){if(Pr)return Yt;Pr=1;const r=oe();return Yt=(s,n)=>new r(s,n).minor,Yt}var Zt,Or;function yc(){if(Or)return Zt;Or=1;const r=oe();return Zt=(s,n)=>new r(s,n).patch,Zt}var Qt,Lr;function Cc(){if(Lr)return Qt;Lr=1;const r=Je();return Qt=(s,n)=>{const a=r(s,n);return a&&a.prerelease.length?a.prerelease:null},Qt}var es,Ar;function ve(){if(Ar)return es;Ar=1;const r=oe();return es=(s,n,a)=>new r(s,a).compare(new r(n,a)),es}var ts,Dr;function Ec(){if(Dr)return ts;Dr=1;const r=ve();return ts=(s,n,a)=>r(n,s,a),ts}var ss,Mr;function Rc(){if(Mr)return ss;Mr=1;const r=ve();return ss=(s,n)=>r(s,n,!0),ss}var rs,qr;function er(){if(qr)return rs;qr=1;const r=oe();return rs=(s,n,a)=>{const o=new r(s,a),i=new r(n,a);return o.compare(i)||o.compareBuild(i)},rs}var ns,Fr;function Tc(){if(Fr)return ns;Fr=1;const r=er();return ns=(s,n)=>s.sort((a,o)=>r(a,o,n)),ns}var as,zr;function kc(){if(zr)return as;zr=1;const r=er();return as=(s,n)=>s.sort((a,o)=>r(o,a,n)),as}var os,Ur;function At(){if(Ur)return os;Ur=1;const r=ve();return os=(s,n,a)=>r(s,n,a)>0,os}var is,Vr;function tr(){if(Vr)return is;Vr=1;const r=ve();return is=(s,n,a)=>r(s,n,a)<0,is}var cs,_r;function Ra(){if(_r)return cs;_r=1;const r=ve();return cs=(s,n,a)=>r(s,n,a)===0,cs}var ls,Wr;function Ta(){if(Wr)return ls;Wr=1;const r=ve();return ls=(s,n,a)=>r(s,n,a)!==0,ls}var ds,Br;function sr(){if(Br)return ds;Br=1;const r=ve();return ds=(s,n,a)=>r(s,n,a)>=0,ds}var us,Gr;function rr(){if(Gr)return us;Gr=1;const r=ve();return us=(s,n,a)=>r(s,n,a)<=0,us}var ms,Hr;function ka(){if(Hr)return ms;Hr=1;const r=Ra(),t=Ta(),s=At(),n=sr(),a=tr(),o=rr();return ms=(d,u,m,c)=>{switch(u){case"===":return typeof d=="object"&&(d=d.version),typeof m=="object"&&(m=m.version),d===m;case"!==":return typeof d=="object"&&(d=d.version),typeof m=="object"&&(m=m.version),d!==m;case"":case"=":case"==":return r(d,m,c);case"!=":return t(d,m,c);case">":return s(d,m,c);case">=":return n(d,m,c);case"<":return a(d,m,c);case"<=":return o(d,m,c);default:throw new TypeError(`Invalid operator: ${u}`)}},ms}var fs,Jr;function Ic(){if(Jr)return fs;Jr=1;const r=oe(),t=Je(),{safeRe:s,t:n}=nt();return fs=(o,i)=>{if(o instanceof r)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let d=null;if(!i.rtl)d=o.match(i.includePrerelease?s[n.COERCEFULL]:s[n.COERCE]);else{const x=i.includePrerelease?s[n.COERCERTLFULL]:s[n.COERCERTL];let v;for(;(v=x.exec(o))&&(!d||d.index+d[0].length!==o.length);)(!d||v.index+v[0].length!==d.index+d[0].length)&&(d=v),x.lastIndex=v.index+v[1].length+v[2].length;x.lastIndex=-1}if(d===null)return null;const u=d[2],m=d[3]||"0",c=d[4]||"0",p=i.includePrerelease&&d[5]?`-${d[5]}`:"",h=i.includePrerelease&&d[6]?`+${d[6]}`:"";return t(`${u}.${m}.${c}${p}${h}`,i)},fs}var hs,Xr;function $c(){if(Xr)return hs;Xr=1;class r{constructor(){this.max=1e3,this.map=new Map}get(s){const n=this.map.get(s);if(n!==void 0)return this.map.delete(s),this.map.set(s,n),n}delete(s){return this.map.delete(s)}set(s,n){if(!this.delete(s)&&n!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(s,n)}return this}}return hs=r,hs}var ps,Kr;function je(){if(Kr)return ps;Kr=1;const r=/\s+/g;class t{constructor(w,R){if(R=a(R),w instanceof t)return w.loose===!!R.loose&&w.includePrerelease===!!R.includePrerelease?w:new t(w.raw,R);if(w instanceof o)return this.raw=w.value,this.set=[[w]],this.formatted=void 0,this;if(this.options=R,this.loose=!!R.loose,this.includePrerelease=!!R.includePrerelease,this.raw=w.trim().replace(r," "),this.set=this.raw.split("||").map(f=>this.parseRange(f.trim())).filter(f=>f.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const f=this.set[0];if(this.set=this.set.filter(S=>!g(S[0])),this.set.length===0)this.set=[f];else if(this.set.length>1){for(const S of this.set)if(S.length===1&&N(S[0])){this.set=[S];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let w=0;w<this.set.length;w++){w>0&&(this.formatted+="||");const R=this.set[w];for(let f=0;f<R.length;f++)f>0&&(this.formatted+=" "),this.formatted+=R[f].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(w){const f=((this.options.includePrerelease&&x)|(this.options.loose&&v))+":"+w,S=n.get(f);if(S)return S;const C=this.options.loose,P=C?u[m.HYPHENRANGELOOSE]:u[m.HYPHENRANGE];w=w.replace(P,L(this.options.includePrerelease)),i("hyphen replace",w),w=w.replace(u[m.COMPARATORTRIM],c),i("comparator trim",w),w=w.replace(u[m.TILDETRIM],p),i("tilde trim",w),w=w.replace(u[m.CARETTRIM],h),i("caret trim",w);let V=w.split(" ").map(Z=>j(Z,this.options)).join(" ").split(/\s+/).map(Z=>X(Z,this.options));C&&(V=V.filter(Z=>(i("loose invalid filter",Z,this.options),!!Z.match(u[m.COMPARATORLOOSE])))),i("range list",V);const q=new Map,G=V.map(Z=>new o(Z,this.options));for(const Z of G){if(g(Z))return[Z];q.set(Z.value,Z)}q.size>1&&q.has("")&&q.delete("");const ae=[...q.values()];return n.set(f,ae),ae}intersects(w,R){if(!(w instanceof t))throw new TypeError("a Range is required");return this.set.some(f=>k(f,R)&&w.set.some(S=>k(S,R)&&f.every(C=>S.every(P=>C.intersects(P,R)))))}test(w){if(!w)return!1;if(typeof w=="string")try{w=new d(w,this.options)}catch{return!1}for(let R=0;R<this.set.length;R++)if(F(this.set[R],w,this.options))return!0;return!1}}ps=t;const s=$c(),n=new s,a=Qs(),o=Dt(),i=Lt(),d=oe(),{safeRe:u,t:m,comparatorTrimReplace:c,tildeTrimReplace:p,caretTrimReplace:h}=nt(),{FLAG_INCLUDE_PRERELEASE:x,FLAG_LOOSE:v}=Ot(),g=b=>b.value==="<0.0.0-0",N=b=>b.value==="",k=(b,w)=>{let R=!0;const f=b.slice();let S=f.pop();for(;R&&f.length;)R=f.every(C=>S.intersects(C,w)),S=f.pop();return R},j=(b,w)=>(b=b.replace(u[m.BUILD],""),i("comp",b,w),b=$(b,w),i("caret",b),b=T(b,w),i("tildes",b),b=D(b,w),i("xrange",b),b=U(b,w),i("stars",b),b),y=b=>!b||b.toLowerCase()==="x"||b==="*",T=(b,w)=>b.trim().split(/\s+/).map(R=>E(R,w)).join(" "),E=(b,w)=>{const R=w.loose?u[m.TILDELOOSE]:u[m.TILDE];return b.replace(R,(f,S,C,P,V)=>{i("tilde",b,f,S,C,P,V);let q;return y(S)?q="":y(C)?q=`>=${S}.0.0 <${+S+1}.0.0-0`:y(P)?q=`>=${S}.${C}.0 <${S}.${+C+1}.0-0`:V?(i("replaceTilde pr",V),q=`>=${S}.${C}.${P}-${V} <${S}.${+C+1}.0-0`):q=`>=${S}.${C}.${P} <${S}.${+C+1}.0-0`,i("tilde return",q),q})},$=(b,w)=>b.trim().split(/\s+/).map(R=>M(R,w)).join(" "),M=(b,w)=>{i("caret",b,w);const R=w.loose?u[m.CARETLOOSE]:u[m.CARET],f=w.includePrerelease?"-0":"";return b.replace(R,(S,C,P,V,q)=>{i("caret",b,S,C,P,V,q);let G;return y(C)?G="":y(P)?G=`>=${C}.0.0${f} <${+C+1}.0.0-0`:y(V)?C==="0"?G=`>=${C}.${P}.0${f} <${C}.${+P+1}.0-0`:G=`>=${C}.${P}.0${f} <${+C+1}.0.0-0`:q?(i("replaceCaret pr",q),C==="0"?P==="0"?G=`>=${C}.${P}.${V}-${q} <${C}.${P}.${+V+1}-0`:G=`>=${C}.${P}.${V}-${q} <${C}.${+P+1}.0-0`:G=`>=${C}.${P}.${V}-${q} <${+C+1}.0.0-0`):(i("no pr"),C==="0"?P==="0"?G=`>=${C}.${P}.${V}${f} <${C}.${P}.${+V+1}-0`:G=`>=${C}.${P}.${V}${f} <${C}.${+P+1}.0-0`:G=`>=${C}.${P}.${V} <${+C+1}.0.0-0`),i("caret return",G),G})},D=(b,w)=>(i("replaceXRanges",b,w),b.split(/\s+/).map(R=>W(R,w)).join(" ")),W=(b,w)=>{b=b.trim();const R=w.loose?u[m.XRANGELOOSE]:u[m.XRANGE];return b.replace(R,(f,S,C,P,V,q)=>{i("xRange",b,f,S,C,P,V,q);const G=y(C),ae=G||y(P),Z=ae||y(V),Xe=Z;return S==="="&&Xe&&(S=""),q=w.includePrerelease?"-0":"",G?S===">"||S==="<"?f="<0.0.0-0":f="*":S&&Xe?(ae&&(P=0),V=0,S===">"?(S=">=",ae?(C=+C+1,P=0,V=0):(P=+P+1,V=0)):S==="<="&&(S="<",ae?C=+C+1:P=+P+1),S==="<"&&(q="-0"),f=`${S+C}.${P}.${V}${q}`):ae?f=`>=${C}.0.0${q} <${+C+1}.0.0-0`:Z&&(f=`>=${C}.${P}.0${q} <${C}.${+P+1}.0-0`),i("xRange return",f),f})},U=(b,w)=>(i("replaceStars",b,w),b.trim().replace(u[m.STAR],"")),X=(b,w)=>(i("replaceGTE0",b,w),b.trim().replace(u[w.includePrerelease?m.GTE0PRE:m.GTE0],"")),L=b=>(w,R,f,S,C,P,V,q,G,ae,Z,Xe)=>(y(f)?R="":y(S)?R=`>=${f}.0.0${b?"-0":""}`:y(C)?R=`>=${f}.${S}.0${b?"-0":""}`:P?R=`>=${R}`:R=`>=${R}${b?"-0":""}`,y(G)?q="":y(ae)?q=`<${+G+1}.0.0-0`:y(Z)?q=`<${G}.${+ae+1}.0-0`:Xe?q=`<=${G}.${ae}.${Z}-${Xe}`:b?q=`<${G}.${ae}.${+Z+1}-0`:q=`<=${q}`,`${R} ${q}`.trim()),F=(b,w,R)=>{for(let f=0;f<b.length;f++)if(!b[f].test(w))return!1;if(w.prerelease.length&&!R.includePrerelease){for(let f=0;f<b.length;f++)if(i(b[f].semver),b[f].semver!==o.ANY&&b[f].semver.prerelease.length>0){const S=b[f].semver;if(S.major===w.major&&S.minor===w.minor&&S.patch===w.patch)return!0}return!1}return!0};return ps}var xs,Yr;function Dt(){if(Yr)return xs;Yr=1;const r=Symbol("SemVer ANY");class t{static get ANY(){return r}constructor(c,p){if(p=s(p),c instanceof t){if(c.loose===!!p.loose)return c;c=c.value}c=c.trim().split(/\s+/).join(" "),i("comparator",c,p),this.options=p,this.loose=!!p.loose,this.parse(c),this.semver===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(c){const p=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],h=c.match(p);if(!h)throw new TypeError(`Invalid comparator: ${c}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new d(h[2],this.options.loose):this.semver=r}toString(){return this.value}test(c){if(i("Comparator.test",c,this.options.loose),this.semver===r||c===r)return!0;if(typeof c=="string")try{c=new d(c,this.options)}catch{return!1}return o(c,this.operator,this.semver,this.options)}intersects(c,p){if(!(c instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(c.value,p).test(this.value):c.operator===""?c.value===""?!0:new u(this.value,p).test(c.semver):(p=s(p),p.includePrerelease&&(this.value==="<0.0.0-0"||c.value==="<0.0.0-0")||!p.includePrerelease&&(this.value.startsWith("<0.0.0")||c.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&c.operator.startsWith(">")||this.operator.startsWith("<")&&c.operator.startsWith("<")||this.semver.version===c.semver.version&&this.operator.includes("=")&&c.operator.includes("=")||o(this.semver,"<",c.semver,p)&&this.operator.startsWith(">")&&c.operator.startsWith("<")||o(this.semver,">",c.semver,p)&&this.operator.startsWith("<")&&c.operator.startsWith(">")))}}xs=t;const s=Qs(),{safeRe:n,t:a}=nt(),o=ka(),i=Lt(),d=oe(),u=je();return xs}var gs,Zr;function Mt(){if(Zr)return gs;Zr=1;const r=je();return gs=(s,n,a)=>{try{n=new r(n,a)}catch{return!1}return n.test(s)},gs}var vs,Qr;function Pc(){if(Qr)return vs;Qr=1;const r=je();return vs=(s,n)=>new r(s,n).set.map(a=>a.map(o=>o.value).join(" ").trim().split(" ")),vs}var js,en;function Oc(){if(en)return js;en=1;const r=oe(),t=je();return js=(n,a,o)=>{let i=null,d=null,u=null;try{u=new t(a,o)}catch{return null}return n.forEach(m=>{u.test(m)&&(!i||d.compare(m)===-1)&&(i=m,d=new r(i,o))}),i},js}var bs,tn;function Lc(){if(tn)return bs;tn=1;const r=oe(),t=je();return bs=(n,a,o)=>{let i=null,d=null,u=null;try{u=new t(a,o)}catch{return null}return n.forEach(m=>{u.test(m)&&(!i||d.compare(m)===1)&&(i=m,d=new r(i,o))}),i},bs}var Ss,sn;function Ac(){if(sn)return Ss;sn=1;const r=oe(),t=je(),s=At();return Ss=(a,o)=>{a=new t(a,o);let i=new r("0.0.0");if(a.test(i)||(i=new r("0.0.0-0"),a.test(i)))return i;i=null;for(let d=0;d<a.set.length;++d){const u=a.set[d];let m=null;u.forEach(c=>{const p=new r(c.semver.version);switch(c.operator){case">":p.prerelease.length===0?p.patch++:p.prerelease.push(0),p.raw=p.format();case"":case">=":(!m||s(p,m))&&(m=p);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${c.operator}`)}}),m&&(!i||s(i,m))&&(i=m)}return i&&a.test(i)?i:null},Ss}var ws,rn;function Dc(){if(rn)return ws;rn=1;const r=je();return ws=(s,n)=>{try{return new r(s,n).range||"*"}catch{return null}},ws}var Ns,nn;function nr(){if(nn)return Ns;nn=1;const r=oe(),t=Dt(),{ANY:s}=t,n=je(),a=Mt(),o=At(),i=tr(),d=rr(),u=sr();return Ns=(c,p,h,x)=>{c=new r(c,x),p=new n(p,x);let v,g,N,k,j;switch(h){case">":v=o,g=d,N=i,k=">",j=">=";break;case"<":v=i,g=u,N=o,k="<",j="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(c,p,x))return!1;for(let y=0;y<p.set.length;++y){const T=p.set[y];let E=null,$=null;if(T.forEach(M=>{M.semver===s&&(M=new t(">=0.0.0")),E=E||M,$=$||M,v(M.semver,E.semver,x)?E=M:N(M.semver,$.semver,x)&&($=M)}),E.operator===k||E.operator===j||(!$.operator||$.operator===k)&&g(c,$.semver))return!1;if($.operator===j&&N(c,$.semver))return!1}return!0},Ns}var ys,an;function Mc(){if(an)return ys;an=1;const r=nr();return ys=(s,n,a)=>r(s,n,">",a),ys}var Cs,on;function qc(){if(on)return Cs;on=1;const r=nr();return Cs=(s,n,a)=>r(s,n,"<",a),Cs}var Es,cn;function Fc(){if(cn)return Es;cn=1;const r=je();return Es=(s,n,a)=>(s=new r(s,a),n=new r(n,a),s.intersects(n,a)),Es}var Rs,ln;function zc(){if(ln)return Rs;ln=1;const r=Mt(),t=ve();return Rs=(s,n,a)=>{const o=[];let i=null,d=null;const u=s.sort((h,x)=>t(h,x,a));for(const h of u)r(h,n,a)?(d=h,i||(i=h)):(d&&o.push([i,d]),d=null,i=null);i&&o.push([i,null]);const m=[];for(const[h,x]of o)h===x?m.push(h):!x&&h===u[0]?m.push("*"):x?h===u[0]?m.push(`<=${x}`):m.push(`${h} - ${x}`):m.push(`>=${h}`);const c=m.join(" || "),p=typeof n.raw=="string"?n.raw:String(n);return c.length<p.length?c:n},Rs}var Ts,dn;function Uc(){if(dn)return Ts;dn=1;const r=je(),t=Dt(),{ANY:s}=t,n=Mt(),a=ve(),o=(p,h,x={})=>{if(p===h)return!0;p=new r(p,x),h=new r(h,x);let v=!1;e:for(const g of p.set){for(const N of h.set){const k=u(g,N,x);if(v=v||k!==null,k)continue e}if(v)return!1}return!0},i=[new t(">=0.0.0-0")],d=[new t(">=0.0.0")],u=(p,h,x)=>{if(p===h)return!0;if(p.length===1&&p[0].semver===s){if(h.length===1&&h[0].semver===s)return!0;x.includePrerelease?p=i:p=d}if(h.length===1&&h[0].semver===s){if(x.includePrerelease)return!0;h=d}const v=new Set;let g,N;for(const D of p)D.operator===">"||D.operator===">="?g=m(g,D,x):D.operator==="<"||D.operator==="<="?N=c(N,D,x):v.add(D.semver);if(v.size>1)return null;let k;if(g&&N){if(k=a(g.semver,N.semver,x),k>0)return null;if(k===0&&(g.operator!==">="||N.operator!=="<="))return null}for(const D of v){if(g&&!n(D,String(g),x)||N&&!n(D,String(N),x))return null;for(const W of h)if(!n(D,String(W),x))return!1;return!0}let j,y,T,E,$=N&&!x.includePrerelease&&N.semver.prerelease.length?N.semver:!1,M=g&&!x.includePrerelease&&g.semver.prerelease.length?g.semver:!1;$&&$.prerelease.length===1&&N.operator==="<"&&$.prerelease[0]===0&&($=!1);for(const D of h){if(E=E||D.operator===">"||D.operator===">=",T=T||D.operator==="<"||D.operator==="<=",g){if(M&&D.semver.prerelease&&D.semver.prerelease.length&&D.semver.major===M.major&&D.semver.minor===M.minor&&D.semver.patch===M.patch&&(M=!1),D.operator===">"||D.operator===">="){if(j=m(g,D,x),j===D&&j!==g)return!1}else if(g.operator===">="&&!n(g.semver,String(D),x))return!1}if(N){if($&&D.semver.prerelease&&D.semver.prerelease.length&&D.semver.major===$.major&&D.semver.minor===$.minor&&D.semver.patch===$.patch&&($=!1),D.operator==="<"||D.operator==="<="){if(y=c(N,D,x),y===D&&y!==N)return!1}else if(N.operator==="<="&&!n(N.semver,String(D),x))return!1}if(!D.operator&&(N||g)&&k!==0)return!1}return!(g&&T&&!N&&k!==0||N&&E&&!g&&k!==0||M||$)},m=(p,h,x)=>{if(!p)return h;const v=a(p.semver,h.semver,x);return v>0?p:v<0||h.operator===">"&&p.operator===">="?h:p},c=(p,h,x)=>{if(!p)return h;const v=a(p.semver,h.semver,x);return v<0?p:v>0||h.operator==="<"&&p.operator==="<="?h:p};return Ts=o,Ts}var ks,un;function Vc(){if(un)return ks;un=1;const r=nt(),t=Ot(),s=oe(),n=Ea(),a=Je(),o=vc(),i=jc(),d=bc(),u=Sc(),m=wc(),c=Nc(),p=yc(),h=Cc(),x=ve(),v=Ec(),g=Rc(),N=er(),k=Tc(),j=kc(),y=At(),T=tr(),E=Ra(),$=Ta(),M=sr(),D=rr(),W=ka(),U=Ic(),X=Dt(),L=je(),F=Mt(),b=Pc(),w=Oc(),R=Lc(),f=Ac(),S=Dc(),C=nr(),P=Mc(),V=qc(),q=Fc(),G=zc(),ae=Uc();return ks={parse:a,valid:o,clean:i,inc:d,diff:u,major:m,minor:c,patch:p,prerelease:h,compare:x,rcompare:v,compareLoose:g,compareBuild:N,sort:k,rsort:j,gt:y,lt:T,eq:E,neq:$,gte:M,lte:D,cmp:W,coerce:U,Comparator:X,Range:L,satisfies:F,toComparators:b,maxSatisfying:w,minSatisfying:R,minVersion:f,validRange:S,outside:C,gtr:P,ltr:V,intersects:q,simplifyRange:G,subset:ae,SemVer:s,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},ks}var _c=Vc();const Wc=mo(_c),Ia=l.forwardRef(({className:r,value:t,status:s="idle",...n},a)=>{const o=()=>{switch(s){case"installing":return"bg-blue-500";case"completed":return"bg-green-500";case"failed":return"bg-red-500";default:return"bg-gray-300"}};return e.jsx("div",{ref:a,className:I("relative h-4 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-800",r),...n,children:e.jsx("div",{className:I("h-full transition-all duration-300 ease-in-out",o()),style:{width:`${t||0}%`}})})});Ia.displayName="Progress";const Bc=/\[(0|31|32|33|34|35|36|37|90|91|92|93|94|95|96|97)m/g;function Gc({isOpen:r,onClose:t,version:s}){const{installStatus:n,startInstall:a,clearStatus:o,isInstalling:i,canCloseDialog:d}=Ca(),u=l.useRef(null),[m,c]=l.useState(!1);l.useEffect(()=>{r&&s&&(console.log("[InstallLogDialog] 对话框打开,开始安装版本:",s),o(),a(s).catch(y=>{console.error("[InstallLogDialog] 启动安装失败:",y)}))},[r,s,a,o]),l.useEffect(()=>{const y=setTimeout(()=>{u.current&&(u.current.scrollTop=u.current.scrollHeight)},100);return()=>clearTimeout(y)});const p=()=>{switch(n.status){case"idle":return 0;case"installing":return Math.min(90,n.logs.length*2);case"completed":return 100;case"failed":return 100;default:return 0}},h=()=>{switch(n.status){case"installing":return"正在安装...";case"completed":return"安装完成";case"failed":return"安装失败";default:return"准备安装"}},x=()=>{switch(n.status){case"installing":return e.jsx(lr,{className:"h-4 w-4 animate-pulse"});case"completed":return e.jsx(Is,{className:"h-4 w-4 text-green-600"});case"failed":return e.jsx(qs,{className:"h-4 w-4 text-red-600"});default:return null}},v=()=>{switch(n.status){case"installing":return"default";case"completed":return"secondary";case"failed":return"destructive";default:return"outline"}},g=y=>y.replace(Bc,"").split(`
80
- `).filter(E=>E.trim()).map((E,$)=>e.jsx("div",{className:"leading-relaxed",children:E},`${E.slice(0,20)}-${$}`)),N=()=>{d()?(o(),t()):O.error("安装过程中无法关闭对话框,请等待安装完成")},k=y=>{y.key==="Escape"&&d()&&N()},j=()=>{c(!m)};return e.jsx(me,{open:r,onOpenChange:N,children:e.jsxs(le,{className:"max-w-2xl max-h-[80vh] flex flex-col",onKeyDown:k,children:[e.jsx(de,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ue,{className:"text-lg font-semibold",children:"正在安装"}),n.status!=="idle"&&e.jsxs(pe,{variant:v(),className:"flex items-center gap-1",children:[x(),h()]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"安装进度"}),n.version&&e.jsxs(pe,{variant:"outline",className:"text-xs",children:["v",n.version]})]}),e.jsx(Ia,{value:p(),status:n.status,className:"w-full h-2"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:h()}),n.duration&&e.jsxs("span",{children:["耗时: ",(n.duration/1e3).toFixed(1),"s"]})]})]}),n.status==="failed"&&e.jsx(Ve,{variant:"destructive",children:e.jsx(_e,{children:"安装失败,请查看详细日志了解具体原因。"})}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:j,className:"flex w-full items-center justify-between h-auto p-0 gap-0 hover:bg-none bg-none text-sm mb-2",children:[e.jsx("h4",{className:"font-medium",children:"安装日志"}),e.jsx("div",{className:"flex items-center gap-1",children:m?e.jsxs(e.Fragment,{children:["收起 ",e.jsx(Ms,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["展开 ",e.jsx(gt,{className:"h-4 w-4"})]})})]}),m&&e.jsx(Ie,{ref:u,className:"h-[300px] w-full rounded-md border bg-background",children:e.jsx("div",{className:"p-4 font-mono text-xs",children:n.logs.length===0?e.jsxs("div",{className:"text-muted-foreground flex items-center gap-2",children:[e.jsx(lr,{className:"h-4 w-4 animate-pulse"}),"等待日志输出..."]}):e.jsx("div",{className:"space-y-1",children:n.logs.map(y=>e.jsx("div",{className:`${y.type==="stderr"?"text-orange-600":"text-foreground"} break-words`,children:g(y.message)},`${y.timestamp}-${y.message.slice(0,50)}`))})})})]})]}),e.jsx(ke,{className:"flex items-center justify-between pt-4 border-t",children:e.jsxs("div",{className:"flex gap-2",children:[n.status==="completed"&&e.jsxs(A,{variant:"outline",onClick:()=>window.location.reload(),className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"重启应用"]}),e.jsx(A,{onClick:N,disabled:!d(),variant:n.status==="failed"?"destructive":"default",children:i()?"安装中...":n.status==="completed"?"完成":(n.status==="failed","关闭")})]})})]})})}const Hc=[{value:"stable",label:"正式版"},{value:"rc",label:"预览版"},{value:"beta",label:"测试版"},{value:"all",label:"全部版本"}];function mn({children:r,defaultSelectedVersion:t}){const[s,n]=l.useState(!1),[a,o]=l.useState(""),[i,d]=l.useState("stable"),[u,m]=l.useState(!1),[c,p]=l.useState([]),[h,x]=l.useState(!1),{startInstall:v}=Ca(),g=l.useCallback(async E=>{try{x(!0);const $=await z.getAvailableVersions(E),M=$.versions.map(D=>({value:D,label:`v${D}`}));p(M),console.log(`[VersionUpgradeDialog] 获取到 ${$.total} 个${E}版本`),t&&$.versions.includes(t||"")&&o(t||"")}catch($){console.error("[VersionUpgradeDialog] 获取版本列表失败:",$),p([])}finally{x(!1)}},[t]);l.useEffect(()=>{s&&g(i)},[s,i,g]);const N=E=>{d(E),o("")},k=E=>{o(E)},j=async()=>{if(a)try{console.log("[VersionUpgradeDialog] 开始安装版本:",a),n(!1),m(!0),await v(a)}catch(E){console.error("[VersionUpgradeDialog] 安装失败:",E),m(!1)}},y=()=>{m(!1),o("")},T=E=>{E||(o(""),d("stable")),n(E)};return e.jsxs(e.Fragment,{children:[e.jsxs(me,{open:s,onOpenChange:T,children:[e.jsx(Te,{asChild:!0,children:r||e.jsxs(A,{className:"flex items-center gap-2",children:[e.jsx(fo,{className:"h-4 w-4"}),"升级版本"]})}),e.jsxs(le,{className:"sm:max-w-md",children:[e.jsxs(de,{children:[e.jsx(ue,{children:"选择安装版本"}),e.jsx(we,{children:"请选择要安装的 xiaozhi-client 版本"})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"version-select",className:"text-sm font-medium",children:"版本选择"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ne,{value:i,onValueChange:N,children:[e.jsx(xe,{id:"version-type-select",className:"w-[150px]",children:e.jsx(ye,{placeholder:"请选择版本类型"})}),e.jsx(ge,{children:Hc.map(E=>e.jsx(ne,{value:E.value,children:E.label},E.value))})]}),e.jsxs(Ne,{value:a,onValueChange:k,disabled:h,children:[e.jsx(xe,{id:"version-select",children:e.jsx(ye,{placeholder:h?"正在获取版本列表...":"请选择版本"})}),e.jsx(ge,{children:h?e.jsx(ne,{value:"loading",disabled:!0,children:"正在获取版本列表..."}):c.length===0?e.jsx(ne,{value:"empty",disabled:!0,children:"暂无可用版本"}):c.map(E=>e.jsx(ne,{value:E.value,children:E.label},E.value))})]})]}),!h&&c.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"当前版本类型暂无可用版本"}),a&&Wc.lt(a,"1.8.0")&&e.jsxs(Ve,{variant:"destructive",children:[e.jsx(ho,{size:18}),e.jsx(wa,{children:"重要提醒"}),e.jsx(_e,{children:"指定版本低于1.8.0,安装后无法再使用Web界面重装,需手动通过命令操作,请谨慎操作!"})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(A,{variant:"outline",onClick:()=>n(!1),children:"取消"}),e.jsx(A,{onClick:j,disabled:!a||h,children:"确定安装"})]})]})]}),e.jsx(Gc,{isOpen:u,onClose:y,version:a})]})}function Jc({className:r}){const[t,s]=l.useState(null),[n,a]=l.useState(null),[o,i]=l.useState(!0),[d,u]=l.useState(!0),[m,c]=l.useState(null),[p,h]=l.useState(!1),x=l.useRef(null);l.useEffect(()=>{(async()=>{try{i(!0),c(null);const j=await z.getVersion();s(j)}catch(j){c(j instanceof Error?j.message:"获取版本信息失败"),console.error("获取版本信息失败:",j)}finally{i(!1)}})()},[]),l.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]),l.useEffect(()=>{t&&(async()=>{try{u(!0);const j=await z.getLatestVersion();a(j)}catch(j){console.error("检查更新失败:",j),a({currentVersion:t?.version||"unknown",latestVersion:null,hasUpdate:!1,error:j instanceof Error?j.message:"检查更新失败"})}finally{u(!1)}})()},[t]);const v=async()=>{if(t?.version)try{await navigator.clipboard.writeText(t.version),h(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>h(!1),2e3)}catch(k){console.error("复制版本号失败:",k)}};if(o)return e.jsx(pe,{variant:"outline",className:r,children:e.jsx("span",{className:"text-xs",children:"加载中..."})});if(m||!t)return e.jsx(pe,{variant:"outline",className:r,children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"版本未知"})});const g=e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zs,{className:"h-3 w-3"}),e.jsx("span",{className:"font-semibold",children:"版本详情"})]}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"名称:"})," ",t.name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"版本:"})," ",t.version]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("strong",{children:"最新版本:"})," ",n.latestVersion||"未知"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"状态:"}),d?"检查中...":n.hasUpdate?"有新版本":"已是最新"]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"描述:"})," ",t.description]}),e.jsxs("div",{children:[e.jsx("strong",{children:"作者:"})," ",t.author]})]}),e.jsx("div",{className:"pt-1 border-t",children:e.jsxs("button",{type:"button",onClick:v,className:"text-xs text-primary hover:underline flex items-center gap-1",children:[e.jsx(xt,{className:"h-3 w-3"}),p?"已复制!":"复制版本号"]})})]}),N=()=>d?null:n?.hasUpdate&&n.latestVersion?e.jsx(mn,{defaultSelectedVersion:n.latestVersion,children:e.jsxs(A,{variant:"link",className:"p-0 gap-1",children:[e.jsx(po,{}),"升级版本"]})}):e.jsx(mn,{defaultSelectedVersion:t.version,children:e.jsx(A,{variant:"link",className:"p-0 gap-1",children:"切换版本"})});return e.jsx(Na,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[N(),e.jsxs(Ys,{children:[e.jsx(Zs,{asChild:!0,children:e.jsxs("span",{className:"text-sm cursor-help",children:["v",t.version]})}),e.jsx(Pt,{children:g})]})]})})}function Xc({title:r}){return e.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b px-4",children:[e.jsx("h1",{className:"text-base font-medium",children:r}),e.jsxs("div",{className:"flex flex-1 justify-end items-center gap-4",children:[e.jsx(Jc,{}),e.jsx("a",{href:"https://qun.qq.com/universal-share/share?ac=1&authKey=c08PvS2zvAF1NN%2F%2BuaOi0ze1AElTIsvFBLwbWUMFc2ixjaZYxqZTUQHzipwd8Kka&busi_data=eyJncm91cENvZGUiOiIxMDU0ODg4NDczIiwidG9rZW4iOiJuSmJUN2cyUEVkNEQ5WXovM3RQbFVNcDluMGVibUNZTUQvL1RuQnFJRjBkZmRZQnRBRTdwU0szL3V2Y0dLc1ZmIiwidWluIjoiMzkxMTcyMDYwMCJ9&data=9cH6_zEC-sN3xYlwzKEWiYF71RLY9CId5taN-gy6XZo7axSlSWDpd1Ojui5hYMQKIgEJYSPw59XYgF5vH2wLog&svctype=4&tempid=h5_group_info",target:"_blank",rel:"noopener noreferrer",children:e.jsx(xc,{size:24,className:"text-slate-800",fill:"currentColor"})}),e.jsx("a",{href:"https://github.com/shenjingnan/xiaozhi-client",target:"_blank",rel:"noopener noreferrer",children:e.jsx(gc,{size:24,className:"text-slate-800",fill:"currentColor"})})]})]})}function Kc(){return e.jsxs("div",{className:"flex h-screen flex-col",children:[e.jsx(Xc,{title:"看板"}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"@container/main flex flex-1 flex-col gap-2",children:e.jsxs("div",{className:"flex flex-col gap-4 py-4 md:gap-6 md:py-6",children:[e.jsx(ec,{}),e.jsx("div",{className:"flex flex-col gap-4 px-4 lg:px-6",children:e.jsx(pc,{initialStatus:"all"})})]})})})]})}function Yc(){return e.jsxs(Xo,{children:[e.jsx($o,{}),e.jsxs(xo,{children:[e.jsx(qt,{path:"/",element:e.jsx(dr,{to:"/dashboard"})}),e.jsx(qt,{path:"/dashboard",element:e.jsx(Kc,{})}),e.jsx(qt,{path:"*",element:e.jsx(dr,{to:"/dashboard",replace:!0})})]}),e.jsx(So,{richColors:!0,closeButton:!0,swipeDirections:[],toastOptions:{classNames:{description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-white group-[.toast]:text-black",error:"group toast group-[.toaster]:bg-red group-[.toaster]:text-red-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg",success:"group toast group-[.toaster]:bg-green group-[.toaster]:text-green-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg",warning:"group toast group-[.toaster]:bg-yellow group-[.toaster]:text-yellow-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg",info:"group toast group-[.toaster]:bg-blue group-[.toaster]:text-blue-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg"}}})]})}go.createRoot(document.getElementById("root")).render(e.jsx(vo.StrictMode,{children:e.jsx(jo,{children:e.jsx(Yc,{})})}));
81
- //# sourceMappingURL=index-BAV6nu4X.js.map