xiaozhi-client 1.7.7 → 1.7.8

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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xiaozhi-client",
3
- "version": "1.7.7",
3
+ "version": "1.7.8",
4
4
  "description": "小智 AI 客户端 命令行工具",
5
5
  "type": "module",
6
6
  "main": "dist/cli.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xiaozhi-client",
3
- "version": "1.7.7",
3
+ "version": "1.7.8",
4
4
  "description": "小智 AI 客户端 命令行工具",
5
5
  "type": "module",
6
6
  "main": "dist/cli.js",
@@ -0,0 +1,31 @@
1
+ var Js=Object.defineProperty;var Xs=(r,t,s)=>t in r?Js(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s;var U=(r,t,s)=>Xs(r,typeof t!="symbol"?t+"":t,s);import{c as it,d as ct,u as lt,r as n,t as j,j as e,S as he,R as $t,O as Ve,P as At,C as Ke,a as dt,X as Dt,b as Ge,D as Je,e as Lt,f as Ot,g as Zs,h as Ys,i as Qs,k as er,l as tr,L as Ut,I as sr,m as _t,n as rr,o as Ne,p as Bt,q as ar,s as qt,v as Ht,w as Ft,A as Vt,x as Kt,y as or,B as nr,E as ir,F as je,W as yt,G as Nt,H as Gt,J as cr,K as Ce,M as Jt,N as lr,Q as dr,U as ur,V as ke,Y as Ee,Z as Xt,_ as mr,$ as Zt,a0 as Yt,a1 as fr,a2 as Qt,a3 as es,a4 as pr,a5 as ts,a6 as hr,a7 as ss,a8 as gr,a9 as rs,aa as as,ab as xr,ac as br,ad as os,ae as wr,af as Sr,ag as vr,ah as jr,ai as Se,aj as yr,ak as Nr,al as Ct,am as Cr,an as kr,ao as kt,ap as Et,aq as Er,ar as Pr,as as Rr,at as st,au as Tr,av as Wr,aw as zr,ax as Mr}from"./react-vendor-Dhmn1GAM.js";import{t as Ir,c as ns,a as Pe,T as $r}from"./utils-DgcJ1IpB.js";import{z as K,o as is,b as Ar,_ as Dr,s as Pt,c as Lr}from"./form-utils-D6Zwv25A.js";import"./radix-ui-BA32w1ww.js";import"./vendor-DCIxzvIG.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&a(c)}).observe(document,{childList:!0,subtree:!0});function s(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(o){if(o.ep)return;o.ep=!0;const i=s(o);fetch(o.href,i)}})();class Or{constructor(t){U(this,"baseUrl");if(t)this.baseUrl=t;else{const s=window.location.protocol,a=window.location.hostname,o=window.location.port;this.baseUrl=`${s}//${a}${o?`:${o}`:""}`}}async request(t,s={}){var c;const a=`${this.baseUrl}${t}`,o={headers:{"Content-Type":"application/json",...s.headers}},i=await fetch(a,{...o,...s});if(!i.ok){let m=`HTTP ${i.status}: ${i.statusText}`;try{m=((c=(await i.json()).error)==null?void 0:c.message)||m}catch{}throw new Error(m)}return i.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.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(){var s;const t=await this.request("/api/config/exists");if(!t.success||((s=t.data)==null?void 0:s.exists)===void 0)throw new Error("检查配置是否存在失败");return t.data.exists}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(){var s;const t=await this.request("/api/status/connected");if(!t.success||((s=t.data)==null?void 0:s.connected)===void 0)throw new Error("检查客户端连接失败");return t.data.connected}async getLastHeartbeat(){var s;const t=await this.request("/api/status/heartbeat");if(!t.success)throw new Error("获取最后心跳时间失败");return((s=t.data)==null?void 0:s.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.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.message||"设置活跃 MCP 服务器失败")}async resetStatus(){const t=await this.request("/api/status/reset",{method:"POST"});if(!t.success)throw new Error(t.message||"重置状态失败")}async addCustomTool(t,s,a,o){if(typeof t=="object"&&"type"in t&&"data"in t){const m=await this.request("/api/tools/custom",{method:"POST",body:JSON.stringify(t)});if(!m.success||!m.data)throw new Error(m.message||"添加自定义工具失败");return m.data.tool}const i=t,c=await this.request("/api/tools/custom",{method:"POST",body:JSON.stringify({workflow:i,customName:s,customDescription:a,parameterConfig:o})});if(!c.success||!c.data)throw new Error(c.message||"添加自定义工具失败");return c.data.tool}async updateCustomTool(t,s){const a=await this.request(`/api/tools/custom/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(s)});if(!a.success||!a.data)throw new Error(a.message||"更新自定义工具失败");return a.data.tool}async removeCustomTool(t){const s=await this.request(`/api/tools/custom/${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success)throw new Error(s.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"){const s=new URLSearchParams;t!=="all"&&s.append("status",t);const a=`/api/tools/list${s.toString()?`?${s.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.message||"重启服务失败")}async stopService(){const t=await this.request("/api/services/stop",{method:"POST"});if(!t.success)throw new Error(t.message||"停止服务失败")}async startService(){const t=await this.request("/api/services/start",{method:"POST"});if(!t.success)throw new Error(t.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 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 clearVersionCache(){const t=await this.request("/api/version/cache/clear",{method:"POST"});if(!t.success)throw new Error(t.message||"清除版本缓存失败")}async getEndpointStatus(t){const s=await this.request(`/api/endpoints/${encodeURIComponent(t)}/status`);if(!s.success||!s.data)throw new Error("获取接入点状态失败");return s.data}async connectEndpoint(t){const s=await this.request(`/api/endpoints/${encodeURIComponent(t)}/connect`,{method:"POST"});if(!s.success)throw new Error(s.message||"连接接入点失败")}async disconnectEndpoint(t){const s=await this.request(`/api/endpoints/${encodeURIComponent(t)}/disconnect`,{method:"POST"});if(!s.success)throw new Error(s.message||"断开接入点失败")}async reconnectEndpoint(t){const s=await this.request(`/api/endpoints/${encodeURIComponent(t)}/reconnect`,{method:"POST"});if(!s.success)throw new Error(s.message||"重连接入点失败")}async addEndpoint(t){const s=await this.request("/api/endpoints/add",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success||!s.data)throw new Error(s.message||"添加接入点失败");return s.data}async removeEndpoint(t){const s=await this.request(`/api/endpoints/${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success)throw new Error(s.message||"移除接入点失败")}}const L=new Or;var Z=(r=>(r.DISCONNECTED="disconnected",r.CONNECTING="connecting",r.CONNECTED="connected",r.RECONNECTING="reconnecting",r))(Z||{});class Ur{constructor(){U(this,"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 a=this.listeners.get(t);a&&(a.delete(s),a.size===0&&this.listeners.delete(t))}emit(t,s){const a=this.listeners.get(t);if(a)for(const o of a)try{o(s)}catch(i){console.error(`[EventBus] 事件监听器执行失败 (${t}):`,i)}}clear(){this.listeners.clear()}getListenerCount(t){var s;return t?((s=this.listeners.get(t))==null?void 0:s.size)||0:Array.from(this.listeners.values()).reduce((a,o)=>a+o.size,0)}}const V=class V{constructor(t={}){U(this,"ws",null);U(this,"url");U(this,"state","disconnected");U(this,"eventBus",new Ur);U(this,"legacyListeners",{});U(this,"reconnectAttempts",0);U(this,"maxReconnectAttempts");U(this,"reconnectInterval");U(this,"reconnectTimer");U(this,"heartbeatTimer");U(this,"heartbeatInterval");U(this,"heartbeatTimeout");U(this,"lastHeartbeat",0);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,this.setupLegacyEventBridge()}static getInstance(t){if(V.instance)return V.instance;if(V.isCreating)throw new Error("[WebSocketManager] 检测到循环创建,请检查代码逻辑");V.isCreating=!0;try{return V.instance=new V(t),console.log("[WebSocketManager] 单例实例已创建"),V.instance}finally{V.isCreating=!1}}static resetInstance(){V.instance&&(V.instance.disconnect(),V.instance.eventBus.clear(),V.instance=null,console.log("[WebSocketManager] 单例实例已重置"))}setupLegacyEventBridge(){this.eventBus.on("connection:connected",()=>{var t,s;(s=(t=this.legacyListeners).connected)==null||s.call(t)}),this.eventBus.on("connection:disconnected",()=>{var t,s;(s=(t=this.legacyListeners).disconnected)==null||s.call(t)}),this.eventBus.on("connection:error",({error:t})=>{var s,a;(a=(s=this.legacyListeners).error)==null||a.call(s,t)}),this.eventBus.on("data:configUpdate",t=>{var s,a;(a=(s=this.legacyListeners).configUpdate)==null||a.call(s,t)}),this.eventBus.on("data:statusUpdate",t=>{var s,a;(a=(s=this.legacyListeners).statusUpdate)==null||a.call(s,t)}),this.eventBus.on("data:restartStatus",t=>{var s,a;(a=(s=this.legacyListeners).restartStatus)==null||a.call(s,t)})}getDefaultWebSocketUrl(){const t=localStorage.getItem("xiaozhi-ws-url");if(t)return t;const s=window.location.protocol==="https:"?"wss:":"ws:",a=window.location.hostname,o=window.location.port==="5173"?9999:window.location.port;return`${s}//${a}${o?`:${o}`:""}`}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}on(t,s){console.warn("[WebSocketManager] on() 方法已废弃,请使用 subscribe() 方法"),this.legacyListeners[t]=s}off(t){console.warn("[WebSocketManager] off() 方法已废弃,请使用 unsubscribe() 方法"),delete this.legacyListeners[t]}getState(){return this.state}isConnected(){var t;return this.state==="connected"&&((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}setUrl(t){this.url!==t&&(this.url=t,localStorage.setItem("xiaozhi-ws-url",t),this.isConnected()&&(this.disconnect(),setTimeout(()=>this.connect(),1e3)))}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){var s;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"heartbeatResponse":this.lastHeartbeat=Date.now(),this.eventBus.emit("system:heartbeat",{timestamp:this.lastHeartbeat});break;case"error":{const a=new Error(((s=t.error)==null?void 0:s.message)||"服务器错误");console.error("[WebSocket] 服务器错误:",t.error),this.eventBus.emit("system:error",{error:a,message:t}),this.eventBus.emit("connection:error",{error:a,context:"server_error"});break}default:console.log("[WebSocket] 未处理的消息类型:",t.type)}}catch(a){console.error("[WebSocket] 消息处理失败:",a),this.eventBus.emit("system:error",{error:a,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(){var t;if(this.isConnected()){const s={type:"clientStatus",data:{status:"connected",timestamp:Date.now()}};(t=this.ws)==null||t.send(JSON.stringify(s))}}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}};U(V,"instance",null),U(V,"isCreating",!1);let ot=V;const I=ot.getInstance(),Rt={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 Oe=null,Ue=null;const oe=it()(ct((r,t)=>({...Rt,setClientStatus:(s,a="http")=>{console.log(`[StatusStore] 设置客户端状态,来源: ${a}`),r(o=>({clientStatus:s,lastSource:a,loading:{...o.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setClientStatus")},setRestartStatus:(s,a="http")=>{console.log(`[StatusStore] 设置重启状态,来源: ${a}`),r(o=>({restartStatus:s,lastSource:a,loading:{...o.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,a="http")=>{console.log(`[StatusStore] 设置完整状态,来源: ${a}`),r(o=>({fullStatus:s,clientStatus:s.client,restartStatus:s.restart||null,lastSource:a,loading:{...o.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setFullStatus")},setLoading:s=>{r(a=>({loading:{...a.loading,...s}}),!1,"setLoading")},setError:s=>{r(a=>({loading:{...a.loading,lastError:s}}),!1,"setError")},getStatus:async()=>{const{fullStatus:s,loading:a}=t();return s&&a.lastUpdated&&Date.now()-a.lastUpdated<30*1e3?s:t().refreshStatus()},refreshStatus:async()=>{const{setLoading:s,setFullStatus:a,setError:o,polling:i}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[StatusStore] 开始刷新状态");const c=await L.getStatus();return a(c,"http"),i.enabled&&t().setPollingConfig({currentRetries:0}),console.log("[StatusStore] 状态刷新成功"),c}catch(c){const m=c instanceof Error?c:new Error("状态刷新失败");if(console.error("[StatusStore] 状态刷新失败:",m),o(m),i.enabled){const h=i.currentRetries+1;t().setPollingConfig({currentRetries:h}),h>=i.maxRetries&&(console.warn("[StatusStore] 达到最大重试次数,停止轮询"),t().stopPolling())}throw m}finally{s({isRefreshing:!1})}},restartService:async()=>{const{setLoading:s,setRestartStatus:a,setError:o,startRestartPolling:i}=t();try{s({isRestarting:!0,lastError:null}),console.log("[StatusStore] 开始重启服务"),a({status:"restarting",timestamp:Date.now()},"http"),await L.restartService(),console.log("[StatusStore] 服务重启请求已发送,开始重连检查"),i()}catch(c){const m=c instanceof Error?c:new Error("服务重启失败");throw console.error("[StatusStore] 服务重启失败:",m),a({status:"failed",error:m.message,timestamp:Date.now()},"http"),o(m),s({isRestarting:!1}),m}},getServiceStatus:async()=>{try{console.log("[StatusStore] 获取服务状态");const s=await L.getServiceStatus();return t().setServiceStatus(s),s}catch(s){const a=s instanceof Error?s:new Error("获取服务状态失败");throw console.error("[StatusStore] 获取服务状态失败:",a),t().setError(a),a}},getServiceHealth:async()=>{try{console.log("[StatusStore] 获取服务健康状态");const s=await L.getServiceHealth();return t().setServiceHealth(s),s}catch(s){const a=s instanceof Error?s:new Error("获取服务健康状态失败");throw console.error("[StatusStore] 获取服务健康状态失败:",a),t().setError(a),a}},startPolling:(s=3e4)=>{const{polling:a,refreshStatus:o}=t();if(a.enabled){console.log("[StatusStore] 轮询已启用,跳过启动");return}console.log(`[StatusStore] 启动状态轮询,间隔: ${s}ms`),r(i=>({polling:{...i.polling,enabled:!0,interval:s,currentRetries:0}}),!1,"startPolling"),o().catch(i=>{console.error("[StatusStore] 轮询初始刷新失败:",i)}),Oe=setInterval(()=>{t().polling.enabled&&o().catch(c=>{console.error("[StatusStore] 轮询刷新失败:",c)})},s)},stopPolling:()=>{console.log("[StatusStore] 停止状态轮询"),r(s=>({polling:{...s.polling,enabled:!1,currentRetries:0}}),!1,"stopPolling"),Oe&&(clearInterval(Oe),Oe=null)},setPollingConfig:s=>{r(a=>({polling:{...a.polling,...s}}),!1,"setPollingConfig")},startRestartPolling:()=>{const{restartPolling:s,refreshStatus:a,setRestartStatus:o,setLoading:i}=t();if(s.enabled){console.log("[StatusStore] 重启轮询已启用,跳过启动");return}console.log("[StatusStore] 启动重启后重连检查轮询");const c=Date.now();r(m=>({restartPolling:{...m.restartPolling,enabled:!0,currentAttempts:0,startTime:c}}),!1,"startRestartPolling"),Ue=setInterval(async()=>{var f;const m=t(),{restartPolling:h}=m;if(!h.enabled)return;const w=Date.now()-(h.startTime||0),x=h.currentAttempts+1;console.log(`[StatusStore] 重启重连检查 (第 ${x} 次,已用时 ${Math.round(w/1e3)}s)`);try{if(((f=(await a()).client)==null?void 0:f.status)==="connected"){console.log("[StatusStore] 服务重连成功,停止重启轮询"),o({status:"completed",timestamp:Date.now()},"polling"),m.stopRestartPolling(),i({isRestarting:!1});return}m.setRestartPollingConfig({currentAttempts:x}),(w>=h.timeout||x>=h.maxAttempts)&&(console.warn("[StatusStore] 重启重连检查超时或达到最大尝试次数"),o({status:"failed",error:"重连超时,服务可能未成功重启",timestamp:Date.now()},"polling"),m.stopRestartPolling(),i({isRestarting:!1}))}catch(u){console.log(`[StatusStore] 重启重连检查失败 (第 ${x} 次):`,u),m.setRestartPollingConfig({currentAttempts:x}),(w>=h.timeout||x>=h.maxAttempts)&&(console.error("[StatusStore] 重启重连检查超时或达到最大尝试次数"),o({status:"failed",error:"重连超时,服务可能未成功重启",timestamp:Date.now()},"polling"),m.stopRestartPolling(),i({isRestarting:!1}))}},s.interval)},stopRestartPolling:()=>{console.log("[StatusStore] 停止重启轮询"),r(s=>({restartPolling:{...s.restartPolling,enabled:!1,currentAttempts:0,startTime:null}}),!1,"stopRestartPolling"),Ue&&(clearInterval(Ue),Ue=null)},setRestartPollingConfig:s=>{r(a=>({restartPolling:{...a.restartPolling,...s}}),!1,"setRestartPollingConfig")},reset:()=>{console.log("[StatusStore] 重置状态"),t().stopPolling(),t().stopRestartPolling(),r(Rt,!1,"reset")},initialize:async()=>{const{setLoading:s,refreshStatus:a}=t();try{s({isLoading:!0}),console.log("[StatusStore] 初始化状态 Store"),I.subscribe("data:statusUpdate",o=>{console.log("[StatusStore] 收到 WebSocket 状态更新"),t().setClientStatus(o,"websocket")}),I.subscribe("data:restartStatus",o=>{console.log("[StatusStore] 收到 WebSocket 重启状态更新"),t().setRestartStatus(o,"websocket")}),await a(),console.log("[StatusStore] 状态 Store 初始化完成")}catch(o){throw console.error("[StatusStore] 状态 Store 初始化失败:",o),o}finally{s({isLoading:!1})}}}),{name:"status-store"})),_r=()=>oe(r=>r.clientStatus),cs=()=>oe(r=>r.restartStatus),ls=()=>oe(r=>r.restartPolling),Br=()=>oe(lt(r=>({getStatus:r.getStatus,refreshStatus:r.refreshStatus,restartService:r.restartService,getServiceStatus:r.getServiceStatus,getServiceHealth:r.getServiceHealth,startPolling:r.startPolling,stopPolling:r.stopPolling,setPollingConfig:r.setPollingConfig,startRestartPolling:r.startRestartPolling,stopRestartPolling:r.stopRestartPolling,setRestartPollingConfig:r.setRestartPollingConfig,reset:r.reset,initialize:r.initialize})));function qr(){const r=cs(),t=ls(),s=n.useRef(null),a=n.useRef(null);n.useEffect(()=>{if(!r)return;const{status:o,timestamp:i,error:c}=r;if(!(s.current===o&&a.current===i))switch(s.current=o,a.current=i,o){case"restarting":j.info("正在重启服务...",{id:"restart-status-progress",description:"请耐心等待",duration:0});break;case"completed":{const m=t.enabled?`服务重启成功!重连检查完成 (${t.currentAttempts}次检查)`:"服务重启成功!";j.dismiss("restart-status-progress"),j.success(m,{id:"restart-status-success",description:"服务已恢复正常运行"});break}case"failed":{const m=c||"服务重启失败",h=t.enabled?`重连检查超时 (${t.currentAttempts}/${t.maxAttempts}次)`:"请检查服务状态或稍后重试";j.dismiss("restart-status-progress"),j.error(m,{id:"restart-status-failed",description:h});break}}},[r,t]),n.useEffect(()=>()=>{s.current=null,a.current=null},[])}function Hr(){return qr(),null}function g(...r){return Ir(ns(r))}const ut=Pe("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"}}),E=n.forwardRef(({className:r,variant:t,size:s,asChild:a=!1,...o},i)=>{const c=a?he:"button";return e.jsx(c,{className:g(ut({variant:t,size:s,className:r})),ref:i,...o})});E.displayName="Button";const re=n.forwardRef(({className:r,type:t,...s},a)=>e.jsx("input",{type:t,className:g("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:a,"data-1p-ignore":!0,...s}));re.displayName="Input";const mt=n.forwardRef(({className:r,orientation:t="horizontal",decorative:s=!0,...a},o)=>e.jsx($t,{ref:o,decorative:s,orientation:t,className:g("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",r),...a}));mt.displayName=$t.displayName;const Fr=Lt,Vr=At,ds=n.forwardRef(({className:r,...t},s)=>e.jsx(Ve,{className:g("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}));ds.displayName=Ve.displayName;const Kr=Pe("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),us=n.forwardRef(({side:r="right",className:t,children:s,...a},o)=>e.jsxs(Vr,{children:[e.jsx(ds,{}),e.jsxs(Ke,{ref:o,className:g(Kr({side:r}),t),...a,children:[s,e.jsxs(dt,{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-secondary",children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));us.displayName=Ke.displayName;const ms=({className:r,...t})=>e.jsx("div",{className:g("flex flex-col space-y-2 text-center sm:text-left",r),...t});ms.displayName="SheetHeader";const fs=n.forwardRef(({className:r,...t},s)=>e.jsx(Ge,{ref:s,className:g("text-lg font-semibold text-foreground",r),...t}));fs.displayName=Ge.displayName;const ps=n.forwardRef(({className:r,...t},s)=>e.jsx(Je,{ref:s,className:g("text-sm text-muted-foreground",r),...t}));ps.displayName=Je.displayName;function be({className:r,...t}){return e.jsx("div",{className:g("animate-pulse rounded-md bg-muted",r),...t})}const hs=Zs,gs=Ys,xs=Qs,ft=n.forwardRef(({className:r,sideOffset:t=4,...s},a)=>e.jsx(Ot,{ref:a,sideOffset:t,className:g("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}));ft.displayName=Ot.displayName;const rt=768;function Gr(){const[r,t]=n.useState(void 0);return n.useEffect(()=>{const s=window.matchMedia(`(max-width: ${rt-1}px)`),a=()=>{t(window.innerWidth<rt)};return s.addEventListener("change",a),t(window.innerWidth<rt),()=>s.removeEventListener("change",a)},[]),!!r}const Jr="sidebar_state",Xr=60*60*24*7,Zr="16rem",Yr="18rem",Qr="3rem",ea="b",bs=n.createContext(null);function Xe(){const r=n.useContext(bs);if(!r)throw new Error("useSidebar must be used within a SidebarProvider.");return r}const pt=n.forwardRef(({defaultOpen:r=!0,open:t,onOpenChange:s,className:a,style:o,children:i,...c},m)=>{const h=Gr(),[w,x]=n.useState(!1),[f,u]=n.useState(r),l=t??f,p=n.useCallback(P=>{const z=typeof P=="function"?P(l):P;s?s(z):u(z),document.cookie=`${Jr}=${z}; path=/; max-age=${Xr}`},[s,l]),S=n.useCallback(()=>h?x(P=>!P):p(P=>!P),[h,p]);n.useEffect(()=>{const P=z=>{z.key===ea&&(z.metaKey||z.ctrlKey)&&(z.preventDefault(),S())};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[S]);const b=l?"expanded":"collapsed",W=n.useMemo(()=>({state:b,open:l,setOpen:p,isMobile:h,openMobile:w,setOpenMobile:x,toggleSidebar:S}),[b,l,p,h,w,S]);return e.jsx(bs.Provider,{value:W,children:e.jsx(hs,{delayDuration:0,children:e.jsx("div",{style:{"--sidebar-width":Zr,"--sidebar-width-icon":Qr,...o},className:g("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",a),ref:m,...c,children:i})})})});pt.displayName="SidebarProvider";const ws=n.forwardRef(({side:r="left",variant:t="sidebar",collapsible:s="offcanvas",className:a,children:o,...i},c)=>{const{isMobile:m,state:h,openMobile:w,setOpenMobile:x}=Xe();return s==="none"?e.jsx("div",{className:g("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",a),ref:c,...i,children:o}):m?e.jsx(Fr,{open:w,onOpenChange:x,...i,children:e.jsxs(us,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":Yr},side:r,children:[e.jsxs(ms,{className:"sr-only",children:[e.jsx(fs,{children:"Sidebar"}),e.jsx(ps,{children:"Displays the mobile sidebar."})]}),e.jsx("div",{className:"flex h-full w-full flex-col",children:o})]})}):e.jsxs("div",{ref:c,className:"group peer hidden text-sidebar-foreground md:block","data-state":h,"data-collapsible":h==="collapsed"?s:"","data-variant":t,"data-side":r,children:[e.jsx("div",{className:g("relative w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",t==="floating"||t==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:g("fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",r==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",t==="floating"||t==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",a),...i,children:e.jsx("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow",children:o})})]})});ws.displayName="Sidebar";const Ss=n.forwardRef(({className:r,onClick:t,...s},a)=>{const{toggleSidebar:o}=Xe();return e.jsxs(E,{ref:a,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:g("h-7 w-7",r),onClick:i=>{t==null||t(i),o()},...s,children:[e.jsx(er,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Ss.displayName="SidebarTrigger";const ta=n.forwardRef(({className:r,...t},s)=>{const{toggleSidebar:a}=Xe();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:a,title:"Toggle Sidebar",className:g("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",r),...t})});ta.displayName="SidebarRail";const ht=n.forwardRef(({className:r,...t},s)=>e.jsx("main",{ref:s,className:g("relative flex w-full flex-1 flex-col bg-background","md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",r),...t}));ht.displayName="SidebarInset";const sa=n.forwardRef(({className:r,...t},s)=>e.jsx(re,{ref:s,"data-sidebar":"input",className:g("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",r),...t}));sa.displayName="SidebarInput";const vs=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:g("flex flex-col gap-2 p-2",r),...t}));vs.displayName="SidebarHeader";const ra=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:g("flex flex-col gap-2 p-2",r),...t}));ra.displayName="SidebarFooter";const aa=n.forwardRef(({className:r,...t},s)=>e.jsx(mt,{ref:s,"data-sidebar":"separator",className:g("mx-2 w-auto bg-sidebar-border",r),...t}));aa.displayName="SidebarSeparator";const js=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:g("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",r),...t}));js.displayName="SidebarContent";const ys=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:g("relative flex w-full min-w-0 flex-col p-2",r),...t}));ys.displayName="SidebarGroup";const oa=n.forwardRef(({className:r,asChild:t=!1,...s},a)=>{const o=t?he:"div";return e.jsx(o,{ref:a,"data-sidebar":"group-label",className:g("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",r),...s})});oa.displayName="SidebarGroupLabel";const na=n.forwardRef(({className:r,asChild:t=!1,...s},a)=>{const o=t?he:"button";return e.jsx(o,{ref:a,"data-sidebar":"group-action",className:g("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",r),...s})});na.displayName="SidebarGroupAction";const Ns=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:g("w-full text-sm",r),...t}));Ns.displayName="SidebarGroupContent";const gt=n.forwardRef(({className:r,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:g("flex w-full min-w-0 flex-col gap-1",r),...t}));gt.displayName="SidebarMenu";const xt=n.forwardRef(({className:r,...t},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:g("group/menu-item relative",r),...t}));xt.displayName="SidebarMenuItem";const ia=Pe("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),bt=n.forwardRef(({asChild:r=!1,isActive:t=!1,variant:s="default",size:a="default",tooltip:o,className:i,...c},m)=>{const h=r?he:"button",{isMobile:w,state:x}=Xe(),f=e.jsx(h,{ref:m,"data-sidebar":"menu-button","data-size":a,"data-active":t,className:g(ia({variant:s,size:a}),i),...c});return o?(typeof o=="string"&&(o={children:o}),e.jsxs(gs,{children:[e.jsx(xs,{asChild:!0,children:f}),e.jsx(ft,{side:"right",align:"center",hidden:x!=="collapsed"||w,...o})]})):f});bt.displayName="SidebarMenuButton";const ca=n.forwardRef(({className:r,asChild:t=!1,showOnHover:s=!1,...a},o)=>{const i=t?he:"button";return e.jsx(i,{ref:o,"data-sidebar":"menu-action",className:g("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",s&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",r),...a})});ca.displayName="SidebarMenuAction";const la=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:g("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r),...t}));la.displayName="SidebarMenuBadge";const da=n.forwardRef(({className:r,showIcon:t=!1,...s},a)=>{const o=n.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{ref:a,"data-sidebar":"menu-skeleton",className:g("flex h-8 items-center gap-2 rounded-md px-2",r),...s,children:[t&&e.jsx(be,{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx(be,{className:"h-4 max-w-[--skeleton-width] flex-1","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});da.displayName="SidebarMenuSkeleton";const ua=n.forwardRef(({className:r,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:g("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",r),...t}));ua.displayName="SidebarMenuSub";const ma=n.forwardRef(({...r},t)=>e.jsx("li",{ref:t,...r}));ma.displayName="SidebarMenuSubItem";const fa=n.forwardRef(({asChild:r=!1,size:t="md",isActive:s,className:a,...o},i)=>{const c=r?he:"a";return e.jsx(c,{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":s,className:g("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",t==="sm"&&"text-xs",t==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",a),...o})});fa.displayName="SidebarMenuSubButton";function pa({items:r}){const t=tr();return e.jsx(ys,{children:e.jsx(Ns,{className:"flex flex-col gap-2",children:e.jsx(gt,{children:r.map(s=>{const o=t.pathname===s.url;return e.jsx(xt,{children:e.jsx(bt,{className:g("min-w-8 duration-200 ease-linear hover:bg-primary/5",o?"bg-primary text-primary-foreground duration-200 ease-linear hover:bg-primary/90 hover:text-primary-foreground active:bg-primary/90 active:text-primary-foreground":"min-w-8 duration-200 ease-linear"),tooltip:s.title,asChild:!0,children:e.jsxs(Ut,{to:s.url,children:[s.icon&&e.jsx(s.icon,{}),e.jsx("span",{children:s.title})]})})},s.title)})})})})}const ha=Pe("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 ne({className:r,variant:t,...s}){return e.jsx("div",{className:g(ha({variant:t}),r),...s})}function ga({className:r,showDetails:t=!1,variant:s="secondary"}){const[a,o]=n.useState(null),[i,c]=n.useState(!0),[m,h]=n.useState(null),[w,x]=n.useState(!1);n.useEffect(()=>{(async()=>{try{c(!0),h(null);const p=await L.getVersion();o(p)}catch(p){h(p instanceof Error?p.message:"获取版本信息失败"),console.error("获取版本信息失败:",p)}finally{c(!1)}})()},[]);const f=async()=>{if(a!=null&&a.version)try{await navigator.clipboard.writeText(a.version),x(!0),setTimeout(()=>x(!1),2e3)}catch(l){console.error("复制版本号失败:",l)}};if(i)return e.jsx(ne,{variant:"outline",className:r,children:e.jsx("span",{className:"text-xs",children:"加载中..."})});if(m||!a)return e.jsx(ne,{variant:"outline",className:r,children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"版本未知"})});const u=e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sr,{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:"名称:"})," ",a.name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"版本:"})," ",a.version]}),e.jsxs("div",{children:[e.jsx("strong",{children:"描述:"})," ",a.description]}),e.jsxs("div",{children:[e.jsx("strong",{children:"作者:"})," ",a.author]})]}),e.jsx("div",{className:"pt-1 border-t",children:e.jsxs("button",{type:"button",onClick:f,className:"text-xs text-primary hover:underline flex items-center gap-1",children:[e.jsx(_t,{className:"h-3 w-3"}),w?"已复制!":"复制版本号"]})})]});return e.jsx(hs,{children:e.jsxs(gs,{children:[e.jsx(xs,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:s,className:`cursor-help hover:bg-secondary/80 transition-colors ${r}`,onClick:f,children:e.jsxs("span",{className:"text-xs font-medium",children:["v",a.version]})}),t&&e.jsx(ne,{variant:"outline",className:"text-xs",children:a.name})]})}),e.jsx(ft,{side:"right",align:"start",className:"max-w-xs",children:u})]})})}const xa={navMain:[{title:"仪表板",url:"/dashboard",icon:rr},{title:"全局配置",url:"/settings",icon:Ne}]};function Cs({...r}){return e.jsxs(ws,{collapsible:"offcanvas",...r,children:[e.jsx(vs,{children:e.jsx(gt,{children:e.jsx(xt,{children:e.jsx(bt,{asChild:!0,className:"data-[slot=sidebar-menu-button]:!p-1.5",children:e.jsxs(Ut,{to:"/",className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base font-semibold",children:"Xiaozhi Client"}),e.jsx(ga,{className:"text-xs"})]})})})})}),e.jsx(js,{children:e.jsx(pa,{items:xa.navMain})})]})}const Ze=or,ba=nr,wa=ar,ks=n.forwardRef(({className:r,...t},s)=>e.jsx(Bt,{className:g("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}));ks.displayName=Bt.displayName;const Re=n.forwardRef(({className:r,...t},s)=>e.jsxs(wa,{children:[e.jsx(ks,{}),e.jsx(qt,{ref:s,className:g("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})]}));Re.displayName=qt.displayName;const Te=({className:r,...t})=>e.jsx("div",{className:g("flex flex-col space-y-2 text-center sm:text-left",r),...t});Te.displayName="AlertDialogHeader";const We=({className:r,...t})=>e.jsx("div",{className:g("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...t});We.displayName="AlertDialogFooter";const ze=n.forwardRef(({className:r,...t},s)=>e.jsx(Ht,{ref:s,className:g("text-lg font-semibold",r),...t}));ze.displayName=Ht.displayName;const Me=n.forwardRef(({className:r,...t},s)=>e.jsx(Ft,{ref:s,className:g("text-sm text-muted-foreground",r),...t}));Me.displayName=Ft.displayName;const Ie=n.forwardRef(({className:r,...t},s)=>e.jsx(Vt,{ref:s,className:g(ut(),r),...t}));Ie.displayName=Vt.displayName;const $e=n.forwardRef(({className:r,...t},s)=>e.jsx(Kt,{ref:s,className:g(ut({variant:"outline"}),"mt-2 sm:mt-0",r),...t}));$e.displayName=Kt.displayName;const fe=Lt,Ae=ir,Sa=At,Ye=dt,Es=n.forwardRef(({className:r,...t},s)=>e.jsx(Ve,{ref:s,className:g("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}));Es.displayName=Ve.displayName;const de=n.forwardRef(({className:r,children:t,...s},a)=>e.jsxs(Sa,{children:[e.jsx(Es,{}),e.jsxs(Ke,{ref:a,className:g("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(dt,{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(Dt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));de.displayName=Ke.displayName;const ue=({className:r,...t})=>e.jsx("div",{className:g("flex flex-col space-y-1.5 text-center sm:text-left",r),...t});ue.displayName="DialogHeader";const we=({className:r,...t})=>e.jsx("div",{className:g("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...t});we.displayName="DialogFooter";const me=n.forwardRef(({className:r,...t},s)=>e.jsx(Ge,{ref:s,className:g("text-lg font-semibold leading-none tracking-tight",r),...t}));me.displayName=Ge.displayName;const pe=n.forwardRef(({className:r,...t},s)=>e.jsx(Je,{ref:s,className:g("text-sm text-muted-foreground",r),...t}));pe.displayName=Je.displayName;const Tt={config:null,loading:{isLoading:!1,isUpdating:!1,isRefreshing:!1,lastUpdated:null,lastError:null},lastSource:null},ie=it()(ct((r,t)=>({...Tt,setConfig:(s,a="http")=>{console.log(`[ConfigStore] 设置配置数据,来源: ${a}`),r(o=>({config:s,lastSource:a,loading:{...o.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setConfig")},setLoading:s=>{r(a=>({loading:{...a.loading,...s}}),!1,"setLoading")},setError:s=>{r(a=>({loading:{...a.loading,lastError:s}}),!1,"setError")},getConfig:async()=>{const{config:s,loading:a}=t();return s&&a.lastUpdated&&Date.now()-a.lastUpdated<5*60*1e3?s:t().refreshConfig()},updateConfig:async s=>{const{setLoading:a,setConfig:o,setError:i}=t();try{a({isUpdating:!0,lastError:null}),console.log("[ConfigStore] 开始更新配置"),await L.updateConfig(s),o(s,"http"),console.log("[ConfigStore] 配置更新成功")}catch(c){const m=c instanceof Error?c:new Error("配置更新失败");throw console.error("[ConfigStore] 配置更新失败:",m),i(m),m}finally{a({isUpdating:!1})}},refreshConfig:async()=>{const{setLoading:s,setConfig:a,setError:o}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[ConfigStore] 开始刷新配置");const i=await L.getConfig();return a(i,"http"),console.log("[ConfigStore] 配置刷新成功"),i}catch(i){const c=i instanceof Error?i:new Error("配置刷新失败");throw console.error("[ConfigStore] 配置刷新失败:",c),o(c),c}finally{s({isRefreshing:!1})}},reloadConfig:async()=>{const{setLoading:s,setConfig:a,setError:o}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[ConfigStore] 开始重新加载配置");const i=await L.reloadConfig();return a(i,"http"),console.log("[ConfigStore] 配置重新加载成功"),i}catch(i){const c=i instanceof Error?i:new Error("配置重新加载失败");throw console.error("[ConfigStore] 配置重新加载失败:",c),o(c),c}finally{s({isRefreshing:!1})}},updateMcpEndpoint:async s=>{const{config:a,updateConfig:o}=t();if(!a)throw new Error("配置未加载,无法更新 MCP 端点");const i={...a,mcpEndpoint:s};await o(i)},updateMcpServers:async s=>{const{config:a,updateConfig:o}=t();if(!a)throw new Error("配置未加载,无法更新 MCP 服务");const i={...a,mcpServers:s};await o(i)},updateConnectionConfig:async s=>{const{config:a,updateConfig:o}=t();if(!a)throw new Error("配置未加载,无法更新连接配置");const i={...a,connection:s};await o(i)},updateModelScopeConfig:async s=>{const{config:a,updateConfig:o}=t();if(!a)throw new Error("配置未加载,无法更新 ModelScope 配置");const i={...a,modelscope:s};await o(i)},updateWebUIConfig:async s=>{const{config:a,updateConfig:o}=t();if(!a)throw new Error("配置未加载,无法更新 Web UI 配置");const i={...a,webUI:s};await o(i)},reset:()=>{console.log("[ConfigStore] 重置状态"),r(Tt,!1,"reset")},initialize:async()=>{const{setLoading:s,refreshConfig:a}=t();try{s({isLoading:!0}),console.log("[ConfigStore] 初始化配置 Store"),I.subscribe("data:configUpdate",o=>{console.log("[ConfigStore] 收到 WebSocket 配置更新"),t().setConfig(o,"websocket")}),await a(),console.log("[ConfigStore] 配置 Store 初始化完成")}catch(o){throw console.error("[ConfigStore] 配置 Store 初始化失败:",o),o}finally{s({isLoading:!1})}}}),{name:"config-store"})),ge=()=>ie(r=>r.config),Ps=()=>ie(r=>{var t;return(t=r.config)==null?void 0:t.mcpEndpoint}),Rs=()=>ie(r=>{var t;return(t=r.config)==null?void 0:t.mcpServers}),va=()=>ie(r=>{var t;return(t=r.config)==null?void 0:t.mcpServerConfig}),Ts=()=>ie(lt(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}))),Wt=r=>`${r.slice(0,30)}...${r.slice(-10)}`,ja=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 ya(){const[r,t]=n.useState(!1),[s,a]=n.useState(!1),[o,i]=n.useState(""),[c,m]=n.useState(!1),[h,w]=n.useState(!1),[x,f]=n.useState(""),[u,l]=n.useState(!1),[p,S]=n.useState(""),[b,W]=n.useState({}),P=ge(),z=Ps(),{refreshConfig:X}=Ts(),_=n.useCallback(async y=>{try{return await L.getEndpointStatus(y)}catch(k){return console.error(`获取接入点状态失败: ${y}`,k),{endpoint:y,connected:!1,initialized:!1,isReconnecting:!1,reconnectAttempts:0,reconnectDelay:0}}},[]),G=n.useCallback((y,k)=>{W($=>({...$,[y]:{...$[y],...k}}))},[]),ee=n.useCallback(async y=>{const k={};for(const $ of y)try{const M=await _($);k[$]={connected:M.connected,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}}catch{k[$]={connected:!1,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}}W(k)},[_]),ce=async y=>{G(y,{isOperating:!0});try{await L.connectEndpoint(y),G(y,{connected:!0,isOperating:!1,lastOperation:{type:"connect",success:!0,message:"连接成功",timestamp:Date.now()}}),j.success("接入点连接成功")}catch(k){G(y,{isOperating:!1,lastOperation:{type:"connect",success:!1,message:k instanceof Error?k.message:"连接失败",timestamp:Date.now()}}),j.error(k instanceof Error?k.message:"接入点连接失败")}},d=async y=>{G(y,{isOperating:!0});try{await L.disconnectEndpoint(y),G(y,{connected:!1,isOperating:!1,lastOperation:{type:"disconnect",success:!0,message:"断开成功",timestamp:Date.now()}}),j.success("接入点断开成功")}catch(k){G(y,{isOperating:!1,lastOperation:{type:"disconnect",success:!1,message:k instanceof Error?k.message:"断开失败",timestamp:Date.now()}}),j.error(k instanceof Error?k.message:"接入点断开失败")}},A=async y=>{var k;try{if((k=navigator.clipboard)!=null&&k.writeText)await navigator.clipboard.writeText(y),j.success("接入点地址已复制到剪贴板");else{const $=document.createElement("textarea");$.value=y,$.style.position="fixed",$.style.opacity="0",document.body.appendChild($),$.select();const M=document.execCommand("copy");if(document.body.removeChild($),M)j.success("接入点地址已复制到剪贴板");else throw new Error("复制命令执行失败")}}catch($){console.error("复制失败:",$),j.error("复制失败,请手动复制")}},C=async()=>{m(!0);try{await L.removeEndpoint(o),await X(),W(y=>{const k={...y};return delete k[o],k}),j.success("接入点已删除"),a(!1),i("")}catch(y){console.error("删除接入点失败:",y),j.error(y instanceof Error?y.message:"删除接入点失败")}finally{m(!1)}},v=async()=>{const y=ja(x);if(y){S(y);return}if((Array.isArray(z)?z:[z]).includes(x)){S("该接入点已存在");return}if(!P){j.error("配置数据未加载,请稍后重试");return}l(!0);try{const $=await L.addEndpoint(x);await X(),W(M=>({...M,[x]:{connected:$.connected,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}})),j.success("接入点添加成功"),w(!1),f(""),S("")}catch($){console.error("添加接入点失败:",$),j.error($ instanceof Error?$.message:"添加接入点失败")}finally{l(!1)}},R=()=>{f(""),S(""),w(!0)},D=y=>{f(y),p&&S("")},B=y=>{i(y),a(!0)},q=n.useMemo(()=>{let y=[];return Array.isArray(z)&&(y=z),typeof z=="string"&&z.length&&y.push(z),y},[z]);return n.useEffect(()=>{r&&q.length>0&&ee(q)},[r,q,ee]),n.useEffect(()=>{if(!r||q.length===0)return;const y=q.map(k=>I.subscribe("data:endpointStatusChanged",M=>{M.endpoint===k&&(console.log(`[McpEndpointSettingButton] 接收到端点 ${k} 状态变更:`,M),G(k,{connected:M.connected,isOperating:!1,lastOperation:{type:M.operation,success:M.success,message:M.message||(M.connected?"连接成功":"断开成功"),timestamp:M.timestamp}}),M.success?j.success(`端点 ${M.operation==="connect"?"连接":M.operation==="disconnect"?"断开":"重连"}成功`):j.error(`端点 ${M.operation==="connect"?"连接":M.operation==="disconnect"?"断开":"重连"}失败: ${M.message||"未知错误"}`))}));return()=>{for(const k of y)k()}},[r,q,G]),e.jsxs(fe,{open:r,onOpenChange:t,children:[e.jsx(Ae,{asChild:!0,children:e.jsx(E,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ne,{className:"size-4"})})}),e.jsxs(de,{className:"min-w-[600px] max-w-[800px] max-h-[80vh] overflow-y-auto",children:[e.jsxs(ue,{className:"mb-4",children:[e.jsx(me,{children:"配置小智服务端接入点"}),e.jsx(pe,{children:"点击保存后,需要重启服务才会生效。"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[q.map(y=>{const k=b[y],$=(k==null?void 0:k.connected)||!1,M=(k==null?void 0:k.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:Wt(y)}),e.jsxs(ne,{className:`flex items-center gap-1 transition-all duration-200 text-xs sm:text-sm ${$?"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:[M?e.jsx(je,{className:"size-3 animate-spin"}):$?e.jsx(yt,{className:"size-3"}):e.jsx(Nt,{className:"size-3"}),M?"操作中":$?"已连接":"未连接"]})]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-end",children:[e.jsx(E,{variant:"outline",size:"icon",onClick:()=>A(y),title:"复制完整地址",className:"transition-all duration-200 hover:scale-105",children:e.jsx(_t,{className:"size-4"})}),$?e.jsx(E,{variant:"outline",size:"icon",onClick:()=>d(y),title:"断开连接",disabled:M,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:M?e.jsx(je,{className:"size-4 animate-spin"}):e.jsx(Nt,{className:"size-4"})}):e.jsx(E,{variant:"outline",size:"icon",onClick:()=>ce(y),title:"连接",disabled:M,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:M?e.jsx(je,{className:"size-4 animate-spin"}):e.jsx(yt,{className:"size-4"})}),e.jsx(E,{variant:"outline",size:"icon",onClick:()=>B(y),title:"删除此接入点",className:"transition-all duration-200 hover:scale-105 hover:text-red-600",children:e.jsx(Gt,{className:"size-4 text-red-500"})})]})]},y)}),q.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(cr,{}),e.jsx("span",{children:"暂无接入点,请添加"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-2 mt-4",children:[e.jsxs(E,{className:"flex-1 flex items-center gap-2",onClick:R,children:[e.jsx(Ce,{className:"size-4"}),e.jsx("span",{className:"text-sm sm:text-base",children:"添加小智服务端接入点"})]}),e.jsx(E,{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(Ze,{open:s,onOpenChange:a,children:e.jsxs(Re,{children:[e.jsxs(Te,{children:[e.jsx(ze,{children:"确认删除接入点"}),e.jsxs(Me,{children:['确定要删除接入点 "',Wt(o),'" 吗?此操作无法撤销。']})]}),e.jsxs(We,{children:[e.jsx($e,{disabled:c,children:"取消"}),e.jsx(Ie,{onClick:C,disabled:c,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:c?"删除中...":"确定删除"})]})]})}),e.jsx(fe,{open:h,onOpenChange:w,children:e.jsxs(de,{className:"sm:max-w-[500px]",children:[e.jsxs(ue,{children:[e.jsx(me,{children:"添加新的接入点"}),e.jsx(pe,{children:"请输入小智服务端接入点地址"})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{placeholder:"请输入接入点地址,例如:wss://api.xiaozhi.me/mcp/?token=... 或 ws(s)://<hostname>:<port>",value:x,onChange:y=>D(y.target.value),disabled:u,className:"font-mono text-sm"}),p&&e.jsx("p",{className:"text-sm text-red-500",children:p})]})}),e.jsxs(we,{children:[e.jsx(Ye,{asChild:!0,children:e.jsx(E,{variant:"outline",disabled:u,children:"取消"})}),e.jsx(E,{onClick:v,disabled:u||!x.trim(),children:u?"添加中...":"确定"})]})]})})]})}const Na=Pe("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ws=n.forwardRef(({className:r,...t},s)=>e.jsx(Jt,{ref:s,className:g(Na(),r),...t}));Ws.displayName=Jt.displayName;const De=dr,zs=n.createContext({}),te=({...r})=>e.jsx(zs.Provider,{value:{name:r.name},children:e.jsx(ur,{...r})}),Qe=()=>{const r=n.useContext(zs),t=n.useContext(Ms),{getFieldState:s,formState:a}=lr(),o=s(r.name,a);if(!r)throw new Error("useFormField should be used within <FormField>");const{id:i}=t;return{id:i,name:r.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},Ms=n.createContext({}),Y=n.forwardRef(({className:r,...t},s)=>{const a=n.useId();return e.jsx(Ms.Provider,{value:{id:a},children:e.jsx("div",{ref:s,className:g("space-y-2",r),...t})})});Y.displayName="FormItem";const ae=n.forwardRef(({className:r,...t},s)=>{const{error:a,formItemId:o}=Qe();return e.jsx(Ws,{ref:s,className:g(a&&"text-destructive",r),htmlFor:o,...t})});ae.displayName="FormLabel";const Q=n.forwardRef(({...r},t)=>{const{error:s,formItemId:a,formDescriptionId:o,formMessageId:i}=Qe();return e.jsx(he,{ref:t,id:a,"aria-describedby":s?`${o} ${i}`:`${o}`,"aria-invalid":!!s,...r})});Q.displayName="FormControl";const Ca=n.forwardRef(({className:r,...t},s)=>{const{formDescriptionId:a}=Qe();return e.jsx("p",{ref:s,id:a,className:g("text-sm text-muted-foreground",r),...t})});Ca.displayName="FormDescription";const se=n.forwardRef(({className:r,children:t,...s},a)=>{const{error:o,formMessageId:i}=Qe(),c=o?String((o==null?void 0:o.message)??""):t;return c?e.jsx("p",{ref:a,id:i,className:g("text-sm font-medium text-destructive",r),...s,children:c}):null});se.displayName="FormMessage";const zt={connectionState:Z.DISCONNECTED,wsUrl:"",connectionStats:{reconnectAttempts:0,maxReconnectAttempts:5,lastHeartbeat:0,eventListenerCount:0},portChangeStatus:void 0,lastError:null,connectedAt:null,disconnectedAt:null},Le=it()(ct((r,t)=>({...zt,setConnectionState:s=>{console.log("[WebSocketStore] 更新连接状态:",s);const a=Date.now(),o={connectionState:s};s===Z.CONNECTED?(o.connectedAt=a,o.lastError=null):s===Z.DISCONNECTED&&(o.disconnectedAt=a),r(o,!1,"setConnectionState");const i=I.getConnectionStats();t().setConnectionStats(i)},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==null?void 0:s.message),r({lastError:s},!1,"setLastError")},setPortChangeStatus:s=>{console.log("[WebSocketStore] 更新端口变更状态:",s==null?void 0:s.status),r({portChangeStatus:s},!1,"setPortChangeStatus")},connect:async()=>{try{console.log("[WebSocketStore] 开始连接 WebSocket"),I.connect()}catch(s){const a=s instanceof Error?s:new Error("连接失败");throw console.error("[WebSocketStore] 连接失败:",a),t().setLastError(a),a}},disconnect:()=>{console.log("[WebSocketStore] 断开 WebSocket 连接"),I.disconnect()},reconnect:async()=>{try{console.log("[WebSocketStore] 重新连接 WebSocket"),I.disconnect(),await new Promise(s=>setTimeout(s,1e3)),I.connect()}catch(s){const a=s instanceof Error?s:new Error("重连失败");throw console.error("[WebSocketStore] 重连失败:",a),t().setLastError(a),a}},send:s=>{try{return I.send(s)}catch(a){const o=a instanceof Error?a:new Error("发送消息失败");return console.error("[WebSocketStore] 发送消息失败:",o),t().setLastError(o),!1}},updateUrl:s=>{console.log("[WebSocketStore] 更新 WebSocket URL:",s),I.setUrl(s),t().setWsUrl(s)},getConnectionInfo:()=>{const s=t();return{state:s.connectionState,url:s.wsUrl,stats:s.connectionStats,isConnected:s.connectionState===Z.CONNECTED}},reset:()=>{console.log("[WebSocketStore] 重置状态"),r(zt,!1,"reset")},initialize:()=>{console.log("[WebSocketStore] 初始化 WebSocket Store"),I.subscribe("connection:connecting",()=>{t().setConnectionState(Z.CONNECTING)}),I.subscribe("connection:connected",()=>{t().setConnectionState(Z.CONNECTED)}),I.subscribe("connection:disconnected",()=>{t().setConnectionState(Z.DISCONNECTED)}),I.subscribe("connection:reconnecting",()=>{t().setConnectionState(Z.RECONNECTING);const a=I.getConnectionStats();t().setConnectionStats(a)}),I.subscribe("connection:error",({error:a})=>{t().setLastError(a)}),I.subscribe("system:heartbeat",()=>{const a=I.getConnectionStats();t().setConnectionStats(a)});const s=I.getConnectionStats();t().setConnectionStats(s),t().setWsUrl(I.getUrl()),console.log("[WebSocketStore] WebSocket Store 初始化完成")},setConnected:s=>{console.warn("[WebSocketStore] setConnected 方法已废弃,请使用 setConnectionState");const a=s?Z.CONNECTED:Z.DISCONNECTED;t().setConnectionState(a)}}),{name:"websocket-store"})),Is=()=>Le(r=>r.connectionState===Z.CONNECTED),ka=()=>Le(r=>r.wsUrl),Ea=()=>Le(r=>r.portChangeStatus),$s=()=>Le(lt(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})));async function Pa(r,t=3e3){try{const s=new AbortController,a=setTimeout(()=>s.abort(),t);let o;try{o=await fetch(`http://localhost:${r}/api/status`,{method:"GET",signal:s.signal})}catch{o=await fetch(`http://localhost:${r}/health`,{method:"GET",signal:s.signal})}return clearTimeout(a),o.ok}catch{return!1}}function Mt(r,t){const s=window.location.protocol==="https:"?"wss:":"ws:",a=window.location.hostname||"localhost";return s==="ws:"&&r===80||s==="wss:"&&r===443?`${s}//${a}`:`${s}//${a}:${r}`}function Ra(r){try{const t=new URL(r),s=Number.parseInt(t.port);return Number.isNaN(s)?null:s}catch{return null}}function et(){console.warn("[useWebSocket] 此 hook 已重构,建议使用新的专用 hooks:useWebSocketConnection()、useConfigData()、useStatusData()");const r=ge(),t=_r(),s=cs(),a=$s(),o=Ts(),i=Br(),[c,m]=n.useState(""),h=n.useRef(!1);n.useEffect(()=>{if(h.current)return;h.current=!0,console.log("[useWebSocket] 初始化 WebSocket 连接和数据加载"),I.isConnected()||I.connect();const b=I.getUrl();m(b),(async()=>{try{await Promise.allSettled([o.getConfig(),i.getStatus()]),console.log("[useWebSocket] 初始数据加载完成")}catch(P){console.error("[useWebSocket] 初始数据加载失败:",P)}})()},[o,i]);const w=n.useCallback(b=>{const W=localStorage.getItem("xiaozhi-ws-url");if(W)return W;let P=9999;if(b)P=b;else if(window.location.port){const z=Number.parseInt(window.location.port);Number.isNaN(z)||(P=z)}else window.location.protocol==="http:"&&!window.location.port?P=80:window.location.protocol==="https:"&&!window.location.port&&(P=443);return Mt(P)},[]),x={connected:I.isConnected(),config:r,status:t,restartStatus:s||void 0},f=n.useCallback(async b=>{console.log("[useWebSocket] updateConfig 调用,使用新的 configActions");try{await o.updateConfig(b)}catch(W){throw console.error("[useWebSocket] 配置更新失败:",W),W}},[o]),u=n.useCallback(async()=>{console.log("[useWebSocket] refreshStatus 调用,使用新的 statusActions");try{await i.refreshStatus()}catch(b){throw console.error("[useWebSocket] 状态刷新失败:",b),b}},[i]),l=n.useCallback(async()=>{console.log("[useWebSocket] restartService 调用,使用新的 statusActions");try{await i.restartService()}catch(b){throw console.error("[useWebSocket] 服务重启失败:",b),b}},[i]),p=n.useCallback(b=>{if(console.log("[useWebSocket] setCustomWsUrl 调用,使用 WebSocketManager"),b)localStorage.setItem("xiaozhi-ws-url",b),I.setUrl(b);else{localStorage.removeItem("xiaozhi-ws-url");const W=w();I.setUrl(W)}m(I.getUrl())},[w]),S=n.useCallback(async b=>{if((Ra(c)||9999)!==b){a.setPortChangeStatus({status:"checking",targetPort:b,timestamp:Date.now()});try{if(a.setPortChangeStatus({status:"checking",targetPort:b,timestamp:Date.now()}),!await Pa(b))throw new Error(`端口 ${b} 不可用`);const z=Mt(b);I.setUrl(z),m(z),console.log(`[WebSocket] 端口切换到 ${b} 成功完成`),a.setPortChangeStatus({status:"completed",targetPort:b,timestamp:Date.now()})}catch(P){const z=P instanceof Error?P.message:"端口切换失败";throw console.error(`[WebSocket] 端口切换到 ${b} 失败:`,z),a.setPortChangeStatus({status:"failed",targetPort:b,error:z,timestamp:Date.now()}),P}}},[c,a]);return{...x,updateConfig:f,refreshStatus:u,restartService:l,wsUrl:c,setCustomWsUrl:p,changePort:S}}const Ta=K.object({port:K.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 Wa(){const[r,t]=n.useState(!1),[s,a]=n.useState(!1),o=ge(),i=Is(),c=Ea(),{changePort:m}=et(),h=ke({resolver:Ee(Ta),defaultValues:{port:"9999"}});n.useEffect(()=>{var f;(f=o==null?void 0:o.webUI)!=null&&f.port&&h.reset({port:o.webUI.port.toString()})},[o,h]);const w=()=>{if(s)return"处理中...";if((c==null?void 0:c.status)==="checking")return"检测端口...";if((c==null?void 0:c.status)==="polling"){const{currentAttempt:f,maxAttempts:u}=c;return`等待服务重启 (${f||0}/${u||45})`}return(c==null?void 0:c.status)==="connecting"?"连接中...":i?"保存并重启":"保存并连接"};async function x(f){var p;const u=Number(f.port),l=(p=o==null?void 0:o.webUI)==null?void 0:p.port;if(u===l){t(!1);return}console.log(`[WebUrlSettingButton] 开始端口切换: ${l} -> ${u}`),a(!0);try{j.info(i?`正在将端口从 ${l} 切换到 ${u}...`:`正在连接到端口 ${u}...`),await m(u),j.success(i?`端口已成功切换到 ${u},页面即将刷新...`:`已成功连接到端口 ${u},页面即将刷新...`),t(!1)}catch(S){console.error("端口切换失败:",S);const b=S instanceof Error?S.message:"端口切换失败";j.error(`端口切换失败: ${b}`)}finally{a(!1)}}return e.jsxs(fe,{open:r,onOpenChange:t,children:[e.jsx(Ae,{asChild:!0,children:e.jsx(E,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ne,{className:"h-4 w-4"})})}),e.jsx(de,{className:"sm:max-w-[250px]",children:e.jsx(De,{...h,children:e.jsxs("form",{onSubmit:h.handleSubmit(x),children:[e.jsxs(ue,{className:"mb-4",children:[e.jsx(me,{children:"配置服务端端口"}),e.jsx(pe,{children:i?"修改端口后将自动重启服务并重新连接。":"请输入服务端端口号,系统将尝试连接。"})]}),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(te,{control:h.control,name:"port",render:({field:f})=>e.jsxs(Y,{children:[e.jsx(Q,{children:e.jsx(re,{placeholder:"服务端端口,默认9999",className:"font-mono text-sm",disabled:s,type:"number",...f})}),e.jsx(se,{})]})})})]}),e.jsxs(we,{className:"mt-4",children:[e.jsx(Ye,{asChild:!0,children:e.jsx(E,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(E,{type:"submit",disabled:s||(c==null?void 0:c.status)==="polling",children:w()})]})]})})})]})}const le=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:g("rounded-lg border bg-card text-card-foreground shadow-sm",r),...t}));le.displayName="Card";const Be=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:g("flex flex-col space-y-1.5 p-6",r),...t}));Be.displayName="CardHeader";const qe=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:g("text-2xl font-semibold leading-none tracking-tight",r),...t}));qe.displayName="CardTitle";const He=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:g("text-sm text-muted-foreground",r),...t}));He.displayName="CardDescription";const ve=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:g("p-6 pt-0",r),...t}));ve.displayName="CardContent";const Fe=n.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:g("flex items-center p-6 pt-0",r),...t}));Fe.displayName="CardFooter";const at=({showValue:r=!0,value:t=0,maxValue:s=100,size:a=60,activeColor:o="#3b82f6",inactiveColor:i="#e5e7eb",symbol:c="%"})=>{const m=(a-6)/2,h=m*2*Math.PI,w=h,x=h-t/s*h;return e.jsxs("div",{className:"relative inline-flex items-center justify-center",children:[e.jsxs("svg",{width:a,height:a,className:"transform -rotate-90",children:[e.jsx("circle",{cx:a/2,cy:a/2,r:m,stroke:i,strokeWidth:6,fill:"none"}),e.jsx("circle",{cx:a/2,cy:a/2,r:m,stroke:o,strokeWidth:6,fill:"none",strokeDasharray:w,strokeDashoffset:x,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,c]})})]})};function za(){const r=Rs(),t=Is(),s=Object.keys(r||{}).length,a=ka(),o=Ps();return e.jsxs("div",{className:"*:data-[slot=card]:shadow-xs @xl/main:grid-cols-2 @5xl/main:grid-cols-4 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.jsxs(le,{className:"@container/card",children:[e.jsxs(Be,{className:"relative",children:[e.jsx(He,{children:"小智接入点"}),e.jsx(qe,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:Array.isArray(o)?o.length:o?1:0}),e.jsx("div",{className:"absolute right-4 top-4 flex flex-col items-center",children:e.jsx(at,{showValue:!1,value:Array.isArray(o)?o.length:o?1:0,maxValue:Math.max(Array.isArray(o)?o.length:1,1),activeColor:"#16a34a",inactiveColor:"#f87171",size:30,symbol:""})})]}),e.jsx(Fe,{className:"flex-col items-end gap-1 text-sm",children:e.jsx(ya,{})})]}),e.jsxs(le,{className:"@container/card",children:[e.jsxs(Be,{className:"relative",children:[e.jsx(He,{children:"Xiaozhi Client"}),e.jsx(qe,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:t?"已连接":"未连接"}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(at,{showValue:!1,value:1,maxValue:1,activeColor:t?"#16a34a":"#f87171",inactiveColor:t?"#16a34a":"#f87171",size:30,symbol:""})})]}),e.jsxs(Fe,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:a}),e.jsx(Wa,{})]})]}),e.jsx(le,{className:"@container/card",children:e.jsxs(Be,{className:"relative",children:[e.jsx(He,{children:"MCP服务"}),e.jsx(qe,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:s}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(at,{showValue:!1,value:s,maxValue:s,activeColor:"#16a34a",inactiveColor:"#f87171",size:30,symbol:""})})]})})]})}const As=n.forwardRef(({className:r,...t},s)=>e.jsx(Xt,{ref:s,className:g("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",r),...t,children:e.jsx(mr,{className:g("flex items-center justify-center text-current"),children:e.jsx(Zt,{className:"h-4 w-4"})})}));As.displayName=Xt.displayName;const Ds=wr,Ls=Sr,wt=n.forwardRef(({className:r,children:t,...s},a)=>e.jsxs(Yt,{ref:a,className:g("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(fr,{asChild:!0,children:e.jsx(Qt,{className:"h-4 w-4 opacity-50"})})]}));wt.displayName=Yt.displayName;const Os=n.forwardRef(({className:r,...t},s)=>e.jsx(es,{ref:s,className:g("flex cursor-default items-center justify-center py-1",r),...t,children:e.jsx(pr,{className:"h-4 w-4"})}));Os.displayName=es.displayName;const Us=n.forwardRef(({className:r,...t},s)=>e.jsx(ts,{ref:s,className:g("flex cursor-default items-center justify-center py-1",r),...t,children:e.jsx(Qt,{className:"h-4 w-4"})}));Us.displayName=ts.displayName;const St=n.forwardRef(({className:r,children:t,position:s="popper",...a},o)=>e.jsx(hr,{children:e.jsxs(ss,{ref:o,className:g("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,...a,children:[e.jsx(Os,{}),e.jsx(gr,{className:g("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Us,{})]})}));St.displayName=ss.displayName;const Ma=n.forwardRef(({className:r,...t},s)=>e.jsx(rs,{ref:s,className:g("py-1.5 pl-8 pr-2 text-sm font-semibold",r),...t}));Ma.displayName=rs.displayName;const ye=n.forwardRef(({className:r,children:t,...s},a)=>e.jsxs(as,{ref:a,className:g("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(xr,{children:e.jsx(Zt,{className:"h-4 w-4"})})}),e.jsx(br,{children:t})]}));ye.displayName=as.displayName;const Ia=n.forwardRef(({className:r,...t},s)=>e.jsx(os,{ref:s,className:g("-mx-1 my-1 h-px bg-muted",r),...t}));Ia.displayName=os.displayName;const $a=is({fieldName:Pt().min(1,"字段名不能为空").regex(/^[a-zA-Z][a-zA-Z0-9_]*$/,"字段名必须以字母开头,只能包含字母、数字和下划线"),description:Pt().min(1,"描述不能为空").max(200,"描述不能超过200个字符"),type:Dr(["string","number","boolean"]),required:Ar()}),Aa=is({parameters:Lr($a).refine(r=>{const t=r.map(s=>s.fieldName);return t.length===new Set(t).size},{message:"字段名不能重复"})});function Da(r){if(!r||!r.properties)return[];const t=r.properties,s=r.required||[];return Object.entries(t).map(([a,o])=>{let i="string";return o.type==="integer"||o.type==="number"?i="number":o.type==="boolean"&&(i="boolean"),{fieldName:a,description:o.description||"",type:i,required:s.includes(a)}})}function _s({open:r,onOpenChange:t,workflow:s,onConfirm:a,onCancel:o,title:i}){const c=ke({resolver:Ee(Aa),defaultValues:{parameters:[]}});n.useEffect(()=>{r&&c.reset({parameters:Da(s.inputSchema)})},[r,s,c.reset]);const{fields:m,append:h,remove:w}=vr({control:c.control,name:"parameters"}),x=()=>{h({fieldName:"",description:"",type:"string",required:!1})},f=p=>{w(p)},u=p=>{a(s,p.parameters),c.reset()},l=()=>{c.reset(),o()};return e.jsx(fe,{open:r,onOpenChange:t,children:e.jsxs(de,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ue,{children:[e.jsx(me,{children:i||`配置工作流参数 - ${s.workflow_name}`}),e.jsx(pe,{children:"为工作流配置输入参数,这些参数将用于生成工具的输入架构。 您可以跳过此步骤使用默认的空参数配置。"})]}),e.jsx(De,{...c,children:e.jsxs("form",{onSubmit:c.handleSubmit(u),className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4 mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-medium",children:"参数列表"}),e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:x,className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"h-4 w-4"}),"添加参数"]})]}),m.length===0&&e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'暂无参数,点击"添加参数"开始配置'}),m.map((p,S)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(te,{control:c.control,name:`parameters.${S}.fieldName`,render:({field:b})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"字段名"}),e.jsx(Q,{children:e.jsx(re,{placeholder:"例如: userName",...b})}),e.jsx(se,{})]})}),e.jsx(te,{control:c.control,name:`parameters.${S}.description`,render:({field:b})=>e.jsxs(Y,{className:"flex-1",children:[e.jsx(ae,{children:"描述"}),e.jsx(Q,{children:e.jsx(re,{placeholder:"例如: 用户名称",...b})}),e.jsx(se,{})]})}),e.jsx(te,{control:c.control,name:`parameters.${S}.type`,render:({field:b})=>e.jsxs(Y,{className:"w-[140px]",children:[e.jsx(ae,{children:"参数类型"}),e.jsxs(Ds,{onValueChange:b.onChange,defaultValue:b.value,children:[e.jsx(Q,{children:e.jsx(wt,{children:e.jsx(Ls,{placeholder:"选择参数类型"})})}),e.jsxs(St,{children:[e.jsx(ye,{value:"string",children:"string"}),e.jsx(ye,{value:"number",children:"number"}),e.jsx(ye,{value:"boolean",children:"boolean"})]})]}),e.jsx(se,{})]})}),e.jsx(te,{control:c.control,name:`parameters.${S}.required`,render:({field:b})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"是否必填"}),e.jsx(Q,{children:e.jsx("div",{className:"flex items-center justify-center h-[40px]",children:e.jsx(As,{checked:b.value,onCheckedChange:b.onChange})})})]})}),e.jsx("div",{className:"flex flex-col h-[72px] justify-end",children:e.jsx(E,{type:"button",variant:"link",size:"sm",onClick:()=>f(S),className:"text-destructive mb-[4px]",children:e.jsx(jr,{className:"h-4 w-4"})})})]},p.id))]}),e.jsxs(we,{children:[e.jsx(E,{type:"button",variant:"outline",onClick:l,children:"取消"}),e.jsx(E,{type:"submit",children:"确认配置"})]})]})})]})})}function nt(r){if(!r||typeof r!="object")throw new Error("服务配置必须是一个有效的对象");if("command"in r&&typeof r.command=="string")return"stdio";if("type"in r&&r.type==="sse")return"sse";if("url"in r&&typeof r.url=="string")return"streamable-http";throw new Error("无法识别的 MCP 服务配置类型。配置必须包含 command 字段(stdio)、type: 'sse' 字段(sse)或 url 字段(streamable-http)")}const vt=n.forwardRef(({className:r,...t},s)=>e.jsx("textarea",{className:g("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}));vt.displayName="Textarea";const La=K.object({config:K.string().min(2,{message:"配置不能为空"})});function It(){const[r,t]=n.useState(!1),[s,a]=n.useState(!1),{updateConfig:o}=et(),i=ge(),c=ke({resolver:Ee(La),defaultValues:{config:""}}),m=(x,f)=>{if(!f||typeof f!="object")return{valid:!1,error:`服务 "${x}" 的配置必须是一个对象`};const u="command"in f,l="type"in f,p="url"in f;if(u){if(!f.command||typeof f.command!="string")return{valid:!1,error:`服务 "${x}" 缺少必需的 command 字段或字段类型不正确`};if(!Array.isArray(f.args))return{valid:!1,error:`服务 "${x}" 的 args 字段必须是数组`}}else if(l&&f.type==="sse"){if(!f.url||typeof f.url!="string")return{valid:!1,error:`服务 "${x}" 缺少必需的 url 字段或字段类型不正确`}}else if(p){if(!f.url||typeof f.url!="string")return{valid:!1,error:`服务 "${x}" 缺少必需的 url 字段或字段类型不正确`};if(f.type&&f.type!=="streamable-http")return{valid:!1,error:`服务 "${x}" 的 type 字段如果存在,必须是 "streamable-http"`}}else return{valid:!1,error:`服务 "${x}" 的配置无效: 必须包含 command 字段(stdio)、type: 'sse' 字段(sse)或 url 字段(streamable-http)`};try{return nt(f),{valid:!0}}catch(S){return{valid:!1,error:`服务 "${x}" 的配置无效: ${S instanceof Error?S.message:"未知错误"}`}}},h=x=>{try{const f=x.trim();if(!f)return{success:!1,error:"配置不能为空"};const u=JSON.parse(f);let l;if(u.mcpServers&&typeof u.mcpServers=="object")l=u.mcpServers;else if(typeof u=="object"&&!Array.isArray(u))try{nt(u),l={[u.command?u.command.split("/").pop()||"mcp-server":u.type==="sse"?"sse-server":"http-server"]:u}}catch{l=u}else return{success:!1,error:"配置格式错误: 必须是对象格式"};for(const[p,S]of Object.entries(l)){const b=m(p,S);if(!b.valid)return{success:!1,error:b.error}}return{success:!0,data:l}}catch(f){return{success:!1,error:`JSON 格式错误: ${f instanceof Error?f.message:"无法解析 JSON"}`}}};async function w(x){if(!i){j.error("配置数据未加载,请稍后重试");return}a(!0);try{const f=h(x.config);if(!f.success){j.error(f.error||"配置验证失败");return}const u=f.data,l=Object.keys(u).filter(b=>b in(i.mcpServers||{}));if(l.length>0){j.error(`服务名称冲突: 以下服务已存在: ${l.join(", ")}`);return}const p={...i,mcpServers:{...u,...i.mcpServers}};await o(p);const S=Object.keys(u).length;j.success(S===1?`已添加 MCP 服务 "${Object.keys(u)[0]}"`:`已添加 ${S} 个 MCP 服务`),c.reset(),t(!1)}catch(f){console.error("更新配置失败:",f),j.error(f instanceof Error?f.message:"更新配置失败")}finally{a(!1)}}return e.jsxs(fe,{open:r,onOpenChange:t,children:[e.jsx(Ae,{asChild:!0,children:e.jsxs(E,{size:"icon",className:"w-full",children:[e.jsx(Ce,{className:"h-4 w-4"}),e.jsx("span",{children:"添加MCP服务"})]})}),e.jsx(de,{className:"sm:max-w-[500px]",children:e.jsx(De,{...c,children:e.jsxs("form",{onSubmit:c.handleSubmit(w),children:[e.jsxs(ue,{className:"mb-4",children:[e.jsx(me,{children:"添加MCP服务"}),e.jsx(pe,{children:"添加后,需要重启服务才会生效。"})]}),e.jsx("div",{className:"grid gap-4",children:e.jsx(te,{control:c.control,name:"config",render:({field:x})=>e.jsxs(Y,{children:[e.jsx(Q,{children:e.jsx(vt,{className:"resize-none h-[300px] font-mono text-sm",disabled:s,placeholder:`支持三种通信方式:
2
+
3
+ 1. 本地进程 (stdio):
4
+ {
5
+ "mcpServers": {
6
+ "local-server": {
7
+ "command": "npx",
8
+ "args": ["-y", "@example/mcp-server"]
9
+ }
10
+ }
11
+ }
12
+
13
+ 2. 服务器推送 (SSE):
14
+ {
15
+ "mcpServers": {
16
+ "sse-server": {
17
+ "type": "sse",
18
+ "url": "https://example.com/sse"
19
+ }
20
+ }
21
+ }
22
+
23
+ 3. 流式 HTTP:
24
+ {
25
+ "mcpServers": {
26
+ "http-server": {
27
+ "url": "https://example.com/mcp"
28
+ }
29
+ }
30
+ }`,...x})}),e.jsx(se,{})]})})}),e.jsxs(we,{className:"mt-4",children:[e.jsx(Ye,{asChild:!0,children:e.jsx(E,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(E,{type:"submit",disabled:s,children:s?"保存中...":"保存"})]})]})})})]})}class Oa{constructor(t){U(this,"baseUrl");if(t)this.baseUrl=t;else{const s=window.location.protocol,a=window.location.hostname,o=window.location.port;this.baseUrl=`${s}//${a}${o?`:${o}`:""}`}}async request(t,s={}){var c;const a=`${this.baseUrl}${t}`,o={headers:{"Content-Type":"application/json",...s.headers}},i=await fetch(a,{...o,...s});if(!i.ok){let m=`HTTP ${i.status}: ${i.statusText}`;try{m=((c=(await i.json()).error)==null?void 0:c.message)||m}catch{}throw new Error(m)}return i.json()}async fetchWorkspaces(){try{const t=await this.request("/api/coze/workspaces");if(!t.success||!t.data)throw new Error(t.message||"获取工作空间列表失败");return t.data}catch(t){throw console.error("获取工作空间列表失败:",t),t}}async fetchWorkflows(t){try{const s=new URLSearchParams;s.append("workspace_id",t.workspace_id),t.page_num!==void 0&&s.append("page_num",t.page_num.toString()),t.page_size!==void 0&&s.append("page_size",t.page_size.toString());const a=await this.request(`/api/coze/workflows?${s.toString()}`);if(!a.success||!a.data)throw new Error(a.message||"获取工作流列表失败");return a.data}catch(s){throw console.error("获取工作流列表失败:",s),s}}async clearCache(){try{const t=await this.request("/api/coze/cache/clear",{method:"POST"});if(!t.success)throw new Error(t.message||"清除缓存失败")}catch(t){throw console.error("清除缓存失败:",t),t}}async getCacheStats(){try{const t=await this.request("/api/coze/cache/stats");if(!t.success||!t.data)throw new Error(t.message||"获取缓存统计失败");return t.data}catch(t){throw console.error("获取缓存统计失败:",t),t}}}const _e=new Oa;function Ua(r={}){const{autoLoadWorkspaces:t=!0,autoLoadWorkflows:s=!0,defaultPageSize:a=20,initialWorkspaceId:o}=r,[i,c]=n.useState([]),[m,h]=n.useState([]),[w,x]=n.useState(o||null),[f,u]=n.useState({selectedWorkspaceId:o||null,workspacesLoading:!1,workflowsLoading:!1,workspacesError:null,workflowsError:null}),[l,p]=n.useState(1),[S,b]=n.useState(a),[W,P]=n.useState(!1),z=n.useMemo(()=>i&&Array.isArray(i)&&i.find(v=>v.id===w)||null,[i,w]),X=n.useCallback(async()=>{u(v=>({...v,workspacesLoading:!0,workspacesError:null}));try{const v=await _e.fetchWorkspaces();c(v.workspaces),u(R=>({...R,workspacesLoading:!1}))}catch(v){const R=v instanceof Error?v.message:"加载工作空间失败";u(D=>({...D,workspacesLoading:!1,workspacesError:R})),console.error("加载工作空间失败:",v)}},[]),_=n.useCallback(async(v={})=>{const R=v.workspace_id||w;if(!R){console.warn("无法加载工作流:未选择工作空间");return}u(D=>({...D,workflowsLoading:!0,workflowsError:null}));try{const D={workspace_id:R,page_num:v.page_num||l,page_size:v.page_size||S},B=await _e.fetchWorkflows(D);h(B.items),P(B.hasMore),u(q=>({...q,workflowsLoading:!1}))}catch(D){const B=D instanceof Error?D.message:"加载工作流失败";u(q=>({...q,workflowsLoading:!1,workflowsError:B})),console.error("加载工作流失败:",D)}},[w,l,S]),G=n.useCallback(v=>{x(v),u(R=>({...R,selectedWorkspaceId:v})),h([]),p(1),P(!1),s&&v&&_({workspace_id:v,page_num:1})},[s,_]),ee=n.useCallback(async()=>{await X()},[X]),ce=n.useCallback(async()=>{w&&await _({workspace_id:w,page_num:l})},[_,w,l]),d=n.useCallback(async()=>{try{await _e.clearCache(),t&&await X(),s&&w&&await _({workspace_id:w,page_num:1})}catch(v){throw console.error("清除缓存失败:",v),v}},[t,s,w,X,_]),A=n.useCallback(v=>{p(v),w&&_({workspace_id:w,page_num:v})},[w,_]),C=n.useCallback(v=>{b(v),p(1),w&&_({workspace_id:w,page_num:1,page_size:v})},[w,_]);return n.useEffect(()=>{t&&X()},[t,X]),n.useEffect(()=>{s&&w&&(async()=>{u(R=>({...R,workflowsLoading:!0,workflowsError:null}));try{const R={workspace_id:w,page_num:1,page_size:S},D=await _e.fetchWorkflows(R);h(D.items),P(D.hasMore),u(B=>({...B,workflowsLoading:!1}))}catch(R){const D=R instanceof Error?R.message:"加载工作流失败";u(B=>({...B,workflowsLoading:!1,workflowsError:D})),console.error("加载工作流失败:",R)}})()},[s,w,S]),{workspaces:i,workflows:m,selectedWorkspace:z,workspacesLoading:f.workspacesLoading,workflowsLoading:f.workflowsLoading,workspacesError:f.workspacesError,workflowsError:f.workflowsError,hasMoreWorkflows:W,selectWorkspace:G,loadWorkflows:_,refreshWorkspaces:ee,refreshWorkflows:ce,clearCache:d,setWorkflows:h,currentPage:l,pageSize:S,setPage:A,setPageSize:C}}function _a({onToolAdded:r}){var jt;const[t,s]=n.useState(!1),[a,o]=n.useState(!1),[i,c]=n.useState({open:!1,action:"add"}),[m,h]=n.useState({open:!1}),[w,x]=n.useState(navigator.onLine),[f,u]=n.useState(new Set),[l,p]=n.useState(!1),{workspaces:S,workflows:b,selectedWorkspace:W,workspacesLoading:P,workflowsLoading:z,workspacesError:X,workflowsError:_,hasMoreWorkflows:G,currentPage:ee,selectWorkspace:ce,refreshWorkflows:d,setPage:A,setWorkflows:C}=Ua({autoLoadWorkspaces:!0,autoLoadWorkflows:!0});n.useEffect(()=>{const N=()=>x(!0),F=()=>x(!1);return window.addEventListener("online",N),window.addEventListener("offline",F),()=>{window.removeEventListener("online",N),window.removeEventListener("offline",F)}},[]),n.useEffect(()=>{if(!P&&S.length>0&&!W&&!l){const N=S[0];console.log(`自动选择第一个工作空间: ${N.name}`),ce(N.id),p(!0)}P&&l&&p(!1)},[S,P,W,l,ce]);const v=N=>{p(!0),ce(N)},R=N=>{if(!w){j.error("网络连接已断开,请检查网络后重试");return}const F=`add_${N.workflow_id}`;if(f.has(F)){j.warning("该工作流正在添加中,请勿重复操作");return}h({open:!0,workflow:N})},D=async(N,F)=>{const O=`add_${N.workflow_id}`;o(!0),u(T=>new Set(T).add(O));try{if(!N.workflow_id||!N.workflow_name||!N.app_id)throw new Error("工作流数据不完整,缺少必要字段");if(!w)throw new Error("网络连接已断开,请检查网络后重试");const T=F.length>0?{parameters:F}:void 0,J={type:"coze",data:{workflow:N,customName:void 0,customDescription:void 0,parameterConfig:T}},xe=await L.addCustomTool(J);j.success(`已添加工作流 "${N.workflow_name}" 为 MCP 工具 "${xe.name}"${F.length>0?`,配置了 ${F.length} 个参数`:""}`),C(Gs=>Gs.map(tt=>tt.workflow_id===N.workflow_id?{...tt,isAddedAsTool:!0,toolName:xe.name}:tt)),r==null||r(),await d()}catch(T){console.error("添加工作流失败:",T);let J="添加工作流失败,请重试";T instanceof Error&&(T.message.includes("已存在")||T.message.includes("冲突")?J=`工作流 "${N.workflow_name}" 已存在,请勿重复添加`:T.message.includes("配置")||T.message.includes("token")?J="系统配置错误,请检查扣子API配置":T.message.includes("验证失败")||T.message.includes("格式")?J="工作流数据格式错误,请联系管理员":T.message.includes("网络")||T.message.includes("超时")||T.message.includes("连接")?J="网络连接失败,请检查网络后重试":T.message.includes("权限")?J="权限不足,请检查API权限配置":T.message.includes("频繁")?J="操作过于频繁,请稍后重试":J=T.message),j.error(J)}finally{o(!1),u(T=>{const J=new Set(T);return J.delete(O),J}),h({open:!1})}},B=()=>{h({open:!1})},q=async N=>{const F=`add_${N.workflow_id}`;o(!0),u(O=>new Set(O).add(F));try{if(!N.workflow_id||!N.workflow_name||!N.app_id)throw new Error("工作流数据不完整,缺少必要字段");if(!w)throw new Error("网络连接已断开,请检查网络后重试");const O={type:"coze",data:{workflow:N,customName:void 0,customDescription:void 0,parameterConfig:void 0}},T=await L.addCustomTool(O);j.success(`已添加工作流 "${N.workflow_name}" 为 MCP 工具 "${T.name}"`),C(J=>J.map(xe=>xe.workflow_id===N.workflow_id?{...xe,isAddedAsTool:!0,toolName:T.name}:xe)),r==null||r(),await d()}catch(O){console.error("添加工作流失败:",O);let T="添加工作流失败,请重试";O instanceof Error&&(O.message.includes("已存在")||O.message.includes("冲突")?T=`工作流 "${N.workflow_name}" 已存在,请勿重复添加`:O.message.includes("配置")||O.message.includes("token")?T="系统配置错误,请检查扣子API配置":O.message.includes("验证失败")||O.message.includes("格式")?T="工作流数据格式错误,请联系管理员":O.message.includes("网络")||O.message.includes("超时")||O.message.includes("连接")?T="网络连接失败,请检查网络后重试":O.message.includes("权限")?T="权限不足,请检查API权限配置":O.message.includes("频繁")?T="操作过于频繁,请稍后重试":T=O.message),j.error(T)}finally{o(!1),u(O=>{const T=new Set(O);return T.delete(F),T}),c({open:!1,action:"add"})}},y=()=>{ee>1&&A(ee-1)},k=()=>{G&&A(ee+1)},$=()=>{W&&d()},M=()=>e.jsx("div",{className:"space-y-2",children:X?e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-red-600 bg-red-50 rounded-md",children:[e.jsx(Ct,{className:"h-4 w-4"}),e.jsxs("span",{children:["加载工作空间失败: ",X]})]}):e.jsxs(Ds,{value:(W==null?void 0:W.id)||"",onValueChange:v,disabled:P,children:[e.jsx(wt,{children:e.jsx(Ls,{placeholder:P?"加载中...":"请选择工作空间"})}),e.jsx(St,{children:S.map(N=>e.jsx(ye,{value:N.id,children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:N.name})})},N.id))})]})}),Vs=()=>W?_?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ct,{className:"h-12 w-12 text-red-500 mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"加载工作流失败"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:_}),e.jsxs(E,{onClick:$,variant:"outline",children:[e.jsx(Cr,{className:"h-4 w-4 mr-2"}),"重试"]})]}):z?e.jsx("div",{className:"space-y-3",children:Array.from({length:3},(N,F)=>F).map(N=>e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg",children:[e.jsx(be,{className:"w-10 h-10 rounded-lg","data-testid":"skeleton"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(be,{className:"h-4 w-1/3","data-testid":"skeleton"}),e.jsx(be,{className:"h-3 w-2/3","data-testid":"skeleton"})]}),e.jsx(be,{className:"w-16 h-8","data-testid":"skeleton"})]},`skeleton-${N}`))}):b.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Se,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"暂无工作流"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"当前工作空间下没有可用的工作流"})]}):e.jsx("div",{className:"space-y-3 max-h-[500px] overflow-auto",children:b.map(N=>e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:bg-slate-50 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center text-lg",children:e.jsx(Se,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-sm truncate",children:N.workflow_name}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"工作流"})]}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:N.description||"暂无描述"})]}),e.jsx("div",{className:"flex-shrink-0",children:N.isAddedAsTool?e.jsx(ne,{variant:"secondary",className:"text-xs bg-green-100 text-green-800",children:"已添加"}):e.jsxs(E,{size:"sm",onClick:()=>R(N),disabled:a,children:[a?e.jsx(je,{className:"h-4 w-4 animate-spin","data-testid":"loader"}):e.jsx(Ce,{className:"h-4 w-4"}),"添加"]})})]},N.workflow_id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Se,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"请先选择工作空间"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"选择一个工作空间后,将显示该空间下的工作流列表"})]}),Ks=()=>!W||b.length===0?null:e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"link",size:"sm",onClick:y,disabled:ee===1,className:"text-muted-foreground",children:e.jsx(yr,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsx("span",{className:"text-sm",children:ee})}),e.jsx(E,{variant:"link",size:"sm",onClick:k,disabled:!G,className:"text-muted-foreground",children:e.jsx(Nr,{className:"h-4 w-4"})})]})});return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{open:t,onOpenChange:s,children:[e.jsx(Ae,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full",children:[e.jsx(Se,{className:"h-4 w-4 mr-2"}),"工作流集成"]})}),e.jsxs(de,{className:"flex flex-col max-w-full w-[1000px]",children:[e.jsx(ue,{className:"flex-shrink-0",children:e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Se,{className:"h-5 w-5"}),"工作流集成"]})}),e.jsx("div",{className:"w-[120px]",children:M()}),e.jsx("div",{className:"flex-1 pr-2 w-full",children:Vs()}),Ks()]})]}),m.workflow&&e.jsx(_s,{open:m.open,onOpenChange:N=>h(F=>({...F,open:N})),workflow:m.workflow,onConfirm:D,onCancel:B,title:"配置工作流参数"}),e.jsx(Ze,{open:i.open,onOpenChange:N=>c(F=>({...F,open:N})),children:e.jsxs(Re,{children:[e.jsxs(Te,{children:[e.jsx(ze,{children:"确认添加工作流"}),e.jsxs(Me,{children:['确定要将工作流 "',(jt=i.workflow)==null?void 0:jt.workflow_name,'" 添加为 MCP 工具吗?']})]}),e.jsxs(We,{children:[e.jsx($e,{children:"取消"}),e.jsx(Ie,{onClick:()=>{i.workflow&&q(i.workflow)},children:"添加"})]})]})})]})}const Ba=K.object({config:K.string().min(2,{message:"配置不能为空"})});function qa({mcpServer:r,mcpServerName:t}){const[s,a]=n.useState(!1),[o,i]=n.useState(!1),c=ge(),{updateConfig:m}=et(),h=ke({resolver:Ee(Ba),defaultValues:{config:JSON.stringify(r,null,2)}});async function w(x){if(!c){j.error("配置数据未加载,请稍后重试");return}i(!0);try{let f;try{f=JSON.parse(x.config)}catch{j.error("JSON格式错误,请检查配置格式");return}if(!f||typeof f!="object"){j.error("配置格式无效");return}const u={...c,mcpServers:{...c.mcpServers,[t]:f}};await m(u),j.success("MCP服务器配置已更新"),a(!1)}catch(f){console.error("更新配置失败:",f),j.error(f instanceof Error?f.message:"更新配置失败")}finally{i(!1)}}return e.jsxs(fe,{open:s,onOpenChange:a,children:[e.jsx(Ae,{asChild:!0,children:e.jsx(E,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(Ne,{className:"h-4 w-4"})})}),e.jsx(de,{className:"sm:max-w-[500px]",children:e.jsx(De,{...h,children:e.jsxs("form",{onSubmit:h.handleSubmit(w),children:[e.jsxs(ue,{className:"mb-4",children:[e.jsxs(me,{children:["配置 ",t," MCP"]}),e.jsx(pe,{children:"点击保存后,需要重启服务才会生效。"})]}),e.jsx("div",{className:"grid gap-4",children:e.jsx(te,{control:h.control,name:"config",render:({field:x})=>e.jsxs(Y,{children:[e.jsx(Q,{children:e.jsx(vt,{placeholder:"MCP服务配置",className:"resize-none h-[300px] font-mono text-sm",disabled:o,...x})}),e.jsx(se,{})]})})}),e.jsxs(we,{className:"mt-4",children:[e.jsx(Ye,{asChild:!0,children:e.jsx(E,{variant:"outline",disabled:o,children:"取消"})}),e.jsx(E,{type:"submit",disabled:o,children:o?"保存中...":"保存"})]})]})})})]})}function Ha({mcpServerName:r}){const[t,s]=n.useState(!1),{updateConfig:a}=et(),o=ge(),i=async()=>{if(!o){j.error("配置未加载,无法删除服务");return}try{s(!0);const c={...o.mcpServers};delete c[r];const m=o.mcpServerConfig?{...o.mcpServerConfig}:void 0;m&&r in m&&delete m[r];const h={...o,mcpServers:c,mcpServerConfig:m};await a(h),j.success(`MCP 服务 "${r}" 已删除`)}catch(c){console.error("删除 MCP 服务失败:",c),j.error(`删除 MCP 服务失败: ${c instanceof Error?c.message:"未知错误"}`)}finally{s(!1)}};return e.jsxs(Ze,{children:[e.jsx(ba,{asChild:!0,children:e.jsx(E,{variant:"destructive",size:"icon",className:"size-8",children:e.jsx(Gt,{className:"h-4 w-4"})})}),e.jsxs(Re,{children:[e.jsxs(Te,{children:[e.jsxs(ze,{children:["确定要删除这个(",r,")MCP服务吗?"]}),e.jsx(Me,{children:"删除后,对应的工具列表也会移除。"})]}),e.jsxs(We,{children:[e.jsx($e,{children:"取消"}),e.jsx(Ie,{onClick:i,disabled:t,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:t?"删除中...":"确定"})]})]})]})}function Bs({disabled:r=!1,variant:t="outline",className:s="",restartingText:a="重启中...",defaultText:o="重启服务"}){const{loading:{isRestarting:i},restartService:c}=oe(),m=ls(),h=async()=>{try{await c()}catch(x){console.error("[RestartButton] 重启失败:",x)}},w=()=>i?m.enabled&&m.startTime?"重连中...":a:o;return e.jsxs(E,{type:"button",onClick:h,variant:t,disabled:i||r,className:ns("flex items-center gap-2 w-[120px]",s),children:[i?e.jsx(je,{className:"size-4 animate-spin"}):e.jsx(kr,{className:"size-4"}),w()]})}function Fa({updateConfig:r}){const t=va(),s=Rs(),[a,o]=n.useState([]),[i,c]=n.useState([]),[m,h]=n.useState(!1),[w,x]=n.useState(null),f=n.useCallback((d,A)=>{var R,D;const{serviceName:C,toolName:v}=(()=>{var B,q;return!d||!d.handler?{serviceName:"unknown",toolName:(d==null?void 0:d.name)||"unknown"}:d.handler.type==="mcp"?{serviceName:((B=d.handler.config)==null?void 0:B.serviceName)||"unknown",toolName:((q=d.handler.config)==null?void 0:q.toolName)||d.name}:d.handler.type==="proxy"&&d.handler.platform==="coze"?{serviceName:"coze",toolName:d.name}:{serviceName:"custom",toolName:d.name}})();return{serverName:C,toolName:v,enable:A,name:d.name,description:d.description,usageCount:(R=d.stats)==null?void 0:R.usageCount,lastUsedTime:(D=d.stats)==null?void 0:D.lastUsedTime,inputSchema:d.inputSchema}},[]),u=n.useCallback(async()=>{h(!0),x(null);try{const[d,A]=await Promise.all([L.getToolsList("enabled"),L.getToolsList("disabled")]),C=d.map(R=>f(R,!0)),v=A.map(R=>f(R,!1));o(C),c(v)}catch(d){console.error("获取工具列表失败:",d);const A=d instanceof Error?d.message:"获取工具列表失败";if(x(A),j.error(A),t){const C=Object.entries(t).flatMap(([D,B])=>Object.entries((B==null?void 0:B.tools)||{}).map(([q,y])=>({serverName:D,toolName:q,...y}))),v=C.filter(D=>D.enable!==!1),R=C.filter(D=>D.enable===!1);o(v),c(R)}}finally{h(!1)}},[t,f]),l=n.useCallback(async()=>{try{const[d,A]=await Promise.all([L.getToolsList("enabled"),L.getToolsList("disabled")]),C=d.map(R=>f(R,!0)),v=A.map(R=>f(R,!1));o(C),c(v)}catch(d){console.error("刷新工具列表失败:",d),j.error("刷新工具列表失败")}},[f]);n.useEffect(()=>{u()},[u]);const[p,S]=n.useState(null),[b,W]=n.useState({open:!1}),P=async(d,A)=>{try{if(A){const C=[...a,...i].find(v=>v.name===d);if(!C){j.error("找不到对应的工具信息");return}if(C.serverName==="coze"){S(d);return}await L.removeCustomTool(d),j.success(`删除工具 ${d} 成功`)}else{const C=[...a,...i].find(v=>v.name===d);if(!C){j.error("找不到对应的工具信息");return}C.serverName==="coze"?await L.addCustomTool({workflow_id:"",workflow_name:d,description:C.description||"",icon_url:"",app_id:""},d,C.description||""):await L.addCustomTool({type:"mcp",data:{serviceName:C.serverName,toolName:C.toolName,customName:d,customDescription:C.description||""}}),j.success(`添加工具 ${d} 成功`)}await l()}catch(C){console.error("切换工具状态失败:",C),j.error(C instanceof Error?C.message:"切换工具状态失败")}},z=async()=>{if(p)try{await L.removeCustomTool(p),j.success(`删除工具 ${p} 成功`),await l()}catch(d){console.error("删除 Coze 工具失败:",d),j.error(d instanceof Error?d.message:"删除 Coze 工具失败")}finally{S(null)}},X=()=>{S(null)},_=d=>{d.serverName==="coze"&&W({open:!0,tool:d})},G=d=>{var A,C,v;return d.serverName==="coze"&&((A=d.handler)==null?void 0:A.type)==="proxy"?{workflow_id:((C=d.handler.config)==null?void 0:C.workflow_id)||"",workflow_name:d.toolName,description:d.description||"",icon_url:"",app_id:((v=d.handler.config)==null?void 0:v.app_id)||"",creator:{id:"",name:""},created_at:0,updated_at:0,isAddedAsTool:!0,toolName:d.name,inputSchema:d.inputSchema}:{workflow_id:"",workflow_name:d.toolName,description:d.description||"",icon_url:"",app_id:"",creator:{id:"",name:""},created_at:0,updated_at:0,isAddedAsTool:!0,toolName:d.name,inputSchema:d.inputSchema}},ee=async(d,A)=>{if(b.tool)try{const C=A.length>0?{parameters:A}:void 0,v=G(b.tool);d.workflow_id&&(v.workflow_id=d.workflow_id),d.app_id&&(v.app_id=d.app_id);const R={type:"coze",data:{workflow:v,customName:void 0,customDescription:void 0,parameterConfig:C}};await L.updateCustomTool(b.tool.name,R),j.success(`工具 "${v.workflow_name}" 参数配置更新成功`),await l()}catch(C){console.error("更新工具参数配置失败:",C);let v="更新工具参数配置失败,请重试";C instanceof Error&&(v=C.message),j.error(v)}finally{W({open:!1})}},ce=()=>{W({open:!1})};return!s||Object.keys(s).length===0?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("div",{className:"flex items-center justify-between px-4 lg:px-6",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"你的聚合 MCP 服务"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"在这里管理你的 MCP 服务器和工具。"})]})}),e.jsx("div",{className:"px-4 lg:px-6",children:e.jsx(le,{className:"border-dashed",children:e.jsxs(ve,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(kt,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"还没有 MCP 服务"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center mb-4",children:"添加你的第一个 MCP 服务器来开始使用强大的工具集成功能。"}),e.jsx(It,{})]})})})]})}):e.jsxs("div",{className:"flex flex-col gap-4 px-4 lg:px-6",children:[e.jsx("h2",{className:"text-2xl font-bold",children:"你的聚合 MCP 服务"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"你可以在这里管理你的 MCP 服务,包括启用/禁用工具,以及查看工具的详细信息。 最终暴露给小智服务端和其他MCP客户端的是这里聚合MCP"}),e.jsxs("div",{className:"*:data-[slot=card]:shadow-xs @xl/main:grid-cols-8 @5xl/main:grid-cols-8 grid grid-cols-1 gap-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",children:[e.jsx(le,{className:"transition-all duration-200 col-span-3",children:e.jsx(ve,{className:"p-4",children:e.jsxs("div",{className:"flex-col",children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4"}),"使用中的工具 (",a.length,")",m&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(加载中...)"})]}),e.jsx("div",{className:"flex-1 space-y-2",children:m?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"加载工具列表中..."})}):w?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 px-4",children:[e.jsx("div",{className:"text-sm text-red-500 mb-2",children:w}),e.jsx(E,{variant:"outline",size:"sm",onClick:u,children:"重试"})]}):a.map(d=>e.jsxs("div",{className:"flex items-start justify-between p-4 bg-slate-50 rounded-md font-mono",children:[e.jsxs("div",{className:"text-md flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 justify-start",children:[e.jsx(ne,{variant:"secondary",className:"rounded-md",children:d.serverName}),e.jsx("span",{children:d.toolName})]}),e.jsx("p",{className:"text-sm text-muted-foreground my-2",children:d.description}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"使用次数:"})," ",e.jsx("span",{className:"text-primary font-bold",children:d.usageCount||0})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"最后使用:"})," ",e.jsx("span",{className:"text-primary font-bold",children:d.lastUsedTime||"-"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[d.serverName==="coze"&&e.jsx(E,{variant:"secondary",size:"icon",className:"size-8 hover:bg-blue-500 hover:text-white",onClick:()=>_(d),title:"配置参数",children:e.jsx(Ne,{size:16})}),e.jsx(E,{variant:"secondary",size:"icon",className:"size-8 hover:bg-red-500 hover:text-white",onClick:()=>P(d.name,!0),children:e.jsx(Er,{size:18})})]})]},d.toolName))})]})})}),e.jsx(le,{className:"transition-all duration-200 col-span-3",children:e.jsx(ve,{className:"p-4",children:e.jsxs("div",{className:"flex-col",children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4"}),"未使用的工具 (",i.length,")",m&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(加载中...)"})]}),e.jsx("div",{className:"flex-1 space-y-2",children:m?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"加载工具列表中..."})}):w?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 px-4",children:[e.jsx("div",{className:"text-sm text-red-500 mb-2",children:w}),e.jsx(E,{variant:"outline",size:"sm",onClick:u,children:"重试"})]}):i.length===0?e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-4 py-20 px-4 bg-slate-50 rounded-md font-mono h-full",children:[e.jsx(kt,{strokeWidth:1.5,size:48,className:"text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"全部工具都已经启用"})]}):i.map(d=>e.jsxs("div",{className:"flex items-start justify-between p-4 bg-slate-50 rounded-md font-mono",children:[e.jsxs("div",{className:"text-md flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 justify-start",children:[e.jsx(ne,{variant:"secondary",className:"rounded-md",children:d.serverName}),e.jsx("span",{children:d.toolName})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d.description}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"使用次数:"})," ",e.jsx("span",{className:"text-primary font-bold",children:d.usageCount||0})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"最后使用:"})," ",e.jsx("span",{className:"text-primary font-bold",children:d.lastUsedTime||"-"})]})]})]}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsx(E,{variant:"secondary",size:"icon",className:"size-8 hover:bg-green-500 hover:text-white",onClick:()=>P(d.name,!1),children:e.jsx(Ce,{className:"h-4 w-4"})})})]},d.toolName))})]})})}),e.jsxs("div",{className:"transition-all duration-200 gap-4 flex flex-col col-span-2",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{}),e.jsx(Bs,{})]}),e.jsx(_a,{onToolAdded:l})]}),Object.entries(s||{}).map(([d,A])=>e.jsxs(le,{className:"transition-all duration-200",children:[e.jsx(ve,{className:"p-0",children:e.jsx("div",{className:"p-4 pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:"flex items-start gap-4 flex-1",children:e.jsx("div",{className:"flex-1",children:e.jsx("div",{className:"flex items-center gap-2 mb-2",children:e.jsx("h3",{className:"text-lg font-semibold",children:d})})})}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[e.jsx(qa,{mcpServerName:d,mcpServer:A}),e.jsx(Ha,{mcpServerName:d})]})]})})}),e.jsx(Fe,{className:"p-4 pt-2",children:e.jsx(ne,{variant:"outline",className:"text-xs",children:nt(A)})})]},d))]})]}),e.jsx(Ze,{open:p!==null,onOpenChange:d=>!d&&S(null),children:e.jsxs(Re,{children:[e.jsxs(Te,{children:[e.jsx(ze,{children:"确认移除 Coze 工作流工具"}),e.jsxs(Me,{children:['移除后需要通过【工作流集成】重新添加并配置入参,确定要移除工具 "',p,'" 吗?']})]}),e.jsxs(We,{children:[e.jsx($e,{onClick:X,children:"取消"}),e.jsx(Ie,{onClick:z,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"确认移除"})]})]})}),b.tool&&e.jsx(_s,{open:b.open,onOpenChange:d=>W(A=>({...A,open:d})),workflow:b.tool,onConfirm:ee,onCancel:ce,title:"配置工作流参数"})]})}function qs({title:r}){return e.jsxs("header",{className:"group-has-data-[collapsible=icon]/sidebar-wrapper:h-12 flex h-12 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear",children:[e.jsxs("div",{className:"flex w-full items-center gap-1 px-4 lg:gap-2 lg:px-6",children:[e.jsx(Ss,{className:"-ml-1"}),e.jsx(mt,{orientation:"vertical",className:"mx-2 data-[orientation=vertical]:h-4"}),e.jsx("h1",{className:"text-base font-medium",children:r})]}),e.jsx("div",{className:"flex w-full justify-end items-center gap-1 px-4 lg:gap-2 lg:px-6",children:e.jsx("a",{href:"https://github.com/shenjingnan/xiaozhi-client",target:"_blank",rel:"noopener noreferrer",children:e.jsx(Pr,{size:24,className:"text-slate-500",fill:"currentColor"})})})]})}class Va{constructor(){U(this,"apiClient");U(this,"webSocketManager");U(this,"initialized",!1);this.apiClient=L,this.webSocketManager=I}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){this.webSocketManager.on(t,s)}offWebSocketEvent(t){this.webSocketManager.off(t)}reconnectWebSocket(){this.webSocketManager.disconnect(),setTimeout(()=>{this.webSocketManager.connect()},1e3)}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((a,o)=>{const i=setTimeout(()=>{this.webSocketManager.off("configUpdate"),o(new Error("等待配置更新通知超时"))},s);this.webSocketManager.on("configUpdate",()=>{clearTimeout(i),this.webSocketManager.off("configUpdate"),a()}),this.updateConfig(t).catch(c=>{clearTimeout(i),this.webSocketManager.off("configUpdate"),o(c)})})}async restartServiceWithNotification(t=3e4){return new Promise((s,a)=>{const o=setTimeout(()=>{this.webSocketManager.off("restartStatus"),a(new Error("等待重启状态通知超时"))},t);this.webSocketManager.on("restartStatus",i=>{i.status==="completed"?(clearTimeout(o),this.webSocketManager.off("restartStatus"),s()):i.status==="failed"&&(clearTimeout(o),this.webSocketManager.off("restartStatus"),a(new Error(i.error||"服务重启失败")))}),this.restartService().catch(i=>{clearTimeout(o),this.webSocketManager.off("restartStatus"),a(i)})})}}const H=new Va;function Ka(){const r=$s(),t=n.useRef(!1);n.useEffect(()=>{if(!t.current)return console.log("[NetworkService] 初始化网络服务"),t.current=!0,H.initialize().catch(l=>{console.error("[NetworkService] 初始化失败:",l)}),H.onWebSocketEvent("connected",()=>{console.log("[NetworkService] WebSocket 已连接"),r.setConnectionState(Z.CONNECTED),s()}),H.onWebSocketEvent("disconnected",()=>{console.log("[NetworkService] WebSocket 已断开"),r.setConnectionState(Z.DISCONNECTED)}),H.onWebSocketEvent("configUpdate",l=>{console.log("[NetworkService] 收到配置更新通知"),ie.getState().setConfig(l,"websocket")}),H.onWebSocketEvent("statusUpdate",l=>{console.log("[NetworkService] 收到状态更新通知"),oe.getState().setClientStatus(l,"websocket")}),H.onWebSocketEvent("restartStatus",l=>{console.log("[NetworkService] 收到重启状态通知:",l),oe.getState().setRestartStatus(l,"websocket")}),H.onWebSocketEvent("error",l=>{console.error("[NetworkService] WebSocket 错误:",l)}),()=>{console.log("[NetworkService] 清理网络服务"),H.destroy(),t.current=!1}},[r]);const s=n.useCallback(async()=>{try{console.log("[NetworkService] 加载初始数据");const[l,p]=await Promise.all([H.getConfig(),H.getClientStatus()]);console.log("[NetworkService] 初始数据加载成功"),ie.getState().setConfig(l,"http"),oe.getState().setClientStatus(p,"http")}catch(l){console.error("[NetworkService] 加载初始数据失败:",l)}},[]),a=n.useCallback(async()=>{try{const l=await H.getConfig();return ie.getState().setConfig(l,"http"),l}catch(l){throw console.error("[NetworkService] 获取配置失败:",l),l}},[]),o=n.useCallback(async l=>{try{console.log("[NetworkService] 更新配置"),await H.updateConfig(l),ie.getState().setConfig(l,"http"),console.log("[NetworkService] 配置更新成功")}catch(p){throw console.error("[NetworkService] 配置更新失败:",p),p}},[]),i=n.useCallback(async()=>{try{const l=await H.getStatus();return oe.getState().setClientStatus(l.client,"http"),l}catch(l){throw console.error("[NetworkService] 获取状态失败:",l),l}},[]),c=n.useCallback(async()=>{try{await i()}catch(l){console.error("[NetworkService] 刷新状态失败:",l)}},[i]),m=n.useCallback(async()=>{try{console.log("[NetworkService] 重启服务"),await H.restartService(),console.log("[NetworkService] 重启请求已发送")}catch(l){throw console.error("[NetworkService] 重启服务失败:",l),l}},[]),h=n.useCallback(async(l=3e4)=>{try{console.log("[NetworkService] 重启服务并等待通知"),await H.restartServiceWithNotification(l),console.log("[NetworkService] 服务重启完成")}catch(p){throw console.error("[NetworkService] 重启服务失败:",p),p}},[]),w=n.useCallback(async(l,p=5e3)=>{try{console.log("[NetworkService] 更新配置并等待通知"),await H.updateConfigWithNotification(l,p),console.log("[NetworkService] 配置更新完成")}catch(S){throw console.error("[NetworkService] 配置更新失败:",S),S}},[]),x=n.useCallback(l=>{console.log("[NetworkService] 设置自定义 WebSocket URL:",l),H.setWebSocketUrl(l),r.setWsUrl(l)},[r]),f=n.useCallback(async l=>{try{console.log(`[NetworkService] 切换到端口 ${l}`),r.setPortChangeStatus({status:"checking",targetPort:l,timestamp:Date.now()});const p=window.location.protocol==="https:"?"wss:":"ws:",S=window.location.hostname,b=`${p}//${S}:${l}`;await m(),await new Promise(W=>setTimeout(W,5e3)),x(b),window.location.reload()}catch(p){throw console.error("[NetworkService] 端口切换失败:",p),r.setPortChangeStatus({status:"failed",targetPort:l,error:p instanceof Error?p.message:"端口切换失败",timestamp:Date.now()}),p}},[r,m,x]),u=n.useCallback(()=>{const l=localStorage.getItem("xiaozhi-ws-url");if(l)return l;const p=window.location.protocol==="https:"?"wss:":"ws:",S=window.location.hostname,b=window.location.port;return`${p}//${S}${b?`:${b}`:""}`},[]);return{getConfig:a,updateConfig:o,getStatus:i,refreshStatus:c,restartService:m,updateConfigWithNotification:w,restartServiceWithNotification:h,setCustomWsUrl:x,getWebSocketUrl:u,changePort:f,loadInitialData:s,isWebSocketConnected:()=>H.isWebSocketConnected(),getWebSocketState:()=>H.getWebSocketState()}}async function Ga(){console.log("[Stores] 开始初始化所有 stores");try{console.log("[Stores] 初始化 WebSocket store"),Le.getState().initialize(),console.log("[Stores] 初始化配置 store"),await ie.getState().initialize(),console.log("[Stores] 初始化状态 store"),await oe.getState().initialize(),console.log("[Stores] 所有 stores 初始化完成")}catch(r){throw console.error("[Stores] Stores 初始化失败:",r),r}}const Hs=n.createContext(null);function Ja({children:r}){const t=Ka(),[s,a]=n.useState(!1);return n.useEffect(()=>{let o=!0;return(async()=>{try{console.log("[WebSocketProvider] 开始初始化 stores"),await Ga(),o&&(a(!0),console.log("[WebSocketProvider] Stores 初始化完成"))}catch(c){console.error("[WebSocketProvider] Stores 初始化失败:",c),o&&a(!0)}})(),()=>{o=!1}},[]),s?e.jsx(Hs.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 Xa(){const r=n.useContext(Hs);if(!r)throw new Error("useNetworkServiceActions must be used within a NetworkServiceProvider");return r}const Za=Ja,Fs=Xa;function Ya(){const{updateConfig:r}=Fs();return e.jsxs(pt,{children:[e.jsx(Cs,{variant:"inset"}),e.jsxs(ht,{children:[e.jsx(qs,{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(za,{}),e.jsx(Fa,{updateConfig:r})]})})})]})]})}const Qa=K.object({modelscope:K.object({apiKey:K.string().optional()}),platforms:K.object({coze:K.object({token:K.string().optional()})}),connection:K.object({heartbeatInterval:K.number().min(1e3,{message:"心跳间隔不能小于1000毫秒"}),heartbeatTimeout:K.number().min(1e3,{message:"心跳超时不能小于1000毫秒"}),reconnectInterval:K.number().min(1e3,{message:"重连间隔不能小于1000毫秒"})})});function eo(){var c,m,h,w,x,f;const r=ge(),{updateConfig:t}=Fs(),[s,a]=n.useState(!1),o=ke({resolver:Ee(Qa),defaultValues:{platforms:{coze:{token:((m=(c=r==null?void 0:r.platforms)==null?void 0:c.coze)==null?void 0:m.token)||""}},modelscope:{apiKey:((h=r==null?void 0:r.modelscope)==null?void 0:h.apiKey)||""},connection:{heartbeatInterval:((w=r==null?void 0:r.connection)==null?void 0:w.heartbeatInterval)||3e4,heartbeatTimeout:((x=r==null?void 0:r.connection)==null?void 0:x.heartbeatTimeout)||1e4,reconnectInterval:((f=r==null?void 0:r.connection)==null?void 0:f.reconnectInterval)||5e3}}});n.useEffect(()=>{var u,l,p,S;o.reset({modelscope:{apiKey:((u=r==null?void 0:r.modelscope)==null?void 0:u.apiKey)||""},connection:{heartbeatInterval:((l=r==null?void 0:r.connection)==null?void 0:l.heartbeatInterval)||3e4,heartbeatTimeout:((p=r==null?void 0:r.connection)==null?void 0:p.heartbeatTimeout)||1e4,reconnectInterval:((S=r==null?void 0:r.connection)==null?void 0:S.reconnectInterval)||5e3}})},[r,o.reset]);async function i(u){var l;if(!r){j.error("配置数据未加载,请稍后重试");return}a(!0);try{const p={...r,modelscope:{apiKey:u.modelscope.apiKey},connection:{heartbeatInterval:u.connection.heartbeatInterval,heartbeatTimeout:u.connection.heartbeatTimeout,reconnectInterval:u.connection.reconnectInterval},platforms:{...(r==null?void 0:r.platforms)??{},coze:{...((l=r==null?void 0:r.platforms)==null?void 0:l.coze)??{},token:u.platforms.coze.token}}};await t(p),j.success("配置已更新")}catch(p){console.error("更新配置失败:",p),j.error(p instanceof Error?p.message:"更新配置失败")}finally{a(!1)}}return e.jsxs(pt,{children:[e.jsx(Cs,{variant:"inset"}),e.jsxs(ht,{children:[e.jsx(qs,{title:"设置"}),e.jsx("div",{className:"flex flex-1 flex-col p-4",children:e.jsx("div",{className:"@container/main flex flex-1 flex-col gap-2 items-center",children:e.jsx("div",{className:"flex flex-col gap-4 py-4 md:gap-6 md:py-6 w-[600px]",children:e.jsx(De,{...o,children:e.jsx("form",{onSubmit:o.handleSubmit(i),children:e.jsxs("div",{className:"grid gap-4",children:[e.jsx(te,{control:o.control,name:"modelscope.apiKey",render:({field:u})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"魔搭社区 API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Q,{children:e.jsx(re,{placeholder:"魔搭社区 API Key",className:"font-mono text-sm",type:"password",disabled:s,autoComplete:"off","data-1p-ignore":!0,...u})}),e.jsx(E,{variant:"outline",onClick:()=>{window.open("https://www.modelscope.cn/my/myaccesstoken","_blank")},children:"打开魔搭社区"})]}),e.jsx(se,{})]})}),e.jsx(te,{control:o.control,name:"platforms.coze.token",render:({field:u})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"扣子身份凭证"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Q,{children:e.jsx(re,{placeholder:"扣子身份凭证",className:"font-mono text-sm",type:"password",autoComplete:"off","data-1p-ignore":!0,disabled:s,...u})}),e.jsx(E,{variant:"outline",onClick:()=>{window.open("https://www.coze.cn/open/oauth/sats","_blank")},children:"打开扣子平台"})]}),e.jsx(se,{})]})}),e.jsx(te,{control:o.control,name:"connection.heartbeatInterval",render:({field:u})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"心跳间隔(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Q,{children:e.jsx(re,{placeholder:"心跳间隔(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...u,value:u.value||"",onChange:l=>{const p=l.target.value;u.onChange(p===""?"":Number(p))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(se,{})]})}),e.jsx(te,{control:o.control,name:"connection.heartbeatTimeout",render:({field:u})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"心跳超时(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Q,{children:e.jsx(re,{placeholder:"心跳超时(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...u,value:u.value||"",onChange:l=>{const p=l.target.value;u.onChange(p===""?"":Number(p))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(se,{})]})}),e.jsx(te,{control:o.control,name:"connection.reconnectInterval",render:({field:u})=>e.jsxs(Y,{children:[e.jsx(ae,{children:"重连间隔(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Q,{children:e.jsx(re,{placeholder:"重连间隔(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...u,value:u.value||"",onChange:l=>{const p=l.target.value;u.onChange(p===""?"":Number(p))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(se,{})]})}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(E,{type:"submit",disabled:s,className:"flex-1",children:s?"保存中...":"保存"}),e.jsx(Bs,{})]})]})})})})})})]})]})}function to(){return e.jsxs(Za,{children:[e.jsx(Hr,{}),e.jsxs(Rr,{children:[e.jsx(st,{path:"/",element:e.jsx(Tr,{to:"/dashboard"})}),e.jsx(st,{path:"/dashboard",element:e.jsx(Ya,{})}),e.jsx(st,{path:"/settings",element:e.jsx(eo,{})})]}),e.jsx($r,{richColors:!0,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"}}})]})}Wr.createRoot(document.getElementById("root")).render(e.jsx(zr.StrictMode,{children:e.jsx(Mr,{children:e.jsx(to,{})})}));
31
+ //# sourceMappingURL=index-4qO90mnJ.js.map