@runweave/server-linux-x64 0.1.21 → 0.1.23
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/manifest.json +141 -141
- package/native.tar.gz +0 -0
- package/package.json +1 -1
- package/payload/app-server/build-info.json +3 -3
- package/payload/app-server/index.cjs +1 -1
- package/payload/backend/build-info.json +4 -4
- package/payload/backend/index.cjs +37 -19
- package/payload/frontend/dist/assets/{_baseUniq-1Km-k-ta.js → _baseUniq-V9OGBCCp.js} +1 -1
- package/payload/frontend/dist/assets/{access-DUvHn-7g.js → access-Bw9yaM2u.js} +1 -1
- package/payload/frontend/dist/assets/{advanced-2iC4XP-k.js → advanced-BspSUvyf.js} +1 -1
- package/payload/frontend/dist/assets/{appearance-F3ep216f.js → appearance-BHYR2QUj.js} +1 -1
- package/payload/frontend/dist/assets/{arc-B_Rv2EgC.js → arc-C4bVuMy6.js} +1 -1
- package/payload/frontend/dist/assets/{architectureDiagram-Q4EWVU46-CAfCOCHn.js → architectureDiagram-Q4EWVU46-B_EOBe6n.js} +1 -1
- package/payload/frontend/dist/assets/{blockDiagram-DXYQGD6D-Dt_EPk2t.js → blockDiagram-DXYQGD6D-aAkbmNO9.js} +1 -1
- package/payload/frontend/dist/assets/{c4Diagram-AHTNJAMY-pJxLy6Ib.js → c4Diagram-AHTNJAMY-DKeUolGU.js} +1 -1
- package/payload/frontend/dist/assets/channel-CBjt7igT.js +1 -0
- package/payload/frontend/dist/assets/{chunk-4BX2VUAB-XIuvwA5G.js → chunk-4BX2VUAB-cB5sH0Mw.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-4TB4RGXK-BaJHFe6f.js → chunk-4TB4RGXK-CxVRfINM.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-55IACEB6-CBN94dv8.js → chunk-55IACEB6-BFRLEEBY.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-EDXVE4YY-BTpbJ8AJ.js → chunk-EDXVE4YY-DA5BuoT3.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-FMBD7UC4-D8EB4vd_.js → chunk-FMBD7UC4-DIvA96Y1.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-OYMX7WX6-CVlwUrKx.js → chunk-OYMX7WX6-8Zl-vtJp.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-QZHKN3VN-CaRy6kUM.js → chunk-QZHKN3VN-DnW4X6Wx.js} +1 -1
- package/payload/frontend/dist/assets/{chunk-YZCP3GAM-D76OSgAi.js → chunk-YZCP3GAM-CH4YkXv-.js} +1 -1
- package/payload/frontend/dist/assets/classDiagram-6PBFFD2Q-HmoWChAG.js +1 -0
- package/payload/frontend/dist/assets/classDiagram-v2-HSJHXN6E-HmoWChAG.js +1 -0
- package/payload/frontend/dist/assets/clone-CiD5LYOe.js +1 -0
- package/payload/frontend/dist/assets/{connection-DbcKyIr4.js → connection-CINMNAPm.js} +1 -1
- package/payload/frontend/dist/assets/{connections-C-JFI1d6.js → connections-DsHGQRR2.js} +1 -1
- package/payload/frontend/dist/assets/{cose-bilkent-S5V4N54A-C8Ve8zWa.js → cose-bilkent-S5V4N54A-Dm1QOjDr.js} +1 -1
- package/payload/frontend/dist/assets/{dagre-KV5264BT-DlutyhBV.js → dagre-KV5264BT-BEbPPDoW.js} +1 -1
- package/payload/frontend/dist/assets/{desktop-hY0qLy1k.js → desktop-1jdcRQ7b.js} +1 -1
- package/payload/frontend/dist/assets/{diagram-5BDNPKRD-BOWSLJh5.js → diagram-5BDNPKRD-C-DmBIhV.js} +1 -1
- package/payload/frontend/dist/assets/{diagram-G4DWMVQ6-DEJYwBtT.js → diagram-G4DWMVQ6-Ddv6Kw2_.js} +1 -1
- package/payload/frontend/dist/assets/{diagram-MMDJMWI5-DCHKtsej.js → diagram-MMDJMWI5-Xae79J8R.js} +1 -1
- package/payload/frontend/dist/assets/{diagram-TYMM5635-DcWqaORk.js → diagram-TYMM5635-CavrGRG2.js} +1 -1
- package/payload/frontend/dist/assets/{erDiagram-SMLLAGMA-BAnv2QR4.js → erDiagram-SMLLAGMA-BRRD8F-e.js} +1 -1
- package/payload/frontend/dist/assets/{flowDiagram-DWJPFMVM-CLJLX_pg.js → flowDiagram-DWJPFMVM-C-ewssi0.js} +1 -1
- package/payload/frontend/dist/assets/{ganttDiagram-T4ZO3ILL-CEwNMCO_.js → ganttDiagram-T4ZO3ILL-BcZnXV6L.js} +1 -1
- package/payload/frontend/dist/assets/{gitGraphDiagram-UUTBAWPF-7qYUaW4T.js → gitGraphDiagram-UUTBAWPF-ZcfWVMGG.js} +1 -1
- package/payload/frontend/dist/assets/{graph-C3pGWAsG.js → graph-DRJG1bKF.js} +1 -1
- package/payload/frontend/dist/assets/{image-DzByFbwW.js → image-GQYH_1h4.js} +1 -1
- package/payload/frontend/dist/assets/{index-X6z9DRtr.js → index-UR7g5PLZ.js} +5 -5
- package/payload/frontend/dist/assets/{infoDiagram-42DDH7IO-uykCNcsm.js → infoDiagram-42DDH7IO-BWsoBaYn.js} +1 -1
- package/payload/frontend/dist/assets/{ishikawaDiagram-UXIWVN3A-DFjUz1ZP.js → ishikawaDiagram-UXIWVN3A-C3ayGr4G.js} +1 -1
- package/payload/frontend/dist/assets/{journeyDiagram-VCZTEJTY-KlFjvI1y.js → journeyDiagram-VCZTEJTY-DB1DxZ1v.js} +1 -1
- package/payload/frontend/dist/assets/{kanban-definition-6JOO6SKY-CWNvauW5.js → kanban-definition-6JOO6SKY-CtZWN0CK.js} +1 -1
- package/payload/frontend/dist/assets/{layout-DEYchOZT.js → layout-KX5XwX_6.js} +1 -1
- package/payload/frontend/dist/assets/{linear-CxNxQzFY.js → linear-DMZrhooi.js} +1 -1
- package/payload/frontend/dist/assets/{main-B5vSE7PX.js → main-LH8ULGFT.js} +4 -4
- package/payload/frontend/dist/assets/{min-D_bax_Q3.js → min-CWc1cxEQ.js} +1 -1
- package/payload/frontend/dist/assets/{mindmap-definition-QFDTVHPH-9CPQZB_P.js → mindmap-definition-QFDTVHPH-tj_8hDDH.js} +1 -1
- package/payload/frontend/dist/assets/{monitoring-BHrlQuyI.js → monitoring-BaUd-PhH.js} +1 -1
- package/payload/frontend/dist/assets/{notifications-C5O4JnTW.js → notifications-CTv1WVBh.js} +1 -1
- package/payload/frontend/dist/assets/{pieDiagram-DEJITSTG-wRY5e0M8.js → pieDiagram-DEJITSTG-Cwc4Gfp4.js} +1 -1
- package/payload/frontend/dist/assets/{quadrantDiagram-34T5L4WZ-t11sO3Dt.js → quadrantDiagram-34T5L4WZ-Clq2RqDJ.js} +1 -1
- package/payload/frontend/dist/assets/{record-content-BQpFEpbH.js → record-content-DQ0F1zbW.js} +1 -1
- package/payload/frontend/dist/assets/{requirementDiagram-MS252O5E-C0CwyWRr.js → requirementDiagram-MS252O5E-gaTHj3JP.js} +1 -1
- package/payload/frontend/dist/assets/{sankeyDiagram-XADWPNL6-BV_woefX.js → sankeyDiagram-XADWPNL6-CyBolt3D.js} +1 -1
- package/payload/frontend/dist/assets/{sequenceDiagram-FGHM5R23-Df4He8NT.js → sequenceDiagram-FGHM5R23-CO4UgRHw.js} +1 -1
- package/payload/frontend/dist/assets/{stateDiagram-FHFEXIEX-BEgdIPpz.js → stateDiagram-FHFEXIEX-ygBwN1Az.js} +1 -1
- package/payload/frontend/dist/assets/stateDiagram-v2-QKLJ7IA2-DTtHtWkN.js +1 -0
- package/payload/frontend/dist/assets/{status-Ce0iPeyb.js → status-BOcUUbE9.js} +1 -1
- package/payload/frontend/dist/assets/suiji-DPDKlWVi.js +1 -0
- package/payload/frontend/dist/assets/{svg-Bw5hEl7G.js → svg-BfkbqvDT.js} +1 -1
- package/payload/frontend/dist/assets/{tabs-DbtEnTWL.js → tabs-88TVAJwX.js} +1 -1
- package/payload/frontend/dist/assets/{timeline-definition-GMOUNBTQ-DwbNhEn4.js → timeline-definition-GMOUNBTQ-8Iy3eg4l.js} +1 -1
- package/payload/frontend/dist/assets/{vennDiagram-DHZGUBPP-pAfUF9dm.js → vennDiagram-DHZGUBPP-DLcttV2t.js} +1 -1
- package/payload/frontend/dist/assets/{wardley-RL74JXVD-DcKkKo7k.js → wardley-RL74JXVD-DUvr0OYP.js} +1 -1
- package/payload/frontend/dist/assets/{wardleyDiagram-NUSXRM2D-B1APfa8B.js → wardleyDiagram-NUSXRM2D-Dm-sdRY6.js} +1 -1
- package/payload/frontend/dist/assets/{xychartDiagram-5P7HB3ND-BaKuAJV-.js → xychartDiagram-5P7HB3ND-DR_MOYh1.js} +1 -1
- package/payload/frontend/dist/build-info.json +4 -4
- package/payload/frontend/dist/companion.html +1 -1
- package/payload/frontend/dist/index.html +2 -2
- package/payload/frontend/dist/assets/channel-DycidetN.js +0 -1
- package/payload/frontend/dist/assets/classDiagram-6PBFFD2Q-5pjklcgn.js +0 -1
- package/payload/frontend/dist/assets/classDiagram-v2-HSJHXN6E-5pjklcgn.js +0 -1
- package/payload/frontend/dist/assets/clone-CUh1yxwY.js +0 -1
- package/payload/frontend/dist/assets/stateDiagram-v2-QKLJ7IA2-DyKoLPVf.js +0 -1
- package/payload/frontend/dist/assets/suiji-CKYE-bFZ.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/appearance-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/appearance-BHYR2QUj.js","assets/index-D9-cSGu-.js","assets/notifications-CTv1WVBh.js","assets/shortcuts-BNrV46nh.js","assets/suiji-DPDKlWVi.js","assets/connection-CINMNAPm.js","assets/record-content-DQ0F1zbW.js","assets/access-Bw9yaM2u.js","assets/tabs-88TVAJwX.js","assets/monitoring-BaUd-PhH.js","assets/advanced-BspSUvyf.js","assets/status-BOcUUbE9.js","assets/desktop-1jdcRQ7b.js","assets/connections-DsHGQRR2.js","assets/browser-CIEzmzuD.js","assets/index-UR7g5PLZ.js","assets/index-BJDOs8Sk.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var x4=Object.defineProperty;var i_=e=>{throw TypeError(e)};var b4=(e,t,r)=>t in e?x4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var St=(e,t,r)=>b4(e,typeof t!="symbol"?t+"":t,r),_p=(e,t,r)=>t.has(e)||i_("Cannot "+r);var Q=(e,t,r)=>(_p(e,t,"read from private field"),r?r.call(e):t.get(e)),Ye=(e,t,r)=>t.has(e)?i_("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ae=(e,t,r,n)=>(_p(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),ut=(e,t,r)=>(_p(e,t,"access private method"),r);var od=(e,t,r,n)=>({set _(s){Ae(e,t,s,r)},get _(){return Q(e,t,n)}});import{r as p,a as ad,g as nC,R as da,b as _4,W as _t,d as ht,u as W,j as o,e as g0,c as y4}from"./index-D9-cSGu-.js";var Ls=function(){return Ls=Object.assign||function(t){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},Ls.apply(this,arguments)};function sC(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]]);return r}function iC(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,i=[],a;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i}function oC(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,i;n<s;n++)(i||!(n in t))&&(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}function aC(e){var t=p.useRef(e);return t.current=e,t}var w4=function(e){var t=aC(e);p.useEffect(function(){return function(){t.current()}},[])},yp,o_;function lC(){if(o_)return yp;o_=1;function e(t){var r=typeof t;return t!=null&&(r=="object"||r=="function")}return yp=e,yp}var wp,a_;function S4(){if(a_)return wp;a_=1;var e=typeof ad=="object"&&ad&&ad.Object===Object&&ad;return wp=e,wp}var Sp,l_;function cC(){if(l_)return Sp;l_=1;var e=S4(),t=typeof self=="object"&&self&&self.Object===Object&&self,r=e||t||Function("return this")();return Sp=r,Sp}var Cp,c_;function C4(){if(c_)return Cp;c_=1;var e=cC(),t=function(){return e.Date.now()};return Cp=t,Cp}var Ep,u_;function E4(){if(u_)return Ep;u_=1;var e=/\s/;function t(r){for(var n=r.length;n--&&e.test(r.charAt(n)););return n}return Ep=t,Ep}var kp,d_;function k4(){if(d_)return kp;d_=1;var e=E4(),t=/^\s+/;function r(n){return n&&n.slice(0,e(n)+1).replace(t,"")}return kp=r,kp}var Ip,h_;function uC(){if(h_)return Ip;h_=1;var e=cC(),t=e.Symbol;return Ip=t,Ip}var Np,f_;function I4(){if(f_)return Np;f_=1;var e=uC(),t=Object.prototype,r=t.hasOwnProperty,n=t.toString,s=e?e.toStringTag:void 0;function i(a){var l=r.call(a,s),c=a[s];try{a[s]=void 0;var u=!0}catch{}var d=n.call(a);return u&&(l?a[s]=c:delete a[s]),d}return Np=i,Np}var Rp,p_;function N4(){if(p_)return Rp;p_=1;var e=Object.prototype,t=e.toString;function r(n){return t.call(n)}return Rp=r,Rp}var jp,m_;function R4(){if(m_)return jp;m_=1;var e=uC(),t=I4(),r=N4(),n="[object Null]",s="[object Undefined]",i=e?e.toStringTag:void 0;function a(l){return l==null?l===void 0?s:n:i&&i in Object(l)?t(l):r(l)}return jp=a,jp}var Ap,g_;function j4(){if(g_)return Ap;g_=1;function e(t){return t!=null&&typeof t=="object"}return Ap=e,Ap}var Tp,v_;function A4(){if(v_)return Tp;v_=1;var e=R4(),t=j4(),r="[object Symbol]";function n(s){return typeof s=="symbol"||t(s)&&e(s)==r}return Tp=n,Tp}var Dp,x_;function T4(){if(x_)return Dp;x_=1;var e=k4(),t=lC(),r=A4(),n=NaN,s=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,a=/^0o[0-7]+$/i,l=parseInt;function c(u){if(typeof u=="number")return u;if(r(u))return n;if(t(u)){var d=typeof u.valueOf=="function"?u.valueOf():u;u=t(d)?d+"":d}if(typeof u!="string")return u===0?u:+u;u=e(u);var h=i.test(u);return h||a.test(u)?l(u.slice(2),h?2:8):s.test(u)?n:+u}return Dp=c,Dp}var Pp,b_;function D4(){if(b_)return Pp;b_=1;var e=lC(),t=C4(),r=T4(),n="Expected a function",s=Math.max,i=Math.min;function a(l,c,u){var d,h,f,m,g,v,x=0,b=!1,_=!1,C=!0;if(typeof l!="function")throw new TypeError(n);c=r(c)||0,e(u)&&(b=!!u.leading,_="maxWait"in u,f=_?s(r(u.maxWait)||0,c):f,C="trailing"in u?!!u.trailing:C);function S(I){var T=d,A=h;return d=h=void 0,x=I,m=l.apply(A,T),m}function w(I){return x=I,g=setTimeout(E,c),b?S(I):m}function y(I){var T=I-v,A=I-x,P=c-T;return _?i(P,f-A):P}function N(I){var T=I-v,A=I-x;return v===void 0||T>=c||T<0||_&&A>=f}function E(){var I=t();if(N(I))return k(I);g=setTimeout(E,y(I))}function k(I){return g=void 0,C&&d?S(I):(d=h=void 0,m)}function D(){g!==void 0&&clearTimeout(g),x=0,d=v=h=g=void 0}function j(){return g===void 0?m:k(t())}function R(){var I=t(),T=N(I);if(d=arguments,h=this,v=I,T){if(g===void 0)return w(v);if(_)return clearTimeout(g),g=setTimeout(E,c),S(v)}return g===void 0&&(g=setTimeout(E,c)),m}return R.cancel=D,R.flush=j,R}return Pp=a,Pp}var P4=D4();const L4=nC(P4);function M4(){var e=(typeof global>"u"?"undefined":typeof global)=="object"&&global&&global.Object===Object&&global,t=typeof self=="object"&&self&&self.Object===Object&&self;return e||t}M4()||(global.Date=Date);function dC(e,t){var r,n=aC(e),s=(r=t==null?void 0:t.wait)!==null&&r!==void 0?r:1e3,i=p.useMemo(function(){return L4(function(){for(var a=[],l=0;l<arguments.length;l++)a[l]=arguments[l];return n.current.apply(n,oC([],iC(a),!1))},s,t)},[]);return w4(function(){i.cancel()}),{run:i,cancel:i.cancel,flush:i.flush}}function hC(e,t){var r=iC(p.useState(e),2),n=r[0],s=r[1],i=dC(function(){s(e)},t).run;return p.useEffect(function(){i()},[e]),n}const O4="modulepreload",B4=function(e){return"/"+e},__={},Vr=function(t,r,n){let s=Promise.resolve();if(r&&r.length>0){let a=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));s=a(r.map(u=>{if(u=B4(u),u in __)return;__[u]=!0;const d=u.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":O4,d||(f.as="script"),f.crossOrigin="",f.href=u,c&&f.setAttribute("nonce",c),document.head.appendChild(f),d)return new Promise((m,g)=>{f.addEventListener("load",m),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return s.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};function hu(e={version:"development"}){return typeof __RUNWEAVE_BUILD_INFO__=="object"?__RUNWEAVE_BUILD_INFO__:e}const wh="runtime-version.";function F4(e){return[["number","版本",e.version],["build","构建",e.buildId],["revision","源码提交",e.sourceRevision],["dirty","包含未提交改动",e.sourceDirty===void 0?void 0:e.sourceDirty?"是":"否"],["built-at","构建时间",e.builtAt],["content","产物摘要",e.contentSha256]].flatMap(([r,n,s])=>s?[{id:`${wh}${r}`,label:n,value:s,kind:r==="built-at"?"time":"text",copyable:!0}]:[])}/**
|
|
3
3
|
* react-router v7.13.2
|
|
4
4
|
*
|
|
@@ -487,14 +487,14 @@ If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHid
|
|
|
487
487
|
|
|
488
488
|
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},tB="DialogDescriptionWarning",rB=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Tk(tB).contentName}}.`;return p.useEffect(()=>{var i;const s=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},lx=xk,Dk=_k,cx=wk,ku=Sk,Cl=Ck,Iu=kk,Nu=Nk,Ru=jk;const Qr=lx,Pk=cx,nB=Ru,ux=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"window");return o.jsx(ku,{ref:n,className:Xe("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",e),...t})});ux.displayName=ku.displayName;const dn=p.forwardRef(({className:e,children:t,...r},n)=>{const s=hr(n,"intersection");return o.jsxs(Pk,{children:[o.jsx(ux,{}),o.jsxs(Cl,{ref:s,className:Xe("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",e),...r,children:[t,o.jsxs(Ru,{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:[o.jsx(vo,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});dn.displayName=Cl.displayName;const Mn=({className:e,...t})=>o.jsx("div",{className:Xe("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Mn.displayName="DialogHeader";const ga=({className:e,...t})=>o.jsx("div",{className:Xe("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});ga.displayName="DialogFooter";const Ur=p.forwardRef(({className:e,...t},r)=>o.jsx(Iu,{ref:r,className:Xe("text-lg font-semibold leading-none tracking-tight",e),...t}));Ur.displayName=Iu.displayName;const Zr=p.forwardRef(({className:e,...t},r)=>o.jsx(Nu,{ref:r,className:Xe("text-sm text-muted-foreground",e),...t}));Zr.displayName=Nu.displayName;const dx=p.forwardRef((e,t)=>{const r=hr(t);return o.jsx(Cl,{...e,ref:r})});dx.displayName="DialogSurface";const Lk=p.createContext(null),Mk=p.createContext(!0),Ok=p.createContext(null);function ju(){return p.useContext(Ok)}function sB(){return p.useContext(Mk)}function iB({children:e}){const t=Gt(),r=p.useRef(!1),n=p.useRef(!1),[s,i]=p.useState(null),a=W((g,v)=>i({action:g,label:v})),l=W(g=>{r.current=!0,((s==null?void 0:s.action)??g)()});p.useEffect(()=>{r.current=!1,i(null)},[t.pathname]);const[c,u]=p.useState({}),d=W((g,v)=>u(x=>{const b={...x};return v?b[g]=v:delete b[g],b})),h=Object.values(c).some(g=>g.busy),f=Object.values(c).some(g=>g.dirty),m=mP(({currentLocation:g,nextLocation:v})=>{const x=Bo(g.pathname);return n.current=x&&!Bo(v.pathname)&&!r.current,n.current||x&&(h||f)&&(g.pathname!==v.pathname||g.search!==v.search)});return p.useEffect(()=>{m.state==="blocked"&&n.current&&m.reset()},[m]),p.useEffect(()=>{if(!Bo(t.pathname)||!f&&!h)return;const g=v=>{v.preventDefault(),v.returnValue=""};return window.addEventListener("beforeunload",g),()=>window.removeEventListener("beforeunload",g)},[h,f,t.pathname]),o.jsxs(Lk.Provider,{value:d,children:[o.jsx(Mk.Provider,{value:!f&&!h,children:o.jsx(Ok.Provider,{value:{active:Bo(t.pathname),preparedLabel:(s==null?void 0:s.label)??null,prepare:a,exit:l},children:e})}),o.jsx(Qr,{open:m.state==="blocked"&&!n.current,onOpenChange:g=>{!g&&m.state==="blocked"&&(r.current=!1,m.reset())},children:o.jsxs(dn,{children:[o.jsxs(Mn,{children:[o.jsx(Ur,{children:h?"正在处理":f?"放弃未保存的修改?":"离开设置?"}),o.jsx(Zr,{children:h?"操作完成后再离开,避免混淆保存目标。":f?"离开后将恢复已保存的配置。":"操作已完成,可以继续离开。"})]}),o.jsxs(ga,{children:[o.jsx(Z,{variant:"ghost",onClick:()=>{m.state==="blocked"&&(r.current=!1,m.reset())},children:"继续编辑"}),!h&&o.jsx(Z,{onClick:()=>{m.state==="blocked"&&m.proceed()},children:"放弃修改并离开"})]})]})})]})}function va(e,t=!1){const r=p.useContext(Lk),n=p.useId();p.useEffect(()=>(r==null||r(n,{dirty:e,busy:t}),()=>r==null?void 0:r(n,null)),[t,e,n,r])}const L0=[{path:"/activity",title:"Activity",icon:cs},{path:"/evolution",title:"Evolution",icon:Ef},{path:"/system-monitor",title:"System Monitor",icon:cs},{path:"/dev-resources",title:"开发资源",icon:wE},{path:"/scheduled-tasks",title:"定时任务",icon:wl},{path:"/prototypes",title:"原型库",icon:Vv}],M0=[{id:"appearance",title:"外观",group:"本台应用",scope:"local",icon:CE},{id:"notifications",title:"桌面通知",group:"本台应用",scope:"local",icon:wL},{id:"shortcuts",title:"快捷键",group:"本台应用",scope:"local",icon:dM},{id:"connections",title:"连接管理",group:"连接与服务",scope:"local",icon:gM},{id:"suiji",title:"随记账户",group:"连接与服务",scope:"account",icon:CO},{id:"access",title:"登录与手机接入",group:"所选电脑",scope:"computer",icon:xE},{id:"monitoring",title:"资源监控与提醒",group:"所选电脑",scope:"computer",icon:cs},{id:"advanced",title:"高级配置",group:"所选电脑",scope:"computer",icon:fO},{id:"status",title:"电脑状态",group:"状态与诊断",scope:"computer",icon:cs},{id:"desktop",title:"本台桌面诊断",group:"状态与诊断",scope:"local",icon:Cf}];function oB(e){return M0.find(t=>t.id===e)??M0[0]}async function Bk(e,t,r){const n=(r==null?void 0:r.clientType)??"web";return me(e,"/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json",...n==="electron"?{"x-auth-client":"electron",...r!=null&&r.connectionId?{"x-connection-id":r.connectionId}:{}}:{}},body:JSON.stringify(t),...n==="web"?{credentials:"include"}:{}})}async function Oy(e,t){return t.clientType==="web"?me(e,"/api/auth/refresh",{method:"POST",credentials:"include"}):me(e,"/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json","x-auth-client":"electron"},body:JSON.stringify({refreshToken:t.refreshToken})})}async function aB(e,t){return me(e,"/api/auth/verify",{headers:{Authorization:`Bearer ${t}`}})}async function lB(e,t,r){return Vs(e,"/api/auth/password",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)})}const cB=60*1e3,Ah=1440*60*1e3,uB=Ah/1e3;function By(e){$v();const t=ht.getItem(e);if(!t)return null;if(!t.trim().startsWith("{"))return{accessToken:t,accessExpiresAt:Date.now()+Ah,sessionId:"legacy-session"};try{const r=JSON.parse(t);return typeof r.accessToken!="string"||typeof r.accessExpiresAt!="number"||typeof r.sessionId!="string"?null:{accessToken:r.accessToken,accessExpiresAt:r.accessExpiresAt,refreshToken:typeof r.refreshToken=="string"?r.refreshToken:void 0,sessionId:r.sessionId}}catch{return null}}function em(e,t){ht.setItem(e,JSON.stringify(t))}function tm(e){return{accessToken:e.accessToken,accessExpiresAt:Date.now()+e.expiresIn*1e3,refreshToken:e.refreshToken,sessionId:e.sessionId}}function O0(e){return!!(e&&e.accessExpiresAt>Date.now())}function Fy(e,t,r){return!e||!r?"unauthenticated":O0(r)?"authenticated":t&&!r.refreshToken?"unauthenticated":"checking"}function $y(e){const t=yl(e);return!((t==null?void 0:t.accessToken)??(t==null?void 0:t.token))||typeof(t.accessExpiresAt??Date.now()+Ah)!="number"||!(t.sessionId??"legacy-session")?null:{accessToken:t.accessToken??t.token??"",accessExpiresAt:t.accessExpiresAt??Date.now()+Ah,refreshToken:t.refreshToken,sessionId:t.sessionId??"legacy-session"}}function hx({apiBase:e,isElectron:t,connectionId:r,webStorageKey:n}){$v();const s=t?`electron:${r??""}`:`web:${n}`,i=p.useMemo(()=>t?$y(r):By(n),[r,t,n]),[a,l]=p.useState(i),[c,u]=p.useState(s),[d,h]=p.useState(()=>Fy(e,t,i)),[f,m]=p.useState(0),g=p.useRef(d),v=c===s,x=v?a:i,b=v?d:Fy(e,t,i);p.useEffect(()=>{const y=N=>{const E=t?Bv:n;N.key===E&&m(k=>k+1)};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[t,n]),p.useEffect(()=>{g.current=b},[b]);const _=W(()=>t?$y(r):By(n)),C=W(()=>{t?r&&pc(r):ht.removeItem(n),l(null),u(s),h("unauthenticated"),g.current="unauthenticated",m(y=>y+1)}),S=W(y=>{const N=tm(y);t?r&&zp(r,N):em(n,N),l(N),u(s),h("authenticated"),g.current="authenticated",m(E=>E+1)}),w=W(y=>{S({accessToken:y,expiresIn:uB,sessionId:(x==null?void 0:x.sessionId)??"legacy-session",refreshToken:x==null?void 0:x.refreshToken})});return p.useEffect(()=>{let y=!1;return(async()=>{const E=_();if(!y){if(l(E),u(s),!e||!E){h("unauthenticated");return}if(O0(E)){l(E),h("authenticated"),t&&aB(e,E.accessToken).catch(k=>{y||k instanceof De&&k.status===401&&(r&&pc(r),l(null),u(s),h("unauthenticated"))});return}if(t&&!E.refreshToken){h("unauthenticated");return}h("checking");try{const k=await Oy(e,t?{clientType:"electron",refreshToken:E.refreshToken??""}:{clientType:"web"});if(y)return;const D=tm(k);t?r&&zp(r,D):em(n,D),l(D),u(s),h("authenticated")}catch(k){if(y)return;if(k instanceof De&&k.status===401&&(t&&r&&pc(r),t||ht.removeItem(n)),t&&!(k instanceof De&&k.status===401)){l(E),u(s),h("authenticated");return}l(null),u(s),h("unauthenticated")}}})(),()=>{y=!0}},[e,s,r,t,_,f,n]),p.useEffect(()=>{const y=()=>{if(!e||document.visibilityState==="hidden"||g.current==="checking")return;const N=_();!N||O0(N)||(g.current="checking",h("checking"),m(E=>E+1))};return document.addEventListener("visibilitychange",y),window.addEventListener("focus",y),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("focus",y)}},[e,_]),p.useEffect(()=>{if(!e||!x||b!=="authenticated"||t&&!x.refreshToken)return;let y=!1;const N=Math.max(x.accessExpiresAt-Date.now()-cB,0),E=window.setTimeout(()=>{Oy(e,t?{clientType:"electron",refreshToken:x.refreshToken??""}:{clientType:"web"}).then(k=>{if(y)return;const D=tm(k);t?r&&zp(r,D):em(n,D),l(D),u(s),h("authenticated")}).catch(k=>{y||(k instanceof De&&k.status===401&&(t&&r&&pc(r),t||ht.removeItem(n)),!(t&&!(k instanceof De&&k.status===401))&&(l(null),u(s),h("unauthenticated")))})},N);return()=>{y=!0,window.clearTimeout(E)}},[e,s,r,x,b,t,n]),{token:(x==null?void 0:x.accessToken)??null,sessionId:(x==null?void 0:x.sessionId)??null,status:b,setSession:S,clearSession:C,setToken:w,clearToken:C}}const fx=p.createContext(null);function Fk(){const e=p.useContext(fx);if(!e)throw new Error("Settings target required");return e}function dB({connection:e,children:t}){const r=hx({apiBase:e.url,connectionId:e.id,isElectron:!0,webStorageKey:"viewer.auth.token"});return o.jsx(fx.Provider,{value:{connection:e,connectionId:e.id,apiBase:e.url,generation:e.generation,auth:r},children:t})}function hB({connection:e,activeConnection:t,workspaceAuth:r,webApiBase:n,children:s}){var i,a;return(i=window.electronAPI)!=null&&i.isElectron&&e&&e.id!==(t==null?void 0:t.id)?o.jsx(dB,{connection:e,children:s},`${e.id}:${e.url}:${e.generation}`):o.jsx(fx.Provider,{value:{connection:e,connectionId:(e==null?void 0:e.id)??null,apiBase:(a=window.electronAPI)!=null&&a.isElectron?(e==null?void 0:e.url)??"":n,generation:e==null?void 0:e.generation,auth:r},children:s})}const sr=p.forwardRef(({className:e,type:t,...r},n)=>o.jsx("input",{type:t,className:Xe("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",e),ref:n,...r}));sr.displayName="Input";function fB({children:e}){var g;const{connection:t,connectionId:r,apiBase:n,auth:s}=Fk(),[i,a]=p.useState(""),[l,c]=p.useState(""),[u,d]=p.useState(!1),[h,f]=p.useState("");va(!!l,u);const m=W(async()=>{var v;if(!u){d(!0),f("");try{s.setSession(await Bk(n,{username:i,password:l},{clientType:(v=window.electronAPI)!=null&&v.isElectron?"electron":"web",connectionId:r??void 0})),c("")}catch(x){f(x instanceof Error?x.message:"登录失败")}finally{d(!1)}}});return(g=window.electronAPI)!=null&&g.isElectron&&(!t||t.available===!1)?o.jsx("p",{role:"alert",children:"所选电脑不可用,请在连接管理中恢复连接。"}):s.status==="checking"?o.jsx("p",{role:"status",children:"正在核对登录状态…"}):s.token&&s.status==="authenticated"?e:o.jsxs("form",{className:"max-w-md space-y-4 rounded-xl border p-5",onSubmit:v=>{v.preventDefault(),m()},children:[o.jsxs("h2",{className:"font-medium",children:["登录",(t==null?void 0:t.name)??"当前电脑"]}),o.jsxs("label",{className:"grid gap-2 text-sm",children:["账号",o.jsx(sr,{autoComplete:"username",value:i,disabled:u,onChange:v=>a(v.target.value)})]}),o.jsxs("label",{className:"grid gap-2 text-sm",children:["密码",o.jsx(sr,{type:"password",autoComplete:"current-password",value:l,disabled:u,onChange:v=>c(v.target.value)})]}),h&&o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:h}),o.jsx(Z,{disabled:u,children:u?"登录中…":"登录"})]})}const pB=["healthy","recovering","unhealthy","blocked","checking","unconfigured","disabled","unsupported"],mB=["node","terminal","feishu","app-server","workspace-services","desktop","background-tasks","research-mcp"];function $k(e,t){return t==="unhealthy"?e==="feishu"?"warning":"error":["unconfigured","unsupported","recovering","blocked"].includes(t)?"warning":"none"}function gB(e,t){const r=new Map(t.map(s=>[s.id,s])),n=e.map(s=>s.state==="blocked"&&s.dependsOn.some(i=>{const a=r.get(i);return a!==void 0&&(a.state==="unhealthy"||a.state==="blocked")})?"none":$k(s.capabilityId,s.state));return n.includes("error")?"error":n.includes("warning")?"warning":"none"}const vB=mB,zy={unsupported:0,disabled:1,unconfigured:2,healthy:3,blocked:4,checking:5,recovering:6,unhealthy:7};function xB(e){return pB.includes(e)}function px(e){let t="unsupported";for(const r of e){const n=xB(r)?r:"unsupported";zy[n]>zy[t]&&(t=n)}return t}function bB(e){return e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9._:-]+/gu,"-").replace(/-{2,}/gu,"-").replace(/^[-.:]+|[-.:]+$/gu,"").slice(0,96)||"unknown"}function zk(e,t){return{...e,target:{kind:"node",nodeId:t},source:{...e.source},items:e.items.map(Hk)}}function _B(e){const t=e.map(Hk),r=new Map(t.map(n=>[n.id,n]));for(let n=0;n<t.length;n+=1){let s=!1;for(const i of t){if(i.state==="disabled"||i.dependsOn.length===0)continue;i.dependsOn.some(l=>{const c=r.get(l);return!c||c.state==="unhealthy"||c.state==="blocked"})&&i.state!=="blocked"&&(i.state="blocked",i.summary="上游依赖不可用,暂时无法判断",i.recovery=null,s=!0)}if(!s)break}return t}function Uk(e){const t=_B(e.flatMap(r=>r.items.flatMap(n=>n.state!=="healthy"||!n.facts.some(s=>s.id==="runtime-installation.state"&&s.value==="restart-required")?[n]:[n,{...n,id:`${n.id}.installation`,label:`${n.label} · 安装生效`,state:"blocked",summary:"已安装产物与运行产物不同,需要通过该服务的更新或重启入口使其生效",dependsOn:[n.id],recovery:null,facts:[]}])));return vB.flatMap(r=>{const n=t.filter(i=>i.capabilityId===r);if(n.length===0)return[];const s=px(n.map(i=>i.state));return[{capabilityId:r,state:s,unhealthy:s==="unhealthy",attention:gB(n,t),items:n}]})}function Hk(e){return{...e,dependsOn:[...e.dependsOn],recovery:e.recovery?{...e.recovery}:null,facts:e.facts.map(t=>({...t})),navigation:e.navigation?{...e.navigation}:null}}const Wk=p.createContext(null);function yB({children:e}){const[t,r]=p.useState(null);return o.jsxs(Wk.Provider,{value:t,children:[e,o.jsx("div",{ref:r,"data-status-notice-viewport":"",className:"pointer-events-none fixed bottom-4 left-4 z-[70] flex max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] flex-col gap-3 overflow-y-auto"})]})}function eo({children:e,className:t,kind:r,onDismiss:n,noticeKey:s,duration:i=8e3,role:a="status"}){const l=p.useContext(Wk),c=hr(),u=W(n);return p.useEffect(()=>{if(!l||i<=0)return;const d=window.setTimeout(u,i);return()=>window.clearTimeout(d)},[l,i,s,u]),l?Yr.createPortal(o.jsxs("div",{ref:c,role:a,"aria-live":a==="alert"?"assertive":"polite","data-status-notice":r,className:`pointer-events-auto relative shrink-0 break-words ${t} pr-10`,children:[e,o.jsx("button",{type:"button","aria-label":"关闭通知",onClick:u,className:"absolute right-1 top-1 flex h-8 w-8 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",children:o.jsx(vo,{className:"h-4 w-4"})})]}),l):null}const qk=p.createContext(null);function Au(){const e=p.useContext(qk);if(!e)throw new Error("RuntimeStatusProvider is missing");return e}function Kk(e,t){const{setFrontendItem:r}=Au();p.useEffect(()=>(r(e,t),()=>r(null,t)),[t,e,r])}const Uy={node:"节点连接",terminal:"Terminal",feishu:"飞书接入","app-server":"App Server","workspace-services":"Workspace Services",desktop:"Desktop","background-tasks":"后台任务","research-mcp":"调查 MCP"};function wB(){const{nodes:e,unhealthyCapabilityIds:t,setPanelOpen:r}=Au(),n=p.useRef(new Set),[s,i]=p.useState(null);return p.useEffect(()=>{if(e.length===0)return;const a=new Set(t),l=t.find(u=>!n.current.has(u));if(n.current=a,!l)return;(async()=>{var u,d;if(document.visibilityState==="visible"&&document.hasFocus())return!1;try{return await((d=(u=window.electronAPI)==null?void 0:u.showRuntimeStatusNotification)==null?void 0:d.call(u,{capabilityId:l,title:`${Uy[l]}运行异常`,body:"请打开运行状态查看异常原因和受影响的功能。"}))??!1}catch{return!1}})().then(u=>{u||i(l)})},[e.length,t]),!s||!t.includes(s)?null:o.jsxs(eo,{kind:"runtime",noticeKey:s,onDismiss:()=>i(null),className:"flex items-start gap-3 rounded-xl border border-red-500/40 bg-background p-4 text-foreground shadow-2xl",children:[o.jsx(pa,{className:"mt-0.5 h-5 w-5 shrink-0 text-red-500"}),o.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>{r(!0),i(null)},children:[o.jsxs("span",{className:"block text-sm font-semibold",children:[Uy[s],"运行异常"]}),o.jsx("span",{className:"mt-1 block text-xs text-muted-foreground",children:"点击查看异常原因和受影响的功能。"})]})]})}async function mx(e){var s,i,a;const t=(s=window.electronAPI)==null?void 0:s.copyRuntimeStatusText;if(((i=window.electronAPI)==null?void 0:i.isElectron)===!0&&t)return t(e);try{if((a=navigator.clipboard)!=null&&a.writeText)return await navigator.clipboard.writeText(e),!0}catch{}const r=document.createElement("textarea");r.value=e,r.setAttribute("readonly",""),r.style.position="fixed",r.style.opacity="0",document.body.append(r),r.select();const n=document.execCommand("copy");return r.remove(),n}const SB=[["backend.process","Backend"],["backend.cli-version","CLI(节点 rw)"],["app-server.process","App Server"],["electron.process","Desktop"],["feishu.bridge-lease","飞书 Bridge"],["research-mcp.process","调查 MCP"],["snapshot-host.process","快照分享 Host"],["push-gateway.process","推送网关"],["suiji-server.process","随记服务"],["remote-desktop-host.process","RemoteDesk Host"]];function Vk({label:e,facts:t,historical:r=!1}){const n=W(async()=>{await mx(`${e}
|
|
489
489
|
${t.map(a=>`${a.label}: ${a.value}`).join(`
|
|
490
|
-
`)}`)}),s=t.find(a=>a.id===`${wh}number`),i=t.find(a=>a.id===`${wh}build`);return o.jsxs("div",{className:"min-w-0 border-t border-border/50 py-3 first:border-0","data-runtime-version":e,children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("span",{className:"text-sm font-medium",children:e}),o.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[o.jsx("span",{className:"break-all text-right font-mono text-xs",children:(s==null?void 0:s.value)??"未上报"}),t.length>0?o.jsx("button",{type:"button","aria-label":`复制 ${e} 版本`,className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted",onClick:()=>void n(),children:o.jsx(go,{className:"h-3 w-3"})}):null]})]}),i?o.jsx("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:i.value}):null,r?o.jsx("p",{className:"mt-1 text-xs text-amber-600",children:"最近上报,当前状态无法确认"}):null,t.length>1?o.jsxs("details",{className:"mt-1 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer",children:"构建详情"}),o.jsx("dl",{className:"mt-2 space-y-1",children:t.filter(a=>a!==s&&a!==i).map(a=>o.jsxs("div",{children:[o.jsxs("dt",{className:"inline",children:[a.label,":"]}),o.jsx("dd",{className:"inline break-all font-mono",children:a.value})]},a.id))})]}):null]})}function CB({items:e}){return o.jsxs("section",{className:"rounded-xl border border-border/70 px-4 py-3","aria-label":"组件版本",children:[o.jsx("h3",{className:"text-sm font-medium",children:"组件版本"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"服务上报的运行版本;CLI 为此节点可调用的 rw。"}),o.jsx("div",{className:"mt-2",children:SB.filter(([t])=>t!=="electron.process"||e.some(r=>r.id===t)).map(([t,r])=>{const n=e.find(s=>s.id===t);return o.jsx(Vk,{label:r,facts:(n==null?void 0:n.facts.filter(s=>s.id.startsWith(wh)))??[],historical:!!n&&["blocked","unhealthy","disabled"].includes(n.state)},t)})})]})}const EB=F4(hu());function kB(){return o.jsx("section",{className:"rounded-xl border border-border/70 px-4","aria-label":"当前页面版本",children:o.jsx(Vk,{label:"Web(当前页面)",facts:EB})})}const IB=[{path:"screenRecording.analysis.enabled",type:"boolean",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"启用本机屏幕事项分析,默认关闭",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.deviceID",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"绑定 ScreenJournal 设备身份",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.effectiveFrom",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"屏幕分析生效日期时间 ISO8601",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.model",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"已验证图片能力的 Codex 模型",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.effort",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"显式模型推理强度",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"storage.screenAnalysisDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"本实例屏幕分析临时作业目录",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{rule:"实例数据目录下 screen-analysis"},migrationSources:["new-field:no-legacy-source"]},{path:"backend.taskSupervision.enabled",type:"boolean",domain:"backend.taskSupervision",sensitive:!1,remote:!1,apply:"reload",description:"启用当前 Codex 终端长任务监控(仍需逐任务手动开启)",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["new-field:no-legacy-source"]},{modelSelection:{provider:"codex",effortPath:"backend.taskSupervision.effort",label:"长任务监控模型",allowDefaultEffort:!1},path:"backend.taskSupervision.model",type:"string",domain:"backend.taskSupervision",sensitive:!1,remote:!0,apply:"reload",description:"长任务监控模型,供目标整理和最终判断使用",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:"gpt-6-astra"},migrationSources:["new-field:no-legacy-source"]},{path:"backend.taskSupervision.effort",type:"string",domain:"backend.taskSupervision",sensitive:!1,remote:!0,apply:"reload",description:"长任务监控推理强度:low、medium、high、xhigh、max 或 ultra",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:"high"},migrationSources:["new-field:no-legacy-source"]},{path:"backend.taskSupervision.classificationTimeoutMs",type:"integer",domain:"backend.taskSupervision",sensitive:!1,remote:!1,apply:"reload",description:"三分类最长等待毫秒,需小于原生 Hook 等待预算",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:9e4},migrationSources:["new-field:no-legacy-source"]},{path:"backend.server.port",type:"integer",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"Backend 监听端口",environmentKeys:["PORT","RUNWEAVE_BACKEND_PORT"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{value:5001},migrationSources:["PORT","RUNWEAVE_BACKEND_PORT"]},{path:"backend.server.host",type:"string",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"Backend 监听地址",environmentKeys:["HOST"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{rule:"独立 Backend 默认 127.0.0.1;桌面托管 Backend 默认 0.0.0.0,由启动入口传入;显式配置优先。"},migrationSources:["HOST"]},{path:"backend.server.strictPort",type:"boolean",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"端口占用时拒绝换端口",environmentKeys:["PORT_STRICT"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{rule:"Stable 恒为 true;Dev Session 按分配端口启动且不得占用其他实例。"},migrationSources:["PORT_STRICT"]},{path:"backend.server.frontendOrigin",type:"string",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"前端允许来源",environmentKeys:["FRONTEND_ORIGIN"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时仅允许现有同源、本机和受控桌面来源;不自动允许任意网站。"},migrationSources:["FRONTEND_ORIGIN"]},{path:"backend.auth.username",type:"string",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"登录用户名",environmentKeys:["AUTH_USERNAME"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["backend-auth.json.username"]},{path:"backend.auth.password",type:"string",domain:"backend.auth",sensitive:!0,remote:!1,apply:"restart",description:"登录密码",environmentKeys:["AUTH_PASSWORD"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["backend-auth.json.password"]},{path:"backend.auth.jwtSecret",type:"string",domain:"backend.auth",sensitive:!0,remote:!1,apply:"restart",description:"JWT 签名密钥",environmentKeys:["AUTH_JWT_SECRET"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["backend-auth.json.jwtSecret"]},{path:"backend.auth.accessTokenTtlSeconds",type:"number",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"访问凭据有效秒数",environmentKeys:["AUTH_ACCESS_TOKEN_TTL_SECONDS","AUTH_TOKEN_TTL_SECONDS"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:86400},migrationSources:["AUTH_ACCESS_TOKEN_TTL_SECONDS","AUTH_TOKEN_TTL_SECONDS"]},{path:"backend.auth.refreshTokenTtlSeconds",type:"number",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"刷新凭据有效秒数",environmentKeys:["AUTH_REFRESH_TOKEN_TTL_SECONDS"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:2592e3},migrationSources:["AUTH_REFRESH_TOKEN_TTL_SECONDS"]},{path:"backend.auth.refreshCookieName",type:"string",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"刷新 Cookie 名称",environmentKeys:["AUTH_REFRESH_COOKIE_NAME"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:"viewer_refresh"},migrationSources:["AUTH_REFRESH_COOKIE_NAME"]},{path:"backend.auth.secureCookies",type:"boolean",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"Cookie 安全标志",environmentKeys:["AUTH_COOKIE_SECURE"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["AUTH_COOKIE_SECURE"]},{path:"backend.tunnelAuth.scope",type:"string",domain:"backend.tunnelAuth",sensitive:!1,remote:!1,apply:"restart",description:"隧道认证作用域",environmentKeys:["RUNWEAVE_TUNNEL_AUTH_SCOPE"],owner:"backend/server",scope:"instance",storage:"settings.yaml",default:{value:"forwarded"},migrationSources:["RUNWEAVE_TUNNEL_AUTH_SCOPE"]},{path:"backend.tunnelAuth.cookieName",type:"string",domain:"backend.tunnelAuth",sensitive:!1,remote:!1,apply:"restart",description:"隧道 Cookie 名称",environmentKeys:["RUNWEAVE_TUNNEL_COOKIE_NAME"],owner:"backend/server",scope:"instance",storage:"settings.yaml",default:{value:"runweave_tunnel"},migrationSources:["RUNWEAVE_TUNNEL_COOKIE_NAME"]},{path:"backend.tunnelAuth.token",type:"string",domain:"backend.tunnelAuth",sensitive:!0,remote:!1,apply:"restart",description:"隧道认证凭据",environmentKeys:["RUNWEAVE_TUNNEL_TOKEN"],owner:"backend/server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_TUNNEL_TOKEN"]},{path:"services.snapshotPublisher.url",type:"string",domain:"services.snapshotPublisher",sensitive:!1,remote:!0,apply:"reload",description:"分享发布服务地址",environmentKeys:["RUNWEAVE_SNAPSHOT_PUBLISH_URL"],owner:"backend/terminal/snapshot-share",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_PUBLISH_URL"]},{path:"services.snapshotPublisher.token",type:"string",domain:"services.snapshotPublisher",sensitive:!0,remote:!0,apply:"reload",description:"分享发布凭据",environmentKeys:["RUNWEAVE_SNAPSHOT_PUBLISH_TOKEN"],owner:"backend/terminal/snapshot-share",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_PUBLISH_TOKEN"]},{path:"services.snapshotHost.directory",type:"string",domain:"services.snapshotHost",sensitive:!1,remote:!1,apply:"restart",description:"独立分享 Host 存储目录",environmentKeys:["RUNWEAVE_SNAPSHOT_HOST_DIR"],owner:"backend/snapshot-share-host",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_HOST_DIR"]},{path:"services.snapshotHost.port",type:"integer",domain:"services.snapshotHost",sensitive:!1,remote:!1,apply:"restart",description:"独立分享 Host 监听端口",environmentKeys:["RUNWEAVE_SNAPSHOT_HOST_PORT"],owner:"backend/snapshot-share-host",scope:"instance",storage:"settings.yaml",default:{value:8093},migrationSources:["RUNWEAVE_SNAPSHOT_HOST_PORT"]},{path:"services.snapshotHost.uploadToken",type:"string",domain:"services.snapshotHost",sensitive:!0,remote:!1,apply:"restart",description:"独立分享 Host 上传凭据",environmentKeys:["RUNWEAVE_SNAPSHOT_UPLOAD_TOKEN"],owner:"backend/snapshot-share-host",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_UPLOAD_TOKEN"]},{path:"services.pushSender.gatewayURL",type:"string",domain:"services.pushSender",sensitive:!1,remote:!0,apply:"reload",description:"推送网关地址",environmentKeys:["RUNWEAVE_PUSH_GATEWAY_URL"],owner:"backend/device-monitor",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["device-monitor/push.json.gatewayURL"]},{path:"services.pushSender.senderToken",type:"string",domain:"services.pushSender",sensitive:!0,remote:!0,apply:"reload",description:"推送发送凭据",environmentKeys:["RUNWEAVE_PUSH_SENDER_TOKEN"],owner:"backend/device-monitor",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["device-monitor/push.json.senderToken"]},{path:"services.pushGateway.keyId",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"APNs key ID",environmentKeys:["APNS_KEY_ID"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["APNS_KEY_ID"]},{path:"services.pushGateway.teamId",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"APNs team ID",environmentKeys:["APNS_TEAM_ID"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["APNS_TEAM_ID"]},{path:"services.pushGateway.privateKeyFile",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"APNs 私钥文件引用",environmentKeys:["APNS_PRIVATE_KEY_FILE"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["APNS_PRIVATE_KEY_FILE"]},{path:"services.pushGateway.directory",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"独立推送网关数据目录",environmentKeys:["PUSH_GATEWAY_DATA_DIR"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["PUSH_GATEWAY_DATA_DIR"]},{path:"services.pushGateway.port",type:"integer",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"独立推送网关端口",environmentKeys:["PUSH_GATEWAY_PORT"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:8092},migrationSources:["PUSH_GATEWAY_PORT"]},{path:"services.pushGateway.bind",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"独立推送网关监听地址",environmentKeys:["PUSH_GATEWAY_BIND"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["PUSH_GATEWAY_BIND"]},{path:"services.pushGateway.adminToken",type:"string",domain:"services.pushGateway",sensitive:!0,remote:!1,apply:"restart",description:"独立推送网关管理凭据",environmentKeys:["PUSH_GATEWAY_ADMIN_TOKEN"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["PUSH_GATEWAY_ADMIN_TOKEN"]},{path:"services.feishu.role",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"飞书运行角色",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:"standalone"},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.host",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"集中 Bridge 监听地址",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.port",type:"integer",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"集中 Bridge 监听端口",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.backends.<backendId>.token",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"节点独立接入凭据",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.backends.<backendId>.displayName",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"通知中的机器显示名(可选,不参与路由)",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.node.url",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"集中 Bridge HTTPS origin",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.node.caCertificate",type:"string",domain:"services.feishu",sensitive:!1,remote:!1,apply:"restart",description:"仅用于飞书 WSS 的可选 PEM CA 公共证书,仍校验主机名及有效期",environmentKeys:[],owner:"backend/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.node.token",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"本节点接入凭据",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.appId",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"飞书应用 ID",environmentKeys:["FEISHU_APP_ID"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_APP_ID"]},{path:"services.feishu.appSecret",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"飞书应用密钥",environmentKeys:["FEISHU_APP_SECRET"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_APP_SECRET"]},{path:"services.feishu.targetChatId",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"飞书目标群聊",environmentKeys:["FEISHU_TARGET_CHAT_ID"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_TARGET_CHAT_ID"]},{path:"services.feishu.allowedOpenIds",type:"array<string>",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"允许调用的用户 ID",environmentKeys:["FEISHU_ALLOWED_OPEN_IDS"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["FEISHU_ALLOWED_OPEN_IDS"]},{path:"services.feishu.notifyOpenIds",type:"array<string>",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"接收通知的用户 ID",environmentKeys:["FEISHU_NOTIFY_OPEN_IDS"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["FEISHU_NOTIFY_OPEN_IDS"]},{path:"services.feishu.legacyWebhook.url",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"旧通知 hook webhook;迁移前核对使用者",environmentKeys:["FEISHU_WEBHOOK_URL"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_WEBHOOK_URL"]},{path:"services.feishu.legacyWebhook.secret",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"旧通知 hook webhook 签名密钥",environmentKeys:["FEISHU_WEBHOOK_SECRET"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_WEBHOOK_SECRET"]},{path:"services.feishu.legacyWebhook.transport",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"旧通知 hook 发送方式",environmentKeys:["FEISHU_NOTIFY_TRANSPORT"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_NOTIFY_TRANSPORT"]},{path:"agents.codex.binary",type:"string",domain:"agents.codex",sensitive:!1,remote:!1,apply:"restart",description:"Codex 可执行文件",environmentKeys:["CODEX_BIN","RUNWEAVE_CODEX_BIN"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时通过 PATH / 平台安装位置查找 codex;显式配置指向同一可执行程序。"},migrationSources:["CODEX_BIN","RUNWEAVE_CODEX_BIN"]},{path:"agents.traex.binary",type:"string",domain:"agents.traex",sensitive:!1,remote:!1,apply:"restart",description:"Trae 可执行文件;多个入口统一",environmentKeys:["TRAEX_BIN","RUNWEAVE_TRAE_BIN"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时通过 PATH / 平台安装位置查找 traex;显式配置指向同一可执行程序。"},migrationSources:["TRAEX_BIN","RUNWEAVE_TRAE_BIN"]},{path:"agents.claude.binary",type:"string",domain:"agents.claude",sensitive:!1,remote:!1,apply:"restart",description:"Claude Code 可执行文件;仅限程序名或绝对路径,不接受命令参数",environmentKeys:[],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"使用当前 Backend 的 PATH 查找 claude;不改变现有默认 provider。"},migrationSources:["new-field:no-legacy-source"]},{path:"agents.claude.configDirectory",type:"string",domain:"agents.claude",sensitive:!1,remote:!1,apply:"restart",description:"Claude 原生配置目录的外部引用;会话根为其 projects 子目录,不复制凭据",environmentKeys:["CLAUDE_CONFIG_DIR"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"显式实例目录优先,否则引用外部 CLAUDE_CONFIG_DIR 或操作系统用户目录下 .claude;必须为绝对路径。"},migrationSources:["CLAUDE_CONFIG_DIR"]},{path:"agents.companion.binary",type:"string",domain:"agents.companion",sensitive:!1,remote:!1,apply:"restart",description:"伴随窗口 Agent 可执行文件",environmentKeys:["RUNWEAVE_COMPANION_AGENT_EXECUTABLE"],owner:"electron/companion",scope:"instance",storage:"settings.yaml",default:{rule:"使用已安装 Codex App 自带执行入口;显式值必须可执行。"},migrationSources:["RUNWEAVE_COMPANION_AGENT_EXECUTABLE"]},{path:"agents.codex.sessionsDirectory",type:"string",domain:"agents.codex",sensitive:!1,remote:!1,apply:"restart",description:"外部 Codex 会话目录引用",environmentKeys:["RUNWEAVE_CODEX_SESSIONS_DIR"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"外部工具拥有的 CODEX_HOME/sessions 或操作系统用户目录下 .codex/sessions,仅引用。"},migrationSources:["RUNWEAVE_CODEX_SESSIONS_DIR"]},{path:"agents.traex.sessionsDirectory",type:"string",domain:"agents.traex",sensitive:!1,remote:!1,apply:"restart",description:"外部 Trae 会话目录引用",environmentKeys:["RUNWEAVE_TRAE_SESSIONS_DIR"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"操作系统用户目录下 .trae/cli/sessions,仅引用。"},migrationSources:["RUNWEAVE_TRAE_SESSIONS_DIR"]},{path:"terminal.defaultShell.command",type:"string",domain:"terminal.defaultShell",sensitive:!1,remote:!1,apply:"reload",description:"当前电脑新终端的默认可执行文件;缺省使用系统 Shell,启动不可用时回退系统默认",environmentKeys:[],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{rule:"系统账户登录 Shell;Windows 使用 ComSpec;不可用时采用平台兜底"},migrationSources:["new-field:no-legacy-source"]},{path:"terminal.defaultShell.args",type:"array<string>",domain:"terminal.defaultShell",sensitive:!1,remote:!1,apply:"reload",description:"默认 Shell 的启动参数;空数组明确不加参数,缺省保留 bash/zsh 的 -l 行为",environmentKeys:[],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{rule:"根据所选程序解析;bash/zsh 为 [-l],其他为空数组"},migrationSources:["new-field:no-legacy-source"]},{path:"terminal.tmux.enabled",type:"boolean",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"tmux 持久终端开关",environmentKeys:["TERMINAL_TMUX_ENABLED"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["TERMINAL_TMUX_ENABLED"]},{path:"terminal.tmux.binary",type:"string",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"tmux 可执行文件",environmentKeys:["TMUX_BINARY"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:"tmux"},migrationSources:["TMUX_BINARY"]},{path:"terminal.tmux.shutdownPolicy",type:"string",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"退出时 tmux 保留策略",environmentKeys:["TERMINAL_TMUX_SHUTDOWN_POLICY"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{rule:"Stable 为 preserve,Dev 为 cleanup。"},migrationSources:["TERMINAL_TMUX_SHUTDOWN_POLICY"]},{path:"terminal.tmux.scanOrphansOnStart",type:"boolean",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"启动时检查孤儿终端",environmentKeys:["TERMINAL_TMUX_SCAN_ORPHANS_ON_START"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["TERMINAL_TMUX_SCAN_ORPHANS_ON_START"]},{path:"terminal.tmux.cleanupOrphans",type:"boolean",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"孤儿终端清理策略",environmentKeys:["TERMINAL_TMUX_CLEANUP_ORPHANS"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["TERMINAL_TMUX_CLEANUP_ORPHANS"]},{path:"scheduledTasks.enabled",type:"boolean",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"定时任务开关",environmentKeys:["RUNWEAVE_SCHEDULED_TASKS_ENABLED"],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["RUNWEAVE_SCHEDULED_TASKS_ENABLED"]},{path:"scheduledTasks.timeoutMs",type:"number",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"任务超时毫秒数",environmentKeys:["RUNWEAVE_SCHEDULED_TASK_TIMEOUT_MS"],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:72e5},migrationSources:["RUNWEAVE_SCHEDULED_TASK_TIMEOUT_MS"]},{path:"scheduledTasks.maxOutputBytes",type:"integer",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"任务输出上限字节数",environmentKeys:["RUNWEAVE_SCHEDULED_TASK_MAX_OUTPUT_BYTES"],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:16777216},migrationSources:["RUNWEAVE_SCHEDULED_TASK_MAX_OUTPUT_BYTES"]},{path:"scheduledTasks.maxConcurrentRuns",type:"integer",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"同时执行的后台任务数",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:4},migrationSources:["new-field:no-legacy-source"]},{modelSelection:{provider:"codex",effortPath:"scheduledTasks.quickInputDefaults.effort",label:"快捷指令后台运行模型",allowDefaultEffort:!0},path:"scheduledTasks.quickInputDefaults.model",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"快捷指令后台运行的 Codex 模型;必须显式选择",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"scheduledTasks.quickInputDefaults.effort",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"快捷指令后台运行的推理强度",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"scheduledTasks.quickInputDefaults.continuationMode",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"新快捷运行自动继续策略:bounded 或 off",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:"bounded"},migrationSources:["new-field:no-legacy-source"]},{path:"scheduledTasks.quickInputDefaults.executionPolicy",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"快捷指令后台运行的执行权限",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:"full-access"},migrationSources:["new-field:no-legacy-source"]},{path:"voice.transcription.language",type:"string",domain:"voice",sensitive:!1,remote:!0,apply:"reload",description:"转写语言",environmentKeys:["RUNWEAVE_VOICE_TRANSCRIPTION_LANGUAGE"],owner:"backend/voice",scope:"instance",storage:"settings.yaml",default:{value:"zh"},migrationSources:["RUNWEAVE_VOICE_TRANSCRIPTION_LANGUAGE"]},{path:"voice.transcription.acceptLanguage",type:"string",domain:"voice",sensitive:!1,remote:!0,apply:"reload",description:"转写请求 Accept-Language",environmentKeys:["RUNWEAVE_VOICE_TRANSCRIPTION_ACCEPT_LANGUAGE"],owner:"backend/voice",scope:"instance",storage:"settings.yaml",default:{value:"zh-CN,zh;q=0.9,en;q=0.8"},migrationSources:["RUNWEAVE_VOICE_TRANSCRIPTION_ACCEPT_LANGUAGE"]},{path:"voice.transcription.prompt",type:"string",domain:"voice",sensitive:!1,remote:!0,apply:"reload",description:"转写提示词",environmentKeys:["RUNWEAVE_VOICE_TRANSCRIPTION_PROMPT"],owner:"backend/voice",scope:"instance",storage:"settings.yaml",default:{value:"请使用简体中文输出转写文本。"},migrationSources:["RUNWEAVE_VOICE_TRANSCRIPTION_PROMPT"]},{path:"knowledge.experience.learning",type:"boolean",domain:"knowledge",sensitive:!1,remote:!1,apply:"restart",description:"经验学习开关",environmentKeys:["RUNWEAVE_EXPERIENCE_LEARNING"],owner:"backend/experience",scope:"instance",storage:"settings.yaml",default:{rule:"Stable 默认启用,Dev 默认关闭;明确配置覆盖默认。"},migrationSources:["RUNWEAVE_EXPERIENCE_LEARNING"]},{path:"storage.browserProfileDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"原 Backend profile 的显式目录",environmentKeys:["BROWSER_PROFILE_DIR"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/backend;已有 Stable 必须显式保留旧路径"},migrationSources:["BROWSER_PROFILE_DIR"]},{path:"storage.authStoreFile",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"认证数据库路径",environmentKeys:["AUTH_STORE_FILE"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<browserProfileDirectory>/auth-store.json"},migrationSources:["AUTH_STORE_FILE"]},{path:"storage.terminalSessionStoreFile",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"终端存储路径",environmentKeys:["TERMINAL_SESSION_STORE_FILE"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<browserProfileDirectory>/terminal-session-store.json"},migrationSources:["TERMINAL_SESSION_STORE_FILE"]},{path:"storage.activityKeyStorage",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Activity 密钥保管方式;system 使用平台默认,file 使用存储目录中仅服务用户可读的密钥,独立无界面服务显式选择 file",environmentKeys:[],owner:"backend/activity",scope:"instance",storage:"settings.yaml",default:{value:"system"},migrationSources:["new-server-installation"]},{path:"storage.activityDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Activity 存储根;旧环境仅测试使用",environmentKeys:["RUNWEAVE_ACTIVITY_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/activity"},migrationSources:["RUNWEAVE_ACTIVITY_HOME"]},{path:"storage.evolutionDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Evolution 存储根;旧环境仅测试使用",environmentKeys:["RUNWEAVE_EVOLUTION_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/evolution"},migrationSources:["RUNWEAVE_EVOLUTION_HOME"]},{path:"storage.experienceDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Experience 存储根",environmentKeys:["RUNWEAVE_EXPERIENCE_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/experience"},migrationSources:["RUNWEAVE_EXPERIENCE_HOME"]},{path:"storage.scheduledTasksDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"定时任务存储根",environmentKeys:["RUNWEAVE_SCHEDULED_TASKS_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/scheduled-tasks"},migrationSources:["RUNWEAVE_SCHEDULED_TASKS_HOME"]},{path:"storage.feishuDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"飞书状态目录",environmentKeys:["RUNWEAVE_FEISHU_STATE_DIR"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/feishu"},migrationSources:["RUNWEAVE_FEISHU_STATE_DIR"]},{path:"logging.level",type:"string",domain:"logging",sensitive:!1,remote:!1,apply:"restart",description:"日志级别",environmentKeys:["RUNWEAVE_LOG_LEVEL"],owner:"backend/logging",scope:"instance",storage:"settings.yaml",default:{value:"info"},migrationSources:["RUNWEAVE_LOG_LEVEL"]},{path:"logging.toFile",type:"boolean",domain:"logging",sensitive:!1,remote:!1,apply:"restart",description:"日志落盘开关",environmentKeys:["RUNWEAVE_LOG_TO_FILE"],owner:"backend/logging",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["RUNWEAVE_LOG_TO_FILE"]},{path:"logging.backendDirectory",type:"string",domain:"logging",sensitive:!1,remote:!1,apply:"restart",description:"Backend 日志目录",environmentKeys:["RUNWEAVE_BACKEND_LOG_DIR"],owner:"backend/logging",scope:"instance",storage:"settings.yaml",default:{rule:"<browserProfileDirectory>/logs/backend"},migrationSources:["RUNWEAVE_BACKEND_LOG_DIR"]},{path:"appServer.discovery",type:"string",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"App Server 发现策略",environmentKeys:["RUNWEAVE_APP_SERVER_DISCOVERY"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{value:"auto"},migrationSources:["RUNWEAVE_APP_SERVER_DISCOVERY"]},{path:"appServer.stateDirectory",type:"string",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"App Server 状态目录",environmentKeys:["RUNWEAVE_APP_SERVER_STATE_DIR"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/app-server"},migrationSources:["RUNWEAVE_APP_SERVER_STATE_DIR"]},{path:"appServer.cloudSyncDirectory",type:"string",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"App Server 云同步模拟目录",environmentKeys:["RUNWEAVE_APP_SERVER_CLOUD_SYNC_DIR"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/app-server/cloud-sync"},migrationSources:["RUNWEAVE_APP_SERVER_CLOUD_SYNC_DIR"]},{path:"appServer.codexStatusIntervalMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"Codex 状态轮询间隔",environmentKeys:["RUNWEAVE_APP_SERVER_CODEX_STATUS_INTERVAL_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{value:3e4},migrationSources:["RUNWEAVE_APP_SERVER_CODEX_STATUS_INTERVAL_MS"]},{path:"appServer.codexStatusStartDelayMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"Codex 状态启动延迟",environmentKeys:["RUNWEAVE_APP_SERVER_CODEX_STATUS_START_DELAY_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{value:1e4},migrationSources:["RUNWEAVE_APP_SERVER_CODEX_STATUS_START_DELAY_MS"]},{path:"appServer.threadStatusIntervalMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"线程状态轮询间隔",environmentKeys:["RUNWEAVE_APP_SERVER_THREAD_STATUS_INTERVAL_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"缺省依次采用 appServer.codexStatusIntervalMs 和 30000 ms。"},migrationSources:["RUNWEAVE_APP_SERVER_THREAD_STATUS_INTERVAL_MS"]},{path:"appServer.threadStatusStartDelayMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"线程状态启动延迟",environmentKeys:["RUNWEAVE_APP_SERVER_THREAD_STATUS_START_DELAY_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"缺省依次采用 appServer.codexStatusStartDelayMs 和 10000 ms。"},migrationSources:["RUNWEAVE_APP_SERVER_THREAD_STATUS_START_DELAY_MS"]},{path:"updates.url",type:"string",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"更新源地址;旧别名合并",environmentKeys:["RUNWEAVE_LOCAL_UPDATES_URL","BROWSER_VIEWER_LOCAL_UPDATES_URL"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{rule:"安装包内 app-update.yml 的只读发行默认值;用户值唯一来自本文件。"},migrationSources:["RUNWEAVE_LOCAL_UPDATES_URL","BROWSER_VIEWER_LOCAL_UPDATES_URL"]},{path:"updates.autoInstallLocal",type:"boolean",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"本地更新自动安装策略",environmentKeys:["RUNWEAVE_AUTO_INSTALL_LOCAL_UPDATES","BROWSER_VIEWER_AUTO_INSTALL_LOCAL_UPDATES"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时仅本机更新源自动安装。"},migrationSources:["RUNWEAVE_AUTO_INSTALL_LOCAL_UPDATES","BROWSER_VIEWER_AUTO_INSTALL_LOCAL_UPDATES"]},{path:"updates.serverHost",type:"string",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"本机更新服务监听地址",environmentKeys:["RUNWEAVE_LOCAL_UPDATES_HOST","BROWSER_VIEWER_LOCAL_UPDATES_HOST"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["RUNWEAVE_LOCAL_UPDATES_HOST","BROWSER_VIEWER_LOCAL_UPDATES_HOST"]},{path:"updates.serverPort",type:"integer",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"本机更新服务监听端口",environmentKeys:["RUNWEAVE_LOCAL_UPDATES_PORT","BROWSER_VIEWER_LOCAL_UPDATES_PORT"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{value:5500},migrationSources:["RUNWEAVE_LOCAL_UPDATES_PORT","BROWSER_VIEWER_LOCAL_UPDATES_PORT"]},{path:"developer.codesignIdentity",type:"string",domain:"developer",sensitive:!1,remote:!1,apply:"restart",description:"本机签名身份选择",environmentKeys:["RUNWEAVE_CODESIGN_IDENTITY"],owner:"scripts/update",scope:"instance",storage:"settings.yaml",default:{rule:"从系统钥匙串可用签名身份中选择;显式更新可将选择写入当前实例。"},migrationSources:["RUNWEAVE_CODESIGN_IDENTITY"]},{path:"developer.minimumFreeBytes",type:"integer",domain:"developer",sensitive:!1,remote:!1,apply:"restart",description:"测试安装资源池剩余磁盘门槛",environmentKeys:["RUNWEAVE_BETA_POOL_MIN_FREE_BYTES"],owner:"scripts/update",scope:"instance",storage:"settings.yaml",default:{rule:"使用 Beta Pool 存储模块的 4 GiB 默认下限。"},migrationSources:["RUNWEAVE_BETA_POOL_MIN_FREE_BYTES"]},{path:"desktop.browser.localEnabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"本机浏览器能力开关",environmentKeys:["RUNWEAVE_BROWSER_LOCAL_ENABLED"],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["RUNWEAVE_BROWSER_LOCAL_ENABLED"]},{path:"desktop.browser.webMcpEnabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"WebMCP 能力开关",environmentKeys:["RUNWEAVE_BROWSER_WEBMCP"],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["RUNWEAVE_BROWSER_WEBMCP"]},{path:"services.suiji.databaseURL",type:"string",domain:"services.suiji",sensitive:!0,remote:!1,apply:"restart",description:"独立随记服务数据库连接",environmentKeys:["DATABASE_URL"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["DATABASE_URL"]},{path:"services.suiji.storageDirectory",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记附件存储目录",environmentKeys:["SUIJI_STORAGE_DIR"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["SUIJI_STORAGE_DIR"]},{path:"services.suiji.host",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记监听地址",environmentKeys:["SUIJI_HOST"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["SUIJI_HOST"]},{path:"services.suiji.port",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记监听端口",environmentKeys:["SUIJI_PORT"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:4783},migrationSources:["SUIJI_PORT"]},{path:"services.suiji.accessSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记访问凭据有效期",environmentKeys:["SUIJI_ACCESS_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:86400},migrationSources:["SUIJI_ACCESS_SECONDS"]},{path:"services.suiji.refreshSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记刷新凭据有效期",environmentKeys:["SUIJI_REFRESH_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:2592e3},migrationSources:["SUIJI_REFRESH_SECONDS"]},{path:"services.suiji.loginAttempts",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记登录尝试次数限制",environmentKeys:["SUIJI_LOGIN_ATTEMPTS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:8},migrationSources:["SUIJI_LOGIN_ATTEMPTS"]},{path:"services.suiji.loginWindowSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记登录限制窗口",environmentKeys:["SUIJI_LOGIN_WINDOW_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:900},migrationSources:["SUIJI_LOGIN_WINDOW_SECONDS"]},{path:"services.suiji.webOrigins",type:"array<string>",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记允许的 Web 来源",environmentKeys:["SUIJI_WEB_ORIGINS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["SUIJI_WEB_ORIGINS"]},{path:"services.suiji.ai.provider",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 AI provider",environmentKeys:["SUIJI_AI_PROVIDER"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:"disabled"},migrationSources:["SUIJI_AI_PROVIDER"]},{path:"services.suiji.ai.codexBinary",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 Codex 可执行文件",environmentKeys:["SUIJI_CODEX_BIN"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:"codex"},migrationSources:["SUIJI_CODEX_BIN"]},{path:"services.suiji.ai.codexHome",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记外部 Codex 登录目录引用",environmentKeys:["SUIJI_CODEX_HOME"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["SUIJI_CODEX_HOME"]},{path:"services.suiji.ai.timeoutSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 AI 超时",environmentKeys:["SUIJI_AI_TIMEOUT_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:180},migrationSources:["SUIJI_AI_TIMEOUT_SECONDS"]},{path:"services.suiji.mcpEnabled",type:"boolean",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 MCP 开关",environmentKeys:["SUIJI_MCP_ENABLED"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["SUIJI_MCP_ENABLED"]},{path:"cli.activeProfile",type:"string",domain:"cli",sensitive:!1,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:"local"},migrationSources:["CLI.config.activeProfile"]},{path:"cli.profiles.<name>.baseUrl",type:"string",domain:"cli",sensitive:!1,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{rule:"未创建连接时使用当前实例的本机端口;Dev 只接受已验证握手的明确连接。"},migrationSources:["CLI.config.profiles.<name>.baseUrl"]},{path:"cli.profiles.<name>.accessToken",type:"string",domain:"cli",sensitive:!0,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["CLI.config.profiles.<name>.accessToken"]},{path:"cli.profiles.<name>.refreshToken",type:"string",domain:"cli",sensitive:!0,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["CLI.config.profiles.<name>.refreshToken"]},{path:"cli.profiles.<name>.expiresAt",type:"string",domain:"cli",sensitive:!1,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["CLI.config.profiles.<name>.expiresAt"]},{path:"desktop.preferences.companion.enabled",type:"boolean",domain:"desktop.preferences",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/companion",scope:"instance",storage:"settings.yaml",default:{rule:"缺省时 Stable 启用、Dev 关闭;全新安装初始化会显式写入 false,优先于此规则。"},migrationSources:["desktop-companion.json.enabled"]},{path:"desktop.browser.proxy.enabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["terminal-browser-proxy.json.enabled"]},{path:"desktop.browser.proxy.port",type:"integer",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:8899},migrationSources:["terminal-browser-proxy.json.port"]},{path:"desktop.browser.defaultProfileId",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:"profile-1"},migrationSources:["terminal-browser-profiles.json.defaultProfileId"]},{path:"desktop.browser.profilePorts.<profileId>",type:"integer",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal-browser-profiles.json.profilePorts.<profileId>"]},{path:"desktop.browser.proxyModes.<profileId>",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{rule:"沿用该 Browser 的宿主默认代理模式;没有持久条目时不创建覆盖。"},migrationSources:["terminal-browser-profiles.json.proxyModes.<profileId>"]},{path:"desktop.browser.worktrees.<projectId>.preferredProfileId",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal-browser-profiles.json.worktrees.<projectId>.preferredProfileId"]},{path:"desktop.browser.headerRules.<profileId>[].id",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.id"]},{path:"desktop.browser.headerRules.<profileId>[].enabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.enabled"]},{path:"desktop.browser.headerRules.<profileId>[].operation",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.operation"]},{path:"desktop.browser.headerRules.<profileId>[].name",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.name"]},{path:"desktop.browser.headerRules.<profileId>[].value",type:"string",domain:"desktop.browser",sensitive:!0,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.value"]},{path:"desktop.browser.headerRules.<profileId>[].urlPattern",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.urlPattern"]},{path:"desktop.tunnels.desktopId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{rule:"仅全新实例首次初始化生成 UUID;存在旧文件必须先显式迁移。"},migrationSources:["tunnels/config.json.desktopId"]},{path:"desktop.tunnels.hosts[].id",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].id"]},{path:"desktop.tunnels.hosts[].name",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].name"]},{path:"desktop.tunnels.hosts[].sshTarget",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].sshTarget"]},{path:"desktop.tunnels.hosts[].autoConnect",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].autoConnect"]},{path:"desktop.tunnels.hosts[].remoteAccess.enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteAccess.enabled"]},{path:"desktop.tunnels.hosts[].remoteAccess.listenAddress",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteAccess.listenAddress"]},{path:"desktop.tunnels.hosts[].remoteAccess.port",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteAccess.port"]},{path:"desktop.tunnels.hosts[].remoteDesktop.enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"是否启用由 Runweave 管理的 RemoteDesk 隧道",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.enabled"]},{path:"desktop.tunnels.hosts[].remoteDesktop.autoDetectLocalHost",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"自动读取本机 RemoteDesk 地址与端口,保持已保存的证书指纹;旧配置未设置时沿用手动地址",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.autoDetectLocalHost"]},{path:"desktop.tunnels.hosts[].remoteDesktop.listenAddress",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"Devbox 内网或 VPN 入口 IPv4",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.listenAddress"]},{path:"desktop.tunnels.hosts[].remoteDesktop.port",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"RemoteDesk 独立中转端口",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.port"]},{path:"desktop.tunnels.hosts[].remoteDesktop.localAddress",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"本机 RemoteDesk 所监听的 LAN IPv4",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.localAddress"]},{path:"desktop.tunnels.hosts[].remoteDesktop.localPort",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"本机 RemoteDesk TLS 监听端口",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.localPort"]},{path:"desktop.tunnels.hosts[].remoteDesktop.certificateFingerprint",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"本机 RemoteDesk 完整 SHA-256 证书指纹",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.certificateFingerprint"]},{path:"desktop.tunnels.hosts[].forwards[].id",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].id"]},{path:"desktop.tunnels.hosts[].forwards[].name",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].name"]},{path:"desktop.tunnels.hosts[].forwards[].port",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].port"]},{path:"desktop.tunnels.hosts[].forwards[].path",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].path"]},{path:"desktop.tunnels.hosts[].forwards[].enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].enabled"]},{path:"desktop.tunnels.hosts[].browser.enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.enabled"]},{path:"desktop.tunnels.hosts[].browser.backendPort",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.backendPort"]},{path:"desktop.tunnels.hosts[].browser.profileId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.profileId"]},{path:"desktop.tunnels.hosts[].browser.approvedBrowserGroupId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.approvedBrowserGroupId"]},{path:"desktop.tunnels.backendEndpoints[].id",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.backendEndpoints[].id"]},{path:"desktop.tunnels.backendEndpoints[].hostId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.backendEndpoints[].hostId"]},{path:"desktop.tunnels.backendEndpoints[].remotePort",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.backendEndpoints[].remotePort"]},{path:"services.pushSender.hostId",type:"string",domain:"services.pushSender",sensitive:!1,remote:!1,apply:"reload",description:"推送主机身份,迁移保留,不自动生成替代身份",environmentKeys:[],owner:"backend/device-monitor",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["device-monitor/push.json.hostId"]},{path:"storage.terminalQuickInputStoreFile",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"旧配置/内容文件定位;模型迁移后其旧路径仅作来源记录",environmentKeys:[],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<terminalSessionStoreFile 所在目录>/terminal-quick-inputs.json"},migrationSources:["StoragePaths.terminalQuickInputStoreFile"]},{path:"desktop.browser.pendingPortMigration.<profileId>",type:"array<number>",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"迁移保留的域版本及偏好状态",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["desktop.browser legacy store (explicit manifest)"]},{path:"desktop.tunnels.revision",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"迁移保留的域版本及偏好状态",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:0},migrationSources:["desktop.tunnels legacy store (explicit manifest)"]},{path:"desktop.tunnels.completedImports",type:"array<string>",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"迁移保留的域版本及偏好状态",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["desktop.tunnels legacy store (explicit manifest)"]}],NB=[["backend.process","Backend","backend"],["app-server.process","App Server","app-server"],["electron.process","Desktop","electron"],["backend.cli-version","CLI(节点 rw)","backend"],["feishu.bridge-lease","飞书 Bridge","feishu-bridge"],["research-mcp.process","调查 MCP","research-mcp"],["snapshot-host.process","快照分享 Host","snapshot-host"],["push-gateway.process","推送网关","push-gateway"],["suiji-server.process","随记服务","suiji-server"],["remote-desktop-host.process","RemoteDesk Host","remote-desktop-host"]];function RB(e){const t=new Map(Uk(e).flatMap(n=>n.items.map(s=>[s.id,s]))),r=[...NB];for(const n of e)for(const s of n.items)(s.capabilityId==="workspace-services"||/^electron\.(cdp-proxy|companion|whistle:|remote-access:|remote-desktop:)/.test(s.id)||/^remote-desktop-host\.(listener|screen-permission|control-permission)$/.test(s.id))&&r.push([s.id,s.label,n.source.id]);return r.map(([n,s,i])=>{var u,d,h;const a=e.find(f=>f.source.id===i),l=t.get(`${i}.source`)??t.get(n)??(a==null?void 0:a.items.find(f=>f.id.endsWith("-report"))),c=(u=l==null?void 0:l.facts.find(f=>f.id==="runtime-installation.state"))==null?void 0:u.value;return{id:n,label:s,sourceId:i,state:(l==null?void 0:l.state)??"unsupported",summary:(l==null?void 0:l.summary)??"未收到此服务的健康报告;未启动、未安装和旧版本无法据此区分",observedAt:(l==null?void 0:l.observedAt)??null,version:((h=(d=t.get(n)??l)==null?void 0:d.facts.find(f=>f.id==="runtime-version.number"))==null?void 0:h.value)??null,installation:(l==null?void 0:l.state)==="healthy"&&(c==="current"||c==="restart-required")?c:"unknown"}})}const jB={healthy:"正常",unhealthy:"异常",blocked:"无法判断",recovering:"恢复中",checking:"检查中",disabled:"已停用",unconfigured:"未配置 / 未上报",unsupported:"未上报 / 需更新"};function AB({reports:e}){const t=RB(e),r=t.filter(s=>["unsupported","unconfigured","blocked","checking"].includes(s.state)).length,n=t.filter(s=>s.installation==="restart-required").length;return o.jsxs("section",{className:"rounded-xl border border-border/70 p-4","aria-label":"本机服务清单",children:[o.jsxs("h3",{className:"text-sm font-medium",children:["服务清单 · ",t.length," 项"]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["此节点所属实例的服务与本机共享 Host;云端和其他实例分别检查。",r>0?` ${r} 项未确认。`:"",n>0?` ${n} 项需要重启。`:""]}),o.jsx("div",{className:"mt-3 divide-y divide-border/50",children:t.map(s=>o.jsxs("details",{className:"py-2","data-runtime-service":s.id,"data-runtime-installation":s.installation,children:[o.jsxs("summary",{className:"flex cursor-pointer items-center justify-between gap-3 text-xs",children:[o.jsx("span",{className:"font-medium",children:s.label}),o.jsxs("span",{className:s.state==="unhealthy"?"text-red-600":s.installation==="restart-required"||["unsupported","unconfigured","blocked","recovering"].includes(s.state)?"text-amber-600":"text-muted-foreground",children:[jB[s.state],s.installation==="restart-required"?" · 需要重启":""]})]}),o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:s.summary}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["运行版本:",s.version??"未上报"," · 安装对照:",s.installation==="current"?"运行产物与安装产物一致":s.installation==="restart-required"?"已安装产物尚未生效,请使用该服务的更新或重启入口":"无法确认;缺少可对照的安装或运行身份"]}),s.observedAt!==null?o.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["最近证据:",new Date(s.observedAt).toLocaleString()]}):null]},s.id))}),o.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"安装一致不代表已包含最新源码;未上报和历史成功不代表当前正常。检查不会自动更新或重启服务。"})]})}const Gk=Object.fromEntries([...new Set(IB.map(e=>e.domain))].map(e=>[e,1]));Object.fromEntries(Object.entries(Gk).map(([e,t])=>[e,[t]]));Object.fromEntries(["appServer","agents.codex","agents.traex","agents.claude"].map(e=>[e,[Gk[e]]]));const TB={"backend.taskSupervision":"长任务监控","backend.server":"Backend 服务","backend.auth":"登录认证","backend.tunnelAuth":"隧道认证","services.snapshotPublisher":"终端分享","services.snapshotHost":"分享托管服务","services.pushSender":"设备通知","services.pushGateway":"推送网关","services.feishu":"飞书","services.suiji":"随记","agents.codex":"Codex","agents.traex":"Traex","agents.claude":"Claude Code","agents.companion":"伴随窗口","desktop.browser":"桌面浏览器","desktop.preferences":"桌面偏好","desktop.tunnels":"远程访问",cli:"CLI 连接",developer:"开发与签名",knowledge:"知识库",logging:"日志",scheduledTasks:"后台任务",storage:"数据存储",terminal:"终端","terminal.defaultShell":"默认 Shell",updates:"更新",voice:"语音",appServer:"App Server"};async function DB(e,t,r,n){const s=await fetch(`${e.replace(/\/+$/,"")}/api/configuration`,{method:n?"PATCH":"GET",redirect:"error",signal:r,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},...n?{body:JSON.stringify(n)}:{}});if(!s.ok){const i=s.status===409?"配置已被其他操作修改,请重新加载后再保存。":s.status===401?"请重新登录当前连接。":s.status===404?"当前电脑版本尚不支持统一配置。":"配置操作失败,请检查字段格式及运行状态。";throw new De(s.status,i)}return s.json()}const Hy={saved:"已保存的配置",default:"默认值",consumerDefault:"由功能模块决定",unset:"未设置",invalid:"配置无效"};function Wy(e,t){if(e.source==="invalid"||e.source==="consumerDefault"||e.source==="unset")return Hy[e.source];if(t){const r=e.value;return r&&typeof r=="object"&&!Array.isArray(r)&&r.configured===!0?"已配置(内容隐藏)":"未配置"}return`${JSON.stringify(e.value)??"未设置"} · ${Hy[e.source]}`}function qy({field:e,status:t,changed:r}){const n=t.state==="applied"?"当前进程已采用":t.state==="pending"?e.apply==="restart"?"已保存,等待所属服务重启":"已保存,等待所属功能重新加载":t.state==="error"?"配置或应用失败":"尚未确认所属服务是否采用";return o.jsxs("div",{className:"space-y-1 break-words text-xs text-muted-foreground",children:[o.jsx("p",{children:n}),o.jsxs("p",{children:["已保存配置的取值:",Wy(t.saved,e.sensitive)]}),t.applied&&o.jsxs("p",{children:["当前进程采用值:",Wy(t.applied,e.sensitive),t.appliedRevision!==null?` · 版本 ${t.appliedRevision}`:""]}),t.saved.source==="consumerDefault"&&"rule"in e.default&&o.jsx("p",{children:e.default.rule}),r&&o.jsx("p",{children:"有未保存的修改;以上为上次读取的结果。"})]})}function Yk(e,t,r){return me(e,"/api/agent-model-catalogs",{headers:{Authorization:`Bearer ${t}`},signal:r})}const PB=["top","right","bottom","left"],ao=Math.min,Rn=Math.max,Th=Math.round,_d=Math.floor,zs=e=>({x:e,y:e}),LB={left:"right",right:"left",bottom:"top",top:"bottom"};function B0(e,t,r){return Rn(e,ao(t,r))}function gi(e,t){return typeof e=="function"?e(t):e}function vi(e){return e.split("-")[0]}function El(e){return e.split("-")[1]}function gx(e){return e==="x"?"y":"x"}function vx(e){return e==="y"?"height":"width"}function Os(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function xx(e){return gx(Os(e))}function MB(e,t,r){r===void 0&&(r=!1);const n=El(e),s=xx(e),i=vx(s);let a=s==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Dh(a)),[a,Dh(a)]}function OB(e){const t=Dh(e);return[F0(e),t,F0(t)]}function F0(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Ky=["left","right"],Vy=["right","left"],BB=["top","bottom"],FB=["bottom","top"];function $B(e,t,r){switch(e){case"top":case"bottom":return r?t?Vy:Ky:t?Ky:Vy;case"left":case"right":return t?BB:FB;default:return[]}}function zB(e,t,r,n){const s=El(e);let i=$B(vi(e),r==="start",n);return s&&(i=i.map(a=>a+"-"+s),t&&(i=i.concat(i.map(F0)))),i}function Dh(e){const t=vi(e);return LB[t]+e.slice(t.length)}function UB(e){return{top:0,right:0,bottom:0,left:0,...e}}function Xk(e){return typeof e!="number"?UB(e):{top:e,right:e,bottom:e,left:e}}function Ph(e){const{x:t,y:r,width:n,height:s}=e;return{width:n,height:s,top:r,left:t,right:t+n,bottom:r+s,x:t,y:r}}function Gy(e,t,r){let{reference:n,floating:s}=e;const i=Os(t),a=xx(t),l=vx(a),c=vi(t),u=i==="y",d=n.x+n.width/2-s.width/2,h=n.y+n.height/2-s.height/2,f=n[l]/2-s[l]/2;let m;switch(c){case"top":m={x:d,y:n.y-s.height};break;case"bottom":m={x:d,y:n.y+n.height};break;case"right":m={x:n.x+n.width,y:h};break;case"left":m={x:n.x-s.width,y:h};break;default:m={x:n.x,y:n.y}}switch(El(t)){case"start":m[a]-=f*(r&&u?-1:1);break;case"end":m[a]+=f*(r&&u?-1:1);break}return m}async function HB(e,t){var r;t===void 0&&(t={});const{x:n,y:s,platform:i,rects:a,elements:l,strategy:c}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:h="floating",altBoundary:f=!1,padding:m=0}=gi(t,e),g=Xk(m),x=l[f?h==="floating"?"reference":"floating":h],b=Ph(await i.getClippingRect({element:(r=await(i.isElement==null?void 0:i.isElement(x)))==null||r?x:x.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:u,rootBoundary:d,strategy:c})),_=h==="floating"?{x:n,y:s,width:a.floating.width,height:a.floating.height}:a.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),S=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},w=Ph(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:_,offsetParent:C,strategy:c}):_);return{top:(b.top-w.top+g.top)/S.y,bottom:(w.bottom-b.bottom+g.bottom)/S.y,left:(b.left-w.left+g.left)/S.x,right:(w.right-b.right+g.right)/S.x}}const WB=50,qB=async(e,t,r)=>{const{placement:n="bottom",strategy:s="absolute",middleware:i=[],platform:a}=r,l=a.detectOverflow?a:{...a,detectOverflow:HB},c=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:d,y:h}=Gy(u,n,c),f=n,m=0;const g={};for(let v=0;v<i.length;v++){const x=i[v];if(!x)continue;const{name:b,fn:_}=x,{x:C,y:S,data:w,reset:y}=await _({x:d,y:h,initialPlacement:n,placement:f,strategy:s,middlewareData:g,rects:u,platform:l,elements:{reference:e,floating:t}});d=C??d,h=S??h,g[b]={...g[b],...w},y&&m<WB&&(m++,typeof y=="object"&&(y.placement&&(f=y.placement),y.rects&&(u=y.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:s}):y.rects),{x:d,y:h}=Gy(u,f,c)),v=-1)}return{x:d,y:h,placement:f,strategy:s,middlewareData:g}},KB=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:n,placement:s,rects:i,platform:a,elements:l,middlewareData:c}=t,{element:u,padding:d=0}=gi(e,t)||{};if(u==null)return{};const h=Xk(d),f={x:r,y:n},m=xx(s),g=vx(m),v=await a.getDimensions(u),x=m==="y",b=x?"top":"left",_=x?"bottom":"right",C=x?"clientHeight":"clientWidth",S=i.reference[g]+i.reference[m]-f[m]-i.floating[g],w=f[m]-i.reference[m],y=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let N=y?y[C]:0;(!N||!await(a.isElement==null?void 0:a.isElement(y)))&&(N=l.floating[C]||i.floating[g]);const E=S/2-w/2,k=N/2-v[g]/2-1,D=ao(h[b],k),j=ao(h[_],k),R=D,I=N-v[g]-j,T=N/2-v[g]/2+E,A=B0(R,T,I),P=!c.arrow&&El(s)!=null&&T!==A&&i.reference[g]/2-(T<R?D:j)-v[g]/2<0,O=P?T<R?T-R:T-I:0;return{[m]:f[m]+O,data:{[m]:A,centerOffset:T-A-O,...P&&{alignmentOffset:O}},reset:P}}}),VB=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,n;const{placement:s,middlewareData:i,rects:a,initialPlacement:l,platform:c,elements:u}=t,{mainAxis:d=!0,crossAxis:h=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:v=!0,...x}=gi(e,t);if((r=i.arrow)!=null&&r.alignmentOffset)return{};const b=vi(s),_=Os(l),C=vi(l)===l,S=await(c.isRTL==null?void 0:c.isRTL(u.floating)),w=f||(C||!v?[Dh(l)]:OB(l)),y=g!=="none";!f&&y&&w.push(...zB(l,v,g,S));const N=[l,...w],E=await c.detectOverflow(t,x),k=[];let D=((n=i.flip)==null?void 0:n.overflows)||[];if(d&&k.push(E[b]),h){const T=MB(s,a,S);k.push(E[T[0]],E[T[1]])}if(D=[...D,{placement:s,overflows:k}],!k.every(T=>T<=0)){var j,R;const T=(((j=i.flip)==null?void 0:j.index)||0)+1,A=N[T];if(A&&(!(h==="alignment"?_!==Os(A):!1)||D.every(L=>Os(L.placement)===_?L.overflows[0]>0:!0)))return{data:{index:T,overflows:D},reset:{placement:A}};let P=(R=D.filter(O=>O.overflows[0]<=0).sort((O,L)=>O.overflows[1]-L.overflows[1])[0])==null?void 0:R.placement;if(!P)switch(m){case"bestFit":{var I;const O=(I=D.filter(L=>{if(y){const B=Os(L.placement);return B===_||B==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(B=>B>0).reduce((B,M)=>B+M,0)]).sort((L,B)=>L[1]-B[1])[0])==null?void 0:I[0];O&&(P=O);break}case"initialPlacement":P=l;break}if(s!==P)return{reset:{placement:P}}}return{}}}};function Yy(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Xy(e){return PB.some(t=>e[t]>=0)}const GB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r,platform:n}=t,{strategy:s="referenceHidden",...i}=gi(e,t);switch(s){case"referenceHidden":{const a=await n.detectOverflow(t,{...i,elementContext:"reference"}),l=Yy(a,r.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:Xy(l)}}}case"escaped":{const a=await n.detectOverflow(t,{...i,altBoundary:!0}),l=Yy(a,r.floating);return{data:{escapedOffsets:l,escaped:Xy(l)}}}default:return{}}}}},Jk=new Set(["left","top"]);async function YB(e,t){const{placement:r,platform:n,elements:s}=e,i=await(n.isRTL==null?void 0:n.isRTL(s.floating)),a=vi(r),l=El(r),c=Os(r)==="y",u=Jk.has(a)?-1:1,d=i&&c?-1:1,h=gi(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return l&&typeof g=="number"&&(m=l==="end"?g*-1:g),c?{x:m*d,y:f*u}:{x:f*u,y:m*d}}const XB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,n;const{x:s,y:i,placement:a,middlewareData:l}=t,c=await YB(t,e);return a===((r=l.offset)==null?void 0:r.placement)&&(n=l.arrow)!=null&&n.alignmentOffset?{}:{x:s+c.x,y:i+c.y,data:{...c,placement:a}}}}},JB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:n,placement:s,platform:i}=t,{mainAxis:a=!0,crossAxis:l=!1,limiter:c={fn:b=>{let{x:_,y:C}=b;return{x:_,y:C}}},...u}=gi(e,t),d={x:r,y:n},h=await i.detectOverflow(t,u),f=Os(vi(s)),m=gx(f);let g=d[m],v=d[f];if(a){const b=m==="y"?"top":"left",_=m==="y"?"bottom":"right",C=g+h[b],S=g-h[_];g=B0(C,g,S)}if(l){const b=f==="y"?"top":"left",_=f==="y"?"bottom":"right",C=v+h[b],S=v-h[_];v=B0(C,v,S)}const x=c.fn({...t,[m]:g,[f]:v});return{...x,data:{x:x.x-r,y:x.y-n,enabled:{[m]:a,[f]:l}}}}}},QB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:n,placement:s,rects:i,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:u=!0}=gi(e,t),d={x:r,y:n},h=Os(s),f=gx(h);let m=d[f],g=d[h];const v=gi(l,t),x=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(c){const C=f==="y"?"height":"width",S=i.reference[f]-i.floating[C]+x.mainAxis,w=i.reference[f]+i.reference[C]-x.mainAxis;m<S?m=S:m>w&&(m=w)}if(u){var b,_;const C=f==="y"?"width":"height",S=Jk.has(vi(s)),w=i.reference[h]-i.floating[C]+(S&&((b=a.offset)==null?void 0:b[h])||0)+(S?0:x.crossAxis),y=i.reference[h]+i.reference[C]+(S?0:((_=a.offset)==null?void 0:_[h])||0)-(S?x.crossAxis:0);g<w?g=w:g>y&&(g=y)}return{[f]:m,[h]:g}}}},ZB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,n;const{placement:s,rects:i,platform:a,elements:l}=t,{apply:c=()=>{},...u}=gi(e,t),d=await a.detectOverflow(t,u),h=vi(s),f=El(s),m=Os(s)==="y",{width:g,height:v}=i.floating;let x,b;h==="top"||h==="bottom"?(x=h,b=f===(await(a.isRTL==null?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(b=h,x=f==="end"?"top":"bottom");const _=v-d.top-d.bottom,C=g-d.left-d.right,S=ao(v-d[x],_),w=ao(g-d[b],C),y=!t.middlewareData.shift;let N=S,E=w;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(E=C),(n=t.middlewareData.shift)!=null&&n.enabled.y&&(N=_),y&&!f){const D=Rn(d.left,0),j=Rn(d.right,0),R=Rn(d.top,0),I=Rn(d.bottom,0);m?E=g-2*(D!==0||j!==0?D+j:Rn(d.left,d.right)):N=v-2*(R!==0||I!==0?R+I:Rn(d.top,d.bottom))}await c({...t,availableWidth:E,availableHeight:N});const k=await a.getDimensions(l.floating);return g!==k.width||v!==k.height?{reset:{rects:!0}}:{}}}};function Tf(){return typeof window<"u"}function kl(e){return Qk(e)?(e.nodeName||"").toLowerCase():"#document"}function jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ys(e){var t;return(t=(Qk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Qk(e){return Tf()?e instanceof Node||e instanceof jn(e).Node:!1}function us(e){return Tf()?e instanceof Element||e instanceof jn(e).Element:!1}function _i(e){return Tf()?e instanceof HTMLElement||e instanceof jn(e).HTMLElement:!1}function Jy(e){return!Tf()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof jn(e).ShadowRoot}function Tu(e){const{overflow:t,overflowX:r,overflowY:n,display:s}=ds(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&s!=="inline"&&s!=="contents"}function eF(e){return/^(table|td|th)$/.test(kl(e))}function Df(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const tF=/transform|translate|scale|rotate|perspective|filter/,rF=/paint|layout|strict|content/,No=e=>!!e&&e!=="none";let rm;function bx(e){const t=us(e)?ds(e):e;return No(t.transform)||No(t.translate)||No(t.scale)||No(t.rotate)||No(t.perspective)||!_x()&&(No(t.backdropFilter)||No(t.filter))||tF.test(t.willChange||"")||rF.test(t.contain||"")}function nF(e){let t=lo(e);for(;_i(t)&&!fl(t);){if(bx(t))return t;if(Df(t))return null;t=lo(t)}return null}function _x(){return rm==null&&(rm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),rm}function fl(e){return/^(html|body|#document)$/.test(kl(e))}function ds(e){return jn(e).getComputedStyle(e)}function Pf(e){return us(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lo(e){if(kl(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Jy(e)&&e.host||Ys(e);return Jy(t)?t.host:t}function Zk(e){const t=lo(e);return fl(t)?e.ownerDocument?e.ownerDocument.body:e.body:_i(t)&&Tu(t)?t:Zk(t)}function $c(e,t,r){var n;t===void 0&&(t=[]),r===void 0&&(r=!0);const s=Zk(e),i=s===((n=e.ownerDocument)==null?void 0:n.body),a=jn(s);if(i){const l=$0(a);return t.concat(a,a.visualViewport||[],Tu(s)?s:[],l&&r?$c(l):[])}else return t.concat(s,$c(s,[],r))}function $0(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function e5(e){const t=ds(e);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const s=_i(e),i=s?e.offsetWidth:r,a=s?e.offsetHeight:n,l=Th(r)!==i||Th(n)!==a;return l&&(r=i,n=a),{width:r,height:n,$:l}}function yx(e){return us(e)?e:e.contextElement}function Va(e){const t=yx(e);if(!_i(t))return zs(1);const r=t.getBoundingClientRect(),{width:n,height:s,$:i}=e5(t);let a=(i?Th(r.width):r.width)/n,l=(i?Th(r.height):r.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const sF=zs(0);function t5(e){const t=jn(e);return!_x()||!t.visualViewport?sF:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function iF(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==jn(e)?!1:t}function ra(e,t,r,n){t===void 0&&(t=!1),r===void 0&&(r=!1);const s=e.getBoundingClientRect(),i=yx(e);let a=zs(1);t&&(n?us(n)&&(a=Va(n)):a=Va(e));const l=iF(i,r,n)?t5(i):zs(0);let c=(s.left+l.x)/a.x,u=(s.top+l.y)/a.y,d=s.width/a.x,h=s.height/a.y;if(i){const f=jn(i),m=n&&us(n)?jn(n):n;let g=f,v=$0(g);for(;v&&n&&m!==g;){const x=Va(v),b=v.getBoundingClientRect(),_=ds(v),C=b.left+(v.clientLeft+parseFloat(_.paddingLeft))*x.x,S=b.top+(v.clientTop+parseFloat(_.paddingTop))*x.y;c*=x.x,u*=x.y,d*=x.x,h*=x.y,c+=C,u+=S,g=jn(v),v=$0(g)}}return Ph({width:d,height:h,x:c,y:u})}function Lf(e,t){const r=Pf(e).scrollLeft;return t?t.left+r:ra(Ys(e)).left+r}function r5(e,t){const r=e.getBoundingClientRect(),n=r.left+t.scrollLeft-Lf(e,r),s=r.top+t.scrollTop;return{x:n,y:s}}function oF(e){let{elements:t,rect:r,offsetParent:n,strategy:s}=e;const i=s==="fixed",a=Ys(n),l=t?Df(t.floating):!1;if(n===a||l&&i)return r;let c={scrollLeft:0,scrollTop:0},u=zs(1);const d=zs(0),h=_i(n);if((h||!h&&!i)&&((kl(n)!=="body"||Tu(a))&&(c=Pf(n)),h)){const m=ra(n);u=Va(n),d.x=m.x+n.clientLeft,d.y=m.y+n.clientTop}const f=a&&!h&&!i?r5(a,c):zs(0);return{width:r.width*u.x,height:r.height*u.y,x:r.x*u.x-c.scrollLeft*u.x+d.x+f.x,y:r.y*u.y-c.scrollTop*u.y+d.y+f.y}}function aF(e){return Array.from(e.getClientRects())}function lF(e){const t=Ys(e),r=Pf(e),n=e.ownerDocument.body,s=Rn(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=Rn(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let a=-r.scrollLeft+Lf(e);const l=-r.scrollTop;return ds(n).direction==="rtl"&&(a+=Rn(t.clientWidth,n.clientWidth)-s),{width:s,height:i,x:a,y:l}}const Qy=25;function cF(e,t){const r=jn(e),n=Ys(e),s=r.visualViewport;let i=n.clientWidth,a=n.clientHeight,l=0,c=0;if(s){i=s.width,a=s.height;const d=_x();(!d||d&&t==="fixed")&&(l=s.offsetLeft,c=s.offsetTop)}const u=Lf(n);if(u<=0){const d=n.ownerDocument,h=d.body,f=getComputedStyle(h),m=d.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,g=Math.abs(n.clientWidth-h.clientWidth-m);g<=Qy&&(i-=g)}else u<=Qy&&(i+=u);return{width:i,height:a,x:l,y:c}}function uF(e,t){const r=ra(e,!0,t==="fixed"),n=r.top+e.clientTop,s=r.left+e.clientLeft,i=_i(e)?Va(e):zs(1),a=e.clientWidth*i.x,l=e.clientHeight*i.y,c=s*i.x,u=n*i.y;return{width:a,height:l,x:c,y:u}}function Zy(e,t,r){let n;if(t==="viewport")n=cF(e,r);else if(t==="document")n=lF(Ys(e));else if(us(t))n=uF(t,r);else{const s=t5(e);n={x:t.x-s.x,y:t.y-s.y,width:t.width,height:t.height}}return Ph(n)}function n5(e,t){const r=lo(e);return r===t||!us(r)||fl(r)?!1:ds(r).position==="fixed"||n5(r,t)}function dF(e,t){const r=t.get(e);if(r)return r;let n=$c(e,[],!1).filter(l=>us(l)&&kl(l)!=="body"),s=null;const i=ds(e).position==="fixed";let a=i?lo(e):e;for(;us(a)&&!fl(a);){const l=ds(a),c=bx(a);!c&&l.position==="fixed"&&(s=null),(i?!c&&!s:!c&&l.position==="static"&&!!s&&(s.position==="absolute"||s.position==="fixed")||Tu(a)&&!c&&n5(e,a))?n=n.filter(d=>d!==a):s=l,a=lo(a)}return t.set(e,n),n}function hF(e){let{element:t,boundary:r,rootBoundary:n,strategy:s}=e;const a=[...r==="clippingAncestors"?Df(t)?[]:dF(t,this._c):[].concat(r),n],l=Zy(t,a[0],s);let c=l.top,u=l.right,d=l.bottom,h=l.left;for(let f=1;f<a.length;f++){const m=Zy(t,a[f],s);c=Rn(m.top,c),u=ao(m.right,u),d=ao(m.bottom,d),h=Rn(m.left,h)}return{width:u-h,height:d-c,x:h,y:c}}function fF(e){const{width:t,height:r}=e5(e);return{width:t,height:r}}function pF(e,t,r){const n=_i(t),s=Ys(t),i=r==="fixed",a=ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=zs(0);function u(){c.x=Lf(s)}if(n||!n&&!i)if((kl(t)!=="body"||Tu(s))&&(l=Pf(t)),n){const m=ra(t,!0,i,t);c.x=m.x+t.clientLeft,c.y=m.y+t.clientTop}else s&&u();i&&!n&&s&&u();const d=s&&!n&&!i?r5(s,l):zs(0),h=a.left+l.scrollLeft-c.x-d.x,f=a.top+l.scrollTop-c.y-d.y;return{x:h,y:f,width:a.width,height:a.height}}function nm(e){return ds(e).position==="static"}function e1(e,t){if(!_i(e)||ds(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Ys(e)===r&&(r=r.ownerDocument.body),r}function s5(e,t){const r=jn(e);if(Df(e))return r;if(!_i(e)){let s=lo(e);for(;s&&!fl(s);){if(us(s)&&!nm(s))return s;s=lo(s)}return r}let n=e1(e,t);for(;n&&eF(n)&&nm(n);)n=e1(n,t);return n&&fl(n)&&nm(n)&&!bx(n)?r:n||nF(e)||r}const mF=async function(e){const t=this.getOffsetParent||s5,r=this.getDimensions,n=await r(e.floating);return{reference:pF(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function gF(e){return ds(e).direction==="rtl"}const vF={convertOffsetParentRelativeRectToViewportRelativeRect:oF,getDocumentElement:Ys,getClippingRect:hF,getOffsetParent:s5,getElementRects:mF,getClientRects:aF,getDimensions:fF,getScale:Va,isElement:us,isRTL:gF};function i5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function xF(e,t){let r=null,n;const s=Ys(e);function i(){var l;clearTimeout(n),(l=r)==null||l.disconnect(),r=null}function a(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const u=e.getBoundingClientRect(),{left:d,top:h,width:f,height:m}=u;if(l||t(),!f||!m)return;const g=_d(h),v=_d(s.clientWidth-(d+f)),x=_d(s.clientHeight-(h+m)),b=_d(d),C={rootMargin:-g+"px "+-v+"px "+-x+"px "+-b+"px",threshold:Rn(0,ao(1,c))||1};let S=!0;function w(y){const N=y[0].intersectionRatio;if(N!==c){if(!S)return a();N?a(!1,N):n=setTimeout(()=>{a(!1,1e-7)},1e3)}N===1&&!i5(u,e.getBoundingClientRect())&&a(),S=!1}try{r=new IntersectionObserver(w,{...C,root:s.ownerDocument})}catch{r=new IntersectionObserver(w,C)}r.observe(e)}return a(!0),i}function o5(e,t,r,n){n===void 0&&(n={});const{ancestorScroll:s=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,u=yx(e),d=s||i?[...u?$c(u):[],...t?$c(t):[]]:[];d.forEach(b=>{s&&b.addEventListener("scroll",r,{passive:!0}),i&&b.addEventListener("resize",r)});const h=u&&l?xF(u,r):null;let f=-1,m=null;a&&(m=new ResizeObserver(b=>{let[_]=b;_&&_.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=m)==null||C.observe(t)})),r()}),u&&!c&&m.observe(u),t&&m.observe(t));let g,v=c?ra(e):null;c&&x();function x(){const b=ra(e);v&&!i5(v,b)&&r(),v=b,g=requestAnimationFrame(x)}return r(),()=>{var b;d.forEach(_=>{s&&_.removeEventListener("scroll",r),i&&_.removeEventListener("resize",r)}),h==null||h(),(b=m)==null||b.disconnect(),m=null,c&&cancelAnimationFrame(g)}}const bF=XB,_F=JB,yF=VB,wF=ZB,SF=GB,t1=KB,CF=QB,EF=(e,t,r)=>{const n=new Map,s={platform:vF,...r},i={...s.platform,_c:n};return qB(e,t,{...s,platform:i})};var kF=typeof document<"u",IF=function(){},eh=kF?p.useLayoutEffect:IF;function Lh(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let r,n,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!Lh(e[n],t[n]))return!1;return!0}if(s=Object.keys(e),r=s.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(t,s[n]))return!1;for(n=r;n--!==0;){const i=s[n];if(!(i==="_owner"&&e.$$typeof)&&!Lh(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function a5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function r1(e,t){const r=a5(e);return Math.round(t*r)/r}function sm(e){const t=p.useRef(e);return eh(()=>{t.current=e}),t}function l5(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:s,elements:{reference:i,floating:a}={},transform:l=!0,whileElementsMounted:c,open:u}=e,[d,h]=p.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=p.useState(n);Lh(f,n)||m(n);const[g,v]=p.useState(null),[x,b]=p.useState(null),_=p.useCallback(L=>{L!==y.current&&(y.current=L,v(L))},[]),C=p.useCallback(L=>{L!==N.current&&(N.current=L,b(L))},[]),S=i||g,w=a||x,y=p.useRef(null),N=p.useRef(null),E=p.useRef(d),k=c!=null,D=sm(c),j=sm(s),R=sm(u),I=p.useCallback(()=>{if(!y.current||!N.current)return;const L={placement:t,strategy:r,middleware:f};j.current&&(L.platform=j.current),EF(y.current,N.current,L).then(B=>{const M={...B,isPositioned:R.current!==!1};T.current&&!Lh(E.current,M)&&(E.current=M,Yr.flushSync(()=>{h(M)}))})},[f,t,r,j,R]);eh(()=>{u===!1&&E.current.isPositioned&&(E.current.isPositioned=!1,h(L=>({...L,isPositioned:!1})))},[u]);const T=p.useRef(!1);eh(()=>(T.current=!0,()=>{T.current=!1}),[]),eh(()=>{if(S&&(y.current=S),w&&(N.current=w),S&&w){if(D.current)return D.current(S,w,I);I()}},[S,w,I,D,k]);const A=p.useMemo(()=>({reference:y,floating:N,setReference:_,setFloating:C}),[_,C]),P=p.useMemo(()=>({reference:S,floating:w}),[S,w]),O=p.useMemo(()=>{const L={position:r,left:0,top:0};if(!P.floating)return L;const B=r1(P.floating,d.x),M=r1(P.floating,d.y);return l?{...L,transform:"translate("+B+"px, "+M+"px)",...a5(P.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:B,top:M}},[r,l,P.floating,d.x,d.y]);return p.useMemo(()=>({...d,update:I,refs:A,elements:P,floatingStyles:O}),[d,I,A,P,O])}const NF=e=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:e,fn(r){const{element:n,padding:s}=typeof e=="function"?e(r):e;return n&&t(n)?n.current!=null?t1({element:n.current,padding:s}).fn(r):{}:n?t1({element:n,padding:s}).fn(r):{}}}},c5=(e,t)=>{const r=bF(e);return{name:r.name,fn:r.fn,options:[e,t]}},u5=(e,t)=>{const r=_F(e);return{name:r.name,fn:r.fn,options:[e,t]}},d5=(e,t)=>({fn:CF(e).fn,options:[e,t]}),h5=(e,t)=>{const r=yF(e);return{name:r.name,fn:r.fn,options:[e,t]}},f5=(e,t)=>{const r=wF(e);return{name:r.name,fn:r.fn,options:[e,t]}},p5=(e,t)=>{const r=SF(e);return{name:r.name,fn:r.fn,options:[e,t]}},m5=(e,t)=>{const r=NF(e);return{name:r.name,fn:r.fn,options:[e,t]}};var RF="Arrow",g5=p.forwardRef((e,t)=>{const{children:r,width:n=10,height:s=5,...i}=e;return o.jsx(or.svg,{...i,ref:t,width:n,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});g5.displayName=RF;var jF=g5;function AF(e){const[t,r]=p.useState(void 0);return io(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const n=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const i=s[0];let a,l;if("borderBoxSize"in i){const c=i.borderBoxSize,u=Array.isArray(c)?c[0]:c;a=u.inlineSize,l=u.blockSize}else a=e.offsetWidth,l=e.offsetHeight;r({width:a,height:l})});return n.observe(e,{box:"border-box"}),()=>n.unobserve(e)}else r(void 0)},[e]),t}var wx="Popper",[v5,Mf]=bi(wx),[TF,x5]=v5(wx),b5=e=>{const{__scopePopper:t,children:r}=e,[n,s]=p.useState(null);return o.jsx(TF,{scope:t,anchor:n,onAnchorChange:s,children:r})};b5.displayName=wx;var _5="PopperAnchor",y5=p.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:n,...s}=e,i=x5(_5,r),a=p.useRef(null),l=wr(t,a),c=p.useRef(null);return p.useEffect(()=>{const u=c.current;c.current=(n==null?void 0:n.current)||a.current,u!==c.current&&i.onAnchorChange(c.current)}),n?null:o.jsx(or.div,{...s,ref:l})});y5.displayName=_5;var Sx="PopperContent",[DF,PF]=v5(Sx),w5=p.forwardRef((e,t)=>{var H,G,z,ee,V,re;const{__scopePopper:r,side:n="bottom",sideOffset:s=0,align:i="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:d=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,x=x5(Sx,r),[b,_]=p.useState(null),C=wr(t,oe=>_(oe)),[S,w]=p.useState(null),y=AF(S),N=(y==null?void 0:y.width)??0,E=(y==null?void 0:y.height)??0,k=n+(i!=="center"?"-"+i:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},j=Array.isArray(u)?u:[u],R=j.length>0,I={padding:D,boundary:j.filter(MF),altBoundary:R},{refs:T,floatingStyles:A,placement:P,isPositioned:O,middlewareData:L}=l5({strategy:"fixed",placement:k,whileElementsMounted:(...oe)=>o5(...oe,{animationFrame:m==="always"}),elements:{reference:x.anchor},middleware:[c5({mainAxis:s+E,alignmentAxis:a}),c&&u5({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?d5():void 0,...I}),c&&h5({...I}),f5({...I,apply:({elements:oe,rects:ce,availableWidth:be,availableHeight:ne})=>{const{width:Te,height:Ve}=ce.reference,Ge=oe.floating.style;Ge.setProperty("--radix-popper-available-width",`${be}px`),Ge.setProperty("--radix-popper-available-height",`${ne}px`),Ge.setProperty("--radix-popper-anchor-width",`${Te}px`),Ge.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),S&&m5({element:S,padding:l}),OF({arrowWidth:N,arrowHeight:E}),f&&p5({strategy:"referenceHidden",...I})]}),[B,M]=E5(P),$=oo(g);io(()=>{O&&($==null||$())},[O,$]);const U=(H=L.arrow)==null?void 0:H.x,F=(G=L.arrow)==null?void 0:G.y,K=((z=L.arrow)==null?void 0:z.centerOffset)!==0,[Y,te]=p.useState();return io(()=>{b&&te(window.getComputedStyle(b).zIndex)},[b]),o.jsx("div",{ref:T.setFloating,"data-radix-popper-content-wrapper":"",style:{...A,transform:O?A.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[(ee=L.transformOrigin)==null?void 0:ee.x,(V=L.transformOrigin)==null?void 0:V.y].join(" "),...((re=L.hide)==null?void 0:re.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(DF,{scope:r,placedSide:B,onArrowChange:w,arrowX:U,arrowY:F,shouldHideArrow:K,children:o.jsx(or.div,{"data-side":B,"data-align":M,...v,ref:C,style:{...v.style,animation:O?void 0:"none"}})})})});w5.displayName=Sx;var S5="PopperArrow",LF={top:"bottom",right:"left",bottom:"top",left:"right"},C5=p.forwardRef(function(t,r){const{__scopePopper:n,...s}=t,i=PF(S5,n),a=LF[i.placedSide];return o.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:o.jsx(jF,{...s,ref:r,style:{...s.style,display:"block"}})})});C5.displayName=S5;function MF(e){return e!==null}var OF=e=>({name:"transformOrigin",options:e,fn(t){var x,b,_;const{placement:r,rects:n,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[u,d]=E5(r),h={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+l/2,m=(((_=s.arrow)==null?void 0:_.y)??0)+c/2;let g="",v="";return u==="bottom"?(g=a?h:`${f}px`,v=`${-c}px`):u==="top"?(g=a?h:`${f}px`,v=`${n.floating.height+c}px`):u==="right"?(g=`${-c}px`,v=a?h:`${m}px`):u==="left"&&(g=`${n.floating.width+c}px`,v=a?h:`${m}px`),{data:{x:g,y:v}}}});function E5(e){const[t,r="center"]=e.split("-");return[t,r]}var Cx=b5,Ex=y5,k5=w5,I5=C5,Of="Popover",[N5]=bi(Of,[Mf]),Du=Mf(),[BF,bo]=N5(Of),R5=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:s,onOpenChange:i,modal:a=!1}=e,l=Du(t),c=p.useRef(null),[u,d]=p.useState(!1),[h,f]=Su({prop:n,defaultProp:s??!1,onChange:i,caller:Of});return o.jsx(Cx,{...l,children:o.jsx(BF,{scope:t,contentId:hi(),triggerRef:c,open:h,onOpenChange:f,onOpenToggle:p.useCallback(()=>f(m=>!m),[f]),hasCustomAnchor:u,onCustomAnchorAdd:p.useCallback(()=>d(!0),[]),onCustomAnchorRemove:p.useCallback(()=>d(!1),[]),modal:a,children:r})})};R5.displayName=Of;var j5="PopoverAnchor",FF=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=bo(j5,r),i=Du(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:l}=s;return p.useEffect(()=>(a(),()=>l()),[a,l]),o.jsx(Ex,{...i,...n,ref:t})});FF.displayName=j5;var A5="PopoverTrigger",T5=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=bo(A5,r),i=Du(r),a=wr(t,s.triggerRef),l=o.jsx(or.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":O5(s.open),...n,ref:a,onClick:st(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?l:o.jsx(Ex,{asChild:!0,...i,children:l})});T5.displayName=A5;var kx="PopoverPortal",[$F,zF]=N5(kx,{forceMount:void 0}),D5=e=>{const{__scopePopover:t,forceMount:r,children:n,container:s}=e,i=bo(kx,t);return o.jsx($F,{scope:t,forceMount:r,children:o.jsx(Gs,{present:r||i.open,children:o.jsx(Nf,{asChild:!0,container:s,children:n})})})};D5.displayName=kx;var pl="PopoverContent",P5=p.forwardRef((e,t)=>{const r=zF(pl,e.__scopePopover),{forceMount:n=r.forceMount,...s}=e,i=bo(pl,e.__scopePopover);return o.jsx(Gs,{present:n||i.open,children:i.modal?o.jsx(HF,{...s,ref:t}):o.jsx(WF,{...s,ref:t})})});P5.displayName=pl;var UF=hl("PopoverContent.RemoveScroll"),HF=p.forwardRef((e,t)=>{const r=bo(pl,e.__scopePopover),n=p.useRef(null),s=wr(t,n),i=p.useRef(!1);return p.useEffect(()=>{const a=n.current;if(a)return jf(a)},[]),o.jsx(Eu,{as:UF,allowPinchZoom:!0,children:o.jsx(L5,{...e,ref:s,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:st(e.onCloseAutoFocus,a=>{var l;a.preventDefault(),i.current||(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:st(e.onPointerDownOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:st(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),WF=p.forwardRef((e,t)=>{const r=bo(pl,e.__scopePopover),n=p.useRef(!1),s=p.useRef(!1);return o.jsx(L5,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(n.current||(l=r.triggerRef.current)==null||l.focus(),i.preventDefault()),n.current=!1,s.current=!1},onInteractOutside:i=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=i.target;((u=r.triggerRef.current)==null?void 0:u.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),L5=p.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onInteractOutside:d,...h}=e,f=bo(pl,r),m=Du(r);return sx(),o.jsx(If,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:i,children:o.jsx(Cu,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:d,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:o.jsx(k5,{"data-state":O5(f.open),role:"dialog",id:f.contentId,...m,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),M5="PopoverClose",qF=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=bo(M5,r);return o.jsx(or.button,{type:"button",...n,ref:t,onClick:st(e.onClick,()=>s.onOpenChange(!1))})});qF.displayName=M5;var KF="PopoverArrow",VF=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=Du(r);return o.jsx(I5,{...s,...n,ref:t})});VF.displayName=KF;function O5(e){return e?"open":"closed"}var GF=R5,YF=T5,XF=D5,B5=P5;const Ix=GF,Nx=YF,Bf=p.forwardRef(({className:e,align:t="center",sideOffset:r=8,...n},s)=>{const i=hr(s,"intersection");return o.jsx(XF,{children:o.jsx(B5,{ref:i,align:t,sideOffset:r,className:Xe("z-50 w-56 rounded-2xl border border-border/60 bg-popover/95 p-1.5 text-popover-foreground shadow-[0_24px_80px_-36px_rgba(17,24,39,0.8)] outline-none backdrop-blur-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...n})})});Bf.displayName=B5.displayName;function F5(e){return{minimal:"极低",low:"低",medium:"中",high:"高",xhigh:"很高",max:"最大",ultra:"极限"}[e]??e}function JF({models:e,model:t,effort:r,summary:n,label:s,disabled:i,allowDefaultEffort:a=!1,onChange:l}){const[c,u]=p.useState(!1),[d,h]=p.useState(null),f=e.find(g=>g.id===d),m=g=>{f&&(l(f.id,g),u(!1))};return o.jsxs(Ix,{open:c,onOpenChange:g=>{u(g),h(null)},children:[o.jsx(Nx,{asChild:!0,children:o.jsxs(Z,{type:"button",variant:"outline",disabled:i,"aria-label":`${s}:${n}`,className:"w-full justify-between",children:[o.jsx("span",{className:"truncate",children:n}),o.jsx(dE,{"data-icon":"inline-end"})]})}),o.jsxs(Bf,{align:"start",className:"w-80 max-w-[calc(100vw-2rem)]","aria-label":f?"选择推理强度":"选择模型版本",children:[o.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[f&&o.jsx(Z,{type:"button",variant:"ghost",size:"icon","aria-label":"返回模型列表",onClick:()=>h(null),children:o.jsx(xi,{})}),o.jsx("span",{className:"text-sm font-medium",children:f?`${f.label} · 推理强度`:"选择模型版本"})]}),o.jsx("div",{className:"flex max-h-72 flex-col gap-1 overflow-y-auto",children:f?o.jsxs(o.Fragment,{children:[a&&o.jsxs(Z,{type:"button",variant:"ghost",className:"justify-between",onClick:()=>m(""),children:["模型默认强度",t===f.id&&!r&&o.jsx(di,{})]}),f.reasoningEfforts.map(g=>o.jsxs(Z,{type:"button",variant:"ghost",className:"justify-between","aria-pressed":t===f.id&&r===g,onClick:()=>m(g),children:[o.jsxs("span",{children:[F5(g)," · ",g,g===f.defaultReasoningEffort?"(模型默认)":""]}),t===f.id&&r===g&&o.jsx(di,{})]},g)),!f.reasoningEfforts.length&&!a&&o.jsx("p",{className:"p-2 text-sm text-muted-foreground",children:"此模型暂无可选推理强度"})]}):e.map(g=>o.jsxs(Z,{type:"button",variant:"ghost",className:"h-auto justify-between py-2",onClick:()=>h(g.id),children:[o.jsxs("span",{className:"flex min-w-0 flex-col items-start gap-1",children:[o.jsx("span",{className:"truncate",children:g.label}),o.jsx("span",{className:"truncate text-xs text-muted-foreground",children:g.id})]}),t===g.id?o.jsx(di,{}):o.jsx(Jr,{})]},g.id))},d??"models")]})]})}function QF({field:e,model:t,effort:r,defaultEffort:n,catalog:s,loading:i,disabled:a,onRetry:l,onChange:c}){const u=e.modelSelection,d=((s==null?void 0:s.availability)==="available"?s.models:[]).map(x=>({...x,reasoningEfforts:x.reasoningEfforts.filter(b=>!u.allowedEfforts||u.allowedEfforts.includes(b))})),h="value"in e.default?e.default.value:null,f=t||(typeof h=="string"?h:""),m=r||n,g=d.find(x=>x.id===f),v=`${(g==null?void 0:g.label)??(f||"未选择模型")} · ${m?F5(m):"模型默认强度"}`;return o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(JF,{models:d,model:f,effort:m,summary:v,label:u.label,disabled:a||!d.length||i,allowDefaultEffort:u.allowDefaultEffort,onChange:c}),i?o.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"正在加载模型…"}):d.length?o.jsxs(o.Fragment,{children:[(s==null?void 0:s.source)==="cache"&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["正在使用此电脑缓存的模型目录。",o.jsx(Z,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:l,children:"刷新"})]}),t&&(!g||r&&!g.reasoningEfforts.includes(r))&&o.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"已保存的模型或推理强度不在当前目录中,保留原值;可重新选择。"})]}):o.jsxs("div",{role:"status",className:"text-xs text-muted-foreground",children:["模型目录暂不可用,已有配置仍会保留。",o.jsx(Z,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:l,children:"重试"})]}),o.jsx(Z,{type:"button",variant:"ghost",size:"sm",className:"self-start",disabled:a,onClick:()=>c(null,null),children:"恢复默认"})]})}const n1={applied:"已生效",restartRequired:"等待所属服务重启",error:"配置错误",unconfigured:"未配置"};function ZF({apiBase:e,token:t,embedded:r=!1,onAuthExpired:n}){const[s,i]=p.useState(null),[a,l]=p.useState({}),[c,u]=p.useState(null),[d,h]=p.useState(!1),[f,m]=p.useState(null),[g,v]=p.useState(!1),x=p.useRef(null),b=W(async()=>{var y;if(!t)return;(y=x.current)==null||y.abort();const w=new AbortController;x.current=w,v(!0);try{const N=await Yk(e,t,w.signal);w.signal.aborted||m(N)}catch{}finally{w.signal.aborted||v(!1)}}),_=s!==null;p.useEffect(()=>{_&&t&&b()},[_,t,b]),p.useEffect(()=>()=>{var w;return(w=x.current)==null?void 0:w.abort()},[]);const C=p.useRef(null);p.useEffect(()=>()=>{var w;return(w=C.current)==null?void 0:w.abort()},[]);const S=W(async(w=!1)=>{var N;if(!t||d||!w&&Object.keys(a).length&&!window.confirm("放弃未保存的修改并重新读取?"))return;(N=C.current)==null||N.abort();const y=new AbortController;C.current=y,h(!0),u(null);try{let E;if(w&&(s==null?void 0:s.savedRevision)!=null&&s.digest){const D={};for(const[j,R]of Object.entries(a)){const I=s.fields.find(T=>T.path===j);if(!I)throw new Error("字段列表已变化,请重新加载。");D[j]=e$(I,R)}E={expectedRevision:s.savedRevision,expectedDigest:s.digest,expectedEnvironment:s.environment,changes:D}}const k=await DB(e,t,y.signal,E);if(y.signal.aborted)return;if(s&&(k.environment.kind!==s.environment.kind||k.environment.instanceId!==s.environment.instanceId))throw new Error("连接实例已变化,请关闭并重新打开配置。");i(k),l({})}catch(E){y.signal.aborted||(E instanceof De&&E.status===401&&(n==null||n()),u(E instanceof Error?E.message:"配置操作失败"))}finally{y.signal.aborted||h(!1)}});return va(r&&Object.keys(a).length>0,r&&d&&Object.keys(a).length>0),p.useEffect(()=>{r&&S()},[r,S]),o.jsxs("details",{open:r?!0:void 0,className:r?"rounded-md border border-border p-3":"rounded-xl border border-border p-4",children:[o.jsx("summary",{className:"cursor-pointer font-medium",children:"当前连接电脑的配置"}),o.jsxs("div",{className:"mt-3 space-y-4",children:[o.jsx("p",{className:"break-all text-xs text-muted-foreground",children:e||window.location.origin}),o.jsx(Z,{variant:"secondary",size:"sm",disabled:d||!t,onClick:()=>void S(),children:"加载配置"}),!t&&o.jsx("p",{children:"登录后可管理当前连接的配置。"}),c&&o.jsx("p",{role:"alert",className:"text-sm text-red-500",children:c}),s&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-xs",children:[s.environment.kind==="stable"?"Stable":"Dev Session"," · ",s.environment.instanceId," · 保存版本 ",s.savedRevision??"不可读取"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"输入框编辑保存值,默认值不会自动写入。应用状态来自当前连接的服务,不代表其他服务或业务连接已验证可用。"}),s.diskError&&o.jsx("p",{role:"alert",children:"磁盘配置无法读取,请在当前电脑运行 rw config doctor。"}),[...new Set(s.fields.filter(w=>!w.path.includes("<")).map(w=>w.domain))].map(w=>o.jsxs("details",{className:"rounded-lg border border-border p-3",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:TB[w]??w}),o.jsx("div",{className:"mt-3 space-y-3",children:s.fields.filter(y=>y.domain===w&&!y.path.includes("<")&&!s.fields.some(N=>{var E;return((E=N.modelSelection)==null?void 0:E.effortPath)===y.path})).map(y=>{var I;const N=Object.hasOwn(a,y.path),E=N?a[y.path]:s.values[y.path],k=E==null?"":typeof E=="string"?E:JSON.stringify(E),D=s.consumers[y.domain],j=(I=s.fieldStates)==null?void 0:I[y.path],R=s.fields.find(T=>{var A;return T.path===((A=y.modelSelection)==null?void 0:A.effortPath)});if(y.modelSelection&&R){const T=Object.hasOwn(a,R.path),A=T?a[R.path]:s.values[R.path];return o.jsxs("div",{className:"flex flex-col gap-2 border-b border-border/60 pb-3",children:[o.jsx("p",{className:"text-sm",children:y.modelSelection.label}),o.jsx("p",{className:"text-xs text-muted-foreground",children:y.description}),[y,R].map(P=>{var L;const O=(L=s.fieldStates)==null?void 0:L[P.path];return O?o.jsxs("div",{children:[o.jsx("p",{className:"text-xs",children:P.path===y.path?"模型":"推理强度"}),o.jsx(qy,{field:P,status:O,changed:N||T})]},P.path):null}),!j&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:[D?n1[D.state]:"状态未知",(D==null?void 0:D.appliedRevision)!=null?` · 生效版本 ${D.appliedRevision}`:""]}),o.jsx(QF,{field:y,model:typeof E=="string"?E:"",effort:typeof A=="string"?A:"",defaultEffort:"value"in R.default&&typeof R.default.value=="string"?R.default.value:"",catalog:f==null?void 0:f.catalogs[y.modelSelection.provider],loading:g,disabled:d,onRetry:()=>void b(),onChange:(P,O)=>l(L=>({...L,[y.path]:P,[R.path]:O}))})]},y.path)}return o.jsxs("div",{className:"space-y-1 border-b border-border/60 pb-3",children:[o.jsx("label",{className:"text-sm",htmlFor:`config-${y.path}`,children:y.description}),j?o.jsx(qy,{field:y,status:j,changed:N}):o.jsxs("p",{className:"text-xs text-muted-foreground",children:[D?n1[D.state]:"状态未知",(D==null?void 0:D.appliedRevision)!=null?` · 生效版本 ${D.appliedRevision}`:""," · 当前服务未提供字段来源"]}),y.sensitive?o.jsxs(o.Fragment,{children:[o.jsxs("select",{disabled:d,"aria-label":`${y.description}操作`,className:"h-9 w-full rounded border bg-background px-2 text-sm",value:N?a[y.path]===null?"delete":"replace":"keep",onChange:T=>l(A=>{const P={...A};return T.target.value==="keep"?delete P[y.path]:P[y.path]=T.target.value==="delete"?null:"",P}),children:[o.jsx("option",{value:"keep",children:s.values[`${y.path}.configured`]?"已配置,保留现有值":"未配置,保持不变"}),o.jsx("option",{value:"replace",children:"替换"}),o.jsx("option",{value:"delete",children:"删除"})]}),N&&a[y.path]!==null&&o.jsx(sr,{disabled:d,id:`config-${y.path}`,type:"password",autoComplete:"new-password",value:a[y.path]??"",onChange:T=>l(A=>({...A,[y.path]:T.target.value}))})]}):o.jsx(sr,{disabled:d,id:`config-${y.path}`,value:k,placeholder:"value"in y.default&&y.default.value!=null?String(y.default.value):"未设置",onChange:T=>l(A=>({...A,[y.path]:T.target.value}))}),!y.sensitive&&o.jsx("p",{className:"text-[11px] text-muted-foreground",children:y.type==="boolean"?"填写 true 或 false":y.type.startsWith("array")?'填写 JSON 数组,例如 ["id1", "id2"]':"留空恢复默认值"}),!y.sensitive&&o.jsx(Z,{size:"sm",variant:"ghost",disabled:d,onClick:()=>l(T=>({...T,[y.path]:null})),children:"恢复默认"})]},y.path)})})]},w)),o.jsx(Z,{variant:"ghost",disabled:d||!Object.keys(a).length,onClick:()=>l({}),children:"取消修改"}),o.jsx(Z,{disabled:d||!Object.keys(a).length||s.savedRevision==null||!!s.diskError,onClick:()=>void S(!0),children:d?"处理中…":"保存配置"})]})]})]})}function e$(e,t){if(t===null||!e.sensitive&&t==="")return null;if(e.sensitive&&!t)throw new Error("替换凭据时请填写新值;删除请使用删除选项。");if(e.type==="string")return t;if(e.type==="boolean"&&!["true","false"].includes(t))throw new Error(`${e.description}需要 true 或 false。`);try{return JSON.parse(t)}catch{throw new Error(`${e.description}格式不正确。`)}}function t$({embedded:e=!1}){var u;const[t,r]=p.useState(null),[n,s]=p.useState(null),[i,a]=p.useState(!1),l=p.useRef(!0);p.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const c=W(async()=>{var d,h;a(!0),s(null);try{const f=await((h=(d=window.electronAPI)==null?void 0:d.getLocalConfigurationStatus)==null?void 0:h.call(d));l.current&&f&&r(f)}catch{l.current&&s("无法读取本台桌面的配置状态。")}finally{l.current&&a(!1)}});return p.useEffect(()=>{e&&c()},[e,c]),(u=window.electronAPI)!=null&&u.getLocalConfigurationStatus?o.jsxs("details",{open:e?!0:void 0,className:e?"rounded-md border border-border p-3":"rounded-xl border border-border p-4",children:[o.jsx("summary",{className:"cursor-pointer font-medium",children:"本台桌面的配置状态"}),o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[o.jsx("p",{children:"浏览器、远程访问和伴随窗口由本台桌面管理。"}),o.jsx(Z,{size:"sm",variant:"secondary",disabled:i,onClick:()=>void c(),children:"刷新桌面状态"}),n&&o.jsx("p",{role:"alert",children:n}),t&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:[t.environment.kind==="stable"?"Stable":"Dev Session"," · ",t.environment.instanceId," · 保存版本 ",t.savedRevision??"不可读取"]}),t.diskError&&o.jsx("p",{role:"alert",children:"磁盘配置无法读取,当前进程仍保留已采用的配置。"}),Object.entries(t.consumers).map(([d,h])=>o.jsxs("p",{className:"break-all",children:[d,":",h.state==="error"?"配置错误":h.state==="applied"?"已生效":h.state==="unconfigured"?"未配置":"等待所属功能重新加载或重启",h.appliedRevision!==null&&` · 生效版本 ${h.appliedRevision}`]},d))]})]})]}):null}const r$=2e3;function n$(){const[e,t]=p.useState(null),[r,n]=p.useState(null);return p.useEffect(()=>{var c,u;const s=(c=window.electronAPI)==null?void 0:c.getRuntimeStats;if(((u=window.electronAPI)==null?void 0:u.isElectron)!==!0||!s)return;let i=!1,a=null;const l=async()=>{try{const d=await s();if(i)return;t(d),n(null)}catch(d){if(i)return;n(String(d))}finally{i||(a=window.setTimeout(()=>{l()},r$))}};return l(),()=>{i=!0,a!==null&&window.clearTimeout(a)}},[]),{snapshot:e,error:r}}const Pu=lx,s$=Dk,i$=cx,$5=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"window");return o.jsx(ku,{ref:n,className:Xe("fixed inset-0 z-50 bg-slate-950/40 backdrop-blur-[1px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t})});$5.displayName=ku.displayName;const o$={top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",right:"right-0 top-0 h-full border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"left-0 top-0 h-full border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left"},Il=p.forwardRef(({side:e="right",showOverlay:t=!0,overlayClassName:r,hideClose:n=!1,className:s,children:i,...a},l)=>{const c=hr(l,"intersection");return o.jsxs(i$,{children:[t?o.jsx($5,{className:r}):null,o.jsxs(Cl,{ref:c,className:Xe("fixed z-50 flex flex-col gap-4 border-border/60 bg-background p-6 text-foreground shadow-[0_28px_90px_-40px_rgba(15,23,42,0.82)] transition ease-out data-[state=open]:animate-in data-[state=closed]:animate-out",o$[e],s),...a,children:[i,n?null:o.jsxs(Ru,{className:"absolute top-4 right-4 inline-flex h-8 w-8 items-center justify-center rounded-md border border-border/60 text-muted-foreground transition-colors hover:border-border hover:text-foreground focus:outline-none",children:[o.jsx(vo,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Il.displayName=Cl.displayName;function Ff({className:e,...t}){return o.jsx("div",{className:Xe("flex flex-col gap-1.5",e),...t})}const Nl=p.forwardRef(({className:e,...t},r)=>o.jsx(Iu,{ref:r,className:Xe("text-base font-semibold",e),...t}));Nl.displayName=Iu.displayName;const Rl=p.forwardRef(({className:e,...t},r)=>o.jsx(Nu,{ref:r,className:Xe("text-sm text-muted-foreground",e),...t}));Rl.displayName=Nu.displayName;const a$={node:"节点连接",terminal:"Terminal",feishu:"飞书接入","app-server":"App Server","workspace-services":"Workspace Services",desktop:"Desktop","background-tasks":"后台任务","research-mcp":"调查 MCP"},Rx={healthy:"正常",recovering:"恢复中",unhealthy:"异常",blocked:"无法判断",checking:"检查中",unconfigured:"未配置",disabled:"已停用",unsupported:"版本不支持"},jx={unhealthy:"bg-red-500",recovering:"bg-amber-500",checking:"bg-slate-400",blocked:"bg-slate-400",healthy:"bg-emerald-500",unconfigured:"bg-slate-400",disabled:"bg-slate-400",unsupported:"bg-slate-400"};function l$(e){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(e)}function z5(e){return e.some(t=>t.id==="frontend.node.http"&&t.state==="healthy")&&e.some(t=>t.id==="frontend.node.auth"&&t.state==="blocked")}function c$({item:e}){const t=Cr(),r=$k(e.capabilityId,e.state),n=W(async s=>{await mx(s)});return o.jsxs("div",{className:"rounded-lg border border-border/60 bg-background/60 p-3","data-runtime-status-item":e.id,"data-runtime-status-state":e.state,children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-sm font-medium",children:e.label}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:e.summary})]}),o.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${r==="warning"?"bg-amber-500":jx[e.state]}`}),Rx[e.state]]})]}),e.recovery?o.jsx("p",{className:"mt-2 text-[11px] text-amber-700 dark:text-amber-300",children:e.recovery.attempt===null?"正在按 owner 恢复策略重试":`重试 ${e.recovery.attempt}${e.recovery.maxAttempts===null?"":` / ${e.recovery.maxAttempts}`}`}):null,e.dependsOn.length>0&&e.state==="blocked"?o.jsxs("p",{className:"mt-2 text-[11px] text-muted-foreground",children:["上游:",e.dependsOn.join("、")]}):null,e.facts.length>0?o.jsx("div",{className:"mt-2 space-y-1",children:e.facts.map(s=>o.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[o.jsx("span",{className:"text-muted-foreground",children:s.label}),o.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[o.jsx("span",{className:"truncate font-mono",children:s.value}),s.copyable?o.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`复制${s.label}`,onClick:()=>void n(s.value),children:o.jsx(go,{className:"h-3 w-3"})}):null]})]},s.id))}):null,o.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px] text-muted-foreground/80",children:[o.jsxs("span",{children:["更新于 ",l$(e.observedAt)]}),e.id.includes("electron.remote-access:")?o.jsx("button",{type:"button",className:"text-xs underline",onClick:()=>Xr.getState().setOpen(!0),children:"管理远程访问"}):null,e.navigation?o.jsxs("button",{type:"button",className:"inline-flex items-center gap-0.5 hover:text-foreground",onClick:()=>t(e.navigation.route),children:[e.navigation.label,o.jsx(Jr,{className:"h-3 w-3"})]}):null]})]})}function u$({capability:e}){const t=e.attention,[r,n]=p.useState(t!=="none"),s=z5(e.items);return o.jsxs("section",{className:"overflow-hidden rounded-xl border border-border/70","data-runtime-status-attention":t,"data-runtime-status-capability":e.capabilityId,"data-runtime-status-state":e.state,children:[o.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 bg-muted/30 px-4 py-3 text-left","aria-expanded":r,onClick:()=>n(i=>!i),children:[o.jsx("span",{className:"text-sm font-medium",children:a$[e.capabilityId]}),o.jsxs("span",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${t==="warning"?"bg-amber-500":jx[e.state]}`}),e.state==="blocked"&&s?"待登录":t==="warning"?"Warning":Rx[e.state],o.jsx(Jr,{className:`h-3.5 w-3.5 transition ${r?"rotate-90":""}`})]})]}),r?o.jsx("div",{className:"space-y-2 border-t border-border/60 p-3",children:e.items.map(i=>o.jsx(c$,{item:i},i.id))}):null]})}function d$(){var i;const e=Cr(),{snapshot:t,error:r}=n$();if(((i=window.electronAPI)==null?void 0:i.isElectron)!==!0)return null;const n=t?t.electron.totalCpuPercent+(t.backend.cpuPercent??0):null,s=t?t.electron.totalMemoryMb+(t.backend.memoryMb??0):null;return o.jsxs("div",{className:"rounded-xl border border-border/70 p-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium",children:"资源摘要"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["CPU ",n===null?"--":`${n.toFixed(1)}%`," · RAM ",s??"--"," MB"]})]}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:()=>e("/system-monitor"),children:"System Monitor"})]}),r?o.jsx("p",{className:"mt-2 text-xs text-amber-600",children:r}):null]})}function h$({apiBase:e,token:t,embedded:r=!1}){const{nodes:n,panelOpen:s,setPanelOpen:i,refresh:a,refreshing:l}=Au(),c=p.useRef(null),u=W(async m=>{await mx(m)}),d=r?"h2":Nl,h=r?"p":Rl,f=o.jsxs(o.Fragment,{children:[o.jsx(Ff,{className:r?"border-b border-border/70 px-3 py-2":"border-b border-border/70 px-6 py-5 pr-14",children:o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx(d,{children:"运行状态"}),o.jsx(h,{children:"当前依赖、恢复状态与最近证据"})]}),o.jsxs(Z,{variant:"secondary",size:"sm",disabled:l,onClick:()=>void a(),children:[o.jsx(Ws,{className:l?"animate-spin":""}),l?"检查中":"重新检查"]})]})}),o.jsxs("div",{className:r?"min-h-0 flex-1 space-y-3 overflow-y-auto py-3":"min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4 sm:px-6",children:[!r&&o.jsx(ZF,{apiBase:e,token:t},`${e}:${t??""}`),!r&&o.jsx(t$,{}),o.jsx(kB,{}),n.map(m=>{const g=m.capabilities.some(v=>z5(v.items));return o.jsxs("article",{className:"space-y-3 rounded-2xl border border-border/70 bg-card/60 p-4","data-runtime-status-node":m.id,children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("h2",{className:"font-semibold",children:m.roles.includes("local")?"本机节点":"连接节点"}),m.roles.map(v=>o.jsx("span",{className:"rounded-full border border-border px-2 py-0.5 text-[10px] text-muted-foreground",children:v==="local"?"本机":"当前连接"},v))]}),o.jsxs("button",{type:"button",className:"mt-1 inline-flex max-w-full items-center gap-1 font-mono text-xs text-muted-foreground hover:text-foreground","aria-label":`${m.roles.includes("local")?"复制本机":"复制当前连接"}地址`,onClick:()=>void u(m.address),children:[o.jsx("span",{className:"truncate",children:m.address}),o.jsx(go,{className:"h-3 w-3 shrink-0"})]})]}),o.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${m.unhealthyCapabilityCount>0?"bg-red-500":m.warningCapabilityCount>0?"bg-amber-500":jx[m.state]}`}),m.unhealthyCapabilityCount>0?"异常":m.warningCapabilityCount>0?"Warning":m.state==="blocked"&&g?"待登录":Rx[m.state]]})]}),g?o.jsx("p",{className:"text-sm text-muted-foreground",children:"服务可连接,登录后查看详细状态。"}):null,o.jsx(AB,{reports:m.reports}),o.jsx(CB,{items:m.capabilities.flatMap(v=>v.items)}),o.jsx("div",{className:"space-y-2",children:m.capabilities.map(v=>o.jsx(u$,{capability:v},v.capabilityId))}),m.roles.includes("local")?o.jsx(d$,{}):null]},m.id)}),n.length===0?o.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"正在检查运行状态…"}):null]})]});return r?o.jsx("section",{className:"space-y-4",children:f}):o.jsx(Pu,{open:s,onOpenChange:i,children:o.jsx(Il,{className:"w-[min(92vw,42rem)] overflow-hidden p-0 sm:max-w-[42rem]",onOpenAutoFocus:()=>{c.current=document.activeElement instanceof HTMLElement?document.activeElement:null},onCloseAutoFocus:m=>{const g=c.current;c.current=null,g!=null&&g.isConnected&&(m.preventDefault(),g.focus({preventScroll:!0}))},children:f})})}const f$=3e3;function U5(e,t){return`${e.replace(/\/+$/u,"")}${t}`}async function H5(e,t){const r=new AbortController,n=window.setTimeout(()=>r.abort(),f$);try{return await fetch(e,{...t,signal:r.signal})}finally{window.clearTimeout(n)}}function W5(e){return e instanceof DOMException&&e.name==="AbortError"?"timeout":"network"}async function p$(e){try{const t=await H5(U5(e,"/health"));return t.ok?{kind:"ok",payload:await t.json()}:{kind:"network"}}catch(t){return{kind:W5(t)}}}async function m$(e,t){try{const r=await H5(U5(e,"/api/runtime-status"),{headers:{Authorization:`Bearer ${t}`}});if(r.status===401)return{kind:"unauthorized"};if(r.status===404)return{kind:"unsupported"};if(!r.ok)return{kind:"network"};const n=await r.json();return n.protocolVersion!==1?{kind:"unsupported"}:{kind:"ok",snapshot:n}}catch(r){return{kind:W5(r)}}}const q5=15e3;function g$(e){switch(e){case"missing-auth":return"当前节点没有可用登录会话";case"unauthorized":return"当前登录会话已失效";case"unsupported":return"当前 Backend 版本不支持详细运行状态";case"timeout":return"详细运行状态请求超时";case"network":return"详细运行状态暂时不可用";case"ok":return"详细运行状态可用"}}function v$(e,t){const r=e.health.kind==="ok"?"healthy":e.failureCount>=2||e.failureSince!==null&&e.observedAt-e.failureSince>=1e4?"unhealthy":"recovering",n=e.status.kind==="ok"?"healthy":e.status.kind==="unauthorized"?"unhealthy":e.status.kind==="unsupported"?"unsupported":e.status.kind==="missing-auth"?"blocked":"recovering",s=e.failureSince??e.observedAt,i=[{id:"frontend.node.http",capabilityId:"node",label:"节点连接",state:r,summary:r==="healthy"?"Backend HTTP 可用":r==="recovering"?"Backend HTTP 正在恢复":"Backend HTTP 持续不可达",observedAt:e.observedAt,dependsOn:[],recovery:r==="healthy"?null:{startedAt:s,attempt:e.failureCount,maxAttempts:2,nextAttemptAt:null,deadlineAt:s+1e4},facts:[{id:"frontend.node.address",label:"连接地址",value:e.address,kind:"address",copyable:!0}],navigation:null},{id:"frontend.node.auth",capabilityId:"node",label:"节点鉴权",state:n,summary:g$(e.status.kind),observedAt:e.observedAt,dependsOn:["frontend.node.http"],recovery:null,facts:[],navigation:null}];return{protocolVersion:1,target:{kind:"node",nodeId:t},source:{id:"frontend",runtime:"frontend",instanceId:"frontend:renderer",capabilityId:"node"},observedAt:e.observedAt,validForMs:q5,items:i}}function x$(e,t){return e?e.reports.map(r=>zk({...r,items:r.items.map(n=>({...n,dependsOn:Array.from(new Set(["frontend.node.http","frontend.node.auth",...n.dependsOn]))}))},t)):[]}function im(e,t){const r=new Map(e.map(n=>[n.source.id,n]));for(const n of t){const s=r.get(n.source.id);(!s||n.observedAt>=s.observedAt)&&r.set(n.source.id,n)}return[...r.values()]}function s1(e){const t=e==null?void 0:e.items.flatMap(r=>r.facts).find(r=>r.id==="electron.local-network.primary");return(t==null?void 0:t.value)??null}function b$(e){const t=new Map;for(const s of e.endpoints){const i=s.status.kind==="ok"?s.status.snapshot:s.lastSnapshot,a=s.health.kind==="ok"?s.health.payload.serviceInstanceId??(i==null?void 0:i.node.serviceInstanceId)??null:(i==null?void 0:i.node.serviceInstanceId)??null,l=a??`connection:${bB(s.address)}`,c=v$(s,l),u=x$(i,l),d=t.get(l),h=im((d==null?void 0:d.reports)??[],[c,...u]);t.set(l,{id:l,serviceInstanceId:a,address:s.roles.includes("current")||!d?s.address:d.address,roles:Array.from(new Set([...(d==null?void 0:d.roles)??[],...s.roles])),reports:h,capabilities:[],state:"checking",unhealthyCapabilityCount:0,warningCapabilityCount:0,generatedAt:s.observedAt})}let r=[...t.values()].find(s=>s.roles.includes("local"));if(!r&&e.electronReport){const s="local-host";r={id:s,serviceInstanceId:null,address:s1(e.electronReport)??"仅本机可用",roles:["local"],reports:[],capabilities:[],state:"checking",unhealthyCapabilityCount:0,warningCapabilityCount:0,generatedAt:e.electronReport.observedAt},t.set(s,r)}if(r&&e.electronReport){const s=e.endpoints.find(a=>a.roles.includes("local")),i=s&&s.health.kind!=="ok"?{...e.electronReport,items:e.electronReport.items.map(a=>a.id==="electron.packaged-backend"?{...a,state:"blocked",summary:"节点连接不可用,Backend 状态由上游根因表达",dependsOn:Array.from(new Set(["frontend.node.http",...a.dependsOn])),recovery:null}:a)}:e.electronReport;r.reports=im(r.reports,[zk(i,r.id)]),r.address=s1(e.electronReport)??"仅本机可用",r.generatedAt=Math.max(r.generatedAt,e.electronReport.observedAt)}const n=[...t.values()].find(s=>s.roles.includes("current"));if(n&&e.frontendItems.length>0){const s={protocolVersion:1,target:{kind:"node",nodeId:n.id},source:{id:"frontend-live",runtime:"frontend",instanceId:"frontend-live",capabilityId:"terminal"},observedAt:Math.max(...e.frontendItems.map(i=>i.observedAt)),validForMs:q5,items:e.frontendItems};n.reports=im(n.reports,[s])}return[...t.values()].map(s=>{const i=Uk(s.reports);return{...s,capabilities:i,state:px(i.map(a=>a.state)),unhealthyCapabilityCount:i.filter(a=>a.attention==="error").length,warningCapabilityCount:i.filter(a=>a.attention==="warning").length}})}const _$=5e3,y$=15e3;function th(e){const t=e||window.location.origin;try{return new URL(t,window.location.origin).origin}catch{return t.replace(/\/+$/u,"")}}function i1(e,t){const r=th(t.apiBase),n=e.get(r);if(!n){e.set(r,{...t,endpointKey:r});return}e.set(r,{...n,roles:Array.from(new Set([...n.roles,...t.roles])),token:t.roles.includes("current")?t.token:n.token})}function o1(e,t){const r=Date.now();return{protocolVersion:1,target:{kind:"local-host"},source:{id:"electron",runtime:"electron",instanceId:"electron:renderer-bridge",capabilityId:"desktop"},observedAt:r,validForMs:15e3,items:[{id:"electron.process",capabilityId:"desktop",label:"Electron process",state:e,summary:t,observedAt:r,dependsOn:[],recovery:null,facts:[],navigation:null}]}}function K5({apiBase:e,token:t,connections:r,isElectron:n,children:s}){const[i,a]=p.useState([]),[l,c]=p.useState(null),[u,d]=p.useState(new Map),[h,f]=p.useState(!1),[m,g]=p.useState(!1),v=p.useRef(i),x=p.useRef(null);v.current=i;const b=p.useMemo(()=>{const j=new Map;if(n){const R=r.find(I=>I.id===Vn);if(R!=null&&R.url){const I=yl(R.id);i1(j,{apiBase:R.url,address:th(R.url),roles:["local"],token:(I==null?void 0:I.accessToken)??(I==null?void 0:I.token)??null})}}return(e||!n)&&i1(j,{apiBase:e,address:th(e),roles:["current"],token:t}),[...j.values()]},[e,r,n,t]),_=W(()=>{if(x.current)return x.current;f(!0);const j=(async()=>{var A;const R=new Map(v.current.map(P=>[P.endpointKey,P])),I=await Promise.all(b.map(async P=>{const O=R.get(P.endpointKey),[L,B]=await Promise.all([p$(P.apiBase),P.token?m$(P.apiBase,P.token):Promise.resolve({kind:"missing-auth"})]),M=Date.now(),$=L.kind!=="ok";return{...P,health:L,status:B,lastSnapshot:B.kind==="ok"?B.snapshot:(O==null?void 0:O.lastSnapshot)??null,failureSince:$?(O==null?void 0:O.failureSince)??M:null,failureCount:$?((O==null?void 0:O.failureCount)??0)+1:0,observedAt:M}}));let T=null;if(n){const P=(A=window.electronAPI)==null?void 0:A.getRuntimeStatusReport;if(!P)T=o1("unsupported","当前 Desktop 版本不支持运行状态协议");else try{T=await P()}catch{T=o1("unhealthy","Electron 状态桥接不可用")}}a(I),c(T)})();return x.current=j.finally(()=>{x.current=null,f(!1)}),x.current});p.useEffect(()=>{let j=!1,R=null;const I=async()=>{await _(),!j&&(R=window.setTimeout(()=>void I(),document.hidden?y$:_$))},T=()=>{R!==null&&window.clearTimeout(R),R=null,I()};return document.addEventListener("visibilitychange",T),I(),()=>{j=!0,R!==null&&window.clearTimeout(R),document.removeEventListener("visibilitychange",T)}},[b,_]);const C=W((j,R)=>{d(I=>{const T=I.get(R);if(j===T||!j&&!T)return I;const A=new Map(I);return j?A.set(R,j):A.delete(R),A})}),S=p.useMemo(()=>b$({endpoints:i,electronReport:l,frontendItems:[...u.values()]}),[l,i,u]),w=S.find(j=>j.roles.includes("current")),y=(w==null?void 0:w.address)??th(e||window.location.origin),N=Array.from(new Set(S.flatMap(j=>j.capabilities.filter(R=>R.attention==="error").map(R=>R.capabilityId)))),E=Array.from(new Set(S.flatMap(j=>j.capabilities.filter(R=>R.attention==="warning").map(R=>R.capabilityId)))).filter(j=>!N.includes(j)),k=px(S.length>0?S.map(j=>j.state):["checking"]),D=p.useMemo(()=>({nodes:S,currentAddress:y,overallState:k,unhealthyCapabilityIds:N,warningCapabilityIds:E,refreshing:h,panelOpen:m,setPanelOpen:g,refresh:_,setFrontendItem:C}),[y,S,k,m,_,h,C,N,E]);return o.jsxs(qk.Provider,{value:D,children:[s,o.jsx(h$,{apiBase:e,token:t}),o.jsx(wB,{})]})}const Ax="runweave:resource-mac-notifications";function V5(){try{return localStorage.getItem(Ax)==="true"}catch{return!1}}const z0=Qn(e=>({enabled:V5(),setEnabled:t=>{localStorage.setItem(Ax,String(t)),e({enabled:t})}}));window.addEventListener("storage",e=>{(e.key===Ax||e.key===null)&&z0.setState({enabled:V5()})});function Mh(e,t){const r={Authorization:`Bearer ${t}`,"Content-Type":"application/json"},n="/api/device/resources";return{snapshot:s=>me(e,n,{headers:r,signal:s}),settings:s=>me(e,`${n}/settings`,{method:"PUT",headers:r,body:JSON.stringify({expectedRevision:s.revision,monitorEnabled:s.monitorEnabled,alertsEnabled:s.alertsEnabled})}),remoteControl:s=>me(e,`${n}/remote-control`,{method:"PUT",headers:r,body:JSON.stringify({expectedRevision:s.revision,enabled:s.enabled})}),snooze:s=>me(e,`${n}/alerts/${encodeURIComponent(s)}/snooze`,{method:"POST",headers:r,body:JSON.stringify({durationMinutes:60})}),terminate:(s,i,a)=>me(e,`${n}/processes/${encodeURIComponent(s)}/terminate`,{method:"POST",headers:r,body:JSON.stringify({force:i,requestId:a})})}}const G5=p.createContext(null);function Tx(){const e=p.useContext(G5);if(!e)throw new Error("Resource monitor provider required");return e}function Y5(e){const[t,r]=p.useState(null),[n,s]=p.useState(null),[i,a]=p.useState(!1),l=z0(w=>w.enabled),c=z0(w=>w.setEnabled),[u,d]=p.useState(null),[h,f]=p.useState(null),m=p.useRef(0),g=p.useRef(new Set),v=p.useRef(()=>{}),x=W(w=>{try{c(w)}catch{throw new Error("无法保存此设备的通知偏好")}d(null)}),b=W(()=>v.current()),_=W(()=>f(null)),C=W(w=>{r(y=>y&&{...y,settings:w,status:w.monitorEnabled?"warming-up":"disabled",alerts:[],canTerminate:!1}),f(null)}),S=W(async w=>{var N;if(!e.token)return;const y=(N=t==null?void 0:t.alerts.find(E=>E.alertId===w))==null?void 0:N.appKey;try{await Mh(e.apiBase,e.token).snooze(w)}catch(E){throw s(E instanceof Error?E.message:String(E)),E}r(E=>E&&{...E,alerts:E.alerts.filter(k=>y?k.appKey!==y:k.alertId!==w)}),f(E=>(E==null?void 0:E.alertId)===w||y&&(E==null?void 0:E.appKey)===y?null:E)});return p.useEffect(()=>{if(!e.token)return;let w=!1,y=!1;const N=new AbortController,E=async()=>{var R,I,T;const j=l&&((R=window.electronAPI)==null?void 0:R.isElectron)===!0;if(!(w||y||document.hidden&&!j||Date.now()-m.current<6e4)){y=!0,m.current=Date.now();try{const A=await Mh(e.apiBase,e.token).snapshot(N.signal);if(w)return;r(A),s(null),a(!1);const P=`runweave:resource-seen:${A.hostId}`;let O=[];try{const L=JSON.parse(localStorage.getItem(P)??"[]");Array.isArray(L)&&(O=L.filter(B=>typeof B=="string").slice(-200))}catch{}for(const L of e.notifications===!1?[]:A.alerts)if(!(O.includes(L.alertId)||g.current.has(`${A.hostId}:${L.alertId}`))){g.current.add(`${A.hostId}:${L.alertId}`),g.current.size>200&&g.current.delete(g.current.values().next().value),O.push(L.alertId),O=O.slice(-200);try{localStorage.setItem(P,JSON.stringify(O))}catch{}if(j)try{const B=await((T=(I=window.electronAPI)==null?void 0:I.showResourceNotification)==null?void 0:T.call(I,{connectionId:e.connectionId,hostId:A.hostId,alertId:L.alertId,appKey:L.appKey,title:`${L.appName} ${L.ruleId==="energy"?"能耗影响较高":"内存占用较大"}`,body:L.ruleId==="energy"?"近 5 分钟多次检测到高占用":"近 5 分钟多次检测到较大内存占用;内存不代表耗电量"}));if(w)return;(B==="failed"||B==="unavailable"||B===void 0)&&d("Mac 系统通知不可用或投递失败,请检查系统通知设置;应用内提醒仍保留")}catch{w||d("Mac 系统通知投递失败,应用内提醒仍保留")}w||f(L)}f(L=>L&&A.alerts.some(B=>B.alertId===L.alertId)?L:null)}catch(A){if(w)return;a(A instanceof De&&A.status===404),s(A instanceof Error?A.message:String(A))}finally{y=!1}}};v.current=()=>void E(),E();const k=window.setInterval(()=>void E(),6e4),D=()=>{document.hidden||E()};return document.addEventListener("visibilitychange",D),()=>{w=!0,N.abort(),window.clearInterval(k),document.removeEventListener("visibilitychange",D),v.current=()=>{}}},[e.apiBase,e.token,e.connectionId,e.notifications,l]),o.jsx(G5.Provider,{value:{data:t,error:n,unsupportedBackend:i,refresh:b,apiBase:e.apiBase,token:e.token,macNotifications:l,setMacNotifications:x,notificationError:u,notice:h,dismissNotice:_,applySettings:C,applyRemoteControl:w=>r(y=>y&&{...y,remoteControl:w}),snooze:S},children:e.children})}var jl=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Uo,Hi,Za,F2,w$=(F2=class extends jl{constructor(){super();Ye(this,Uo);Ye(this,Hi);Ye(this,Za);Ae(this,Za,t=>{if(typeof window<"u"&&window.addEventListener){const r=()=>t();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Q(this,Hi)||this.setEventListener(Q(this,Za))}onUnsubscribe(){var t;this.hasListeners()||((t=Q(this,Hi))==null||t.call(this),Ae(this,Hi,void 0))}setEventListener(t){var r;Ae(this,Za,t),(r=Q(this,Hi))==null||r.call(this),Ae(this,Hi,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){Q(this,Uo)!==t&&(Ae(this,Uo,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(r=>{r(t)})}isFocused(){var t;return typeof Q(this,Uo)=="boolean"?Q(this,Uo):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Uo=new WeakMap,Hi=new WeakMap,Za=new WeakMap,F2),$f=new w$,S$={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Wi,Iv,$2,C$=($2=class{constructor(){Ye(this,Wi,S$);Ye(this,Iv,!1)}setTimeoutProvider(e){Ae(this,Wi,e)}setTimeout(e,t){return Q(this,Wi).setTimeout(e,t)}clearTimeout(e){Q(this,Wi).clearTimeout(e)}setInterval(e,t){return Q(this,Wi).setInterval(e,t)}clearInterval(e){Q(this,Wi).clearInterval(e)}},Wi=new WeakMap,Iv=new WeakMap,$2),Fo=new C$;function E$(e){setTimeout(e,0)}var k$=typeof window>"u"||"Deno"in globalThis;function ln(){}function I$(e,t){return typeof e=="function"?e(t):e}function U0(e){return typeof e=="number"&&e>=0&&e!==1/0}function X5(e,t){return Math.max(e+(t||0)-Date.now(),0)}function no(e,t){return typeof e=="function"?e(t):e}function In(e,t){return typeof e=="function"?e(t):e}function a1(e,t){const{type:r="all",exact:n,fetchStatus:s,predicate:i,queryKey:a,stale:l}=e;if(a){if(n){if(t.queryHash!==Dx(a,t.options))return!1}else if(!zc(t.queryKey,a))return!1}if(r!=="all"){const c=t.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||s&&s!==t.state.fetchStatus||i&&!i(t))}function l1(e,t){const{exact:r,status:n,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(r){if(na(t.options.mutationKey)!==na(i))return!1}else if(!zc(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||s&&!s(t))}function Dx(e,t){return((t==null?void 0:t.queryKeyHashFn)||na)(e)}function na(e){return JSON.stringify(e,(t,r)=>H0(r)?Object.keys(r).sort().reduce((n,s)=>(n[s]=r[s],n),{}):r)}function zc(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(r=>zc(e[r],t[r])):!1}var N$=Object.prototype.hasOwnProperty;function J5(e,t,r=0){if(e===t)return e;if(r>500)return t;const n=c1(e)&&c1(t);if(!n&&!(H0(e)&&H0(t)))return t;const i=(n?e:Object.keys(e)).length,a=n?t:Object.keys(t),l=a.length,c=n?new Array(l):{};let u=0;for(let d=0;d<l;d++){const h=n?d:a[d],f=e[h],m=t[h];if(f===m){c[h]=f,(n?d<i:N$.call(e,h))&&u++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){c[h]=m;continue}const g=J5(f,m,r+1);c[h]=g,g===f&&u++}return i===l&&u===i?e:c}function Oh(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}function c1(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function H0(e){if(!u1(e))return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(!u1(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function u1(e){return Object.prototype.toString.call(e)==="[object Object]"}function R$(e){return new Promise(t=>{Fo.setTimeout(t,e)})}function W0(e,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,t):r.structuralSharing!==!1?J5(e,t):t}function j$(e,t,r=0){const n=[...e,t];return r&&n.length>r?n.slice(1):n}function A$(e,t,r=0){const n=[t,...e];return r&&n.length>r?n.slice(0,-1):n}var Px=Symbol();function Q5(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Px?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Lx(e,t){return typeof e=="function"?e(...t):!!e}function T$(e,t,r){let n=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),n||(n=!0,s.aborted?r():s.addEventListener("abort",r,{once:!0})),s)}),e}var Uc=(()=>{let e=()=>k$;return{isServer(){return e()},setIsServer(t){e=t}}})();function q0(){let e,t;const r=new Promise((s,i)=>{e=s,t=i});r.status="pending",r.catch(()=>{});function n(s){Object.assign(r,s),delete r.resolve,delete r.reject}return r.resolve=s=>{n({status:"fulfilled",value:s}),e(s)},r.reject=s=>{n({status:"rejected",reason:s}),t(s)},r}var D$=E$;function P$(){let e=[],t=0,r=l=>{l()},n=l=>{l()},s=D$;const i=l=>{t?e.push(l):s(()=>{r(l)})},a=()=>{const l=e;e=[],l.length&&s(()=>{n(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;t++;try{c=l()}finally{t--,t||a()}return c},batchCalls:l=>(...c)=>{i(()=>{l(...c)})},schedule:i,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{n=l},setScheduler:l=>{s=l}}}var _r=P$(),el,qi,tl,z2,L$=(z2=class extends jl{constructor(){super();Ye(this,el,!0);Ye(this,qi);Ye(this,tl);Ae(this,tl,t=>{if(typeof window<"u"&&window.addEventListener){const r=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Q(this,qi)||this.setEventListener(Q(this,tl))}onUnsubscribe(){var t;this.hasListeners()||((t=Q(this,qi))==null||t.call(this),Ae(this,qi,void 0))}setEventListener(t){var r;Ae(this,tl,t),(r=Q(this,qi))==null||r.call(this),Ae(this,qi,t(this.setOnline.bind(this)))}setOnline(t){Q(this,el)!==t&&(Ae(this,el,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return Q(this,el)}},el=new WeakMap,qi=new WeakMap,tl=new WeakMap,z2),sa=new L$;function M$(e){return Math.min(1e3*2**e,3e4)}function Z5(e){return(e??"online")==="online"?sa.isOnline():!0}var K0=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function e3(e){let t=!1,r=0,n;const s=q0(),i=()=>s.status!=="pending",a=v=>{var x;if(!i()){const b=new K0(v);f(b),(x=e.onCancel)==null||x.call(e,b)}},l=()=>{t=!0},c=()=>{t=!1},u=()=>$f.isFocused()&&(e.networkMode==="always"||sa.isOnline())&&e.canRun(),d=()=>Z5(e.networkMode)&&e.canRun(),h=v=>{i()||(n==null||n(),s.resolve(v))},f=v=>{i()||(n==null||n(),s.reject(v))},m=()=>new Promise(v=>{var x;n=b=>{(i()||u())&&v(b)},(x=e.onPause)==null||x.call(e)}).then(()=>{var v;n=void 0,i()||(v=e.onContinue)==null||v.call(e)}),g=()=>{if(i())return;let v;const x=r===0?e.initialPromise:void 0;try{v=x??e.fn()}catch(b){v=Promise.reject(b)}Promise.resolve(v).then(h).catch(b=>{var y;if(i())return;const _=e.retry??(Uc.isServer()?0:3),C=e.retryDelay??M$,S=typeof C=="function"?C(r,b):C,w=_===!0||typeof _=="number"&&r<_||typeof _=="function"&&_(r,b);if(t||!w){f(b);return}r++,(y=e.onFail)==null||y.call(e,r,b),R$(S).then(()=>u()?void 0:m()).then(()=>{t?f(b):g()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(n==null||n(),s),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?g():m().then(g),s)}}var Ho,U2,t3=(U2=class{constructor(){Ye(this,Ho)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),U0(this.gcTime)&&Ae(this,Ho,Fo.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Uc.isServer()?1/0:300*1e3))}clearGcTimeout(){Q(this,Ho)!==void 0&&(Fo.clearTimeout(Q(this,Ho)),Ae(this,Ho,void 0))}},Ho=new WeakMap,U2);function O$(e){return{onFetch:(t,r)=>{var d,h,f,m,g;const n=t.options,s=(f=(h=(d=t.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:f.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],a=((g=t.state.data)==null?void 0:g.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let v=!1;const x=C=>{T$(C,()=>t.signal,()=>v=!0)},b=Q5(t.options,t.fetchOptions),_=async(C,S,w)=>{if(v)return Promise.reject(t.signal.reason);if(S==null&&C.pages.length)return Promise.resolve(C);const N=(()=>{const j={client:t.client,queryKey:t.queryKey,pageParam:S,direction:w?"backward":"forward",meta:t.options.meta};return x(j),j})(),E=await b(N),{maxPages:k}=t.options,D=w?A$:j$;return{pages:D(C.pages,E,k),pageParams:D(C.pageParams,S,k)}};if(s&&i.length){const C=s==="backward",S=C?r3:V0,w={pages:i,pageParams:a},y=S(n,w);l=await _(w,y,C)}else{const C=e??i.length;do{const S=c===0?a[0]??n.initialPageParam:V0(n,l);if(c>0&&S==null)break;l=await _(l,S),c++}while(c<C)}return l};t.options.persister?t.fetchFn=()=>{var v,x;return(x=(v=t.options).persister)==null?void 0:x.call(v,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r)}:t.fetchFn=u}}}function V0(e,{pages:t,pageParams:r}){const n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,r[n],r):void 0}function r3(e,{pages:t,pageParams:r}){var n;return t.length>0?(n=e.getPreviousPageParam)==null?void 0:n.call(e,t[0],t,r[0],r):void 0}function B$(e,t){return t?V0(e,t)!=null:!1}function F$(e,t){return!t||!e.getPreviousPageParam?!1:r3(e,t)!=null}var rl,Wo,nl,Un,qo,kr,au,Ko,En,n3,ni,H2,$$=(H2=class extends t3{constructor(t){super();Ye(this,En);Ye(this,rl);Ye(this,Wo);Ye(this,nl);Ye(this,Un);Ye(this,qo);Ye(this,kr);Ye(this,au);Ye(this,Ko);Ae(this,Ko,!1),Ae(this,au,t.defaultOptions),this.setOptions(t.options),this.observers=[],Ae(this,qo,t.client),Ae(this,Un,Q(this,qo).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Ae(this,Wo,h1(this.options)),this.state=t.state??Q(this,Wo),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return Q(this,rl)}get promise(){var t;return(t=Q(this,kr))==null?void 0:t.promise}setOptions(t){if(this.options={...Q(this,au),...t},t!=null&&t._type&&Ae(this,rl,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=h1(this.options);r.data!==void 0&&(this.setState(d1(r.data,r.dataUpdatedAt)),Ae(this,Wo,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Q(this,Un).remove(this)}setData(t,r){const n=W0(this.state.data,t,this.options);return ut(this,En,ni).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(t){ut(this,En,ni).call(this,{type:"setState",state:t})}cancel(t){var n,s;const r=(n=Q(this,kr))==null?void 0:n.promise;return(s=Q(this,kr))==null||s.cancel(t),r?r.then(ln).catch(ln):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return Q(this,Wo)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>In(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Px||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>no(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!X5(this.state.dataUpdatedAt,t)}onFocus(){var r;const t=this.observers.find(n=>n.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(r=Q(this,kr))==null||r.continue()}onOnline(){var r;const t=this.observers.find(n=>n.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(r=Q(this,kr))==null||r.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Q(this,Un).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(r=>r!==t),this.observers.length||(Q(this,kr)&&(Q(this,Ko)||ut(this,En,n3).call(this)?Q(this,kr).cancel({revert:!0}):Q(this,kr).cancelRetry()),this.scheduleGc()),Q(this,Un).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ut(this,En,ni).call(this,{type:"invalidate"})}async fetch(t,r){var u,d,h,f,m,g,v,x,b,_,C;if(this.state.fetchStatus!=="idle"&&((u=Q(this,kr))==null?void 0:u.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Q(this,kr))return Q(this,kr).continueRetry(),Q(this,kr).promise}if(t&&this.setOptions(t),!this.options.queryFn){const S=this.observers.find(w=>w.options.queryFn);S&&this.setOptions(S.options)}const n=new AbortController,s=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(Ae(this,Ko,!0),n.signal)})},i=()=>{const S=Q5(this.options,r),y=(()=>{const N={client:Q(this,qo),queryKey:this.queryKey,meta:this.meta};return s(N),N})();return Ae(this,Ko,!1),this.options.persister?this.options.persister(S,y,this):S(y)},l=(()=>{const S={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Q(this,qo),state:this.state,fetchFn:i};return s(S),S})(),c=Q(this,rl)==="infinite"?O$(this.options.pages):this.options.behavior;c==null||c.onFetch(l,this),Ae(this,nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&ut(this,En,ni).call(this,{type:"fetch",meta:(h=l.fetchOptions)==null?void 0:h.meta}),Ae(this,kr,e3({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:S=>{S instanceof K0&&S.revert&&this.setState({...Q(this,nl),fetchStatus:"idle"}),n.abort()},onFail:(S,w)=>{ut(this,En,ni).call(this,{type:"failed",failureCount:S,error:w})},onPause:()=>{ut(this,En,ni).call(this,{type:"pause"})},onContinue:()=>{ut(this,En,ni).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const S=await Q(this,kr).start();if(S===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(S),(m=(f=Q(this,Un).config).onSuccess)==null||m.call(f,S,this),(v=(g=Q(this,Un).config).onSettled)==null||v.call(g,S,this.state.error,this),S}catch(S){if(S instanceof K0){if(S.silent)return Q(this,kr).promise;if(S.revert){if(this.state.data===void 0)throw S;return this.state.data}}throw ut(this,En,ni).call(this,{type:"error",error:S}),(b=(x=Q(this,Un).config).onError)==null||b.call(x,S,this),(C=(_=Q(this,Un).config).onSettled)==null||C.call(_,this.state.data,S,this),S}finally{this.scheduleGc()}}},rl=new WeakMap,Wo=new WeakMap,nl=new WeakMap,Un=new WeakMap,qo=new WeakMap,kr=new WeakMap,au=new WeakMap,Ko=new WeakMap,En=new WeakSet,n3=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},ni=function(t){const r=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...s3(n.data,this.options),fetchMeta:t.meta??null};case"success":const s={...n,...d1(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Ae(this,nl,t.manual?s:void 0),s;case"error":const i=t.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=r(this.state),_r.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Q(this,Un).notify({query:this,type:"updated",action:t})})},H2);function s3(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Z5(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function d1(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function h1(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,r=t!==void 0,n=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var vn,bt,lu,on,Vo,sl,ii,Ki,cu,il,ol,Go,Yo,Vi,al,It,mc,G0,Y0,X0,J0,Q0,Z0,eg,o3,W2,i3=(W2=class extends jl{constructor(t,r){super();Ye(this,It);Ye(this,vn);Ye(this,bt);Ye(this,lu);Ye(this,on);Ye(this,Vo);Ye(this,sl);Ye(this,ii);Ye(this,Ki);Ye(this,cu);Ye(this,il);Ye(this,ol);Ye(this,Go);Ye(this,Yo);Ye(this,Vi);Ye(this,al,new Set);this.options=r,Ae(this,vn,t),Ae(this,Ki,null),Ae(this,ii,q0()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Q(this,bt).addObserver(this),f1(Q(this,bt),this.options)?ut(this,It,mc).call(this):this.updateResult(),ut(this,It,J0).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return tg(Q(this,bt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return tg(Q(this,bt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ut(this,It,Q0).call(this),ut(this,It,Z0).call(this),Q(this,bt).removeObserver(this)}setOptions(t){const r=this.options,n=Q(this,bt);if(this.options=Q(this,vn).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof In(this.options.enabled,Q(this,bt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ut(this,It,eg).call(this),Q(this,bt).setOptions(this.options),r._defaulted&&!Oh(this.options,r)&&Q(this,vn).getQueryCache().notify({type:"observerOptionsUpdated",query:Q(this,bt),observer:this});const s=this.hasListeners();s&&p1(Q(this,bt),n,this.options,r)&&ut(this,It,mc).call(this),this.updateResult(),s&&(Q(this,bt)!==n||In(this.options.enabled,Q(this,bt))!==In(r.enabled,Q(this,bt))||no(this.options.staleTime,Q(this,bt))!==no(r.staleTime,Q(this,bt)))&&ut(this,It,G0).call(this);const i=ut(this,It,Y0).call(this);s&&(Q(this,bt)!==n||In(this.options.enabled,Q(this,bt))!==In(r.enabled,Q(this,bt))||i!==Q(this,Vi))&&ut(this,It,X0).call(this,i)}getOptimisticResult(t){const r=Q(this,vn).getQueryCache().build(Q(this,vn),t),n=this.createResult(r,t);return U$(this,n)&&(Ae(this,on,n),Ae(this,sl,this.options),Ae(this,Vo,Q(this,bt).state)),n}getCurrentResult(){return Q(this,on)}trackResult(t,r){return new Proxy(t,{get:(n,s)=>(this.trackProp(s),r==null||r(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&Q(this,ii).status==="pending"&&Q(this,ii).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s))})}trackProp(t){Q(this,al).add(t)}getCurrentQuery(){return Q(this,bt)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const r=Q(this,vn).defaultQueryOptions(t),n=Q(this,vn).getQueryCache().build(Q(this,vn),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(t){return ut(this,It,mc).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Q(this,on)))}createResult(t,r){var k;const n=Q(this,bt),s=this.options,i=Q(this,on),a=Q(this,Vo),l=Q(this,sl),u=t!==n?t.state:Q(this,lu),{state:d}=t;let h={...d},f=!1,m;if(r._optimisticResults){const D=this.hasListeners(),j=!D&&f1(t,r),R=D&&p1(t,n,r,s);(j||R)&&(h={...h,...s3(d.data,t.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:g,errorUpdatedAt:v,status:x}=h;m=h.data;let b=!1;if(r.placeholderData!==void 0&&m===void 0&&x==="pending"){let D;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(D=i.data,b=!0):D=typeof r.placeholderData=="function"?r.placeholderData((k=Q(this,ol))==null?void 0:k.state.data,Q(this,ol)):r.placeholderData,D!==void 0&&(x="success",m=W0(i==null?void 0:i.data,D,r),f=!0)}if(r.select&&m!==void 0&&!b)if(i&&m===(a==null?void 0:a.data)&&r.select===Q(this,cu))m=Q(this,il);else try{Ae(this,cu,r.select),m=r.select(m),m=W0(i==null?void 0:i.data,m,r),Ae(this,il,m),Ae(this,Ki,null)}catch(D){Ae(this,Ki,D)}Q(this,Ki)&&(g=Q(this,Ki),m=Q(this,il),v=Date.now(),x="error");const _=h.fetchStatus==="fetching",C=x==="pending",S=x==="error",w=C&&_,y=m!==void 0,E={status:x,fetchStatus:h.fetchStatus,isPending:C,isSuccess:x==="success",isError:S,isInitialLoading:w,isLoading:w,data:m,dataUpdatedAt:h.dataUpdatedAt,error:g,errorUpdatedAt:v,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!C,isLoadingError:S&&!y,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:S&&y,isStale:Mx(t,r),refetch:this.refetch,promise:Q(this,ii),isEnabled:In(r.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const D=E.data!==void 0,j=E.status==="error"&&!D,R=A=>{j?A.reject(E.error):D&&A.resolve(E.data)},I=()=>{const A=Ae(this,ii,E.promise=q0());R(A)},T=Q(this,ii);switch(T.status){case"pending":t.queryHash===n.queryHash&&R(T);break;case"fulfilled":(j||E.data!==T.value)&&I();break;case"rejected":(!j||E.error!==T.reason)&&I();break}}return E}updateResult(){const t=Q(this,on),r=this.createResult(Q(this,bt),this.options);if(Ae(this,Vo,Q(this,bt).state),Ae(this,sl,this.options),Q(this,Vo).data!==void 0&&Ae(this,ol,Q(this,bt)),Oh(r,t))return;Ae(this,on,r);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!Q(this,al).size)return!0;const a=new Set(i??Q(this,al));return this.options.throwOnError&&a.add("error"),Object.keys(Q(this,on)).some(l=>{const c=l;return Q(this,on)[c]!==t[c]&&a.has(c)})};ut(this,It,o3).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ut(this,It,J0).call(this)}},vn=new WeakMap,bt=new WeakMap,lu=new WeakMap,on=new WeakMap,Vo=new WeakMap,sl=new WeakMap,ii=new WeakMap,Ki=new WeakMap,cu=new WeakMap,il=new WeakMap,ol=new WeakMap,Go=new WeakMap,Yo=new WeakMap,Vi=new WeakMap,al=new WeakMap,It=new WeakSet,mc=function(t){ut(this,It,eg).call(this);let r=Q(this,bt).fetch(this.options,t);return t!=null&&t.throwOnError||(r=r.catch(ln)),r},G0=function(){ut(this,It,Q0).call(this);const t=no(this.options.staleTime,Q(this,bt));if(Uc.isServer()||Q(this,on).isStale||!U0(t))return;const n=X5(Q(this,on).dataUpdatedAt,t)+1;Ae(this,Go,Fo.setTimeout(()=>{Q(this,on).isStale||this.updateResult()},n))},Y0=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Q(this,bt)):this.options.refetchInterval)??!1},X0=function(t){ut(this,It,Z0).call(this),Ae(this,Vi,t),!(Uc.isServer()||In(this.options.enabled,Q(this,bt))===!1||!U0(Q(this,Vi))||Q(this,Vi)===0)&&Ae(this,Yo,Fo.setInterval(()=>{(this.options.refetchIntervalInBackground||$f.isFocused())&&ut(this,It,mc).call(this)},Q(this,Vi)))},J0=function(){ut(this,It,G0).call(this),ut(this,It,X0).call(this,ut(this,It,Y0).call(this))},Q0=function(){Q(this,Go)!==void 0&&(Fo.clearTimeout(Q(this,Go)),Ae(this,Go,void 0))},Z0=function(){Q(this,Yo)!==void 0&&(Fo.clearInterval(Q(this,Yo)),Ae(this,Yo,void 0))},eg=function(){const t=Q(this,vn).getQueryCache().build(Q(this,vn),this.options);if(t===Q(this,bt))return;const r=Q(this,bt);Ae(this,bt,t),Ae(this,lu,t.state),this.hasListeners()&&(r==null||r.removeObserver(this),t.addObserver(this))},o3=function(t){_r.batch(()=>{t.listeners&&this.listeners.forEach(r=>{r(Q(this,on))}),Q(this,vn).getQueryCache().notify({query:Q(this,bt),type:"observerResultsUpdated"})})},W2);function z$(e,t){return In(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&In(t.retryOnMount,e)===!1)}function f1(e,t){return z$(e,t)||e.state.data!==void 0&&tg(e,t,t.refetchOnMount)}function tg(e,t,r){if(In(t.enabled,e)!==!1&&no(t.staleTime,e)!=="static"){const n=typeof r=="function"?r(e):r;return n==="always"||n!==!1&&Mx(e,t)}return!1}function p1(e,t,r,n){return(e!==t||In(n.enabled,e)===!1)&&(!r.suspense||e.state.status!=="error")&&Mx(e,r)}function Mx(e,t){return In(t.enabled,e)!==!1&&e.isStaleByTime(no(t.staleTime,e))}function U$(e,t){return!Oh(e.getCurrentResult(),t)}var H$=class extends i3{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){var g,v;const{state:r}=e,n=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:a,isRefetchError:l}=n,c=(v=(g=r.fetchMeta)==null?void 0:g.fetchMore)==null?void 0:v.direction,u=a&&c==="forward",d=s&&c==="forward",h=a&&c==="backward",f=s&&c==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:B$(t,r.data),hasPreviousPage:F$(t,r.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:h,isFetchingPreviousPage:f,isRefetchError:l&&!u&&!h,isRefetching:i&&!d&&!f}}},uu,As,Kr,Xo,Ts,Ti,q2,W$=(q2=class extends t3{constructor(t){super();Ye(this,Ts);Ye(this,uu);Ye(this,As);Ye(this,Kr);Ye(this,Xo);Ae(this,uu,t.client),this.mutationId=t.mutationId,Ae(this,Kr,t.mutationCache),Ae(this,As,[]),this.state=t.state||a3(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Q(this,As).includes(t)||(Q(this,As).push(t),this.clearGcTimeout(),Q(this,Kr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Ae(this,As,Q(this,As).filter(r=>r!==t)),this.scheduleGc(),Q(this,Kr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Q(this,As).length||(this.state.status==="pending"?this.scheduleGc():Q(this,Kr).remove(this))}continue(){var t;return((t=Q(this,Xo))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var a,l,c,u,d,h,f,m,g,v,x,b,_,C,S,w,y,N;const r=()=>{ut(this,Ts,Ti).call(this,{type:"continue"})},n={client:Q(this,uu),meta:this.options.meta,mutationKey:this.options.mutationKey};Ae(this,Xo,e3({fn:()=>this.options.mutationFn?this.options.mutationFn(t,n):Promise.reject(new Error("No mutationFn found")),onFail:(E,k)=>{ut(this,Ts,Ti).call(this,{type:"failed",failureCount:E,error:k})},onPause:()=>{ut(this,Ts,Ti).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Q(this,Kr).canRun(this)}));const s=this.state.status==="pending",i=!Q(this,Xo).canStart();try{if(s)r();else{ut(this,Ts,Ti).call(this,{type:"pending",variables:t,isPaused:i}),Q(this,Kr).config.onMutate&&await Q(this,Kr).config.onMutate(t,this,n);const k=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,t,n));k!==this.state.context&&ut(this,Ts,Ti).call(this,{type:"pending",context:k,variables:t,isPaused:i})}const E=await Q(this,Xo).start();return await((u=(c=Q(this,Kr).config).onSuccess)==null?void 0:u.call(c,E,t,this.state.context,this,n)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,E,t,this.state.context,n)),await((m=(f=Q(this,Kr).config).onSettled)==null?void 0:m.call(f,E,null,this.state.variables,this.state.context,this,n)),await((v=(g=this.options).onSettled)==null?void 0:v.call(g,E,null,t,this.state.context,n)),ut(this,Ts,Ti).call(this,{type:"success",data:E}),E}catch(E){try{await((b=(x=Q(this,Kr).config).onError)==null?void 0:b.call(x,E,t,this.state.context,this,n))}catch(k){Promise.reject(k)}try{await((C=(_=this.options).onError)==null?void 0:C.call(_,E,t,this.state.context,n))}catch(k){Promise.reject(k)}try{await((w=(S=Q(this,Kr).config).onSettled)==null?void 0:w.call(S,void 0,E,this.state.variables,this.state.context,this,n))}catch(k){Promise.reject(k)}try{await((N=(y=this.options).onSettled)==null?void 0:N.call(y,void 0,E,t,this.state.context,n))}catch(k){Promise.reject(k)}throw ut(this,Ts,Ti).call(this,{type:"error",error:E}),E}finally{Q(this,Kr).runNext(this)}}},uu=new WeakMap,As=new WeakMap,Kr=new WeakMap,Xo=new WeakMap,Ts=new WeakSet,Ti=function(t){const r=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=r(this.state),_r.batch(()=>{Q(this,As).forEach(n=>{n.onMutationUpdate(t)}),Q(this,Kr).notify({mutation:this,type:"updated",action:t})})},q2);function a3(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var oi,os,du,K2,l3=(K2=class extends jl{constructor(t={}){super();Ye(this,oi);Ye(this,os);Ye(this,du);this.config=t,Ae(this,oi,new Set),Ae(this,os,new Map),Ae(this,du,0)}build(t,r,n){const s=new W$({client:t,mutationCache:this,mutationId:++od(this,du)._,options:t.defaultMutationOptions(r),state:n});return this.add(s),s}add(t){Q(this,oi).add(t);const r=yd(t);if(typeof r=="string"){const n=Q(this,os).get(r);n?n.push(t):Q(this,os).set(r,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Q(this,oi).delete(t)){const r=yd(t);if(typeof r=="string"){const n=Q(this,os).get(r);if(n)if(n.length>1){const s=n.indexOf(t);s!==-1&&n.splice(s,1)}else n[0]===t&&Q(this,os).delete(r)}}this.notify({type:"removed",mutation:t})}canRun(t){const r=yd(t);if(typeof r=="string"){const n=Q(this,os).get(r),s=n==null?void 0:n.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){var n;const r=yd(t);if(typeof r=="string"){const s=(n=Q(this,os).get(r))==null?void 0:n.find(i=>i!==t&&i.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}else return Promise.resolve()}clear(){_r.batch(()=>{Q(this,oi).forEach(t=>{this.notify({type:"removed",mutation:t})}),Q(this,oi).clear(),Q(this,os).clear()})}getAll(){return Array.from(Q(this,oi))}find(t){const r={exact:!0,...t};return this.getAll().find(n=>l1(r,n))}findAll(t={}){return this.getAll().filter(r=>l1(t,r))}notify(t){_r.batch(()=>{this.listeners.forEach(r=>{r(t)})})}resumePausedMutations(){const t=this.getAll().filter(r=>r.state.isPaused);return _r.batch(()=>Promise.all(t.map(r=>r.continue().catch(ln))))}},oi=new WeakMap,os=new WeakMap,du=new WeakMap,K2);function yd(e){var t;return(t=e.options.scope)==null?void 0:t.id}var ai,Gi,xn,li,pi,rh,rg,V2,q$=(V2=class extends jl{constructor(r,n){super();Ye(this,pi);Ye(this,ai);Ye(this,Gi);Ye(this,xn);Ye(this,li);Ae(this,ai,r),this.setOptions(n),this.bindMethods(),ut(this,pi,rh).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var s;const n=this.options;this.options=Q(this,ai).defaultMutationOptions(r),Oh(this.options,n)||Q(this,ai).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Q(this,xn),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&na(n.mutationKey)!==na(this.options.mutationKey)?this.reset():((s=Q(this,xn))==null?void 0:s.state.status)==="pending"&&Q(this,xn).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Q(this,xn))==null||r.removeObserver(this)}onMutationUpdate(r){ut(this,pi,rh).call(this),ut(this,pi,rg).call(this,r)}getCurrentResult(){return Q(this,Gi)}reset(){var r;(r=Q(this,xn))==null||r.removeObserver(this),Ae(this,xn,void 0),ut(this,pi,rh).call(this),ut(this,pi,rg).call(this)}mutate(r,n){var s;return Ae(this,li,n),(s=Q(this,xn))==null||s.removeObserver(this),Ae(this,xn,Q(this,ai).getMutationCache().build(Q(this,ai),this.options)),Q(this,xn).addObserver(this),Q(this,xn).execute(r)}},ai=new WeakMap,Gi=new WeakMap,xn=new WeakMap,li=new WeakMap,pi=new WeakSet,rh=function(){var n;const r=((n=Q(this,xn))==null?void 0:n.state)??a3();Ae(this,Gi,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},rg=function(r){_r.batch(()=>{var n,s,i,a,l,c,u,d;if(Q(this,li)&&this.hasListeners()){const h=Q(this,Gi).variables,f=Q(this,Gi).context,m={client:Q(this,ai),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(s=(n=Q(this,li)).onSuccess)==null||s.call(n,r.data,h,f,m)}catch(g){Promise.reject(g)}try{(a=(i=Q(this,li)).onSettled)==null||a.call(i,r.data,null,h,f,m)}catch(g){Promise.reject(g)}}else if((r==null?void 0:r.type)==="error"){try{(c=(l=Q(this,li)).onError)==null||c.call(l,r.error,h,f,m)}catch(g){Promise.reject(g)}try{(d=(u=Q(this,li)).onSettled)==null||d.call(u,void 0,r.error,h,f,m)}catch(g){Promise.reject(g)}}}this.listeners.forEach(h=>{h(Q(this,Gi))})})},V2),Ds,G2,c3=(G2=class extends jl{constructor(t={}){super();Ye(this,Ds);this.config=t,Ae(this,Ds,new Map)}build(t,r,n){const s=r.queryKey,i=r.queryHash??Dx(s,r);let a=this.get(i);return a||(a=new $$({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(r),state:n,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){Q(this,Ds).has(t.queryHash)||(Q(this,Ds).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const r=Q(this,Ds).get(t.queryHash);r&&(t.destroy(),r===t&&Q(this,Ds).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){_r.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Q(this,Ds).get(t)}getAll(){return[...Q(this,Ds).values()]}find(t){const r={exact:!0,...t};return this.getAll().find(n=>a1(r,n))}findAll(t={}){const r=this.getAll();return Object.keys(t).length>0?r.filter(n=>a1(t,n)):r}notify(t){_r.batch(()=>{this.listeners.forEach(r=>{r(t)})})}onFocus(){_r.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){_r.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ds=new WeakMap,G2),Jt,Yi,Xi,ll,cl,Ji,ul,dl,Y2,K$=(Y2=class{constructor(e={}){Ye(this,Jt);Ye(this,Yi);Ye(this,Xi);Ye(this,ll);Ye(this,cl);Ye(this,Ji);Ye(this,ul);Ye(this,dl);Ae(this,Jt,e.queryCache||new c3),Ae(this,Yi,e.mutationCache||new l3),Ae(this,Xi,e.defaultOptions||{}),Ae(this,ll,new Map),Ae(this,cl,new Map),Ae(this,Ji,0)}mount(){od(this,Ji)._++,Q(this,Ji)===1&&(Ae(this,ul,$f.subscribe(async e=>{e&&(await this.resumePausedMutations(),Q(this,Jt).onFocus())})),Ae(this,dl,sa.subscribe(async e=>{e&&(await this.resumePausedMutations(),Q(this,Jt).onOnline())})))}unmount(){var e,t;od(this,Ji)._--,Q(this,Ji)===0&&((e=Q(this,ul))==null||e.call(this),Ae(this,ul,void 0),(t=Q(this,dl))==null||t.call(this),Ae(this,dl,void 0))}isFetching(e){return Q(this,Jt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return Q(this,Yi).findAll({...e,status:"pending"}).length}getQueryData(e){var r;const t=this.defaultQueryOptions({queryKey:e});return(r=Q(this,Jt).get(t.queryHash))==null?void 0:r.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),r=Q(this,Jt).build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(no(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return Q(this,Jt).findAll(e).map(({queryKey:t,state:r})=>{const n=r.data;return[t,n]})}setQueryData(e,t,r){const n=this.defaultQueryOptions({queryKey:e}),s=Q(this,Jt).get(n.queryHash),i=s==null?void 0:s.state.data,a=I$(t,i);if(a!==void 0)return Q(this,Jt).build(this,n).setData(a,{...r,manual:!0})}setQueriesData(e,t,r){return _r.batch(()=>Q(this,Jt).findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(e){var r;const t=this.defaultQueryOptions({queryKey:e});return(r=Q(this,Jt).get(t.queryHash))==null?void 0:r.state}removeQueries(e){const t=Q(this,Jt);_r.batch(()=>{t.findAll(e).forEach(r=>{t.remove(r)})})}resetQueries(e,t){const r=Q(this,Jt);return _r.batch(()=>(r.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const r={revert:!0,...t},n=_r.batch(()=>Q(this,Jt).findAll(e).map(s=>s.cancel(r)));return Promise.all(n).then(ln).catch(ln)}invalidateQueries(e,t={}){return _r.batch(()=>(Q(this,Jt).findAll(e).forEach(r=>{r.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const r={...t,cancelRefetch:t.cancelRefetch??!0},n=_r.batch(()=>Q(this,Jt).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,r);return r.throwOnError||(i=i.catch(ln)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(ln)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const r=Q(this,Jt).build(this,t);return r.isStaleByTime(no(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ln).catch(ln)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ln).catch(ln)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return sa.isOnline()?Q(this,Yi).resumePausedMutations():Promise.resolve()}getQueryCache(){return Q(this,Jt)}getMutationCache(){return Q(this,Yi)}getDefaultOptions(){return Q(this,Xi)}setDefaultOptions(e){Ae(this,Xi,e)}setQueryDefaults(e,t){Q(this,ll).set(na(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...Q(this,ll).values()],r={};return t.forEach(n=>{zc(e,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(e,t){Q(this,cl).set(na(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...Q(this,cl).values()],r={};return t.forEach(n=>{zc(e,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(e){if(e._defaulted)return e;const t={...Q(this,Xi).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Dx(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Px&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...Q(this,Xi).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){Q(this,Jt).clear(),Q(this,Yi).clear()}},Jt=new WeakMap,Yi=new WeakMap,Xi=new WeakMap,ll=new WeakMap,cl=new WeakMap,Ji=new WeakMap,ul=new WeakMap,dl=new WeakMap,Y2),u3=p.createContext(void 0),xs=e=>{const t=p.useContext(u3);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},V$=({client:e,children:t})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(u3.Provider,{value:e,children:t})),d3=p.createContext(!1),G$=()=>p.useContext(d3);d3.Provider;function Y$(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var X$=p.createContext(Y$()),J$=()=>p.useContext(X$),Q$=(e,t,r)=>{const n=r!=null&&r.state.error&&typeof e.throwOnError=="function"?Lx(e.throwOnError,[r.state.error,r]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||n)&&(t.isReset()||(e.retryOnMount=!1))},Z$=e=>{p.useEffect(()=>{e.clearReset()},[e])},ez=({result:e,errorResetBoundary:t,throwOnError:r,query:n,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(s&&e.data===void 0||Lx(r,[e.error,n])),tz=e=>{if(e.suspense){const r=s=>s==="static"?s:Math.max(s??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...s)=>r(n(...s)):r(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},rz=(e,t)=>e.isLoading&&e.isFetching&&!t,nz=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,m1=(e,t,r)=>t.fetchOptimistic(e).catch(()=>{r.clearReset()});function h3(e,t,r){var m,g,v,x;const n=G$(),s=J$(),i=xs(),a=i.defaultQueryOptions(e);(g=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||g.call(m,a);const l=i.getQueryCache().get(a.queryHash),c=e.subscribed!==!1;a._optimisticResults=n?"isRestoring":c?"optimistic":void 0,tz(a),Q$(a,s,l),Z$(s);const u=!i.getQueryCache().get(a.queryHash),[d]=p.useState(()=>new t(i,a)),h=d.getOptimisticResult(a),f=!n&&c;if(p.useSyncExternalStore(p.useCallback(b=>{const _=f?d.subscribe(_r.batchCalls(b)):ln;return d.updateResult(),_},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),p.useEffect(()=>{d.setOptions(a)},[a,d]),nz(a,h))throw m1(a,d,s);if(ez({result:h,errorResetBoundary:s,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw h.error;if((x=(v=i.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||x.call(v,a,h),a.experimental_prefetchInRender&&!Uc.isServer()&&rz(h,n)){const b=u?m1(a,d,s):l==null?void 0:l.promise;b==null||b.catch(ln).finally(()=>{d.updateResult()})}return a.notifyOnChangeProps?h:d.trackResult(h)}function Ct(e,t){return h3(e,i3)}function nr(e,t){const r=xs(),[n]=p.useState(()=>new q$(r,e));p.useEffect(()=>{n.setOptions(e)},[n,e]);const s=p.useSyncExternalStore(p.useCallback(a=>n.subscribe(_r.batchCalls(a)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=p.useCallback((a,l)=>{n.mutate(a,l).catch(ln)},[n]);if(s.error&&Lx(n.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function ia(e,t){return h3(e,H$)}const sz=15e3,iz=30*6e4;function ml(e){const t=e.apiBase.trim().replace(/\/+$/,"")||"same-origin";return`${e.connectionId??"web"}::${t}${e.generation===void 0?"":`::${e.generation}`}`}function f3({children:e,onUnauthorized:t,scope:r}){const n=p.useRef(new Map),s=p.useRef(t);s.current=t;let i=n.current.get(r);if(!i){const a=l=>{var c;l&&typeof l=="object"&&"status"in l&&l.status===401&&((c=s.current)==null||c.call(s))};i=new K$({mutationCache:new l3({onError:a}),queryCache:new c3({onError:a}),defaultOptions:{queries:{gcTime:iz,retry:!1,staleTime:sz},mutations:{retry:!1}}}),n.current.set(r,i)}return p.useEffect(()=>{const a=n.current;return()=>{for(const l of a.values())l.clear();a.clear()}},[]),o.jsx(V$,{client:i,children:e})}const p3={appearance:p.lazy(()=>Vr(()=>import("./appearance-F3ep216f.js"),__vite__mapDeps([0,1]))),notifications:p.lazy(()=>Vr(()=>import("./notifications-C5O4JnTW.js"),__vite__mapDeps([2,1]))),shortcuts:p.lazy(()=>Vr(()=>import("./shortcuts-BNrV46nh.js"),__vite__mapDeps([3,1]))),suiji:p.lazy(()=>Vr(()=>import("./suiji-CKYE-bFZ.js"),__vite__mapDeps([4,1,5,6]))),access:p.lazy(()=>Vr(()=>import("./access-DUvHn-7g.js"),__vite__mapDeps([7,1,8]))),monitoring:p.lazy(()=>Vr(()=>import("./monitoring-BHrlQuyI.js"),__vite__mapDeps([9,1]))),advanced:p.lazy(()=>Vr(()=>import("./advanced-2iC4XP-k.js"),__vite__mapDeps([10,1]))),status:p.lazy(()=>Vr(()=>import("./status-Ce0iPeyb.js"),__vite__mapDeps([11,1,8]))),desktop:p.lazy(()=>Vr(()=>import("./desktop-hY0qLy1k.js"),__vite__mapDeps([12,1])))},oz=p.lazy(()=>Vr(()=>import("./connections-C-JFI1d6.js"),__vite__mapDeps([13,1,8])));function az({pageId:e,connections:t}){var i;const r=Fk(),n=p3[e],s=ml({apiBase:r.apiBase,connectionId:r.connectionId,generation:r.generation});return o.jsx(fB,{children:o.jsx(K5,{apiBase:r.apiBase,token:r.auth.token,connections:t,isElectron:((i=window.electronAPI)==null?void 0:i.isElectron)===!0,children:o.jsx(f3,{scope:s,onUnauthorized:r.auth.clearToken,children:o.jsx(Y5,{apiBase:r.apiBase,token:r.auth.token,connectionId:r.connectionId??s,notifications:!1,children:o.jsx(n,{})},`${s}:${r.auth.sessionId}`)})})})}function lz(e){var C,S,w;const t=sB(),r=ju(),n=Gt(),s=Cr(),i=rx(),a=oB(n.pathname.split("/")[2]??"appearance"),l=a.id==="connections"?null:p3[a.id],c=e.pageContent!==void 0,u=L0.find(y=>n.pathname===y.path||n.pathname.startsWith(y.path+"/")),d=c?(u==null?void 0:u.title)??(n.pathname.startsWith("/background-runs")?"后台运行":n.pathname==="/login"?"登录":"连接管理"):a.title,h=p.useRef((C=e.activeConnection)==null?void 0:C.id),f=new URLSearchParams(n.search),m=f.get("target")??h.current,g=e.connections.find(y=>y.id===m),v=hr(void 0,"window"),x=p.useRef(null),b=p.useRef(null);p.useEffect(()=>{var y,N;(y=x.current)==null||y.focus({preventScroll:!0}),(N=b.current)==null||N.scrollTo(0,0)},[d,n.search]),p.useEffect(()=>{!c&&n.pathname!==`/settings/${a.id}`&&s(`/settings/${a.id}${n.search}`,{replace:!0,state:n.state})},[c,n.pathname,n.search,n.state,s,a.id]);const _=()=>{const y=e.background??Ih(n);s(y?y.pathname+y.search+y.hash:"/terminal",{state:y==null?void 0:y.state})};return o.jsx(hB,{connection:g,activeConnection:e.activeConnection,workspaceAuth:e.workspaceAuth,webApiBase:e.webApiBase,children:o.jsx(Qr,{open:!0,children:o.jsxs(dx,{"aria-describedby":void 0,ref:v,className:"settings-screen",role:"dialog","aria-modal":"true",onEscapeKeyDown:y=>y.preventDefault(),onInteractOutside:y=>y.preventDefault(),children:[o.jsxs("aside",{className:"settings-sidebar",children:[o.jsxs("button",{className:"settings-back",title:(r==null?void 0:r.preparedLabel)??"返回当前终端",onClick:()=>r==null?void 0:r.exit(_),children:[o.jsx(xi,{className:"size-4"}),"返回终端"]}),(r==null?void 0:r.preparedLabel)&&o.jsx("p",{role:"status",className:"px-2 text-xs text-primary",children:"已准备会话,从上方返回终端"}),o.jsxs("nav",{"aria-label":"应用导航",className:"mt-2 shrink-0 border-b pb-2",children:[o.jsx("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:"应用导航"}),L0.map(y=>o.jsxs("button",{"aria-current":(u==null?void 0:u.path)===y.path?"page":void 0,className:`settings-nav ${(u==null?void 0:u.path)===y.path?"active":""}`,onClick:()=>s(y.path,{state:{settingsBackground:e.background}}),children:[o.jsx(y.icon,{className:"size-4"}),y.title]},y.path))]}),o.jsx("h2",{className:"px-2 pb-1 pt-2 text-sm font-semibold",children:"全局设置"}),o.jsx("nav",{"aria-label":"设置分类",className:"shrink-0",children:["本台应用","连接与服务","所选电脑","状态与诊断"].map(y=>{var N;return o.jsxs("div",{className:"mb-1",children:[o.jsx("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:y}),y==="所选电脑"&&((N=window.electronAPI)==null?void 0:N.isElectron)&&o.jsxs("select",{"aria-label":"所选电脑",className:"mb-1 h-7 w-full rounded-md border bg-background px-2 text-xs",value:(g==null?void 0:g.id)??"",onChange:E=>{const k=new URLSearchParams(n.search);k.set("target",E.target.value),s(`${n.pathname}?${k}`,{state:n.state})},children:[!g&&o.jsx("option",{value:"",children:"请选择电脑"}),e.connections.map(E=>o.jsx("option",{value:E.id,children:E.name},E.id))]}),M0.filter(E=>E.group===y).map(E=>o.jsxs("button",{"aria-current":!c&&E.id===a.id?"page":void 0,className:`settings-nav ${!c&&E.id===a.id?"active":""}`,onClick:()=>i(E.id),children:[o.jsx(E.icon,{className:"size-4"}),E.title]},E.id))]},y)})}),o.jsxs("div",{className:"mt-auto shrink-0 border-t pt-2",children:[o.jsxs("button",{className:"settings-nav text-rose-600 dark:text-rose-400 disabled:cursor-not-allowed disabled:opacity-50",disabled:!t,title:t?"退出工作区当前连接的登录":"请先保存修改或返回工作区放弃修改,并等待当前操作完成",onClick:()=>{t&&(e.workspaceAuth.clearToken(),s("/login"))},children:[o.jsx(bE,{className:"size-4"}),"退出登录"]}),o.jsxs("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:["工作区 · ",((S=e.activeConnection)==null?void 0:S.name)??"当前电脑"]})]})]}),o.jsx("main",{ref:b,className:"settings-content",children:o.jsxs("div",{className:`settings-wrap ${c?"management-wrap":""}`,children:[o.jsxs("header",{className:"mb-4 flex flex-wrap items-center justify-between gap-2",children:[o.jsx(Ur,{asChild:!0,children:o.jsx("h1",{ref:x,tabIndex:-1,className:"text-xl font-semibold outline-none",children:d})}),o.jsx("span",{className:"rounded border px-2 py-1 text-xs text-muted-foreground",children:c?`当前连接 · ${((w=e.activeConnection)==null?void 0:w.name)??"当前电脑"}`:a.scope==="computer"?`所选电脑 · ${(g==null?void 0:g.name)??"当前电脑"}`:a.scope==="account"?"随记账户":"本台应用"})]}),o.jsx(p.Suspense,{fallback:o.jsx("p",{role:"status",children:"正在加载…"}),children:c?o.jsx("div",{className:"management-content",children:e.pageContent}):a.scope==="computer"?o.jsx(az,{pageId:a.id,connections:e.connections},`${g==null?void 0:g.id}:${g==null?void 0:g.url}:${g==null?void 0:g.generation}:${e.workspaceAuth.sessionId}`):a.id==="connections"?o.jsx(oz,{...e}):l?o.jsx(l,{}):null})]})})]})})})}const m3=p.createContext(null);function zf({activeConnectionId:e,connectionName:t="当前电脑",apiBase:r,children:n,onAuthExpired:s,token:i,remote:a=null,connectionGeneration:l}){const c=ml({apiBase:r,connectionId:e??null,generation:(a==null?void 0:a.generation)??l}),u=p.useMemo(()=>({activeConnectionId:e??null,connectionName:t,apiBase:r,onAuthExpired:s,scope:c,token:i,remote:a}),[e,t,r,s,a,c,i]);return o.jsx(m3.Provider,{value:u,children:n})}function vt(){const e=p.useContext(m3);if(!e)throw new Error("TerminalRuntimeProvider is missing");return e}const g1=e=>Symbol.iterator in e,v1=e=>"entries"in e,x1=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[s,i]of r)if(!n.has(s)||!Object.is(i,n.get(s)))return!1;return!0},cz=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let s=r.next(),i=n.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=r.next(),i=n.next()}return!!s.done&&!!i.done};function uz(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:g1(e)&&g1(t)?v1(e)&&v1(t)?x1(e,t):cz(e,t):x1({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function An(e){const t=_t.useRef(void 0);return r=>{const n=e(r);return uz(t.current,n)?t.current:t.current=n}}function Ox(e){return`viewer.terminal.recent.${e}`}function oa(e){const t=ht.getItem(Ox(e));if(!t)return null;try{const r=JSON.parse(t);if(typeof r.projectId!="string")return null;const n=r.projectSessionIds&&typeof r.projectSessionIds=="object"&&!Array.isArray(r.projectSessionIds)?Object.fromEntries(Object.entries(r.projectSessionIds).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string")):{},s=r.contextProjectIdByParentProjectId&&typeof r.contextProjectIdByParentProjectId=="object"&&!Array.isArray(r.contextProjectIdByParentProjectId)?Object.fromEntries(Object.entries(r.contextProjectIdByParentProjectId).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string")):{[r.projectId]:r.projectId};if(typeof r.terminalSessionId=="string"){const i=s[r.projectId]??r.projectId;return{projectId:r.projectId,terminalSessionId:r.terminalSessionId,projectSessionIds:{[i]:r.terminalSessionId,...n},contextProjectIdByParentProjectId:s}}return r.terminalSessionId!==null?null:{projectId:r.projectId,terminalSessionId:null,projectSessionIds:n,contextProjectIdByParentProjectId:s}}catch{return null}}function dz(e,t){const r=oa(e),n={...(r==null?void 0:r.projectSessionIds)??{}};t.terminalSessionId&&(n[t.projectId]=t.terminalSessionId);const s={...(r==null?void 0:r.contextProjectIdByParentProjectId)??{},[t.parentProjectId]:t.projectId};ht.setItem(Ox(e),JSON.stringify({projectId:t.parentProjectId,terminalSessionId:t.terminalSessionId,projectSessionIds:n,contextProjectIdByParentProjectId:s}))}function hz(e,t,r){const n=oa(e);if(!n)return;const s={...n.projectSessionIds},i=s[r];delete s[r];const a={...n.contextProjectIdByParentProjectId};a[t]===r&&(a[t]=t),ht.setItem(Ox(e),JSON.stringify({projectId:n.projectId,terminalSessionId:n.terminalSessionId===i?null:n.terminalSessionId,projectSessionIds:s,contextProjectIdByParentProjectId:a}))}const jt={all:e=>["connection",e,"terminal"],projects:e=>[...jt.all(e),"projects"],projectContexts:(e,t)=>[...jt.all(e),"project-contexts",t],projectContextBranchStatuses:(e,t)=>[...jt.all(e),"project-context-branch-statuses",t],workspaceServices:(e,t,r)=>[...jt.all(e),"workspace-services",t,r],sessions:e=>[...jt.all(e),"sessions"],preview:(e,t)=>[...jt.all(e),"preview",t],previewFileSearch:e=>[...jt.preview(e.scope,e.projectId),"file-search",e.query],previewFile:e=>[...jt.preview(e.scope,e.projectId),"file",e.path],previewChanges:(e,t)=>[...jt.preview(e,t),"changes"],previewDiff:e=>[...jt.preview(e.scope,e.projectId),"diff",e.kind,e.path]},_o=[],bs=[],Uf=[];function fz(e){var r;return((r=e.state.data)==null?void 0:r.services.some(n=>n.status==="starting"||n.status==="stopping"))?1e3:3e3}function _s(){const{apiBase:e,scope:t,token:r}=vt();return Ct({queryKey:jt.projects(t),queryFn:()=>Hv(e,r)})}function Zn(){const{apiBase:e,scope:t,token:r}=vt();return Ct({queryKey:jt.sessions(t),queryFn:()=>_u(e,r)})}function Hf(e){var a;const{apiBase:t,scope:r,token:n}=vt(),i=((a=_s().data)==null?void 0:a.some(l=>l.projectId===e))??!1;return Ct({queryKey:jt.projectContexts(r,e??""),queryFn:()=>eE(t,n,e??""),enabled:!!(e&&i),refetchInterval:3e3,refetchOnWindowFocus:!0})}function pz(e,t,r=!0){var c;const{apiBase:n,scope:s,token:i}=vt(),l=((c=_s().data)==null?void 0:c.some(u=>u.projectId===e))??!1;return Ct({queryKey:jt.workspaceServices(s,e??"",t??""),queryFn:()=>rL(n,i,e??"",t??""),enabled:u=>r&&!!(e&&t&&l)&&!oE(u.state.error),refetchInterval:fz,refetchOnWindowFocus:!0,retry:!1})}function Al(){const e=xs(),{scope:t}=vt();return{queryClient:e,scope:t}}function om(e,t,r){e.setQueryData(jt.projects(t),n=>r(n??_o))}function Ga(e,t,r){e.setQueryData(jt.sessions(t),n=>r(n??bs))}const g3=6e5;function v3(e){return e.state!=="ready"||!e.checkedAt||Date.now()-Date.parse(e.checkedAt)>=g3}function mz(e,t,r){var u,d;const{apiBase:n,scope:s,token:i}=vt(),l=((d=(u=_s().data)==null?void 0:u.find(h=>h.projectId===e))==null?void 0:d.mainBranch)??null,c=t.filter(h=>h.availability==="available"&&h.path);return Ct({queryKey:[...jt.projectContextBranchStatuses(s,e??""),l,c.map(({projectId:h,path:f,head:m})=>[h,f,m])],queryFn:async()=>{const h=[];for(let f=0;f<c.length;f+=4){const m=await B6(n,i,e??"",{projectIds:c.slice(f,f+4).map(g=>g.projectId)});h.push(...m.statuses)}return h},enabled:r&&!!e&&c.length>0,staleTime:3e4,refetchInterval:h=>h.state.error||!h.state.data||h.state.data.some(f=>f.state!=="not-repository"&&v3(f))?3e4:g3,refetchOnWindowFocus:!0,retry:!1})}function x3(){const e=Zn().data??bs,t=tt(An(r=>({bellMarkers:r.bellMarkers,completionMarkers:r.completionMarkers,terminalStateBySessionId:r.terminalStateBySessionId})));return p.useMemo(()=>FO(t,e),[t,e])}var b3="AlertDialog",[gz]=bi(b3,[vk]),yi=vk(),_3=e=>{const{__scopeAlertDialog:t,...r}=e,n=yi(t);return o.jsx(lx,{...n,...r,modal:!0})};_3.displayName=b3;var vz="AlertDialogTrigger",y3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Dk,{...s,...n,ref:t})});y3.displayName=vz;var xz="AlertDialogPortal",w3=e=>{const{__scopeAlertDialog:t,...r}=e,n=yi(t);return o.jsx(cx,{...n,...r})};w3.displayName=xz;var bz="AlertDialogOverlay",S3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(ku,{...s,...n,ref:t})});S3.displayName=bz;var Ya="AlertDialogContent",[_z,yz]=gz(Ya),wz=K7("AlertDialogContent"),C3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,children:n,...s}=e,i=yi(r),a=p.useRef(null),l=wr(t,a),c=p.useRef(null);return o.jsx(Z9,{contentName:Ya,titleName:E3,docsSlug:"alert-dialog",children:o.jsx(_z,{scope:r,cancelRef:c,children:o.jsxs(Cl,{role:"alertdialog",...i,...s,ref:l,onOpenAutoFocus:st(s.onOpenAutoFocus,u=>{var d;u.preventDefault(),(d=c.current)==null||d.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[o.jsx(wz,{children:n}),o.jsx(Cz,{contentRef:a})]})})})});C3.displayName=Ya;var E3="AlertDialogTitle",k3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Iu,{...s,...n,ref:t})});k3.displayName=E3;var I3="AlertDialogDescription",N3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Nu,{...s,...n,ref:t})});N3.displayName=I3;var Sz="AlertDialogAction",R3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Ru,{...s,...n,ref:t})});R3.displayName=Sz;var j3="AlertDialogCancel",A3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,{cancelRef:s}=yz(j3,r),i=yi(r),a=wr(t,s);return o.jsx(Ru,{...i,...n,ref:a})});A3.displayName=j3;var Cz=({contentRef:e})=>{const t=`\`${Ya}\` requires a description for the component to be accessible for screen reader users.
|
|
490
|
+
`)}`)}),s=t.find(a=>a.id===`${wh}number`),i=t.find(a=>a.id===`${wh}build`);return o.jsxs("div",{className:"min-w-0 border-t border-border/50 py-3 first:border-0","data-runtime-version":e,children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("span",{className:"text-sm font-medium",children:e}),o.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[o.jsx("span",{className:"break-all text-right font-mono text-xs",children:(s==null?void 0:s.value)??"未上报"}),t.length>0?o.jsx("button",{type:"button","aria-label":`复制 ${e} 版本`,className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted",onClick:()=>void n(),children:o.jsx(go,{className:"h-3 w-3"})}):null]})]}),i?o.jsx("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:i.value}):null,r?o.jsx("p",{className:"mt-1 text-xs text-amber-600",children:"最近上报,当前状态无法确认"}):null,t.length>1?o.jsxs("details",{className:"mt-1 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer",children:"构建详情"}),o.jsx("dl",{className:"mt-2 space-y-1",children:t.filter(a=>a!==s&&a!==i).map(a=>o.jsxs("div",{children:[o.jsxs("dt",{className:"inline",children:[a.label,":"]}),o.jsx("dd",{className:"inline break-all font-mono",children:a.value})]},a.id))})]}):null]})}function CB({items:e}){return o.jsxs("section",{className:"rounded-xl border border-border/70 px-4 py-3","aria-label":"组件版本",children:[o.jsx("h3",{className:"text-sm font-medium",children:"组件版本"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"服务上报的运行版本;CLI 为此节点可调用的 rw。"}),o.jsx("div",{className:"mt-2",children:SB.filter(([t])=>t!=="electron.process"||e.some(r=>r.id===t)).map(([t,r])=>{const n=e.find(s=>s.id===t);return o.jsx(Vk,{label:r,facts:(n==null?void 0:n.facts.filter(s=>s.id.startsWith(wh)))??[],historical:!!n&&["blocked","unhealthy","disabled"].includes(n.state)},t)})})]})}const EB=F4(hu());function kB(){return o.jsx("section",{className:"rounded-xl border border-border/70 px-4","aria-label":"当前页面版本",children:o.jsx(Vk,{label:"Web(当前页面)",facts:EB})})}const IB=[{path:"screenRecording.analysis.enabled",type:"boolean",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"启用本机屏幕事项分析,默认关闭",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.deviceID",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"绑定 ScreenJournal 设备身份",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.effectiveFrom",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"屏幕分析生效日期时间 ISO8601",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.model",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"已验证图片能力的 Codex 模型",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"screenRecording.analysis.effort",type:"string",domain:"screenRecording.analysis",sensitive:!1,remote:!1,apply:"reload",description:"显式模型推理强度",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"storage.screenAnalysisDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"本实例屏幕分析临时作业目录",environmentKeys:[],owner:"backend/screen-recording-analysis",scope:"instance",storage:"settings.yaml",default:{rule:"实例数据目录下 screen-analysis"},migrationSources:["new-field:no-legacy-source"]},{path:"backend.taskSupervision.enabled",type:"boolean",domain:"backend.taskSupervision",sensitive:!1,remote:!1,apply:"reload",description:"启用当前 Codex 终端长任务监控(仍需逐任务手动开启)",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["new-field:no-legacy-source"]},{modelSelection:{provider:"codex",effortPath:"backend.taskSupervision.effort",label:"长任务监控模型",allowDefaultEffort:!1},path:"backend.taskSupervision.model",type:"string",domain:"backend.taskSupervision",sensitive:!1,remote:!0,apply:"reload",description:"长任务监控模型,供目标整理和最终判断使用",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:"gpt-6-astra"},migrationSources:["new-field:no-legacy-source"]},{path:"backend.taskSupervision.effort",type:"string",domain:"backend.taskSupervision",sensitive:!1,remote:!0,apply:"reload",description:"长任务监控推理强度:low、medium、high、xhigh、max 或 ultra",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:"high"},migrationSources:["new-field:no-legacy-source"]},{path:"backend.taskSupervision.classificationTimeoutMs",type:"integer",domain:"backend.taskSupervision",sensitive:!1,remote:!1,apply:"reload",description:"三分类最长等待毫秒,需小于原生 Hook 等待预算",environmentKeys:[],owner:"backend/task-supervision",scope:"instance",storage:"settings.yaml",default:{value:9e4},migrationSources:["new-field:no-legacy-source"]},{path:"backend.server.port",type:"integer",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"Backend 监听端口",environmentKeys:["PORT","RUNWEAVE_BACKEND_PORT"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{value:5001},migrationSources:["PORT","RUNWEAVE_BACKEND_PORT"]},{path:"backend.server.host",type:"string",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"Backend 监听地址",environmentKeys:["HOST"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{rule:"独立 Backend 默认 127.0.0.1;桌面托管 Backend 默认 0.0.0.0,由启动入口传入;显式配置优先。"},migrationSources:["HOST"]},{path:"backend.server.strictPort",type:"boolean",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"端口占用时拒绝换端口",environmentKeys:["PORT_STRICT"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{rule:"Stable 恒为 true;Dev Session 按分配端口启动且不得占用其他实例。"},migrationSources:["PORT_STRICT"]},{path:"backend.server.frontendOrigin",type:"string",domain:"backend.server",sensitive:!1,remote:!1,apply:"restart",description:"前端允许来源",environmentKeys:["FRONTEND_ORIGIN"],owner:"backend/bootstrap",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时仅允许现有同源、本机和受控桌面来源;不自动允许任意网站。"},migrationSources:["FRONTEND_ORIGIN"]},{path:"backend.auth.username",type:"string",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"登录用户名",environmentKeys:["AUTH_USERNAME"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["backend-auth.json.username"]},{path:"backend.auth.password",type:"string",domain:"backend.auth",sensitive:!0,remote:!1,apply:"restart",description:"登录密码",environmentKeys:["AUTH_PASSWORD"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["backend-auth.json.password"]},{path:"backend.auth.jwtSecret",type:"string",domain:"backend.auth",sensitive:!0,remote:!1,apply:"restart",description:"JWT 签名密钥",environmentKeys:["AUTH_JWT_SECRET"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["backend-auth.json.jwtSecret"]},{path:"backend.auth.accessTokenTtlSeconds",type:"number",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"访问凭据有效秒数",environmentKeys:["AUTH_ACCESS_TOKEN_TTL_SECONDS","AUTH_TOKEN_TTL_SECONDS"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:86400},migrationSources:["AUTH_ACCESS_TOKEN_TTL_SECONDS","AUTH_TOKEN_TTL_SECONDS"]},{path:"backend.auth.refreshTokenTtlSeconds",type:"number",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"刷新凭据有效秒数",environmentKeys:["AUTH_REFRESH_TOKEN_TTL_SECONDS"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:2592e3},migrationSources:["AUTH_REFRESH_TOKEN_TTL_SECONDS"]},{path:"backend.auth.refreshCookieName",type:"string",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"刷新 Cookie 名称",environmentKeys:["AUTH_REFRESH_COOKIE_NAME"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:"viewer_refresh"},migrationSources:["AUTH_REFRESH_COOKIE_NAME"]},{path:"backend.auth.secureCookies",type:"boolean",domain:"backend.auth",sensitive:!1,remote:!1,apply:"restart",description:"Cookie 安全标志",environmentKeys:["AUTH_COOKIE_SECURE"],owner:"backend/auth",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["AUTH_COOKIE_SECURE"]},{path:"backend.tunnelAuth.scope",type:"string",domain:"backend.tunnelAuth",sensitive:!1,remote:!1,apply:"restart",description:"隧道认证作用域",environmentKeys:["RUNWEAVE_TUNNEL_AUTH_SCOPE"],owner:"backend/server",scope:"instance",storage:"settings.yaml",default:{value:"forwarded"},migrationSources:["RUNWEAVE_TUNNEL_AUTH_SCOPE"]},{path:"backend.tunnelAuth.cookieName",type:"string",domain:"backend.tunnelAuth",sensitive:!1,remote:!1,apply:"restart",description:"隧道 Cookie 名称",environmentKeys:["RUNWEAVE_TUNNEL_COOKIE_NAME"],owner:"backend/server",scope:"instance",storage:"settings.yaml",default:{value:"runweave_tunnel"},migrationSources:["RUNWEAVE_TUNNEL_COOKIE_NAME"]},{path:"backend.tunnelAuth.token",type:"string",domain:"backend.tunnelAuth",sensitive:!0,remote:!1,apply:"restart",description:"隧道认证凭据",environmentKeys:["RUNWEAVE_TUNNEL_TOKEN"],owner:"backend/server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_TUNNEL_TOKEN"]},{path:"services.snapshotPublisher.url",type:"string",domain:"services.snapshotPublisher",sensitive:!1,remote:!0,apply:"reload",description:"分享发布服务地址",environmentKeys:["RUNWEAVE_SNAPSHOT_PUBLISH_URL"],owner:"backend/terminal/snapshot-share",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_PUBLISH_URL"]},{path:"services.snapshotPublisher.token",type:"string",domain:"services.snapshotPublisher",sensitive:!0,remote:!0,apply:"reload",description:"分享发布凭据",environmentKeys:["RUNWEAVE_SNAPSHOT_PUBLISH_TOKEN"],owner:"backend/terminal/snapshot-share",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_PUBLISH_TOKEN"]},{path:"services.snapshotHost.directory",type:"string",domain:"services.snapshotHost",sensitive:!1,remote:!1,apply:"restart",description:"独立分享 Host 存储目录",environmentKeys:["RUNWEAVE_SNAPSHOT_HOST_DIR"],owner:"backend/snapshot-share-host",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_HOST_DIR"]},{path:"services.snapshotHost.port",type:"integer",domain:"services.snapshotHost",sensitive:!1,remote:!1,apply:"restart",description:"独立分享 Host 监听端口",environmentKeys:["RUNWEAVE_SNAPSHOT_HOST_PORT"],owner:"backend/snapshot-share-host",scope:"instance",storage:"settings.yaml",default:{value:8093},migrationSources:["RUNWEAVE_SNAPSHOT_HOST_PORT"]},{path:"services.snapshotHost.uploadToken",type:"string",domain:"services.snapshotHost",sensitive:!0,remote:!1,apply:"restart",description:"独立分享 Host 上传凭据",environmentKeys:["RUNWEAVE_SNAPSHOT_UPLOAD_TOKEN"],owner:"backend/snapshot-share-host",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["RUNWEAVE_SNAPSHOT_UPLOAD_TOKEN"]},{path:"services.pushSender.gatewayURL",type:"string",domain:"services.pushSender",sensitive:!1,remote:!0,apply:"reload",description:"推送网关地址",environmentKeys:["RUNWEAVE_PUSH_GATEWAY_URL"],owner:"backend/device-monitor",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["device-monitor/push.json.gatewayURL"]},{path:"services.pushSender.senderToken",type:"string",domain:"services.pushSender",sensitive:!0,remote:!0,apply:"reload",description:"推送发送凭据",environmentKeys:["RUNWEAVE_PUSH_SENDER_TOKEN"],owner:"backend/device-monitor",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["device-monitor/push.json.senderToken"]},{path:"services.pushGateway.keyId",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"APNs key ID",environmentKeys:["APNS_KEY_ID"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["APNS_KEY_ID"]},{path:"services.pushGateway.teamId",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"APNs team ID",environmentKeys:["APNS_TEAM_ID"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["APNS_TEAM_ID"]},{path:"services.pushGateway.privateKeyFile",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"APNs 私钥文件引用",environmentKeys:["APNS_PRIVATE_KEY_FILE"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["APNS_PRIVATE_KEY_FILE"]},{path:"services.pushGateway.directory",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"独立推送网关数据目录",environmentKeys:["PUSH_GATEWAY_DATA_DIR"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["PUSH_GATEWAY_DATA_DIR"]},{path:"services.pushGateway.port",type:"integer",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"独立推送网关端口",environmentKeys:["PUSH_GATEWAY_PORT"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:8092},migrationSources:["PUSH_GATEWAY_PORT"]},{path:"services.pushGateway.bind",type:"string",domain:"services.pushGateway",sensitive:!1,remote:!1,apply:"restart",description:"独立推送网关监听地址",environmentKeys:["PUSH_GATEWAY_BIND"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["PUSH_GATEWAY_BIND"]},{path:"services.pushGateway.adminToken",type:"string",domain:"services.pushGateway",sensitive:!0,remote:!1,apply:"restart",description:"独立推送网关管理凭据",environmentKeys:["PUSH_GATEWAY_ADMIN_TOKEN"],owner:"push-gateway",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["PUSH_GATEWAY_ADMIN_TOKEN"]},{path:"services.feishu.role",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"飞书运行角色",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:"standalone"},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.host",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"集中 Bridge 监听地址",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.port",type:"integer",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"集中 Bridge 监听端口",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.backends.<backendId>.token",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"节点独立接入凭据",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.hub.backends.<backendId>.displayName",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"通知中的机器显示名(可选,不参与路由)",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.node.url",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"集中 Bridge HTTPS origin",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.node.caCertificate",type:"string",domain:"services.feishu",sensitive:!1,remote:!1,apply:"restart",description:"仅用于飞书 WSS 的可选 PEM CA 公共证书,仍校验主机名及有效期",environmentKeys:[],owner:"backend/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.node.token",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"本节点接入凭据",environmentKeys:[],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new field; no legacy source"]},{path:"services.feishu.appId",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"飞书应用 ID",environmentKeys:["FEISHU_APP_ID"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_APP_ID"]},{path:"services.feishu.appSecret",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"飞书应用密钥",environmentKeys:["FEISHU_APP_SECRET"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_APP_SECRET"]},{path:"services.feishu.targetChatId",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"飞书目标群聊",environmentKeys:["FEISHU_TARGET_CHAT_ID"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_TARGET_CHAT_ID"]},{path:"services.feishu.allowedOpenIds",type:"array<string>",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"允许调用的用户 ID",environmentKeys:["FEISHU_ALLOWED_OPEN_IDS"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["FEISHU_ALLOWED_OPEN_IDS"]},{path:"services.feishu.notifyOpenIds",type:"array<string>",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"接收通知的用户 ID",environmentKeys:["FEISHU_NOTIFY_OPEN_IDS"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["FEISHU_NOTIFY_OPEN_IDS"]},{path:"services.feishu.legacyWebhook.url",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"旧通知 hook webhook;迁移前核对使用者",environmentKeys:["FEISHU_WEBHOOK_URL"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_WEBHOOK_URL"]},{path:"services.feishu.legacyWebhook.secret",type:"string",domain:"services.feishu",sensitive:!0,remote:!0,apply:"restart",description:"旧通知 hook webhook 签名密钥",environmentKeys:["FEISHU_WEBHOOK_SECRET"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_WEBHOOK_SECRET"]},{path:"services.feishu.legacyWebhook.transport",type:"string",domain:"services.feishu",sensitive:!1,remote:!0,apply:"restart",description:"旧通知 hook 发送方式",environmentKeys:["FEISHU_NOTIFY_TRANSPORT"],owner:"cli/feishu",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["FEISHU_NOTIFY_TRANSPORT"]},{path:"agents.codex.binary",type:"string",domain:"agents.codex",sensitive:!1,remote:!1,apply:"restart",description:"Codex 可执行文件",environmentKeys:["CODEX_BIN","RUNWEAVE_CODEX_BIN"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时通过 PATH / 平台安装位置查找 codex;显式配置指向同一可执行程序。"},migrationSources:["CODEX_BIN","RUNWEAVE_CODEX_BIN"]},{path:"agents.traex.binary",type:"string",domain:"agents.traex",sensitive:!1,remote:!1,apply:"restart",description:"Trae 可执行文件;多个入口统一",environmentKeys:["TRAEX_BIN","RUNWEAVE_TRAE_BIN"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时通过 PATH / 平台安装位置查找 traex;显式配置指向同一可执行程序。"},migrationSources:["TRAEX_BIN","RUNWEAVE_TRAE_BIN"]},{path:"agents.claude.binary",type:"string",domain:"agents.claude",sensitive:!1,remote:!1,apply:"restart",description:"Claude Code 可执行文件;仅限程序名或绝对路径,不接受命令参数",environmentKeys:[],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"使用当前 Backend 的 PATH 查找 claude;不改变现有默认 provider。"},migrationSources:["new-field:no-legacy-source"]},{path:"agents.claude.configDirectory",type:"string",domain:"agents.claude",sensitive:!1,remote:!1,apply:"restart",description:"Claude 原生配置目录的外部引用;会话根为其 projects 子目录,不复制凭据",environmentKeys:["CLAUDE_CONFIG_DIR"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"显式实例目录优先,否则引用外部 CLAUDE_CONFIG_DIR 或操作系统用户目录下 .claude;必须为绝对路径。"},migrationSources:["CLAUDE_CONFIG_DIR"]},{path:"agents.companion.binary",type:"string",domain:"agents.companion",sensitive:!1,remote:!1,apply:"restart",description:"伴随窗口 Agent 可执行文件",environmentKeys:["RUNWEAVE_COMPANION_AGENT_EXECUTABLE"],owner:"electron/companion",scope:"instance",storage:"settings.yaml",default:{rule:"使用已安装 Codex App 自带执行入口;显式值必须可执行。"},migrationSources:["RUNWEAVE_COMPANION_AGENT_EXECUTABLE"]},{path:"agents.codex.sessionsDirectory",type:"string",domain:"agents.codex",sensitive:!1,remote:!1,apply:"restart",description:"外部 Codex 会话目录引用",environmentKeys:["RUNWEAVE_CODEX_SESSIONS_DIR"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"外部工具拥有的 CODEX_HOME/sessions 或操作系统用户目录下 .codex/sessions,仅引用。"},migrationSources:["RUNWEAVE_CODEX_SESSIONS_DIR"]},{path:"agents.traex.sessionsDirectory",type:"string",domain:"agents.traex",sensitive:!1,remote:!1,apply:"restart",description:"外部 Trae 会话目录引用",environmentKeys:["RUNWEAVE_TRAE_SESSIONS_DIR"],owner:"backend+app-server",scope:"instance",storage:"settings.yaml",default:{rule:"操作系统用户目录下 .trae/cli/sessions,仅引用。"},migrationSources:["RUNWEAVE_TRAE_SESSIONS_DIR"]},{path:"terminal.defaultShell.command",type:"string",domain:"terminal.defaultShell",sensitive:!1,remote:!1,apply:"reload",description:"当前电脑新终端的默认可执行文件;缺省使用系统 Shell,启动不可用时回退系统默认",environmentKeys:[],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{rule:"系统账户登录 Shell;Windows 使用 ComSpec;不可用时采用平台兜底"},migrationSources:["new-field:no-legacy-source"]},{path:"terminal.defaultShell.args",type:"array<string>",domain:"terminal.defaultShell",sensitive:!1,remote:!1,apply:"reload",description:"默认 Shell 的启动参数;空数组明确不加参数,缺省保留 bash/zsh 的 -l 行为",environmentKeys:[],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{rule:"根据所选程序解析;bash/zsh 为 [-l],其他为空数组"},migrationSources:["new-field:no-legacy-source"]},{path:"terminal.tmux.enabled",type:"boolean",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"tmux 持久终端开关",environmentKeys:["TERMINAL_TMUX_ENABLED"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["TERMINAL_TMUX_ENABLED"]},{path:"terminal.tmux.binary",type:"string",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"tmux 可执行文件",environmentKeys:["TMUX_BINARY"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:"tmux"},migrationSources:["TMUX_BINARY"]},{path:"terminal.tmux.shutdownPolicy",type:"string",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"退出时 tmux 保留策略",environmentKeys:["TERMINAL_TMUX_SHUTDOWN_POLICY"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{rule:"Stable 为 preserve,Dev 为 cleanup。"},migrationSources:["TERMINAL_TMUX_SHUTDOWN_POLICY"]},{path:"terminal.tmux.scanOrphansOnStart",type:"boolean",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"启动时检查孤儿终端",environmentKeys:["TERMINAL_TMUX_SCAN_ORPHANS_ON_START"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["TERMINAL_TMUX_SCAN_ORPHANS_ON_START"]},{path:"terminal.tmux.cleanupOrphans",type:"boolean",domain:"terminal",sensitive:!1,remote:!1,apply:"restart",description:"孤儿终端清理策略",environmentKeys:["TERMINAL_TMUX_CLEANUP_ORPHANS"],owner:"backend/terminal",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["TERMINAL_TMUX_CLEANUP_ORPHANS"]},{path:"scheduledTasks.enabled",type:"boolean",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"定时任务开关",environmentKeys:["RUNWEAVE_SCHEDULED_TASKS_ENABLED"],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["RUNWEAVE_SCHEDULED_TASKS_ENABLED"]},{path:"scheduledTasks.timeoutMs",type:"number",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"任务超时毫秒数",environmentKeys:["RUNWEAVE_SCHEDULED_TASK_TIMEOUT_MS"],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:72e5},migrationSources:["RUNWEAVE_SCHEDULED_TASK_TIMEOUT_MS"]},{path:"scheduledTasks.maxOutputBytes",type:"integer",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"任务输出上限字节数",environmentKeys:["RUNWEAVE_SCHEDULED_TASK_MAX_OUTPUT_BYTES"],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:16777216},migrationSources:["RUNWEAVE_SCHEDULED_TASK_MAX_OUTPUT_BYTES"]},{path:"scheduledTasks.maxConcurrentRuns",type:"integer",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"同时执行的后台任务数",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:4},migrationSources:["new-field:no-legacy-source"]},{modelSelection:{provider:"codex",effortPath:"scheduledTasks.quickInputDefaults.effort",label:"快捷指令后台运行模型",allowDefaultEffort:!0},path:"scheduledTasks.quickInputDefaults.model",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"快捷指令后台运行的 Codex 模型;必须显式选择",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"scheduledTasks.quickInputDefaults.effort",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"快捷指令后台运行的推理强度",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["new-field:no-legacy-source"]},{path:"scheduledTasks.quickInputDefaults.continuationMode",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"新快捷运行自动继续策略:bounded 或 off",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:"bounded"},migrationSources:["new-field:no-legacy-source"]},{path:"scheduledTasks.quickInputDefaults.executionPolicy",type:"string",domain:"scheduledTasks",sensitive:!1,remote:!0,apply:"restart",description:"快捷指令后台运行的执行权限",environmentKeys:[],owner:"backend/scheduled-tasks",scope:"instance",storage:"settings.yaml",default:{value:"full-access"},migrationSources:["new-field:no-legacy-source"]},{path:"voice.transcription.language",type:"string",domain:"voice",sensitive:!1,remote:!0,apply:"reload",description:"转写语言",environmentKeys:["RUNWEAVE_VOICE_TRANSCRIPTION_LANGUAGE"],owner:"backend/voice",scope:"instance",storage:"settings.yaml",default:{value:"zh"},migrationSources:["RUNWEAVE_VOICE_TRANSCRIPTION_LANGUAGE"]},{path:"voice.transcription.acceptLanguage",type:"string",domain:"voice",sensitive:!1,remote:!0,apply:"reload",description:"转写请求 Accept-Language",environmentKeys:["RUNWEAVE_VOICE_TRANSCRIPTION_ACCEPT_LANGUAGE"],owner:"backend/voice",scope:"instance",storage:"settings.yaml",default:{value:"zh-CN,zh;q=0.9,en;q=0.8"},migrationSources:["RUNWEAVE_VOICE_TRANSCRIPTION_ACCEPT_LANGUAGE"]},{path:"voice.transcription.prompt",type:"string",domain:"voice",sensitive:!1,remote:!0,apply:"reload",description:"转写提示词",environmentKeys:["RUNWEAVE_VOICE_TRANSCRIPTION_PROMPT"],owner:"backend/voice",scope:"instance",storage:"settings.yaml",default:{value:"请使用简体中文输出转写文本。"},migrationSources:["RUNWEAVE_VOICE_TRANSCRIPTION_PROMPT"]},{path:"knowledge.experience.learning",type:"boolean",domain:"knowledge",sensitive:!1,remote:!1,apply:"restart",description:"经验学习开关",environmentKeys:["RUNWEAVE_EXPERIENCE_LEARNING"],owner:"backend/experience",scope:"instance",storage:"settings.yaml",default:{rule:"Stable 默认启用,Dev 默认关闭;明确配置覆盖默认。"},migrationSources:["RUNWEAVE_EXPERIENCE_LEARNING"]},{path:"storage.browserProfileDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"原 Backend profile 的显式目录",environmentKeys:["BROWSER_PROFILE_DIR"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/backend;已有 Stable 必须显式保留旧路径"},migrationSources:["BROWSER_PROFILE_DIR"]},{path:"storage.authStoreFile",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"认证数据库路径",environmentKeys:["AUTH_STORE_FILE"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<browserProfileDirectory>/auth-store.json"},migrationSources:["AUTH_STORE_FILE"]},{path:"storage.terminalSessionStoreFile",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"终端存储路径",environmentKeys:["TERMINAL_SESSION_STORE_FILE"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<browserProfileDirectory>/terminal-session-store.json"},migrationSources:["TERMINAL_SESSION_STORE_FILE"]},{path:"storage.activityKeyStorage",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Activity 密钥保管方式;system 使用平台默认,file 使用存储目录中仅服务用户可读的密钥,独立无界面服务显式选择 file",environmentKeys:[],owner:"backend/activity",scope:"instance",storage:"settings.yaml",default:{value:"system"},migrationSources:["new-server-installation"]},{path:"storage.activityDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Activity 存储根;旧环境仅测试使用",environmentKeys:["RUNWEAVE_ACTIVITY_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/activity"},migrationSources:["RUNWEAVE_ACTIVITY_HOME"]},{path:"storage.evolutionDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Evolution 存储根;旧环境仅测试使用",environmentKeys:["RUNWEAVE_EVOLUTION_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/evolution"},migrationSources:["RUNWEAVE_EVOLUTION_HOME"]},{path:"storage.experienceDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"Experience 存储根",environmentKeys:["RUNWEAVE_EXPERIENCE_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/experience"},migrationSources:["RUNWEAVE_EXPERIENCE_HOME"]},{path:"storage.scheduledTasksDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"定时任务存储根",environmentKeys:["RUNWEAVE_SCHEDULED_TASKS_HOME"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/scheduled-tasks"},migrationSources:["RUNWEAVE_SCHEDULED_TASKS_HOME"]},{path:"storage.feishuDirectory",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"飞书状态目录",environmentKeys:["RUNWEAVE_FEISHU_STATE_DIR"],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/feishu"},migrationSources:["RUNWEAVE_FEISHU_STATE_DIR"]},{path:"logging.level",type:"string",domain:"logging",sensitive:!1,remote:!1,apply:"restart",description:"日志级别",environmentKeys:["RUNWEAVE_LOG_LEVEL"],owner:"backend/logging",scope:"instance",storage:"settings.yaml",default:{value:"info"},migrationSources:["RUNWEAVE_LOG_LEVEL"]},{path:"logging.toFile",type:"boolean",domain:"logging",sensitive:!1,remote:!1,apply:"restart",description:"日志落盘开关",environmentKeys:["RUNWEAVE_LOG_TO_FILE"],owner:"backend/logging",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["RUNWEAVE_LOG_TO_FILE"]},{path:"logging.backendDirectory",type:"string",domain:"logging",sensitive:!1,remote:!1,apply:"restart",description:"Backend 日志目录",environmentKeys:["RUNWEAVE_BACKEND_LOG_DIR"],owner:"backend/logging",scope:"instance",storage:"settings.yaml",default:{rule:"<browserProfileDirectory>/logs/backend"},migrationSources:["RUNWEAVE_BACKEND_LOG_DIR"]},{path:"appServer.discovery",type:"string",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"App Server 发现策略",environmentKeys:["RUNWEAVE_APP_SERVER_DISCOVERY"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{value:"auto"},migrationSources:["RUNWEAVE_APP_SERVER_DISCOVERY"]},{path:"appServer.stateDirectory",type:"string",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"App Server 状态目录",environmentKeys:["RUNWEAVE_APP_SERVER_STATE_DIR"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/app-server"},migrationSources:["RUNWEAVE_APP_SERVER_STATE_DIR"]},{path:"appServer.cloudSyncDirectory",type:"string",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"App Server 云同步模拟目录",environmentKeys:["RUNWEAVE_APP_SERVER_CLOUD_SYNC_DIR"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"<configRoot>/data/app-server/cloud-sync"},migrationSources:["RUNWEAVE_APP_SERVER_CLOUD_SYNC_DIR"]},{path:"appServer.codexStatusIntervalMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"Codex 状态轮询间隔",environmentKeys:["RUNWEAVE_APP_SERVER_CODEX_STATUS_INTERVAL_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{value:3e4},migrationSources:["RUNWEAVE_APP_SERVER_CODEX_STATUS_INTERVAL_MS"]},{path:"appServer.codexStatusStartDelayMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"Codex 状态启动延迟",environmentKeys:["RUNWEAVE_APP_SERVER_CODEX_STATUS_START_DELAY_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{value:1e4},migrationSources:["RUNWEAVE_APP_SERVER_CODEX_STATUS_START_DELAY_MS"]},{path:"appServer.threadStatusIntervalMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"线程状态轮询间隔",environmentKeys:["RUNWEAVE_APP_SERVER_THREAD_STATUS_INTERVAL_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"缺省依次采用 appServer.codexStatusIntervalMs 和 30000 ms。"},migrationSources:["RUNWEAVE_APP_SERVER_THREAD_STATUS_INTERVAL_MS"]},{path:"appServer.threadStatusStartDelayMs",type:"number",domain:"appServer",sensitive:!1,remote:!1,apply:"restart",description:"线程状态启动延迟",environmentKeys:["RUNWEAVE_APP_SERVER_THREAD_STATUS_START_DELAY_MS"],owner:"app-server",scope:"instance",storage:"settings.yaml",default:{rule:"缺省依次采用 appServer.codexStatusStartDelayMs 和 10000 ms。"},migrationSources:["RUNWEAVE_APP_SERVER_THREAD_STATUS_START_DELAY_MS"]},{path:"updates.url",type:"string",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"更新源地址;旧别名合并",environmentKeys:["RUNWEAVE_LOCAL_UPDATES_URL","BROWSER_VIEWER_LOCAL_UPDATES_URL"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{rule:"安装包内 app-update.yml 的只读发行默认值;用户值唯一来自本文件。"},migrationSources:["RUNWEAVE_LOCAL_UPDATES_URL","BROWSER_VIEWER_LOCAL_UPDATES_URL"]},{path:"updates.autoInstallLocal",type:"boolean",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"本地更新自动安装策略",environmentKeys:["RUNWEAVE_AUTO_INSTALL_LOCAL_UPDATES","BROWSER_VIEWER_AUTO_INSTALL_LOCAL_UPDATES"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{rule:"未指定时仅本机更新源自动安装。"},migrationSources:["RUNWEAVE_AUTO_INSTALL_LOCAL_UPDATES","BROWSER_VIEWER_AUTO_INSTALL_LOCAL_UPDATES"]},{path:"updates.serverHost",type:"string",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"本机更新服务监听地址",environmentKeys:["RUNWEAVE_LOCAL_UPDATES_HOST","BROWSER_VIEWER_LOCAL_UPDATES_HOST"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["RUNWEAVE_LOCAL_UPDATES_HOST","BROWSER_VIEWER_LOCAL_UPDATES_HOST"]},{path:"updates.serverPort",type:"integer",domain:"updates",sensitive:!1,remote:!1,apply:"restart",description:"本机更新服务监听端口",environmentKeys:["RUNWEAVE_LOCAL_UPDATES_PORT","BROWSER_VIEWER_LOCAL_UPDATES_PORT"],owner:"electron/updater",scope:"instance",storage:"settings.yaml",default:{value:5500},migrationSources:["RUNWEAVE_LOCAL_UPDATES_PORT","BROWSER_VIEWER_LOCAL_UPDATES_PORT"]},{path:"developer.codesignIdentity",type:"string",domain:"developer",sensitive:!1,remote:!1,apply:"restart",description:"本机签名身份选择",environmentKeys:["RUNWEAVE_CODESIGN_IDENTITY"],owner:"scripts/update",scope:"instance",storage:"settings.yaml",default:{rule:"从系统钥匙串可用签名身份中选择;显式更新可将选择写入当前实例。"},migrationSources:["RUNWEAVE_CODESIGN_IDENTITY"]},{path:"developer.minimumFreeBytes",type:"integer",domain:"developer",sensitive:!1,remote:!1,apply:"restart",description:"测试安装资源池剩余磁盘门槛",environmentKeys:["RUNWEAVE_BETA_POOL_MIN_FREE_BYTES"],owner:"scripts/update",scope:"instance",storage:"settings.yaml",default:{rule:"使用 Beta Pool 存储模块的 4 GiB 默认下限。"},migrationSources:["RUNWEAVE_BETA_POOL_MIN_FREE_BYTES"]},{path:"desktop.browser.localEnabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"本机浏览器能力开关",environmentKeys:["RUNWEAVE_BROWSER_LOCAL_ENABLED"],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:!0},migrationSources:["RUNWEAVE_BROWSER_LOCAL_ENABLED"]},{path:"desktop.browser.webMcpEnabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"WebMCP 能力开关",environmentKeys:["RUNWEAVE_BROWSER_WEBMCP"],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["RUNWEAVE_BROWSER_WEBMCP"]},{path:"services.suiji.databaseURL",type:"string",domain:"services.suiji",sensitive:!0,remote:!1,apply:"restart",description:"独立随记服务数据库连接",environmentKeys:["DATABASE_URL"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["DATABASE_URL"]},{path:"services.suiji.storageDirectory",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记附件存储目录",environmentKeys:["SUIJI_STORAGE_DIR"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["SUIJI_STORAGE_DIR"]},{path:"services.suiji.host",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记监听地址",environmentKeys:["SUIJI_HOST"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:"127.0.0.1"},migrationSources:["SUIJI_HOST"]},{path:"services.suiji.port",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记监听端口",environmentKeys:["SUIJI_PORT"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:4783},migrationSources:["SUIJI_PORT"]},{path:"services.suiji.accessSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记访问凭据有效期",environmentKeys:["SUIJI_ACCESS_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:86400},migrationSources:["SUIJI_ACCESS_SECONDS"]},{path:"services.suiji.refreshSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记刷新凭据有效期",environmentKeys:["SUIJI_REFRESH_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:2592e3},migrationSources:["SUIJI_REFRESH_SECONDS"]},{path:"services.suiji.loginAttempts",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记登录尝试次数限制",environmentKeys:["SUIJI_LOGIN_ATTEMPTS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:8},migrationSources:["SUIJI_LOGIN_ATTEMPTS"]},{path:"services.suiji.loginWindowSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记登录限制窗口",environmentKeys:["SUIJI_LOGIN_WINDOW_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:900},migrationSources:["SUIJI_LOGIN_WINDOW_SECONDS"]},{path:"services.suiji.webOrigins",type:"array<string>",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记允许的 Web 来源",environmentKeys:["SUIJI_WEB_ORIGINS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["SUIJI_WEB_ORIGINS"]},{path:"services.suiji.ai.provider",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 AI provider",environmentKeys:["SUIJI_AI_PROVIDER"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:"disabled"},migrationSources:["SUIJI_AI_PROVIDER"]},{path:"services.suiji.ai.codexBinary",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 Codex 可执行文件",environmentKeys:["SUIJI_CODEX_BIN"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:"codex"},migrationSources:["SUIJI_CODEX_BIN"]},{path:"services.suiji.ai.codexHome",type:"string",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记外部 Codex 登录目录引用",environmentKeys:["SUIJI_CODEX_HOME"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["SUIJI_CODEX_HOME"]},{path:"services.suiji.ai.timeoutSeconds",type:"integer",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 AI 超时",environmentKeys:["SUIJI_AI_TIMEOUT_SECONDS"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:180},migrationSources:["SUIJI_AI_TIMEOUT_SECONDS"]},{path:"services.suiji.mcpEnabled",type:"boolean",domain:"services.suiji",sensitive:!1,remote:!1,apply:"restart",description:"随记 MCP 开关",environmentKeys:["SUIJI_MCP_ENABLED"],owner:"suiji-server",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["SUIJI_MCP_ENABLED"]},{path:"cli.activeProfile",type:"string",domain:"cli",sensitive:!1,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:"local"},migrationSources:["CLI.config.activeProfile"]},{path:"cli.profiles.<name>.baseUrl",type:"string",domain:"cli",sensitive:!1,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{rule:"未创建连接时使用当前实例的本机端口;Dev 只接受已验证握手的明确连接。"},migrationSources:["CLI.config.profiles.<name>.baseUrl"]},{path:"cli.profiles.<name>.accessToken",type:"string",domain:"cli",sensitive:!0,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["CLI.config.profiles.<name>.accessToken"]},{path:"cli.profiles.<name>.refreshToken",type:"string",domain:"cli",sensitive:!0,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["CLI.config.profiles.<name>.refreshToken"]},{path:"cli.profiles.<name>.expiresAt",type:"string",domain:"cli",sensitive:!1,remote:!1,apply:"reload",description:"CLI 连接配置及会话;敏感字段仅本机可读写",environmentKeys:[],owner:"cli/profile-store",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["CLI.config.profiles.<name>.expiresAt"]},{path:"desktop.preferences.companion.enabled",type:"boolean",domain:"desktop.preferences",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/companion",scope:"instance",storage:"settings.yaml",default:{rule:"缺省时 Stable 启用、Dev 关闭;全新安装初始化会显式写入 false,优先于此规则。"},migrationSources:["desktop-companion.json.enabled"]},{path:"desktop.browser.proxy.enabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["terminal-browser-proxy.json.enabled"]},{path:"desktop.browser.proxy.port",type:"integer",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:8899},migrationSources:["terminal-browser-proxy.json.port"]},{path:"desktop.browser.defaultProfileId",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:"profile-1"},migrationSources:["terminal-browser-profiles.json.defaultProfileId"]},{path:"desktop.browser.profilePorts.<profileId>",type:"integer",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal-browser-profiles.json.profilePorts.<profileId>"]},{path:"desktop.browser.proxyModes.<profileId>",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{rule:"沿用该 Browser 的宿主默认代理模式;没有持久条目时不创建覆盖。"},migrationSources:["terminal-browser-profiles.json.proxyModes.<profileId>"]},{path:"desktop.browser.worktrees.<projectId>.preferredProfileId",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"持久配置字段",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal-browser-profiles.json.worktrees.<projectId>.preferredProfileId"]},{path:"desktop.browser.headerRules.<profileId>[].id",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.id"]},{path:"desktop.browser.headerRules.<profileId>[].enabled",type:"boolean",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.enabled"]},{path:"desktop.browser.headerRules.<profileId>[].operation",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.operation"]},{path:"desktop.browser.headerRules.<profileId>[].name",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.name"]},{path:"desktop.browser.headerRules.<profileId>[].value",type:"string",domain:"desktop.browser",sensitive:!0,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.value"]},{path:"desktop.browser.headerRules.<profileId>[].urlPattern",type:"string",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"浏览器请求头规则;value 可能是凭据,按敏感字段处理",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["terminal.browser.headerRules.<profileId>.urlPattern"]},{path:"desktop.tunnels.desktopId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{rule:"仅全新实例首次初始化生成 UUID;存在旧文件必须先显式迁移。"},migrationSources:["tunnels/config.json.desktopId"]},{path:"desktop.tunnels.hosts[].id",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].id"]},{path:"desktop.tunnels.hosts[].name",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].name"]},{path:"desktop.tunnels.hosts[].sshTarget",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].sshTarget"]},{path:"desktop.tunnels.hosts[].autoConnect",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].autoConnect"]},{path:"desktop.tunnels.hosts[].remoteAccess.enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteAccess.enabled"]},{path:"desktop.tunnels.hosts[].remoteAccess.listenAddress",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteAccess.listenAddress"]},{path:"desktop.tunnels.hosts[].remoteAccess.port",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteAccess.port"]},{path:"desktop.tunnels.hosts[].remoteDesktop.enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"是否启用由 Runweave 管理的 RemoteDesk 隧道",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.enabled"]},{path:"desktop.tunnels.hosts[].remoteDesktop.autoDetectLocalHost",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"自动读取本机 RemoteDesk 地址与端口,保持已保存的证书指纹;旧配置未设置时沿用手动地址",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:!1},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.autoDetectLocalHost"]},{path:"desktop.tunnels.hosts[].remoteDesktop.listenAddress",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"Devbox 内网或 VPN 入口 IPv4",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.listenAddress"]},{path:"desktop.tunnels.hosts[].remoteDesktop.port",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"RemoteDesk 独立中转端口",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.port"]},{path:"desktop.tunnels.hosts[].remoteDesktop.localAddress",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"本机 RemoteDesk 所监听的 LAN IPv4",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.localAddress"]},{path:"desktop.tunnels.hosts[].remoteDesktop.localPort",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"本机 RemoteDesk TLS 监听端口",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.localPort"]},{path:"desktop.tunnels.hosts[].remoteDesktop.certificateFingerprint",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"本机 RemoteDesk 完整 SHA-256 证书指纹",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].remoteDesktop.certificateFingerprint"]},{path:"desktop.tunnels.hosts[].forwards[].id",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].id"]},{path:"desktop.tunnels.hosts[].forwards[].name",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].name"]},{path:"desktop.tunnels.hosts[].forwards[].port",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].port"]},{path:"desktop.tunnels.hosts[].forwards[].path",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].path"]},{path:"desktop.tunnels.hosts[].forwards[].enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].forwards[].enabled"]},{path:"desktop.tunnels.hosts[].browser.enabled",type:"boolean",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.enabled"]},{path:"desktop.tunnels.hosts[].browser.backendPort",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.backendPort"]},{path:"desktop.tunnels.hosts[].browser.profileId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.profileId"]},{path:"desktop.tunnels.hosts[].browser.approvedBrowserGroupId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.hosts[].browser.approvedBrowserGroupId"]},{path:"desktop.tunnels.backendEndpoints[].id",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.backendEndpoints[].id"]},{path:"desktop.tunnels.backendEndpoints[].hostId",type:"string",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.backendEndpoints[].hostId"]},{path:"desktop.tunnels.backendEndpoints[].remotePort",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"隧道配置;desktopId/host ID 迁移时必须保持",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["tunnels/config.json.backendEndpoints[].remotePort"]},{path:"services.pushSender.hostId",type:"string",domain:"services.pushSender",sensitive:!1,remote:!1,apply:"reload",description:"推送主机身份,迁移保留,不自动生成替代身份",environmentKeys:[],owner:"backend/device-monitor",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["device-monitor/push.json.hostId"]},{path:"storage.terminalQuickInputStoreFile",type:"string",domain:"storage",sensitive:!1,remote:!1,apply:"restart",description:"旧配置/内容文件定位;模型迁移后其旧路径仅作来源记录",environmentKeys:[],owner:"config-node/paths",scope:"instance",storage:"settings.yaml",default:{rule:"<terminalSessionStoreFile 所在目录>/terminal-quick-inputs.json"},migrationSources:["StoragePaths.terminalQuickInputStoreFile"]},{path:"desktop.browser.pendingPortMigration.<profileId>",type:"array<number>",domain:"desktop.browser",sensitive:!1,remote:!1,apply:"reload",description:"迁移保留的域版本及偏好状态",environmentKeys:[],owner:"electron/browser",scope:"instance",storage:"settings.yaml",default:{value:null},migrationSources:["desktop.browser legacy store (explicit manifest)"]},{path:"desktop.tunnels.revision",type:"integer",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"迁移保留的域版本及偏好状态",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:0},migrationSources:["desktop.tunnels legacy store (explicit manifest)"]},{path:"desktop.tunnels.completedImports",type:"array<string>",domain:"desktop.tunnels",sensitive:!1,remote:!1,apply:"reload",description:"迁移保留的域版本及偏好状态",environmentKeys:[],owner:"electron/tunnels",scope:"instance",storage:"settings.yaml",default:{value:[]},migrationSources:["desktop.tunnels legacy store (explicit manifest)"]}],NB=[["backend.process","Backend","backend"],["app-server.process","App Server","app-server"],["electron.process","Desktop","electron"],["backend.cli-version","CLI(节点 rw)","backend"],["feishu.bridge-lease","飞书 Bridge","feishu-bridge"],["research-mcp.process","调查 MCP","research-mcp"],["snapshot-host.process","快照分享 Host","snapshot-host"],["push-gateway.process","推送网关","push-gateway"],["suiji-server.process","随记服务","suiji-server"],["remote-desktop-host.process","RemoteDesk Host","remote-desktop-host"]];function RB(e){const t=new Map(Uk(e).flatMap(n=>n.items.map(s=>[s.id,s]))),r=[...NB];for(const n of e)for(const s of n.items)(s.capabilityId==="workspace-services"||/^electron\.(cdp-proxy|companion|whistle:|remote-access:|remote-desktop:)/.test(s.id)||/^remote-desktop-host\.(listener|screen-permission|control-permission)$/.test(s.id))&&r.push([s.id,s.label,n.source.id]);return r.map(([n,s,i])=>{var u,d,h;const a=e.find(f=>f.source.id===i),l=t.get(`${i}.source`)??t.get(n)??(a==null?void 0:a.items.find(f=>f.id.endsWith("-report"))),c=(u=l==null?void 0:l.facts.find(f=>f.id==="runtime-installation.state"))==null?void 0:u.value;return{id:n,label:s,sourceId:i,state:(l==null?void 0:l.state)??"unsupported",summary:(l==null?void 0:l.summary)??"未收到此服务的健康报告;未启动、未安装和旧版本无法据此区分",observedAt:(l==null?void 0:l.observedAt)??null,version:((h=(d=t.get(n)??l)==null?void 0:d.facts.find(f=>f.id==="runtime-version.number"))==null?void 0:h.value)??null,installation:(l==null?void 0:l.state)==="healthy"&&(c==="current"||c==="restart-required")?c:"unknown"}})}const jB={healthy:"正常",unhealthy:"异常",blocked:"无法判断",recovering:"恢复中",checking:"检查中",disabled:"已停用",unconfigured:"未配置 / 未上报",unsupported:"未上报 / 需更新"};function AB({reports:e}){const t=RB(e),r=t.filter(s=>["unsupported","unconfigured","blocked","checking"].includes(s.state)).length,n=t.filter(s=>s.installation==="restart-required").length;return o.jsxs("section",{className:"rounded-xl border border-border/70 p-4","aria-label":"本机服务清单",children:[o.jsxs("h3",{className:"text-sm font-medium",children:["服务清单 · ",t.length," 项"]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["此节点所属实例的服务与本机共享 Host;云端和其他实例分别检查。",r>0?` ${r} 项未确认。`:"",n>0?` ${n} 项需要重启。`:""]}),o.jsx("div",{className:"mt-3 divide-y divide-border/50",children:t.map(s=>o.jsxs("details",{className:"py-2","data-runtime-service":s.id,"data-runtime-installation":s.installation,children:[o.jsxs("summary",{className:"flex cursor-pointer items-center justify-between gap-3 text-xs",children:[o.jsx("span",{className:"font-medium",children:s.label}),o.jsxs("span",{className:s.state==="unhealthy"?"text-red-600":s.installation==="restart-required"||["unsupported","unconfigured","blocked","recovering"].includes(s.state)?"text-amber-600":"text-muted-foreground",children:[jB[s.state],s.installation==="restart-required"?" · 需要重启":""]})]}),o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:s.summary}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["运行版本:",s.version??"未上报"," · 安装对照:",s.installation==="current"?"运行产物与安装产物一致":s.installation==="restart-required"?"已安装产物尚未生效,请使用该服务的更新或重启入口":"无法确认;缺少可对照的安装或运行身份"]}),s.observedAt!==null?o.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["最近证据:",new Date(s.observedAt).toLocaleString()]}):null]},s.id))}),o.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"安装一致不代表已包含最新源码;未上报和历史成功不代表当前正常。检查不会自动更新或重启服务。"})]})}const Gk=Object.fromEntries([...new Set(IB.map(e=>e.domain))].map(e=>[e,1]));Object.fromEntries(Object.entries(Gk).map(([e,t])=>[e,[t]]));Object.fromEntries(["appServer","agents.codex","agents.traex","agents.claude"].map(e=>[e,[Gk[e]]]));const TB={"backend.taskSupervision":"长任务监控","backend.server":"Backend 服务","backend.auth":"登录认证","backend.tunnelAuth":"隧道认证","services.snapshotPublisher":"终端分享","services.snapshotHost":"分享托管服务","services.pushSender":"设备通知","services.pushGateway":"推送网关","services.feishu":"飞书","services.suiji":"随记","agents.codex":"Codex","agents.traex":"Traex","agents.claude":"Claude Code","agents.companion":"伴随窗口","desktop.browser":"桌面浏览器","desktop.preferences":"桌面偏好","desktop.tunnels":"远程访问",cli:"CLI 连接",developer:"开发与签名",knowledge:"知识库",logging:"日志",scheduledTasks:"后台任务",storage:"数据存储",terminal:"终端","terminal.defaultShell":"默认 Shell",updates:"更新",voice:"语音",appServer:"App Server"};async function DB(e,t,r,n){const s=await fetch(`${e.replace(/\/+$/,"")}/api/configuration`,{method:n?"PATCH":"GET",redirect:"error",signal:r,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},...n?{body:JSON.stringify(n)}:{}});if(!s.ok){const i=s.status===409?"配置已被其他操作修改,请重新加载后再保存。":s.status===401?"请重新登录当前连接。":s.status===404?"当前电脑版本尚不支持统一配置。":"配置操作失败,请检查字段格式及运行状态。";throw new De(s.status,i)}return s.json()}const Hy={saved:"已保存的配置",default:"默认值",consumerDefault:"由功能模块决定",unset:"未设置",invalid:"配置无效"};function Wy(e,t){if(e.source==="invalid"||e.source==="consumerDefault"||e.source==="unset")return Hy[e.source];if(t){const r=e.value;return r&&typeof r=="object"&&!Array.isArray(r)&&r.configured===!0?"已配置(内容隐藏)":"未配置"}return`${JSON.stringify(e.value)??"未设置"} · ${Hy[e.source]}`}function qy({field:e,status:t,changed:r}){const n=t.state==="applied"?"当前进程已采用":t.state==="pending"?e.apply==="restart"?"已保存,等待所属服务重启":"已保存,等待所属功能重新加载":t.state==="error"?"配置或应用失败":"尚未确认所属服务是否采用";return o.jsxs("div",{className:"space-y-1 break-words text-xs text-muted-foreground",children:[o.jsx("p",{children:n}),o.jsxs("p",{children:["已保存配置的取值:",Wy(t.saved,e.sensitive)]}),t.applied&&o.jsxs("p",{children:["当前进程采用值:",Wy(t.applied,e.sensitive),t.appliedRevision!==null?` · 版本 ${t.appliedRevision}`:""]}),t.saved.source==="consumerDefault"&&"rule"in e.default&&o.jsx("p",{children:e.default.rule}),r&&o.jsx("p",{children:"有未保存的修改;以上为上次读取的结果。"})]})}function Yk(e,t,r){return me(e,"/api/agent-model-catalogs",{headers:{Authorization:`Bearer ${t}`},signal:r})}const PB=["top","right","bottom","left"],ao=Math.min,Rn=Math.max,Th=Math.round,_d=Math.floor,zs=e=>({x:e,y:e}),LB={left:"right",right:"left",bottom:"top",top:"bottom"};function B0(e,t,r){return Rn(e,ao(t,r))}function gi(e,t){return typeof e=="function"?e(t):e}function vi(e){return e.split("-")[0]}function El(e){return e.split("-")[1]}function gx(e){return e==="x"?"y":"x"}function vx(e){return e==="y"?"height":"width"}function Os(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function xx(e){return gx(Os(e))}function MB(e,t,r){r===void 0&&(r=!1);const n=El(e),s=xx(e),i=vx(s);let a=s==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Dh(a)),[a,Dh(a)]}function OB(e){const t=Dh(e);return[F0(e),t,F0(t)]}function F0(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Ky=["left","right"],Vy=["right","left"],BB=["top","bottom"],FB=["bottom","top"];function $B(e,t,r){switch(e){case"top":case"bottom":return r?t?Vy:Ky:t?Ky:Vy;case"left":case"right":return t?BB:FB;default:return[]}}function zB(e,t,r,n){const s=El(e);let i=$B(vi(e),r==="start",n);return s&&(i=i.map(a=>a+"-"+s),t&&(i=i.concat(i.map(F0)))),i}function Dh(e){const t=vi(e);return LB[t]+e.slice(t.length)}function UB(e){return{top:0,right:0,bottom:0,left:0,...e}}function Xk(e){return typeof e!="number"?UB(e):{top:e,right:e,bottom:e,left:e}}function Ph(e){const{x:t,y:r,width:n,height:s}=e;return{width:n,height:s,top:r,left:t,right:t+n,bottom:r+s,x:t,y:r}}function Gy(e,t,r){let{reference:n,floating:s}=e;const i=Os(t),a=xx(t),l=vx(a),c=vi(t),u=i==="y",d=n.x+n.width/2-s.width/2,h=n.y+n.height/2-s.height/2,f=n[l]/2-s[l]/2;let m;switch(c){case"top":m={x:d,y:n.y-s.height};break;case"bottom":m={x:d,y:n.y+n.height};break;case"right":m={x:n.x+n.width,y:h};break;case"left":m={x:n.x-s.width,y:h};break;default:m={x:n.x,y:n.y}}switch(El(t)){case"start":m[a]-=f*(r&&u?-1:1);break;case"end":m[a]+=f*(r&&u?-1:1);break}return m}async function HB(e,t){var r;t===void 0&&(t={});const{x:n,y:s,platform:i,rects:a,elements:l,strategy:c}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:h="floating",altBoundary:f=!1,padding:m=0}=gi(t,e),g=Xk(m),x=l[f?h==="floating"?"reference":"floating":h],b=Ph(await i.getClippingRect({element:(r=await(i.isElement==null?void 0:i.isElement(x)))==null||r?x:x.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:u,rootBoundary:d,strategy:c})),_=h==="floating"?{x:n,y:s,width:a.floating.width,height:a.floating.height}:a.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),S=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},w=Ph(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:_,offsetParent:C,strategy:c}):_);return{top:(b.top-w.top+g.top)/S.y,bottom:(w.bottom-b.bottom+g.bottom)/S.y,left:(b.left-w.left+g.left)/S.x,right:(w.right-b.right+g.right)/S.x}}const WB=50,qB=async(e,t,r)=>{const{placement:n="bottom",strategy:s="absolute",middleware:i=[],platform:a}=r,l=a.detectOverflow?a:{...a,detectOverflow:HB},c=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:d,y:h}=Gy(u,n,c),f=n,m=0;const g={};for(let v=0;v<i.length;v++){const x=i[v];if(!x)continue;const{name:b,fn:_}=x,{x:C,y:S,data:w,reset:y}=await _({x:d,y:h,initialPlacement:n,placement:f,strategy:s,middlewareData:g,rects:u,platform:l,elements:{reference:e,floating:t}});d=C??d,h=S??h,g[b]={...g[b],...w},y&&m<WB&&(m++,typeof y=="object"&&(y.placement&&(f=y.placement),y.rects&&(u=y.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:s}):y.rects),{x:d,y:h}=Gy(u,f,c)),v=-1)}return{x:d,y:h,placement:f,strategy:s,middlewareData:g}},KB=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:n,placement:s,rects:i,platform:a,elements:l,middlewareData:c}=t,{element:u,padding:d=0}=gi(e,t)||{};if(u==null)return{};const h=Xk(d),f={x:r,y:n},m=xx(s),g=vx(m),v=await a.getDimensions(u),x=m==="y",b=x?"top":"left",_=x?"bottom":"right",C=x?"clientHeight":"clientWidth",S=i.reference[g]+i.reference[m]-f[m]-i.floating[g],w=f[m]-i.reference[m],y=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let N=y?y[C]:0;(!N||!await(a.isElement==null?void 0:a.isElement(y)))&&(N=l.floating[C]||i.floating[g]);const E=S/2-w/2,k=N/2-v[g]/2-1,D=ao(h[b],k),j=ao(h[_],k),R=D,I=N-v[g]-j,T=N/2-v[g]/2+E,A=B0(R,T,I),P=!c.arrow&&El(s)!=null&&T!==A&&i.reference[g]/2-(T<R?D:j)-v[g]/2<0,O=P?T<R?T-R:T-I:0;return{[m]:f[m]+O,data:{[m]:A,centerOffset:T-A-O,...P&&{alignmentOffset:O}},reset:P}}}),VB=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var r,n;const{placement:s,middlewareData:i,rects:a,initialPlacement:l,platform:c,elements:u}=t,{mainAxis:d=!0,crossAxis:h=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:v=!0,...x}=gi(e,t);if((r=i.arrow)!=null&&r.alignmentOffset)return{};const b=vi(s),_=Os(l),C=vi(l)===l,S=await(c.isRTL==null?void 0:c.isRTL(u.floating)),w=f||(C||!v?[Dh(l)]:OB(l)),y=g!=="none";!f&&y&&w.push(...zB(l,v,g,S));const N=[l,...w],E=await c.detectOverflow(t,x),k=[];let D=((n=i.flip)==null?void 0:n.overflows)||[];if(d&&k.push(E[b]),h){const T=MB(s,a,S);k.push(E[T[0]],E[T[1]])}if(D=[...D,{placement:s,overflows:k}],!k.every(T=>T<=0)){var j,R;const T=(((j=i.flip)==null?void 0:j.index)||0)+1,A=N[T];if(A&&(!(h==="alignment"?_!==Os(A):!1)||D.every(L=>Os(L.placement)===_?L.overflows[0]>0:!0)))return{data:{index:T,overflows:D},reset:{placement:A}};let P=(R=D.filter(O=>O.overflows[0]<=0).sort((O,L)=>O.overflows[1]-L.overflows[1])[0])==null?void 0:R.placement;if(!P)switch(m){case"bestFit":{var I;const O=(I=D.filter(L=>{if(y){const B=Os(L.placement);return B===_||B==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(B=>B>0).reduce((B,M)=>B+M,0)]).sort((L,B)=>L[1]-B[1])[0])==null?void 0:I[0];O&&(P=O);break}case"initialPlacement":P=l;break}if(s!==P)return{reset:{placement:P}}}return{}}}};function Yy(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Xy(e){return PB.some(t=>e[t]>=0)}const GB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r,platform:n}=t,{strategy:s="referenceHidden",...i}=gi(e,t);switch(s){case"referenceHidden":{const a=await n.detectOverflow(t,{...i,elementContext:"reference"}),l=Yy(a,r.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:Xy(l)}}}case"escaped":{const a=await n.detectOverflow(t,{...i,altBoundary:!0}),l=Yy(a,r.floating);return{data:{escapedOffsets:l,escaped:Xy(l)}}}default:return{}}}}},Jk=new Set(["left","top"]);async function YB(e,t){const{placement:r,platform:n,elements:s}=e,i=await(n.isRTL==null?void 0:n.isRTL(s.floating)),a=vi(r),l=El(r),c=Os(r)==="y",u=Jk.has(a)?-1:1,d=i&&c?-1:1,h=gi(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return l&&typeof g=="number"&&(m=l==="end"?g*-1:g),c?{x:m*d,y:f*u}:{x:f*u,y:m*d}}const XB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,n;const{x:s,y:i,placement:a,middlewareData:l}=t,c=await YB(t,e);return a===((r=l.offset)==null?void 0:r.placement)&&(n=l.arrow)!=null&&n.alignmentOffset?{}:{x:s+c.x,y:i+c.y,data:{...c,placement:a}}}}},JB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:n,placement:s,platform:i}=t,{mainAxis:a=!0,crossAxis:l=!1,limiter:c={fn:b=>{let{x:_,y:C}=b;return{x:_,y:C}}},...u}=gi(e,t),d={x:r,y:n},h=await i.detectOverflow(t,u),f=Os(vi(s)),m=gx(f);let g=d[m],v=d[f];if(a){const b=m==="y"?"top":"left",_=m==="y"?"bottom":"right",C=g+h[b],S=g-h[_];g=B0(C,g,S)}if(l){const b=f==="y"?"top":"left",_=f==="y"?"bottom":"right",C=v+h[b],S=v-h[_];v=B0(C,v,S)}const x=c.fn({...t,[m]:g,[f]:v});return{...x,data:{x:x.x-r,y:x.y-n,enabled:{[m]:a,[f]:l}}}}}},QB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:r,y:n,placement:s,rects:i,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:u=!0}=gi(e,t),d={x:r,y:n},h=Os(s),f=gx(h);let m=d[f],g=d[h];const v=gi(l,t),x=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(c){const C=f==="y"?"height":"width",S=i.reference[f]-i.floating[C]+x.mainAxis,w=i.reference[f]+i.reference[C]-x.mainAxis;m<S?m=S:m>w&&(m=w)}if(u){var b,_;const C=f==="y"?"width":"height",S=Jk.has(vi(s)),w=i.reference[h]-i.floating[C]+(S&&((b=a.offset)==null?void 0:b[h])||0)+(S?0:x.crossAxis),y=i.reference[h]+i.reference[C]+(S?0:((_=a.offset)==null?void 0:_[h])||0)-(S?x.crossAxis:0);g<w?g=w:g>y&&(g=y)}return{[f]:m,[h]:g}}}},ZB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var r,n;const{placement:s,rects:i,platform:a,elements:l}=t,{apply:c=()=>{},...u}=gi(e,t),d=await a.detectOverflow(t,u),h=vi(s),f=El(s),m=Os(s)==="y",{width:g,height:v}=i.floating;let x,b;h==="top"||h==="bottom"?(x=h,b=f===(await(a.isRTL==null?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(b=h,x=f==="end"?"top":"bottom");const _=v-d.top-d.bottom,C=g-d.left-d.right,S=ao(v-d[x],_),w=ao(g-d[b],C),y=!t.middlewareData.shift;let N=S,E=w;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(E=C),(n=t.middlewareData.shift)!=null&&n.enabled.y&&(N=_),y&&!f){const D=Rn(d.left,0),j=Rn(d.right,0),R=Rn(d.top,0),I=Rn(d.bottom,0);m?E=g-2*(D!==0||j!==0?D+j:Rn(d.left,d.right)):N=v-2*(R!==0||I!==0?R+I:Rn(d.top,d.bottom))}await c({...t,availableWidth:E,availableHeight:N});const k=await a.getDimensions(l.floating);return g!==k.width||v!==k.height?{reset:{rects:!0}}:{}}}};function Tf(){return typeof window<"u"}function kl(e){return Qk(e)?(e.nodeName||"").toLowerCase():"#document"}function jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ys(e){var t;return(t=(Qk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Qk(e){return Tf()?e instanceof Node||e instanceof jn(e).Node:!1}function us(e){return Tf()?e instanceof Element||e instanceof jn(e).Element:!1}function _i(e){return Tf()?e instanceof HTMLElement||e instanceof jn(e).HTMLElement:!1}function Jy(e){return!Tf()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof jn(e).ShadowRoot}function Tu(e){const{overflow:t,overflowX:r,overflowY:n,display:s}=ds(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&s!=="inline"&&s!=="contents"}function eF(e){return/^(table|td|th)$/.test(kl(e))}function Df(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const tF=/transform|translate|scale|rotate|perspective|filter/,rF=/paint|layout|strict|content/,No=e=>!!e&&e!=="none";let rm;function bx(e){const t=us(e)?ds(e):e;return No(t.transform)||No(t.translate)||No(t.scale)||No(t.rotate)||No(t.perspective)||!_x()&&(No(t.backdropFilter)||No(t.filter))||tF.test(t.willChange||"")||rF.test(t.contain||"")}function nF(e){let t=lo(e);for(;_i(t)&&!fl(t);){if(bx(t))return t;if(Df(t))return null;t=lo(t)}return null}function _x(){return rm==null&&(rm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),rm}function fl(e){return/^(html|body|#document)$/.test(kl(e))}function ds(e){return jn(e).getComputedStyle(e)}function Pf(e){return us(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lo(e){if(kl(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Jy(e)&&e.host||Ys(e);return Jy(t)?t.host:t}function Zk(e){const t=lo(e);return fl(t)?e.ownerDocument?e.ownerDocument.body:e.body:_i(t)&&Tu(t)?t:Zk(t)}function $c(e,t,r){var n;t===void 0&&(t=[]),r===void 0&&(r=!0);const s=Zk(e),i=s===((n=e.ownerDocument)==null?void 0:n.body),a=jn(s);if(i){const l=$0(a);return t.concat(a,a.visualViewport||[],Tu(s)?s:[],l&&r?$c(l):[])}else return t.concat(s,$c(s,[],r))}function $0(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function e5(e){const t=ds(e);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const s=_i(e),i=s?e.offsetWidth:r,a=s?e.offsetHeight:n,l=Th(r)!==i||Th(n)!==a;return l&&(r=i,n=a),{width:r,height:n,$:l}}function yx(e){return us(e)?e:e.contextElement}function Va(e){const t=yx(e);if(!_i(t))return zs(1);const r=t.getBoundingClientRect(),{width:n,height:s,$:i}=e5(t);let a=(i?Th(r.width):r.width)/n,l=(i?Th(r.height):r.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const sF=zs(0);function t5(e){const t=jn(e);return!_x()||!t.visualViewport?sF:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function iF(e,t,r){return t===void 0&&(t=!1),!r||t&&r!==jn(e)?!1:t}function ra(e,t,r,n){t===void 0&&(t=!1),r===void 0&&(r=!1);const s=e.getBoundingClientRect(),i=yx(e);let a=zs(1);t&&(n?us(n)&&(a=Va(n)):a=Va(e));const l=iF(i,r,n)?t5(i):zs(0);let c=(s.left+l.x)/a.x,u=(s.top+l.y)/a.y,d=s.width/a.x,h=s.height/a.y;if(i){const f=jn(i),m=n&&us(n)?jn(n):n;let g=f,v=$0(g);for(;v&&n&&m!==g;){const x=Va(v),b=v.getBoundingClientRect(),_=ds(v),C=b.left+(v.clientLeft+parseFloat(_.paddingLeft))*x.x,S=b.top+(v.clientTop+parseFloat(_.paddingTop))*x.y;c*=x.x,u*=x.y,d*=x.x,h*=x.y,c+=C,u+=S,g=jn(v),v=$0(g)}}return Ph({width:d,height:h,x:c,y:u})}function Lf(e,t){const r=Pf(e).scrollLeft;return t?t.left+r:ra(Ys(e)).left+r}function r5(e,t){const r=e.getBoundingClientRect(),n=r.left+t.scrollLeft-Lf(e,r),s=r.top+t.scrollTop;return{x:n,y:s}}function oF(e){let{elements:t,rect:r,offsetParent:n,strategy:s}=e;const i=s==="fixed",a=Ys(n),l=t?Df(t.floating):!1;if(n===a||l&&i)return r;let c={scrollLeft:0,scrollTop:0},u=zs(1);const d=zs(0),h=_i(n);if((h||!h&&!i)&&((kl(n)!=="body"||Tu(a))&&(c=Pf(n)),h)){const m=ra(n);u=Va(n),d.x=m.x+n.clientLeft,d.y=m.y+n.clientTop}const f=a&&!h&&!i?r5(a,c):zs(0);return{width:r.width*u.x,height:r.height*u.y,x:r.x*u.x-c.scrollLeft*u.x+d.x+f.x,y:r.y*u.y-c.scrollTop*u.y+d.y+f.y}}function aF(e){return Array.from(e.getClientRects())}function lF(e){const t=Ys(e),r=Pf(e),n=e.ownerDocument.body,s=Rn(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=Rn(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let a=-r.scrollLeft+Lf(e);const l=-r.scrollTop;return ds(n).direction==="rtl"&&(a+=Rn(t.clientWidth,n.clientWidth)-s),{width:s,height:i,x:a,y:l}}const Qy=25;function cF(e,t){const r=jn(e),n=Ys(e),s=r.visualViewport;let i=n.clientWidth,a=n.clientHeight,l=0,c=0;if(s){i=s.width,a=s.height;const d=_x();(!d||d&&t==="fixed")&&(l=s.offsetLeft,c=s.offsetTop)}const u=Lf(n);if(u<=0){const d=n.ownerDocument,h=d.body,f=getComputedStyle(h),m=d.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,g=Math.abs(n.clientWidth-h.clientWidth-m);g<=Qy&&(i-=g)}else u<=Qy&&(i+=u);return{width:i,height:a,x:l,y:c}}function uF(e,t){const r=ra(e,!0,t==="fixed"),n=r.top+e.clientTop,s=r.left+e.clientLeft,i=_i(e)?Va(e):zs(1),a=e.clientWidth*i.x,l=e.clientHeight*i.y,c=s*i.x,u=n*i.y;return{width:a,height:l,x:c,y:u}}function Zy(e,t,r){let n;if(t==="viewport")n=cF(e,r);else if(t==="document")n=lF(Ys(e));else if(us(t))n=uF(t,r);else{const s=t5(e);n={x:t.x-s.x,y:t.y-s.y,width:t.width,height:t.height}}return Ph(n)}function n5(e,t){const r=lo(e);return r===t||!us(r)||fl(r)?!1:ds(r).position==="fixed"||n5(r,t)}function dF(e,t){const r=t.get(e);if(r)return r;let n=$c(e,[],!1).filter(l=>us(l)&&kl(l)!=="body"),s=null;const i=ds(e).position==="fixed";let a=i?lo(e):e;for(;us(a)&&!fl(a);){const l=ds(a),c=bx(a);!c&&l.position==="fixed"&&(s=null),(i?!c&&!s:!c&&l.position==="static"&&!!s&&(s.position==="absolute"||s.position==="fixed")||Tu(a)&&!c&&n5(e,a))?n=n.filter(d=>d!==a):s=l,a=lo(a)}return t.set(e,n),n}function hF(e){let{element:t,boundary:r,rootBoundary:n,strategy:s}=e;const a=[...r==="clippingAncestors"?Df(t)?[]:dF(t,this._c):[].concat(r),n],l=Zy(t,a[0],s);let c=l.top,u=l.right,d=l.bottom,h=l.left;for(let f=1;f<a.length;f++){const m=Zy(t,a[f],s);c=Rn(m.top,c),u=ao(m.right,u),d=ao(m.bottom,d),h=Rn(m.left,h)}return{width:u-h,height:d-c,x:h,y:c}}function fF(e){const{width:t,height:r}=e5(e);return{width:t,height:r}}function pF(e,t,r){const n=_i(t),s=Ys(t),i=r==="fixed",a=ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=zs(0);function u(){c.x=Lf(s)}if(n||!n&&!i)if((kl(t)!=="body"||Tu(s))&&(l=Pf(t)),n){const m=ra(t,!0,i,t);c.x=m.x+t.clientLeft,c.y=m.y+t.clientTop}else s&&u();i&&!n&&s&&u();const d=s&&!n&&!i?r5(s,l):zs(0),h=a.left+l.scrollLeft-c.x-d.x,f=a.top+l.scrollTop-c.y-d.y;return{x:h,y:f,width:a.width,height:a.height}}function nm(e){return ds(e).position==="static"}function e1(e,t){if(!_i(e)||ds(e).position==="fixed")return null;if(t)return t(e);let r=e.offsetParent;return Ys(e)===r&&(r=r.ownerDocument.body),r}function s5(e,t){const r=jn(e);if(Df(e))return r;if(!_i(e)){let s=lo(e);for(;s&&!fl(s);){if(us(s)&&!nm(s))return s;s=lo(s)}return r}let n=e1(e,t);for(;n&&eF(n)&&nm(n);)n=e1(n,t);return n&&fl(n)&&nm(n)&&!bx(n)?r:n||nF(e)||r}const mF=async function(e){const t=this.getOffsetParent||s5,r=this.getDimensions,n=await r(e.floating);return{reference:pF(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function gF(e){return ds(e).direction==="rtl"}const vF={convertOffsetParentRelativeRectToViewportRelativeRect:oF,getDocumentElement:Ys,getClippingRect:hF,getOffsetParent:s5,getElementRects:mF,getClientRects:aF,getDimensions:fF,getScale:Va,isElement:us,isRTL:gF};function i5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function xF(e,t){let r=null,n;const s=Ys(e);function i(){var l;clearTimeout(n),(l=r)==null||l.disconnect(),r=null}function a(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const u=e.getBoundingClientRect(),{left:d,top:h,width:f,height:m}=u;if(l||t(),!f||!m)return;const g=_d(h),v=_d(s.clientWidth-(d+f)),x=_d(s.clientHeight-(h+m)),b=_d(d),C={rootMargin:-g+"px "+-v+"px "+-x+"px "+-b+"px",threshold:Rn(0,ao(1,c))||1};let S=!0;function w(y){const N=y[0].intersectionRatio;if(N!==c){if(!S)return a();N?a(!1,N):n=setTimeout(()=>{a(!1,1e-7)},1e3)}N===1&&!i5(u,e.getBoundingClientRect())&&a(),S=!1}try{r=new IntersectionObserver(w,{...C,root:s.ownerDocument})}catch{r=new IntersectionObserver(w,C)}r.observe(e)}return a(!0),i}function o5(e,t,r,n){n===void 0&&(n={});const{ancestorScroll:s=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,u=yx(e),d=s||i?[...u?$c(u):[],...t?$c(t):[]]:[];d.forEach(b=>{s&&b.addEventListener("scroll",r,{passive:!0}),i&&b.addEventListener("resize",r)});const h=u&&l?xF(u,r):null;let f=-1,m=null;a&&(m=new ResizeObserver(b=>{let[_]=b;_&&_.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=m)==null||C.observe(t)})),r()}),u&&!c&&m.observe(u),t&&m.observe(t));let g,v=c?ra(e):null;c&&x();function x(){const b=ra(e);v&&!i5(v,b)&&r(),v=b,g=requestAnimationFrame(x)}return r(),()=>{var b;d.forEach(_=>{s&&_.removeEventListener("scroll",r),i&&_.removeEventListener("resize",r)}),h==null||h(),(b=m)==null||b.disconnect(),m=null,c&&cancelAnimationFrame(g)}}const bF=XB,_F=JB,yF=VB,wF=ZB,SF=GB,t1=KB,CF=QB,EF=(e,t,r)=>{const n=new Map,s={platform:vF,...r},i={...s.platform,_c:n};return qB(e,t,{...s,platform:i})};var kF=typeof document<"u",IF=function(){},eh=kF?p.useLayoutEffect:IF;function Lh(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let r,n,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!Lh(e[n],t[n]))return!1;return!0}if(s=Object.keys(e),r=s.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(t,s[n]))return!1;for(n=r;n--!==0;){const i=s[n];if(!(i==="_owner"&&e.$$typeof)&&!Lh(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function a5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function r1(e,t){const r=a5(e);return Math.round(t*r)/r}function sm(e){const t=p.useRef(e);return eh(()=>{t.current=e}),t}function l5(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:s,elements:{reference:i,floating:a}={},transform:l=!0,whileElementsMounted:c,open:u}=e,[d,h]=p.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=p.useState(n);Lh(f,n)||m(n);const[g,v]=p.useState(null),[x,b]=p.useState(null),_=p.useCallback(L=>{L!==y.current&&(y.current=L,v(L))},[]),C=p.useCallback(L=>{L!==N.current&&(N.current=L,b(L))},[]),S=i||g,w=a||x,y=p.useRef(null),N=p.useRef(null),E=p.useRef(d),k=c!=null,D=sm(c),j=sm(s),R=sm(u),I=p.useCallback(()=>{if(!y.current||!N.current)return;const L={placement:t,strategy:r,middleware:f};j.current&&(L.platform=j.current),EF(y.current,N.current,L).then(B=>{const M={...B,isPositioned:R.current!==!1};T.current&&!Lh(E.current,M)&&(E.current=M,Yr.flushSync(()=>{h(M)}))})},[f,t,r,j,R]);eh(()=>{u===!1&&E.current.isPositioned&&(E.current.isPositioned=!1,h(L=>({...L,isPositioned:!1})))},[u]);const T=p.useRef(!1);eh(()=>(T.current=!0,()=>{T.current=!1}),[]),eh(()=>{if(S&&(y.current=S),w&&(N.current=w),S&&w){if(D.current)return D.current(S,w,I);I()}},[S,w,I,D,k]);const A=p.useMemo(()=>({reference:y,floating:N,setReference:_,setFloating:C}),[_,C]),P=p.useMemo(()=>({reference:S,floating:w}),[S,w]),O=p.useMemo(()=>{const L={position:r,left:0,top:0};if(!P.floating)return L;const B=r1(P.floating,d.x),M=r1(P.floating,d.y);return l?{...L,transform:"translate("+B+"px, "+M+"px)",...a5(P.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:B,top:M}},[r,l,P.floating,d.x,d.y]);return p.useMemo(()=>({...d,update:I,refs:A,elements:P,floatingStyles:O}),[d,I,A,P,O])}const NF=e=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:e,fn(r){const{element:n,padding:s}=typeof e=="function"?e(r):e;return n&&t(n)?n.current!=null?t1({element:n.current,padding:s}).fn(r):{}:n?t1({element:n,padding:s}).fn(r):{}}}},c5=(e,t)=>{const r=bF(e);return{name:r.name,fn:r.fn,options:[e,t]}},u5=(e,t)=>{const r=_F(e);return{name:r.name,fn:r.fn,options:[e,t]}},d5=(e,t)=>({fn:CF(e).fn,options:[e,t]}),h5=(e,t)=>{const r=yF(e);return{name:r.name,fn:r.fn,options:[e,t]}},f5=(e,t)=>{const r=wF(e);return{name:r.name,fn:r.fn,options:[e,t]}},p5=(e,t)=>{const r=SF(e);return{name:r.name,fn:r.fn,options:[e,t]}},m5=(e,t)=>{const r=NF(e);return{name:r.name,fn:r.fn,options:[e,t]}};var RF="Arrow",g5=p.forwardRef((e,t)=>{const{children:r,width:n=10,height:s=5,...i}=e;return o.jsx(or.svg,{...i,ref:t,width:n,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});g5.displayName=RF;var jF=g5;function AF(e){const[t,r]=p.useState(void 0);return io(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const n=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const i=s[0];let a,l;if("borderBoxSize"in i){const c=i.borderBoxSize,u=Array.isArray(c)?c[0]:c;a=u.inlineSize,l=u.blockSize}else a=e.offsetWidth,l=e.offsetHeight;r({width:a,height:l})});return n.observe(e,{box:"border-box"}),()=>n.unobserve(e)}else r(void 0)},[e]),t}var wx="Popper",[v5,Mf]=bi(wx),[TF,x5]=v5(wx),b5=e=>{const{__scopePopper:t,children:r}=e,[n,s]=p.useState(null);return o.jsx(TF,{scope:t,anchor:n,onAnchorChange:s,children:r})};b5.displayName=wx;var _5="PopperAnchor",y5=p.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:n,...s}=e,i=x5(_5,r),a=p.useRef(null),l=wr(t,a),c=p.useRef(null);return p.useEffect(()=>{const u=c.current;c.current=(n==null?void 0:n.current)||a.current,u!==c.current&&i.onAnchorChange(c.current)}),n?null:o.jsx(or.div,{...s,ref:l})});y5.displayName=_5;var Sx="PopperContent",[DF,PF]=v5(Sx),w5=p.forwardRef((e,t)=>{var H,G,z,ee,V,re;const{__scopePopper:r,side:n="bottom",sideOffset:s=0,align:i="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:d=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,x=x5(Sx,r),[b,_]=p.useState(null),C=wr(t,oe=>_(oe)),[S,w]=p.useState(null),y=AF(S),N=(y==null?void 0:y.width)??0,E=(y==null?void 0:y.height)??0,k=n+(i!=="center"?"-"+i:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},j=Array.isArray(u)?u:[u],R=j.length>0,I={padding:D,boundary:j.filter(MF),altBoundary:R},{refs:T,floatingStyles:A,placement:P,isPositioned:O,middlewareData:L}=l5({strategy:"fixed",placement:k,whileElementsMounted:(...oe)=>o5(...oe,{animationFrame:m==="always"}),elements:{reference:x.anchor},middleware:[c5({mainAxis:s+E,alignmentAxis:a}),c&&u5({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?d5():void 0,...I}),c&&h5({...I}),f5({...I,apply:({elements:oe,rects:ce,availableWidth:be,availableHeight:ne})=>{const{width:Te,height:Ve}=ce.reference,Ge=oe.floating.style;Ge.setProperty("--radix-popper-available-width",`${be}px`),Ge.setProperty("--radix-popper-available-height",`${ne}px`),Ge.setProperty("--radix-popper-anchor-width",`${Te}px`),Ge.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),S&&m5({element:S,padding:l}),OF({arrowWidth:N,arrowHeight:E}),f&&p5({strategy:"referenceHidden",...I})]}),[B,M]=E5(P),$=oo(g);io(()=>{O&&($==null||$())},[O,$]);const U=(H=L.arrow)==null?void 0:H.x,F=(G=L.arrow)==null?void 0:G.y,K=((z=L.arrow)==null?void 0:z.centerOffset)!==0,[Y,te]=p.useState();return io(()=>{b&&te(window.getComputedStyle(b).zIndex)},[b]),o.jsx("div",{ref:T.setFloating,"data-radix-popper-content-wrapper":"",style:{...A,transform:O?A.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[(ee=L.transformOrigin)==null?void 0:ee.x,(V=L.transformOrigin)==null?void 0:V.y].join(" "),...((re=L.hide)==null?void 0:re.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(DF,{scope:r,placedSide:B,onArrowChange:w,arrowX:U,arrowY:F,shouldHideArrow:K,children:o.jsx(or.div,{"data-side":B,"data-align":M,...v,ref:C,style:{...v.style,animation:O?void 0:"none"}})})})});w5.displayName=Sx;var S5="PopperArrow",LF={top:"bottom",right:"left",bottom:"top",left:"right"},C5=p.forwardRef(function(t,r){const{__scopePopper:n,...s}=t,i=PF(S5,n),a=LF[i.placedSide];return o.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:o.jsx(jF,{...s,ref:r,style:{...s.style,display:"block"}})})});C5.displayName=S5;function MF(e){return e!==null}var OF=e=>({name:"transformOrigin",options:e,fn(t){var x,b,_;const{placement:r,rects:n,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[u,d]=E5(r),h={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+l/2,m=(((_=s.arrow)==null?void 0:_.y)??0)+c/2;let g="",v="";return u==="bottom"?(g=a?h:`${f}px`,v=`${-c}px`):u==="top"?(g=a?h:`${f}px`,v=`${n.floating.height+c}px`):u==="right"?(g=`${-c}px`,v=a?h:`${m}px`):u==="left"&&(g=`${n.floating.width+c}px`,v=a?h:`${m}px`),{data:{x:g,y:v}}}});function E5(e){const[t,r="center"]=e.split("-");return[t,r]}var Cx=b5,Ex=y5,k5=w5,I5=C5,Of="Popover",[N5]=bi(Of,[Mf]),Du=Mf(),[BF,bo]=N5(Of),R5=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:s,onOpenChange:i,modal:a=!1}=e,l=Du(t),c=p.useRef(null),[u,d]=p.useState(!1),[h,f]=Su({prop:n,defaultProp:s??!1,onChange:i,caller:Of});return o.jsx(Cx,{...l,children:o.jsx(BF,{scope:t,contentId:hi(),triggerRef:c,open:h,onOpenChange:f,onOpenToggle:p.useCallback(()=>f(m=>!m),[f]),hasCustomAnchor:u,onCustomAnchorAdd:p.useCallback(()=>d(!0),[]),onCustomAnchorRemove:p.useCallback(()=>d(!1),[]),modal:a,children:r})})};R5.displayName=Of;var j5="PopoverAnchor",FF=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=bo(j5,r),i=Du(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:l}=s;return p.useEffect(()=>(a(),()=>l()),[a,l]),o.jsx(Ex,{...i,...n,ref:t})});FF.displayName=j5;var A5="PopoverTrigger",T5=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=bo(A5,r),i=Du(r),a=wr(t,s.triggerRef),l=o.jsx(or.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":O5(s.open),...n,ref:a,onClick:st(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?l:o.jsx(Ex,{asChild:!0,...i,children:l})});T5.displayName=A5;var kx="PopoverPortal",[$F,zF]=N5(kx,{forceMount:void 0}),D5=e=>{const{__scopePopover:t,forceMount:r,children:n,container:s}=e,i=bo(kx,t);return o.jsx($F,{scope:t,forceMount:r,children:o.jsx(Gs,{present:r||i.open,children:o.jsx(Nf,{asChild:!0,container:s,children:n})})})};D5.displayName=kx;var pl="PopoverContent",P5=p.forwardRef((e,t)=>{const r=zF(pl,e.__scopePopover),{forceMount:n=r.forceMount,...s}=e,i=bo(pl,e.__scopePopover);return o.jsx(Gs,{present:n||i.open,children:i.modal?o.jsx(HF,{...s,ref:t}):o.jsx(WF,{...s,ref:t})})});P5.displayName=pl;var UF=hl("PopoverContent.RemoveScroll"),HF=p.forwardRef((e,t)=>{const r=bo(pl,e.__scopePopover),n=p.useRef(null),s=wr(t,n),i=p.useRef(!1);return p.useEffect(()=>{const a=n.current;if(a)return jf(a)},[]),o.jsx(Eu,{as:UF,allowPinchZoom:!0,children:o.jsx(L5,{...e,ref:s,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:st(e.onCloseAutoFocus,a=>{var l;a.preventDefault(),i.current||(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:st(e.onPointerDownOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:st(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),WF=p.forwardRef((e,t)=>{const r=bo(pl,e.__scopePopover),n=p.useRef(!1),s=p.useRef(!1);return o.jsx(L5,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(n.current||(l=r.triggerRef.current)==null||l.focus(),i.preventDefault()),n.current=!1,s.current=!1},onInteractOutside:i=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=i.target;((u=r.triggerRef.current)==null?void 0:u.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),L5=p.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onInteractOutside:d,...h}=e,f=bo(pl,r),m=Du(r);return sx(),o.jsx(If,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:i,children:o.jsx(Cu,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:d,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:o.jsx(k5,{"data-state":O5(f.open),role:"dialog",id:f.contentId,...m,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),M5="PopoverClose",qF=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=bo(M5,r);return o.jsx(or.button,{type:"button",...n,ref:t,onClick:st(e.onClick,()=>s.onOpenChange(!1))})});qF.displayName=M5;var KF="PopoverArrow",VF=p.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=Du(r);return o.jsx(I5,{...s,...n,ref:t})});VF.displayName=KF;function O5(e){return e?"open":"closed"}var GF=R5,YF=T5,XF=D5,B5=P5;const Ix=GF,Nx=YF,Bf=p.forwardRef(({className:e,align:t="center",sideOffset:r=8,...n},s)=>{const i=hr(s,"intersection");return o.jsx(XF,{children:o.jsx(B5,{ref:i,align:t,sideOffset:r,className:Xe("z-50 w-56 rounded-2xl border border-border/60 bg-popover/95 p-1.5 text-popover-foreground shadow-[0_24px_80px_-36px_rgba(17,24,39,0.8)] outline-none backdrop-blur-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...n})})});Bf.displayName=B5.displayName;function F5(e){return{minimal:"极低",low:"低",medium:"中",high:"高",xhigh:"很高",max:"最大",ultra:"极限"}[e]??e}function JF({models:e,model:t,effort:r,summary:n,label:s,disabled:i,allowDefaultEffort:a=!1,onChange:l}){const[c,u]=p.useState(!1),[d,h]=p.useState(null),f=e.find(g=>g.id===d),m=g=>{f&&(l(f.id,g),u(!1))};return o.jsxs(Ix,{open:c,onOpenChange:g=>{u(g),h(null)},children:[o.jsx(Nx,{asChild:!0,children:o.jsxs(Z,{type:"button",variant:"outline",disabled:i,"aria-label":`${s}:${n}`,className:"w-full justify-between",children:[o.jsx("span",{className:"truncate",children:n}),o.jsx(dE,{"data-icon":"inline-end"})]})}),o.jsxs(Bf,{align:"start",className:"w-80 max-w-[calc(100vw-2rem)]","aria-label":f?"选择推理强度":"选择模型版本",children:[o.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[f&&o.jsx(Z,{type:"button",variant:"ghost",size:"icon","aria-label":"返回模型列表",onClick:()=>h(null),children:o.jsx(xi,{})}),o.jsx("span",{className:"text-sm font-medium",children:f?`${f.label} · 推理强度`:"选择模型版本"})]}),o.jsx("div",{className:"flex max-h-72 flex-col gap-1 overflow-y-auto",children:f?o.jsxs(o.Fragment,{children:[a&&o.jsxs(Z,{type:"button",variant:"ghost",className:"justify-between",onClick:()=>m(""),children:["模型默认强度",t===f.id&&!r&&o.jsx(di,{})]}),f.reasoningEfforts.map(g=>o.jsxs(Z,{type:"button",variant:"ghost",className:"justify-between","aria-pressed":t===f.id&&r===g,onClick:()=>m(g),children:[o.jsxs("span",{children:[F5(g)," · ",g,g===f.defaultReasoningEffort?"(模型默认)":""]}),t===f.id&&r===g&&o.jsx(di,{})]},g)),!f.reasoningEfforts.length&&!a&&o.jsx("p",{className:"p-2 text-sm text-muted-foreground",children:"此模型暂无可选推理强度"})]}):e.map(g=>o.jsxs(Z,{type:"button",variant:"ghost",className:"h-auto justify-between py-2",onClick:()=>h(g.id),children:[o.jsxs("span",{className:"flex min-w-0 flex-col items-start gap-1",children:[o.jsx("span",{className:"truncate",children:g.label}),o.jsx("span",{className:"truncate text-xs text-muted-foreground",children:g.id})]}),t===g.id?o.jsx(di,{}):o.jsx(Jr,{})]},g.id))},d??"models")]})]})}function QF({field:e,model:t,effort:r,defaultEffort:n,catalog:s,loading:i,disabled:a,onRetry:l,onChange:c}){const u=e.modelSelection,d=((s==null?void 0:s.availability)==="available"?s.models:[]).map(x=>({...x,reasoningEfforts:x.reasoningEfforts.filter(b=>!u.allowedEfforts||u.allowedEfforts.includes(b))})),h="value"in e.default?e.default.value:null,f=t||(typeof h=="string"?h:""),m=r||n,g=d.find(x=>x.id===f),v=`${(g==null?void 0:g.label)??(f||"未选择模型")} · ${m?F5(m):"模型默认强度"}`;return o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(JF,{models:d,model:f,effort:m,summary:v,label:u.label,disabled:a||!d.length||i,allowDefaultEffort:u.allowDefaultEffort,onChange:c}),i?o.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"正在加载模型…"}):d.length?o.jsxs(o.Fragment,{children:[(s==null?void 0:s.source)==="cache"&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["正在使用此电脑缓存的模型目录。",o.jsx(Z,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:l,children:"刷新"})]}),t&&(!g||r&&!g.reasoningEfforts.includes(r))&&o.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"已保存的模型或推理强度不在当前目录中,保留原值;可重新选择。"})]}):o.jsxs("div",{role:"status",className:"text-xs text-muted-foreground",children:["模型目录暂不可用,已有配置仍会保留。",o.jsx(Z,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:l,children:"重试"})]}),o.jsx(Z,{type:"button",variant:"ghost",size:"sm",className:"self-start",disabled:a,onClick:()=>c(null,null),children:"恢复默认"})]})}const n1={applied:"已生效",restartRequired:"等待所属服务重启",error:"配置错误",unconfigured:"未配置"};function ZF({apiBase:e,token:t,embedded:r=!1,onAuthExpired:n}){const[s,i]=p.useState(null),[a,l]=p.useState({}),[c,u]=p.useState(null),[d,h]=p.useState(!1),[f,m]=p.useState(null),[g,v]=p.useState(!1),x=p.useRef(null),b=W(async()=>{var y;if(!t)return;(y=x.current)==null||y.abort();const w=new AbortController;x.current=w,v(!0);try{const N=await Yk(e,t,w.signal);w.signal.aborted||m(N)}catch{}finally{w.signal.aborted||v(!1)}}),_=s!==null;p.useEffect(()=>{_&&t&&b()},[_,t,b]),p.useEffect(()=>()=>{var w;return(w=x.current)==null?void 0:w.abort()},[]);const C=p.useRef(null);p.useEffect(()=>()=>{var w;return(w=C.current)==null?void 0:w.abort()},[]);const S=W(async(w=!1)=>{var N;if(!t||d||!w&&Object.keys(a).length&&!window.confirm("放弃未保存的修改并重新读取?"))return;(N=C.current)==null||N.abort();const y=new AbortController;C.current=y,h(!0),u(null);try{let E;if(w&&(s==null?void 0:s.savedRevision)!=null&&s.digest){const D={};for(const[j,R]of Object.entries(a)){const I=s.fields.find(T=>T.path===j);if(!I)throw new Error("字段列表已变化,请重新加载。");D[j]=e$(I,R)}E={expectedRevision:s.savedRevision,expectedDigest:s.digest,expectedEnvironment:s.environment,changes:D}}const k=await DB(e,t,y.signal,E);if(y.signal.aborted)return;if(s&&(k.environment.kind!==s.environment.kind||k.environment.instanceId!==s.environment.instanceId))throw new Error("连接实例已变化,请关闭并重新打开配置。");i(k),l({})}catch(E){y.signal.aborted||(E instanceof De&&E.status===401&&(n==null||n()),u(E instanceof Error?E.message:"配置操作失败"))}finally{y.signal.aborted||h(!1)}});return va(r&&Object.keys(a).length>0,r&&d&&Object.keys(a).length>0),p.useEffect(()=>{r&&S()},[r,S]),o.jsxs("details",{open:r?!0:void 0,className:r?"rounded-md border border-border p-3":"rounded-xl border border-border p-4",children:[o.jsx("summary",{className:"cursor-pointer font-medium",children:"当前连接电脑的配置"}),o.jsxs("div",{className:"mt-3 space-y-4",children:[o.jsx("p",{className:"break-all text-xs text-muted-foreground",children:e||window.location.origin}),o.jsx(Z,{variant:"secondary",size:"sm",disabled:d||!t,onClick:()=>void S(),children:"加载配置"}),!t&&o.jsx("p",{children:"登录后可管理当前连接的配置。"}),c&&o.jsx("p",{role:"alert",className:"text-sm text-red-500",children:c}),s&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-xs",children:[s.environment.kind==="stable"?"Stable":"Dev Session"," · ",s.environment.instanceId," · 保存版本 ",s.savedRevision??"不可读取"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"输入框编辑保存值,默认值不会自动写入。应用状态来自当前连接的服务,不代表其他服务或业务连接已验证可用。"}),s.diskError&&o.jsx("p",{role:"alert",children:"磁盘配置无法读取,请在当前电脑运行 rw config doctor。"}),[...new Set(s.fields.filter(w=>!w.path.includes("<")).map(w=>w.domain))].map(w=>o.jsxs("details",{className:"rounded-lg border border-border p-3",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:TB[w]??w}),o.jsx("div",{className:"mt-3 space-y-3",children:s.fields.filter(y=>y.domain===w&&!y.path.includes("<")&&!s.fields.some(N=>{var E;return((E=N.modelSelection)==null?void 0:E.effortPath)===y.path})).map(y=>{var I;const N=Object.hasOwn(a,y.path),E=N?a[y.path]:s.values[y.path],k=E==null?"":typeof E=="string"?E:JSON.stringify(E),D=s.consumers[y.domain],j=(I=s.fieldStates)==null?void 0:I[y.path],R=s.fields.find(T=>{var A;return T.path===((A=y.modelSelection)==null?void 0:A.effortPath)});if(y.modelSelection&&R){const T=Object.hasOwn(a,R.path),A=T?a[R.path]:s.values[R.path];return o.jsxs("div",{className:"flex flex-col gap-2 border-b border-border/60 pb-3",children:[o.jsx("p",{className:"text-sm",children:y.modelSelection.label}),o.jsx("p",{className:"text-xs text-muted-foreground",children:y.description}),[y,R].map(P=>{var L;const O=(L=s.fieldStates)==null?void 0:L[P.path];return O?o.jsxs("div",{children:[o.jsx("p",{className:"text-xs",children:P.path===y.path?"模型":"推理强度"}),o.jsx(qy,{field:P,status:O,changed:N||T})]},P.path):null}),!j&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:[D?n1[D.state]:"状态未知",(D==null?void 0:D.appliedRevision)!=null?` · 生效版本 ${D.appliedRevision}`:""]}),o.jsx(QF,{field:y,model:typeof E=="string"?E:"",effort:typeof A=="string"?A:"",defaultEffort:"value"in R.default&&typeof R.default.value=="string"?R.default.value:"",catalog:f==null?void 0:f.catalogs[y.modelSelection.provider],loading:g,disabled:d,onRetry:()=>void b(),onChange:(P,O)=>l(L=>({...L,[y.path]:P,[R.path]:O}))})]},y.path)}return o.jsxs("div",{className:"space-y-1 border-b border-border/60 pb-3",children:[o.jsx("label",{className:"text-sm",htmlFor:`config-${y.path}`,children:y.description}),j?o.jsx(qy,{field:y,status:j,changed:N}):o.jsxs("p",{className:"text-xs text-muted-foreground",children:[D?n1[D.state]:"状态未知",(D==null?void 0:D.appliedRevision)!=null?` · 生效版本 ${D.appliedRevision}`:""," · 当前服务未提供字段来源"]}),y.sensitive?o.jsxs(o.Fragment,{children:[o.jsxs("select",{disabled:d,"aria-label":`${y.description}操作`,className:"h-9 w-full rounded border bg-background px-2 text-sm",value:N?a[y.path]===null?"delete":"replace":"keep",onChange:T=>l(A=>{const P={...A};return T.target.value==="keep"?delete P[y.path]:P[y.path]=T.target.value==="delete"?null:"",P}),children:[o.jsx("option",{value:"keep",children:s.values[`${y.path}.configured`]?"已配置,保留现有值":"未配置,保持不变"}),o.jsx("option",{value:"replace",children:"替换"}),o.jsx("option",{value:"delete",children:"删除"})]}),N&&a[y.path]!==null&&o.jsx(sr,{disabled:d,id:`config-${y.path}`,type:"password",autoComplete:"new-password",value:a[y.path]??"",onChange:T=>l(A=>({...A,[y.path]:T.target.value}))})]}):o.jsx(sr,{disabled:d,id:`config-${y.path}`,value:k,placeholder:"value"in y.default&&y.default.value!=null?String(y.default.value):"未设置",onChange:T=>l(A=>({...A,[y.path]:T.target.value}))}),!y.sensitive&&o.jsx("p",{className:"text-[11px] text-muted-foreground",children:y.type==="boolean"?"填写 true 或 false":y.type.startsWith("array")?'填写 JSON 数组,例如 ["id1", "id2"]':"留空恢复默认值"}),!y.sensitive&&o.jsx(Z,{size:"sm",variant:"ghost",disabled:d,onClick:()=>l(T=>({...T,[y.path]:null})),children:"恢复默认"})]},y.path)})})]},w)),o.jsx(Z,{variant:"ghost",disabled:d||!Object.keys(a).length,onClick:()=>l({}),children:"取消修改"}),o.jsx(Z,{disabled:d||!Object.keys(a).length||s.savedRevision==null||!!s.diskError,onClick:()=>void S(!0),children:d?"处理中…":"保存配置"})]})]})]})}function e$(e,t){if(t===null||!e.sensitive&&t==="")return null;if(e.sensitive&&!t)throw new Error("替换凭据时请填写新值;删除请使用删除选项。");if(e.type==="string")return t;if(e.type==="boolean"&&!["true","false"].includes(t))throw new Error(`${e.description}需要 true 或 false。`);try{return JSON.parse(t)}catch{throw new Error(`${e.description}格式不正确。`)}}function t$({embedded:e=!1}){var u;const[t,r]=p.useState(null),[n,s]=p.useState(null),[i,a]=p.useState(!1),l=p.useRef(!0);p.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const c=W(async()=>{var d,h;a(!0),s(null);try{const f=await((h=(d=window.electronAPI)==null?void 0:d.getLocalConfigurationStatus)==null?void 0:h.call(d));l.current&&f&&r(f)}catch{l.current&&s("无法读取本台桌面的配置状态。")}finally{l.current&&a(!1)}});return p.useEffect(()=>{e&&c()},[e,c]),(u=window.electronAPI)!=null&&u.getLocalConfigurationStatus?o.jsxs("details",{open:e?!0:void 0,className:e?"rounded-md border border-border p-3":"rounded-xl border border-border p-4",children:[o.jsx("summary",{className:"cursor-pointer font-medium",children:"本台桌面的配置状态"}),o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[o.jsx("p",{children:"浏览器、远程访问和伴随窗口由本台桌面管理。"}),o.jsx(Z,{size:"sm",variant:"secondary",disabled:i,onClick:()=>void c(),children:"刷新桌面状态"}),n&&o.jsx("p",{role:"alert",children:n}),t&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:[t.environment.kind==="stable"?"Stable":"Dev Session"," · ",t.environment.instanceId," · 保存版本 ",t.savedRevision??"不可读取"]}),t.diskError&&o.jsx("p",{role:"alert",children:"磁盘配置无法读取,当前进程仍保留已采用的配置。"}),Object.entries(t.consumers).map(([d,h])=>o.jsxs("p",{className:"break-all",children:[d,":",h.state==="error"?"配置错误":h.state==="applied"?"已生效":h.state==="unconfigured"?"未配置":"等待所属功能重新加载或重启",h.appliedRevision!==null&&` · 生效版本 ${h.appliedRevision}`]},d))]})]})]}):null}const r$=2e3;function n$(){const[e,t]=p.useState(null),[r,n]=p.useState(null);return p.useEffect(()=>{var c,u;const s=(c=window.electronAPI)==null?void 0:c.getRuntimeStats;if(((u=window.electronAPI)==null?void 0:u.isElectron)!==!0||!s)return;let i=!1,a=null;const l=async()=>{try{const d=await s();if(i)return;t(d),n(null)}catch(d){if(i)return;n(String(d))}finally{i||(a=window.setTimeout(()=>{l()},r$))}};return l(),()=>{i=!0,a!==null&&window.clearTimeout(a)}},[]),{snapshot:e,error:r}}const Pu=lx,s$=Dk,i$=cx,$5=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"window");return o.jsx(ku,{ref:n,className:Xe("fixed inset-0 z-50 bg-slate-950/40 backdrop-blur-[1px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t})});$5.displayName=ku.displayName;const o$={top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",right:"right-0 top-0 h-full border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"left-0 top-0 h-full border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left"},Il=p.forwardRef(({side:e="right",showOverlay:t=!0,overlayClassName:r,hideClose:n=!1,className:s,children:i,...a},l)=>{const c=hr(l,"intersection");return o.jsxs(i$,{children:[t?o.jsx($5,{className:r}):null,o.jsxs(Cl,{ref:c,className:Xe("fixed z-50 flex flex-col gap-4 border-border/60 bg-background p-6 text-foreground shadow-[0_28px_90px_-40px_rgba(15,23,42,0.82)] transition ease-out data-[state=open]:animate-in data-[state=closed]:animate-out",o$[e],s),...a,children:[i,n?null:o.jsxs(Ru,{className:"absolute top-4 right-4 inline-flex h-8 w-8 items-center justify-center rounded-md border border-border/60 text-muted-foreground transition-colors hover:border-border hover:text-foreground focus:outline-none",children:[o.jsx(vo,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Il.displayName=Cl.displayName;function Ff({className:e,...t}){return o.jsx("div",{className:Xe("flex flex-col gap-1.5",e),...t})}const Nl=p.forwardRef(({className:e,...t},r)=>o.jsx(Iu,{ref:r,className:Xe("text-base font-semibold",e),...t}));Nl.displayName=Iu.displayName;const Rl=p.forwardRef(({className:e,...t},r)=>o.jsx(Nu,{ref:r,className:Xe("text-sm text-muted-foreground",e),...t}));Rl.displayName=Nu.displayName;const a$={node:"节点连接",terminal:"Terminal",feishu:"飞书接入","app-server":"App Server","workspace-services":"Workspace Services",desktop:"Desktop","background-tasks":"后台任务","research-mcp":"调查 MCP"},Rx={healthy:"正常",recovering:"恢复中",unhealthy:"异常",blocked:"无法判断",checking:"检查中",unconfigured:"未配置",disabled:"已停用",unsupported:"版本不支持"},jx={unhealthy:"bg-red-500",recovering:"bg-amber-500",checking:"bg-slate-400",blocked:"bg-slate-400",healthy:"bg-emerald-500",unconfigured:"bg-slate-400",disabled:"bg-slate-400",unsupported:"bg-slate-400"};function l$(e){return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(e)}function z5(e){return e.some(t=>t.id==="frontend.node.http"&&t.state==="healthy")&&e.some(t=>t.id==="frontend.node.auth"&&t.state==="blocked")}function c$({item:e}){const t=Cr(),r=$k(e.capabilityId,e.state),n=W(async s=>{await mx(s)});return o.jsxs("div",{className:"rounded-lg border border-border/60 bg-background/60 p-3","data-runtime-status-item":e.id,"data-runtime-status-state":e.state,children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-sm font-medium",children:e.label}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:e.summary})]}),o.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${r==="warning"?"bg-amber-500":jx[e.state]}`}),Rx[e.state]]})]}),e.recovery?o.jsx("p",{className:"mt-2 text-[11px] text-amber-700 dark:text-amber-300",children:e.recovery.attempt===null?"正在按 owner 恢复策略重试":`重试 ${e.recovery.attempt}${e.recovery.maxAttempts===null?"":` / ${e.recovery.maxAttempts}`}`}):null,e.dependsOn.length>0&&e.state==="blocked"?o.jsxs("p",{className:"mt-2 text-[11px] text-muted-foreground",children:["上游:",e.dependsOn.join("、")]}):null,e.facts.length>0?o.jsx("div",{className:"mt-2 space-y-1",children:e.facts.map(s=>o.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[o.jsx("span",{className:"text-muted-foreground",children:s.label}),o.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[o.jsx("span",{className:"truncate font-mono",children:s.value}),s.copyable?o.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`复制${s.label}`,onClick:()=>void n(s.value),children:o.jsx(go,{className:"h-3 w-3"})}):null]})]},s.id))}):null,o.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px] text-muted-foreground/80",children:[o.jsxs("span",{children:["更新于 ",l$(e.observedAt)]}),e.id.includes("electron.remote-access:")?o.jsx("button",{type:"button",className:"text-xs underline",onClick:()=>Xr.getState().setOpen(!0),children:"管理远程访问"}):null,e.navigation?o.jsxs("button",{type:"button",className:"inline-flex items-center gap-0.5 hover:text-foreground",onClick:()=>t(e.navigation.route),children:[e.navigation.label,o.jsx(Jr,{className:"h-3 w-3"})]}):null]})]})}function u$({capability:e}){const t=e.attention,[r,n]=p.useState(t!=="none"),s=z5(e.items);return o.jsxs("section",{className:"overflow-hidden rounded-xl border border-border/70","data-runtime-status-attention":t,"data-runtime-status-capability":e.capabilityId,"data-runtime-status-state":e.state,children:[o.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 bg-muted/30 px-4 py-3 text-left","aria-expanded":r,onClick:()=>n(i=>!i),children:[o.jsx("span",{className:"text-sm font-medium",children:a$[e.capabilityId]}),o.jsxs("span",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${t==="warning"?"bg-amber-500":jx[e.state]}`}),e.state==="blocked"&&s?"待登录":t==="warning"?"Warning":Rx[e.state],o.jsx(Jr,{className:`h-3.5 w-3.5 transition ${r?"rotate-90":""}`})]})]}),r?o.jsx("div",{className:"space-y-2 border-t border-border/60 p-3",children:e.items.map(i=>o.jsx(c$,{item:i},i.id))}):null]})}function d$(){var i;const e=Cr(),{snapshot:t,error:r}=n$();if(((i=window.electronAPI)==null?void 0:i.isElectron)!==!0)return null;const n=t?t.electron.totalCpuPercent+(t.backend.cpuPercent??0):null,s=t?t.electron.totalMemoryMb+(t.backend.memoryMb??0):null;return o.jsxs("div",{className:"rounded-xl border border-border/70 p-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium",children:"资源摘要"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["CPU ",n===null?"--":`${n.toFixed(1)}%`," · RAM ",s??"--"," MB"]})]}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:()=>e("/system-monitor"),children:"System Monitor"})]}),r?o.jsx("p",{className:"mt-2 text-xs text-amber-600",children:r}):null]})}function h$({apiBase:e,token:t,embedded:r=!1}){const{nodes:n,panelOpen:s,setPanelOpen:i,refresh:a,refreshing:l}=Au(),c=p.useRef(null),u=W(async m=>{await mx(m)}),d=r?"h2":Nl,h=r?"p":Rl,f=o.jsxs(o.Fragment,{children:[o.jsx(Ff,{className:r?"border-b border-border/70 px-3 py-2":"border-b border-border/70 px-6 py-5 pr-14",children:o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx(d,{children:"运行状态"}),o.jsx(h,{children:"当前依赖、恢复状态与最近证据"})]}),o.jsxs(Z,{variant:"secondary",size:"sm",disabled:l,onClick:()=>void a(),children:[o.jsx(Ws,{className:l?"animate-spin":""}),l?"检查中":"重新检查"]})]})}),o.jsxs("div",{className:r?"min-h-0 flex-1 space-y-3 overflow-y-auto py-3":"min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4 sm:px-6",children:[!r&&o.jsx(ZF,{apiBase:e,token:t},`${e}:${t??""}`),!r&&o.jsx(t$,{}),o.jsx(kB,{}),n.map(m=>{const g=m.capabilities.some(v=>z5(v.items));return o.jsxs("article",{className:"space-y-3 rounded-2xl border border-border/70 bg-card/60 p-4","data-runtime-status-node":m.id,children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("h2",{className:"font-semibold",children:m.roles.includes("local")?"本机节点":"连接节点"}),m.roles.map(v=>o.jsx("span",{className:"rounded-full border border-border px-2 py-0.5 text-[10px] text-muted-foreground",children:v==="local"?"本机":"当前连接"},v))]}),o.jsxs("button",{type:"button",className:"mt-1 inline-flex max-w-full items-center gap-1 font-mono text-xs text-muted-foreground hover:text-foreground","aria-label":`${m.roles.includes("local")?"复制本机":"复制当前连接"}地址`,onClick:()=>void u(m.address),children:[o.jsx("span",{className:"truncate",children:m.address}),o.jsx(go,{className:"h-3 w-3 shrink-0"})]})]}),o.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${m.unhealthyCapabilityCount>0?"bg-red-500":m.warningCapabilityCount>0?"bg-amber-500":jx[m.state]}`}),m.unhealthyCapabilityCount>0?"异常":m.warningCapabilityCount>0?"Warning":m.state==="blocked"&&g?"待登录":Rx[m.state]]})]}),g?o.jsx("p",{className:"text-sm text-muted-foreground",children:"服务可连接,登录后查看详细状态。"}):null,o.jsx(AB,{reports:m.reports}),o.jsx(CB,{items:m.capabilities.flatMap(v=>v.items)}),o.jsx("div",{className:"space-y-2",children:m.capabilities.map(v=>o.jsx(u$,{capability:v},v.capabilityId))}),m.roles.includes("local")?o.jsx(d$,{}):null]},m.id)}),n.length===0?o.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"正在检查运行状态…"}):null]})]});return r?o.jsx("section",{className:"space-y-4",children:f}):o.jsx(Pu,{open:s,onOpenChange:i,children:o.jsx(Il,{className:"w-[min(92vw,42rem)] overflow-hidden p-0 sm:max-w-[42rem]",onOpenAutoFocus:()=>{c.current=document.activeElement instanceof HTMLElement?document.activeElement:null},onCloseAutoFocus:m=>{const g=c.current;c.current=null,g!=null&&g.isConnected&&(m.preventDefault(),g.focus({preventScroll:!0}))},children:f})})}const f$=3e3;function U5(e,t){return`${e.replace(/\/+$/u,"")}${t}`}async function H5(e,t){const r=new AbortController,n=window.setTimeout(()=>r.abort(),f$);try{return await fetch(e,{...t,signal:r.signal})}finally{window.clearTimeout(n)}}function W5(e){return e instanceof DOMException&&e.name==="AbortError"?"timeout":"network"}async function p$(e){try{const t=await H5(U5(e,"/health"));return t.ok?{kind:"ok",payload:await t.json()}:{kind:"network"}}catch(t){return{kind:W5(t)}}}async function m$(e,t){try{const r=await H5(U5(e,"/api/runtime-status"),{headers:{Authorization:`Bearer ${t}`}});if(r.status===401)return{kind:"unauthorized"};if(r.status===404)return{kind:"unsupported"};if(!r.ok)return{kind:"network"};const n=await r.json();return n.protocolVersion!==1?{kind:"unsupported"}:{kind:"ok",snapshot:n}}catch(r){return{kind:W5(r)}}}const q5=15e3;function g$(e){switch(e){case"missing-auth":return"当前节点没有可用登录会话";case"unauthorized":return"当前登录会话已失效";case"unsupported":return"当前 Backend 版本不支持详细运行状态";case"timeout":return"详细运行状态请求超时";case"network":return"详细运行状态暂时不可用";case"ok":return"详细运行状态可用"}}function v$(e,t){const r=e.health.kind==="ok"?"healthy":e.failureCount>=2||e.failureSince!==null&&e.observedAt-e.failureSince>=1e4?"unhealthy":"recovering",n=e.status.kind==="ok"?"healthy":e.status.kind==="unauthorized"?"unhealthy":e.status.kind==="unsupported"?"unsupported":e.status.kind==="missing-auth"?"blocked":"recovering",s=e.failureSince??e.observedAt,i=[{id:"frontend.node.http",capabilityId:"node",label:"节点连接",state:r,summary:r==="healthy"?"Backend HTTP 可用":r==="recovering"?"Backend HTTP 正在恢复":"Backend HTTP 持续不可达",observedAt:e.observedAt,dependsOn:[],recovery:r==="healthy"?null:{startedAt:s,attempt:e.failureCount,maxAttempts:2,nextAttemptAt:null,deadlineAt:s+1e4},facts:[{id:"frontend.node.address",label:"连接地址",value:e.address,kind:"address",copyable:!0}],navigation:null},{id:"frontend.node.auth",capabilityId:"node",label:"节点鉴权",state:n,summary:g$(e.status.kind),observedAt:e.observedAt,dependsOn:["frontend.node.http"],recovery:null,facts:[],navigation:null}];return{protocolVersion:1,target:{kind:"node",nodeId:t},source:{id:"frontend",runtime:"frontend",instanceId:"frontend:renderer",capabilityId:"node"},observedAt:e.observedAt,validForMs:q5,items:i}}function x$(e,t){return e?e.reports.map(r=>zk({...r,items:r.items.map(n=>({...n,dependsOn:Array.from(new Set(["frontend.node.http","frontend.node.auth",...n.dependsOn]))}))},t)):[]}function im(e,t){const r=new Map(e.map(n=>[n.source.id,n]));for(const n of t){const s=r.get(n.source.id);(!s||n.observedAt>=s.observedAt)&&r.set(n.source.id,n)}return[...r.values()]}function s1(e){const t=e==null?void 0:e.items.flatMap(r=>r.facts).find(r=>r.id==="electron.local-network.primary");return(t==null?void 0:t.value)??null}function b$(e){const t=new Map;for(const s of e.endpoints){const i=s.status.kind==="ok"?s.status.snapshot:s.lastSnapshot,a=s.health.kind==="ok"?s.health.payload.serviceInstanceId??(i==null?void 0:i.node.serviceInstanceId)??null:(i==null?void 0:i.node.serviceInstanceId)??null,l=a??`connection:${bB(s.address)}`,c=v$(s,l),u=x$(i,l),d=t.get(l),h=im((d==null?void 0:d.reports)??[],[c,...u]);t.set(l,{id:l,serviceInstanceId:a,address:s.roles.includes("current")||!d?s.address:d.address,roles:Array.from(new Set([...(d==null?void 0:d.roles)??[],...s.roles])),reports:h,capabilities:[],state:"checking",unhealthyCapabilityCount:0,warningCapabilityCount:0,generatedAt:s.observedAt})}let r=[...t.values()].find(s=>s.roles.includes("local"));if(!r&&e.electronReport){const s="local-host";r={id:s,serviceInstanceId:null,address:s1(e.electronReport)??"仅本机可用",roles:["local"],reports:[],capabilities:[],state:"checking",unhealthyCapabilityCount:0,warningCapabilityCount:0,generatedAt:e.electronReport.observedAt},t.set(s,r)}if(r&&e.electronReport){const s=e.endpoints.find(a=>a.roles.includes("local")),i=s&&s.health.kind!=="ok"?{...e.electronReport,items:e.electronReport.items.map(a=>a.id==="electron.packaged-backend"?{...a,state:"blocked",summary:"节点连接不可用,Backend 状态由上游根因表达",dependsOn:Array.from(new Set(["frontend.node.http",...a.dependsOn])),recovery:null}:a)}:e.electronReport;r.reports=im(r.reports,[zk(i,r.id)]),r.address=s1(e.electronReport)??"仅本机可用",r.generatedAt=Math.max(r.generatedAt,e.electronReport.observedAt)}const n=[...t.values()].find(s=>s.roles.includes("current"));if(n&&e.frontendItems.length>0){const s={protocolVersion:1,target:{kind:"node",nodeId:n.id},source:{id:"frontend-live",runtime:"frontend",instanceId:"frontend-live",capabilityId:"terminal"},observedAt:Math.max(...e.frontendItems.map(i=>i.observedAt)),validForMs:q5,items:e.frontendItems};n.reports=im(n.reports,[s])}return[...t.values()].map(s=>{const i=Uk(s.reports);return{...s,capabilities:i,state:px(i.map(a=>a.state)),unhealthyCapabilityCount:i.filter(a=>a.attention==="error").length,warningCapabilityCount:i.filter(a=>a.attention==="warning").length}})}const _$=5e3,y$=15e3;function th(e){const t=e||window.location.origin;try{return new URL(t,window.location.origin).origin}catch{return t.replace(/\/+$/u,"")}}function i1(e,t){const r=th(t.apiBase),n=e.get(r);if(!n){e.set(r,{...t,endpointKey:r});return}e.set(r,{...n,roles:Array.from(new Set([...n.roles,...t.roles])),token:t.roles.includes("current")?t.token:n.token})}function o1(e,t){const r=Date.now();return{protocolVersion:1,target:{kind:"local-host"},source:{id:"electron",runtime:"electron",instanceId:"electron:renderer-bridge",capabilityId:"desktop"},observedAt:r,validForMs:15e3,items:[{id:"electron.process",capabilityId:"desktop",label:"Electron process",state:e,summary:t,observedAt:r,dependsOn:[],recovery:null,facts:[],navigation:null}]}}function K5({apiBase:e,token:t,connections:r,isElectron:n,children:s}){const[i,a]=p.useState([]),[l,c]=p.useState(null),[u,d]=p.useState(new Map),[h,f]=p.useState(!1),[m,g]=p.useState(!1),v=p.useRef(i),x=p.useRef(null);v.current=i;const b=p.useMemo(()=>{const j=new Map;if(n){const R=r.find(I=>I.id===Vn);if(R!=null&&R.url){const I=yl(R.id);i1(j,{apiBase:R.url,address:th(R.url),roles:["local"],token:(I==null?void 0:I.accessToken)??(I==null?void 0:I.token)??null})}}return(e||!n)&&i1(j,{apiBase:e,address:th(e),roles:["current"],token:t}),[...j.values()]},[e,r,n,t]),_=W(()=>{if(x.current)return x.current;f(!0);const j=(async()=>{var A;const R=new Map(v.current.map(P=>[P.endpointKey,P])),I=await Promise.all(b.map(async P=>{const O=R.get(P.endpointKey),[L,B]=await Promise.all([p$(P.apiBase),P.token?m$(P.apiBase,P.token):Promise.resolve({kind:"missing-auth"})]),M=Date.now(),$=L.kind!=="ok";return{...P,health:L,status:B,lastSnapshot:B.kind==="ok"?B.snapshot:(O==null?void 0:O.lastSnapshot)??null,failureSince:$?(O==null?void 0:O.failureSince)??M:null,failureCount:$?((O==null?void 0:O.failureCount)??0)+1:0,observedAt:M}}));let T=null;if(n){const P=(A=window.electronAPI)==null?void 0:A.getRuntimeStatusReport;if(!P)T=o1("unsupported","当前 Desktop 版本不支持运行状态协议");else try{T=await P()}catch{T=o1("unhealthy","Electron 状态桥接不可用")}}a(I),c(T)})();return x.current=j.finally(()=>{x.current=null,f(!1)}),x.current});p.useEffect(()=>{let j=!1,R=null;const I=async()=>{await _(),!j&&(R=window.setTimeout(()=>void I(),document.hidden?y$:_$))},T=()=>{R!==null&&window.clearTimeout(R),R=null,I()};return document.addEventListener("visibilitychange",T),I(),()=>{j=!0,R!==null&&window.clearTimeout(R),document.removeEventListener("visibilitychange",T)}},[b,_]);const C=W((j,R)=>{d(I=>{const T=I.get(R);if(j===T||!j&&!T)return I;const A=new Map(I);return j?A.set(R,j):A.delete(R),A})}),S=p.useMemo(()=>b$({endpoints:i,electronReport:l,frontendItems:[...u.values()]}),[l,i,u]),w=S.find(j=>j.roles.includes("current")),y=(w==null?void 0:w.address)??th(e||window.location.origin),N=Array.from(new Set(S.flatMap(j=>j.capabilities.filter(R=>R.attention==="error").map(R=>R.capabilityId)))),E=Array.from(new Set(S.flatMap(j=>j.capabilities.filter(R=>R.attention==="warning").map(R=>R.capabilityId)))).filter(j=>!N.includes(j)),k=px(S.length>0?S.map(j=>j.state):["checking"]),D=p.useMemo(()=>({nodes:S,currentAddress:y,overallState:k,unhealthyCapabilityIds:N,warningCapabilityIds:E,refreshing:h,panelOpen:m,setPanelOpen:g,refresh:_,setFrontendItem:C}),[y,S,k,m,_,h,C,N,E]);return o.jsxs(qk.Provider,{value:D,children:[s,o.jsx(h$,{apiBase:e,token:t}),o.jsx(wB,{})]})}const Ax="runweave:resource-mac-notifications";function V5(){try{return localStorage.getItem(Ax)==="true"}catch{return!1}}const z0=Qn(e=>({enabled:V5(),setEnabled:t=>{localStorage.setItem(Ax,String(t)),e({enabled:t})}}));window.addEventListener("storage",e=>{(e.key===Ax||e.key===null)&&z0.setState({enabled:V5()})});function Mh(e,t){const r={Authorization:`Bearer ${t}`,"Content-Type":"application/json"},n="/api/device/resources";return{snapshot:s=>me(e,n,{headers:r,signal:s}),settings:s=>me(e,`${n}/settings`,{method:"PUT",headers:r,body:JSON.stringify({expectedRevision:s.revision,monitorEnabled:s.monitorEnabled,alertsEnabled:s.alertsEnabled})}),remoteControl:s=>me(e,`${n}/remote-control`,{method:"PUT",headers:r,body:JSON.stringify({expectedRevision:s.revision,enabled:s.enabled})}),snooze:s=>me(e,`${n}/alerts/${encodeURIComponent(s)}/snooze`,{method:"POST",headers:r,body:JSON.stringify({durationMinutes:60})}),terminate:(s,i,a)=>me(e,`${n}/processes/${encodeURIComponent(s)}/terminate`,{method:"POST",headers:r,body:JSON.stringify({force:i,requestId:a})})}}const G5=p.createContext(null);function Tx(){const e=p.useContext(G5);if(!e)throw new Error("Resource monitor provider required");return e}function Y5(e){const[t,r]=p.useState(null),[n,s]=p.useState(null),[i,a]=p.useState(!1),l=z0(w=>w.enabled),c=z0(w=>w.setEnabled),[u,d]=p.useState(null),[h,f]=p.useState(null),m=p.useRef(0),g=p.useRef(new Set),v=p.useRef(()=>{}),x=W(w=>{try{c(w)}catch{throw new Error("无法保存此设备的通知偏好")}d(null)}),b=W(()=>v.current()),_=W(()=>f(null)),C=W(w=>{r(y=>y&&{...y,settings:w,status:w.monitorEnabled?"warming-up":"disabled",alerts:[],canTerminate:!1}),f(null)}),S=W(async w=>{var N;if(!e.token)return;const y=(N=t==null?void 0:t.alerts.find(E=>E.alertId===w))==null?void 0:N.appKey;try{await Mh(e.apiBase,e.token).snooze(w)}catch(E){throw s(E instanceof Error?E.message:String(E)),E}r(E=>E&&{...E,alerts:E.alerts.filter(k=>y?k.appKey!==y:k.alertId!==w)}),f(E=>(E==null?void 0:E.alertId)===w||y&&(E==null?void 0:E.appKey)===y?null:E)});return p.useEffect(()=>{if(!e.token)return;let w=!1,y=!1;const N=new AbortController,E=async()=>{var R,I,T;const j=l&&((R=window.electronAPI)==null?void 0:R.isElectron)===!0;if(!(w||y||document.hidden&&!j||Date.now()-m.current<6e4)){y=!0,m.current=Date.now();try{const A=await Mh(e.apiBase,e.token).snapshot(N.signal);if(w)return;r(A),s(null),a(!1);const P=`runweave:resource-seen:${A.hostId}`;let O=[];try{const L=JSON.parse(localStorage.getItem(P)??"[]");Array.isArray(L)&&(O=L.filter(B=>typeof B=="string").slice(-200))}catch{}for(const L of e.notifications===!1?[]:A.alerts)if(!(O.includes(L.alertId)||g.current.has(`${A.hostId}:${L.alertId}`))){g.current.add(`${A.hostId}:${L.alertId}`),g.current.size>200&&g.current.delete(g.current.values().next().value),O.push(L.alertId),O=O.slice(-200);try{localStorage.setItem(P,JSON.stringify(O))}catch{}if(j)try{const B=await((T=(I=window.electronAPI)==null?void 0:I.showResourceNotification)==null?void 0:T.call(I,{connectionId:e.connectionId,hostId:A.hostId,alertId:L.alertId,appKey:L.appKey,title:`${L.appName} ${L.ruleId==="energy"?"能耗影响较高":"内存占用较大"}`,body:L.ruleId==="energy"?"近 5 分钟多次检测到高占用":"近 5 分钟多次检测到较大内存占用;内存不代表耗电量"}));if(w)return;(B==="failed"||B==="unavailable"||B===void 0)&&d("Mac 系统通知不可用或投递失败,请检查系统通知设置;应用内提醒仍保留")}catch{w||d("Mac 系统通知投递失败,应用内提醒仍保留")}w||f(L)}f(L=>L&&A.alerts.some(B=>B.alertId===L.alertId)?L:null)}catch(A){if(w)return;a(A instanceof De&&A.status===404),s(A instanceof Error?A.message:String(A))}finally{y=!1}}};v.current=()=>void E(),E();const k=window.setInterval(()=>void E(),6e4),D=()=>{document.hidden||E()};return document.addEventListener("visibilitychange",D),()=>{w=!0,N.abort(),window.clearInterval(k),document.removeEventListener("visibilitychange",D),v.current=()=>{}}},[e.apiBase,e.token,e.connectionId,e.notifications,l]),o.jsx(G5.Provider,{value:{data:t,error:n,unsupportedBackend:i,refresh:b,apiBase:e.apiBase,token:e.token,macNotifications:l,setMacNotifications:x,notificationError:u,notice:h,dismissNotice:_,applySettings:C,applyRemoteControl:w=>r(y=>y&&{...y,remoteControl:w}),snooze:S},children:e.children})}var jl=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Uo,Hi,Za,F2,w$=(F2=class extends jl{constructor(){super();Ye(this,Uo);Ye(this,Hi);Ye(this,Za);Ae(this,Za,t=>{if(typeof window<"u"&&window.addEventListener){const r=()=>t();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Q(this,Hi)||this.setEventListener(Q(this,Za))}onUnsubscribe(){var t;this.hasListeners()||((t=Q(this,Hi))==null||t.call(this),Ae(this,Hi,void 0))}setEventListener(t){var r;Ae(this,Za,t),(r=Q(this,Hi))==null||r.call(this),Ae(this,Hi,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){Q(this,Uo)!==t&&(Ae(this,Uo,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(r=>{r(t)})}isFocused(){var t;return typeof Q(this,Uo)=="boolean"?Q(this,Uo):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Uo=new WeakMap,Hi=new WeakMap,Za=new WeakMap,F2),$f=new w$,S$={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Wi,Iv,$2,C$=($2=class{constructor(){Ye(this,Wi,S$);Ye(this,Iv,!1)}setTimeoutProvider(e){Ae(this,Wi,e)}setTimeout(e,t){return Q(this,Wi).setTimeout(e,t)}clearTimeout(e){Q(this,Wi).clearTimeout(e)}setInterval(e,t){return Q(this,Wi).setInterval(e,t)}clearInterval(e){Q(this,Wi).clearInterval(e)}},Wi=new WeakMap,Iv=new WeakMap,$2),Fo=new C$;function E$(e){setTimeout(e,0)}var k$=typeof window>"u"||"Deno"in globalThis;function ln(){}function I$(e,t){return typeof e=="function"?e(t):e}function U0(e){return typeof e=="number"&&e>=0&&e!==1/0}function X5(e,t){return Math.max(e+(t||0)-Date.now(),0)}function no(e,t){return typeof e=="function"?e(t):e}function In(e,t){return typeof e=="function"?e(t):e}function a1(e,t){const{type:r="all",exact:n,fetchStatus:s,predicate:i,queryKey:a,stale:l}=e;if(a){if(n){if(t.queryHash!==Dx(a,t.options))return!1}else if(!zc(t.queryKey,a))return!1}if(r!=="all"){const c=t.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||s&&s!==t.state.fetchStatus||i&&!i(t))}function l1(e,t){const{exact:r,status:n,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(r){if(na(t.options.mutationKey)!==na(i))return!1}else if(!zc(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||s&&!s(t))}function Dx(e,t){return((t==null?void 0:t.queryKeyHashFn)||na)(e)}function na(e){return JSON.stringify(e,(t,r)=>H0(r)?Object.keys(r).sort().reduce((n,s)=>(n[s]=r[s],n),{}):r)}function zc(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(r=>zc(e[r],t[r])):!1}var N$=Object.prototype.hasOwnProperty;function J5(e,t,r=0){if(e===t)return e;if(r>500)return t;const n=c1(e)&&c1(t);if(!n&&!(H0(e)&&H0(t)))return t;const i=(n?e:Object.keys(e)).length,a=n?t:Object.keys(t),l=a.length,c=n?new Array(l):{};let u=0;for(let d=0;d<l;d++){const h=n?d:a[d],f=e[h],m=t[h];if(f===m){c[h]=f,(n?d<i:N$.call(e,h))&&u++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){c[h]=m;continue}const g=J5(f,m,r+1);c[h]=g,g===f&&u++}return i===l&&u===i?e:c}function Oh(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}function c1(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function H0(e){if(!u1(e))return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(!u1(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function u1(e){return Object.prototype.toString.call(e)==="[object Object]"}function R$(e){return new Promise(t=>{Fo.setTimeout(t,e)})}function W0(e,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,t):r.structuralSharing!==!1?J5(e,t):t}function j$(e,t,r=0){const n=[...e,t];return r&&n.length>r?n.slice(1):n}function A$(e,t,r=0){const n=[t,...e];return r&&n.length>r?n.slice(0,-1):n}var Px=Symbol();function Q5(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Px?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Lx(e,t){return typeof e=="function"?e(...t):!!e}function T$(e,t,r){let n=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),n||(n=!0,s.aborted?r():s.addEventListener("abort",r,{once:!0})),s)}),e}var Uc=(()=>{let e=()=>k$;return{isServer(){return e()},setIsServer(t){e=t}}})();function q0(){let e,t;const r=new Promise((s,i)=>{e=s,t=i});r.status="pending",r.catch(()=>{});function n(s){Object.assign(r,s),delete r.resolve,delete r.reject}return r.resolve=s=>{n({status:"fulfilled",value:s}),e(s)},r.reject=s=>{n({status:"rejected",reason:s}),t(s)},r}var D$=E$;function P$(){let e=[],t=0,r=l=>{l()},n=l=>{l()},s=D$;const i=l=>{t?e.push(l):s(()=>{r(l)})},a=()=>{const l=e;e=[],l.length&&s(()=>{n(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;t++;try{c=l()}finally{t--,t||a()}return c},batchCalls:l=>(...c)=>{i(()=>{l(...c)})},schedule:i,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{n=l},setScheduler:l=>{s=l}}}var _r=P$(),el,qi,tl,z2,L$=(z2=class extends jl{constructor(){super();Ye(this,el,!0);Ye(this,qi);Ye(this,tl);Ae(this,tl,t=>{if(typeof window<"u"&&window.addEventListener){const r=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Q(this,qi)||this.setEventListener(Q(this,tl))}onUnsubscribe(){var t;this.hasListeners()||((t=Q(this,qi))==null||t.call(this),Ae(this,qi,void 0))}setEventListener(t){var r;Ae(this,tl,t),(r=Q(this,qi))==null||r.call(this),Ae(this,qi,t(this.setOnline.bind(this)))}setOnline(t){Q(this,el)!==t&&(Ae(this,el,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return Q(this,el)}},el=new WeakMap,qi=new WeakMap,tl=new WeakMap,z2),sa=new L$;function M$(e){return Math.min(1e3*2**e,3e4)}function Z5(e){return(e??"online")==="online"?sa.isOnline():!0}var K0=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function e3(e){let t=!1,r=0,n;const s=q0(),i=()=>s.status!=="pending",a=v=>{var x;if(!i()){const b=new K0(v);f(b),(x=e.onCancel)==null||x.call(e,b)}},l=()=>{t=!0},c=()=>{t=!1},u=()=>$f.isFocused()&&(e.networkMode==="always"||sa.isOnline())&&e.canRun(),d=()=>Z5(e.networkMode)&&e.canRun(),h=v=>{i()||(n==null||n(),s.resolve(v))},f=v=>{i()||(n==null||n(),s.reject(v))},m=()=>new Promise(v=>{var x;n=b=>{(i()||u())&&v(b)},(x=e.onPause)==null||x.call(e)}).then(()=>{var v;n=void 0,i()||(v=e.onContinue)==null||v.call(e)}),g=()=>{if(i())return;let v;const x=r===0?e.initialPromise:void 0;try{v=x??e.fn()}catch(b){v=Promise.reject(b)}Promise.resolve(v).then(h).catch(b=>{var y;if(i())return;const _=e.retry??(Uc.isServer()?0:3),C=e.retryDelay??M$,S=typeof C=="function"?C(r,b):C,w=_===!0||typeof _=="number"&&r<_||typeof _=="function"&&_(r,b);if(t||!w){f(b);return}r++,(y=e.onFail)==null||y.call(e,r,b),R$(S).then(()=>u()?void 0:m()).then(()=>{t?f(b):g()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(n==null||n(),s),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?g():m().then(g),s)}}var Ho,U2,t3=(U2=class{constructor(){Ye(this,Ho)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),U0(this.gcTime)&&Ae(this,Ho,Fo.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Uc.isServer()?1/0:300*1e3))}clearGcTimeout(){Q(this,Ho)!==void 0&&(Fo.clearTimeout(Q(this,Ho)),Ae(this,Ho,void 0))}},Ho=new WeakMap,U2);function O$(e){return{onFetch:(t,r)=>{var d,h,f,m,g;const n=t.options,s=(f=(h=(d=t.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:f.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],a=((g=t.state.data)==null?void 0:g.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let v=!1;const x=C=>{T$(C,()=>t.signal,()=>v=!0)},b=Q5(t.options,t.fetchOptions),_=async(C,S,w)=>{if(v)return Promise.reject(t.signal.reason);if(S==null&&C.pages.length)return Promise.resolve(C);const N=(()=>{const j={client:t.client,queryKey:t.queryKey,pageParam:S,direction:w?"backward":"forward",meta:t.options.meta};return x(j),j})(),E=await b(N),{maxPages:k}=t.options,D=w?A$:j$;return{pages:D(C.pages,E,k),pageParams:D(C.pageParams,S,k)}};if(s&&i.length){const C=s==="backward",S=C?r3:V0,w={pages:i,pageParams:a},y=S(n,w);l=await _(w,y,C)}else{const C=e??i.length;do{const S=c===0?a[0]??n.initialPageParam:V0(n,l);if(c>0&&S==null)break;l=await _(l,S),c++}while(c<C)}return l};t.options.persister?t.fetchFn=()=>{var v,x;return(x=(v=t.options).persister)==null?void 0:x.call(v,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r)}:t.fetchFn=u}}}function V0(e,{pages:t,pageParams:r}){const n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,r[n],r):void 0}function r3(e,{pages:t,pageParams:r}){var n;return t.length>0?(n=e.getPreviousPageParam)==null?void 0:n.call(e,t[0],t,r[0],r):void 0}function B$(e,t){return t?V0(e,t)!=null:!1}function F$(e,t){return!t||!e.getPreviousPageParam?!1:r3(e,t)!=null}var rl,Wo,nl,Un,qo,kr,au,Ko,En,n3,ni,H2,$$=(H2=class extends t3{constructor(t){super();Ye(this,En);Ye(this,rl);Ye(this,Wo);Ye(this,nl);Ye(this,Un);Ye(this,qo);Ye(this,kr);Ye(this,au);Ye(this,Ko);Ae(this,Ko,!1),Ae(this,au,t.defaultOptions),this.setOptions(t.options),this.observers=[],Ae(this,qo,t.client),Ae(this,Un,Q(this,qo).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Ae(this,Wo,h1(this.options)),this.state=t.state??Q(this,Wo),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return Q(this,rl)}get promise(){var t;return(t=Q(this,kr))==null?void 0:t.promise}setOptions(t){if(this.options={...Q(this,au),...t},t!=null&&t._type&&Ae(this,rl,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=h1(this.options);r.data!==void 0&&(this.setState(d1(r.data,r.dataUpdatedAt)),Ae(this,Wo,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Q(this,Un).remove(this)}setData(t,r){const n=W0(this.state.data,t,this.options);return ut(this,En,ni).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(t){ut(this,En,ni).call(this,{type:"setState",state:t})}cancel(t){var n,s;const r=(n=Q(this,kr))==null?void 0:n.promise;return(s=Q(this,kr))==null||s.cancel(t),r?r.then(ln).catch(ln):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return Q(this,Wo)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>In(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Px||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>no(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!X5(this.state.dataUpdatedAt,t)}onFocus(){var r;const t=this.observers.find(n=>n.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(r=Q(this,kr))==null||r.continue()}onOnline(){var r;const t=this.observers.find(n=>n.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(r=Q(this,kr))==null||r.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Q(this,Un).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(r=>r!==t),this.observers.length||(Q(this,kr)&&(Q(this,Ko)||ut(this,En,n3).call(this)?Q(this,kr).cancel({revert:!0}):Q(this,kr).cancelRetry()),this.scheduleGc()),Q(this,Un).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ut(this,En,ni).call(this,{type:"invalidate"})}async fetch(t,r){var u,d,h,f,m,g,v,x,b,_,C;if(this.state.fetchStatus!=="idle"&&((u=Q(this,kr))==null?void 0:u.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Q(this,kr))return Q(this,kr).continueRetry(),Q(this,kr).promise}if(t&&this.setOptions(t),!this.options.queryFn){const S=this.observers.find(w=>w.options.queryFn);S&&this.setOptions(S.options)}const n=new AbortController,s=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(Ae(this,Ko,!0),n.signal)})},i=()=>{const S=Q5(this.options,r),y=(()=>{const N={client:Q(this,qo),queryKey:this.queryKey,meta:this.meta};return s(N),N})();return Ae(this,Ko,!1),this.options.persister?this.options.persister(S,y,this):S(y)},l=(()=>{const S={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Q(this,qo),state:this.state,fetchFn:i};return s(S),S})(),c=Q(this,rl)==="infinite"?O$(this.options.pages):this.options.behavior;c==null||c.onFetch(l,this),Ae(this,nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&ut(this,En,ni).call(this,{type:"fetch",meta:(h=l.fetchOptions)==null?void 0:h.meta}),Ae(this,kr,e3({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:S=>{S instanceof K0&&S.revert&&this.setState({...Q(this,nl),fetchStatus:"idle"}),n.abort()},onFail:(S,w)=>{ut(this,En,ni).call(this,{type:"failed",failureCount:S,error:w})},onPause:()=>{ut(this,En,ni).call(this,{type:"pause"})},onContinue:()=>{ut(this,En,ni).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const S=await Q(this,kr).start();if(S===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(S),(m=(f=Q(this,Un).config).onSuccess)==null||m.call(f,S,this),(v=(g=Q(this,Un).config).onSettled)==null||v.call(g,S,this.state.error,this),S}catch(S){if(S instanceof K0){if(S.silent)return Q(this,kr).promise;if(S.revert){if(this.state.data===void 0)throw S;return this.state.data}}throw ut(this,En,ni).call(this,{type:"error",error:S}),(b=(x=Q(this,Un).config).onError)==null||b.call(x,S,this),(C=(_=Q(this,Un).config).onSettled)==null||C.call(_,this.state.data,S,this),S}finally{this.scheduleGc()}}},rl=new WeakMap,Wo=new WeakMap,nl=new WeakMap,Un=new WeakMap,qo=new WeakMap,kr=new WeakMap,au=new WeakMap,Ko=new WeakMap,En=new WeakSet,n3=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},ni=function(t){const r=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...s3(n.data,this.options),fetchMeta:t.meta??null};case"success":const s={...n,...d1(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Ae(this,nl,t.manual?s:void 0),s;case"error":const i=t.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=r(this.state),_r.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Q(this,Un).notify({query:this,type:"updated",action:t})})},H2);function s3(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Z5(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function d1(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function h1(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,r=t!==void 0,n=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var vn,bt,lu,on,Vo,sl,ii,Ki,cu,il,ol,Go,Yo,Vi,al,It,mc,G0,Y0,X0,J0,Q0,Z0,eg,o3,W2,i3=(W2=class extends jl{constructor(t,r){super();Ye(this,It);Ye(this,vn);Ye(this,bt);Ye(this,lu);Ye(this,on);Ye(this,Vo);Ye(this,sl);Ye(this,ii);Ye(this,Ki);Ye(this,cu);Ye(this,il);Ye(this,ol);Ye(this,Go);Ye(this,Yo);Ye(this,Vi);Ye(this,al,new Set);this.options=r,Ae(this,vn,t),Ae(this,Ki,null),Ae(this,ii,q0()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Q(this,bt).addObserver(this),f1(Q(this,bt),this.options)?ut(this,It,mc).call(this):this.updateResult(),ut(this,It,J0).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return tg(Q(this,bt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return tg(Q(this,bt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ut(this,It,Q0).call(this),ut(this,It,Z0).call(this),Q(this,bt).removeObserver(this)}setOptions(t){const r=this.options,n=Q(this,bt);if(this.options=Q(this,vn).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof In(this.options.enabled,Q(this,bt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ut(this,It,eg).call(this),Q(this,bt).setOptions(this.options),r._defaulted&&!Oh(this.options,r)&&Q(this,vn).getQueryCache().notify({type:"observerOptionsUpdated",query:Q(this,bt),observer:this});const s=this.hasListeners();s&&p1(Q(this,bt),n,this.options,r)&&ut(this,It,mc).call(this),this.updateResult(),s&&(Q(this,bt)!==n||In(this.options.enabled,Q(this,bt))!==In(r.enabled,Q(this,bt))||no(this.options.staleTime,Q(this,bt))!==no(r.staleTime,Q(this,bt)))&&ut(this,It,G0).call(this);const i=ut(this,It,Y0).call(this);s&&(Q(this,bt)!==n||In(this.options.enabled,Q(this,bt))!==In(r.enabled,Q(this,bt))||i!==Q(this,Vi))&&ut(this,It,X0).call(this,i)}getOptimisticResult(t){const r=Q(this,vn).getQueryCache().build(Q(this,vn),t),n=this.createResult(r,t);return U$(this,n)&&(Ae(this,on,n),Ae(this,sl,this.options),Ae(this,Vo,Q(this,bt).state)),n}getCurrentResult(){return Q(this,on)}trackResult(t,r){return new Proxy(t,{get:(n,s)=>(this.trackProp(s),r==null||r(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&Q(this,ii).status==="pending"&&Q(this,ii).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s))})}trackProp(t){Q(this,al).add(t)}getCurrentQuery(){return Q(this,bt)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const r=Q(this,vn).defaultQueryOptions(t),n=Q(this,vn).getQueryCache().build(Q(this,vn),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(t){return ut(this,It,mc).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Q(this,on)))}createResult(t,r){var k;const n=Q(this,bt),s=this.options,i=Q(this,on),a=Q(this,Vo),l=Q(this,sl),u=t!==n?t.state:Q(this,lu),{state:d}=t;let h={...d},f=!1,m;if(r._optimisticResults){const D=this.hasListeners(),j=!D&&f1(t,r),R=D&&p1(t,n,r,s);(j||R)&&(h={...h,...s3(d.data,t.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:g,errorUpdatedAt:v,status:x}=h;m=h.data;let b=!1;if(r.placeholderData!==void 0&&m===void 0&&x==="pending"){let D;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(D=i.data,b=!0):D=typeof r.placeholderData=="function"?r.placeholderData((k=Q(this,ol))==null?void 0:k.state.data,Q(this,ol)):r.placeholderData,D!==void 0&&(x="success",m=W0(i==null?void 0:i.data,D,r),f=!0)}if(r.select&&m!==void 0&&!b)if(i&&m===(a==null?void 0:a.data)&&r.select===Q(this,cu))m=Q(this,il);else try{Ae(this,cu,r.select),m=r.select(m),m=W0(i==null?void 0:i.data,m,r),Ae(this,il,m),Ae(this,Ki,null)}catch(D){Ae(this,Ki,D)}Q(this,Ki)&&(g=Q(this,Ki),m=Q(this,il),v=Date.now(),x="error");const _=h.fetchStatus==="fetching",C=x==="pending",S=x==="error",w=C&&_,y=m!==void 0,E={status:x,fetchStatus:h.fetchStatus,isPending:C,isSuccess:x==="success",isError:S,isInitialLoading:w,isLoading:w,data:m,dataUpdatedAt:h.dataUpdatedAt,error:g,errorUpdatedAt:v,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!C,isLoadingError:S&&!y,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:S&&y,isStale:Mx(t,r),refetch:this.refetch,promise:Q(this,ii),isEnabled:In(r.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const D=E.data!==void 0,j=E.status==="error"&&!D,R=A=>{j?A.reject(E.error):D&&A.resolve(E.data)},I=()=>{const A=Ae(this,ii,E.promise=q0());R(A)},T=Q(this,ii);switch(T.status){case"pending":t.queryHash===n.queryHash&&R(T);break;case"fulfilled":(j||E.data!==T.value)&&I();break;case"rejected":(!j||E.error!==T.reason)&&I();break}}return E}updateResult(){const t=Q(this,on),r=this.createResult(Q(this,bt),this.options);if(Ae(this,Vo,Q(this,bt).state),Ae(this,sl,this.options),Q(this,Vo).data!==void 0&&Ae(this,ol,Q(this,bt)),Oh(r,t))return;Ae(this,on,r);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!Q(this,al).size)return!0;const a=new Set(i??Q(this,al));return this.options.throwOnError&&a.add("error"),Object.keys(Q(this,on)).some(l=>{const c=l;return Q(this,on)[c]!==t[c]&&a.has(c)})};ut(this,It,o3).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ut(this,It,J0).call(this)}},vn=new WeakMap,bt=new WeakMap,lu=new WeakMap,on=new WeakMap,Vo=new WeakMap,sl=new WeakMap,ii=new WeakMap,Ki=new WeakMap,cu=new WeakMap,il=new WeakMap,ol=new WeakMap,Go=new WeakMap,Yo=new WeakMap,Vi=new WeakMap,al=new WeakMap,It=new WeakSet,mc=function(t){ut(this,It,eg).call(this);let r=Q(this,bt).fetch(this.options,t);return t!=null&&t.throwOnError||(r=r.catch(ln)),r},G0=function(){ut(this,It,Q0).call(this);const t=no(this.options.staleTime,Q(this,bt));if(Uc.isServer()||Q(this,on).isStale||!U0(t))return;const n=X5(Q(this,on).dataUpdatedAt,t)+1;Ae(this,Go,Fo.setTimeout(()=>{Q(this,on).isStale||this.updateResult()},n))},Y0=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Q(this,bt)):this.options.refetchInterval)??!1},X0=function(t){ut(this,It,Z0).call(this),Ae(this,Vi,t),!(Uc.isServer()||In(this.options.enabled,Q(this,bt))===!1||!U0(Q(this,Vi))||Q(this,Vi)===0)&&Ae(this,Yo,Fo.setInterval(()=>{(this.options.refetchIntervalInBackground||$f.isFocused())&&ut(this,It,mc).call(this)},Q(this,Vi)))},J0=function(){ut(this,It,G0).call(this),ut(this,It,X0).call(this,ut(this,It,Y0).call(this))},Q0=function(){Q(this,Go)!==void 0&&(Fo.clearTimeout(Q(this,Go)),Ae(this,Go,void 0))},Z0=function(){Q(this,Yo)!==void 0&&(Fo.clearInterval(Q(this,Yo)),Ae(this,Yo,void 0))},eg=function(){const t=Q(this,vn).getQueryCache().build(Q(this,vn),this.options);if(t===Q(this,bt))return;const r=Q(this,bt);Ae(this,bt,t),Ae(this,lu,t.state),this.hasListeners()&&(r==null||r.removeObserver(this),t.addObserver(this))},o3=function(t){_r.batch(()=>{t.listeners&&this.listeners.forEach(r=>{r(Q(this,on))}),Q(this,vn).getQueryCache().notify({query:Q(this,bt),type:"observerResultsUpdated"})})},W2);function z$(e,t){return In(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&In(t.retryOnMount,e)===!1)}function f1(e,t){return z$(e,t)||e.state.data!==void 0&&tg(e,t,t.refetchOnMount)}function tg(e,t,r){if(In(t.enabled,e)!==!1&&no(t.staleTime,e)!=="static"){const n=typeof r=="function"?r(e):r;return n==="always"||n!==!1&&Mx(e,t)}return!1}function p1(e,t,r,n){return(e!==t||In(n.enabled,e)===!1)&&(!r.suspense||e.state.status!=="error")&&Mx(e,r)}function Mx(e,t){return In(t.enabled,e)!==!1&&e.isStaleByTime(no(t.staleTime,e))}function U$(e,t){return!Oh(e.getCurrentResult(),t)}var H$=class extends i3{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){var g,v;const{state:r}=e,n=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:a,isRefetchError:l}=n,c=(v=(g=r.fetchMeta)==null?void 0:g.fetchMore)==null?void 0:v.direction,u=a&&c==="forward",d=s&&c==="forward",h=a&&c==="backward",f=s&&c==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:B$(t,r.data),hasPreviousPage:F$(t,r.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:h,isFetchingPreviousPage:f,isRefetchError:l&&!u&&!h,isRefetching:i&&!d&&!f}}},uu,As,Kr,Xo,Ts,Ti,q2,W$=(q2=class extends t3{constructor(t){super();Ye(this,Ts);Ye(this,uu);Ye(this,As);Ye(this,Kr);Ye(this,Xo);Ae(this,uu,t.client),this.mutationId=t.mutationId,Ae(this,Kr,t.mutationCache),Ae(this,As,[]),this.state=t.state||a3(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Q(this,As).includes(t)||(Q(this,As).push(t),this.clearGcTimeout(),Q(this,Kr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Ae(this,As,Q(this,As).filter(r=>r!==t)),this.scheduleGc(),Q(this,Kr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Q(this,As).length||(this.state.status==="pending"?this.scheduleGc():Q(this,Kr).remove(this))}continue(){var t;return((t=Q(this,Xo))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var a,l,c,u,d,h,f,m,g,v,x,b,_,C,S,w,y,N;const r=()=>{ut(this,Ts,Ti).call(this,{type:"continue"})},n={client:Q(this,uu),meta:this.options.meta,mutationKey:this.options.mutationKey};Ae(this,Xo,e3({fn:()=>this.options.mutationFn?this.options.mutationFn(t,n):Promise.reject(new Error("No mutationFn found")),onFail:(E,k)=>{ut(this,Ts,Ti).call(this,{type:"failed",failureCount:E,error:k})},onPause:()=>{ut(this,Ts,Ti).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Q(this,Kr).canRun(this)}));const s=this.state.status==="pending",i=!Q(this,Xo).canStart();try{if(s)r();else{ut(this,Ts,Ti).call(this,{type:"pending",variables:t,isPaused:i}),Q(this,Kr).config.onMutate&&await Q(this,Kr).config.onMutate(t,this,n);const k=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,t,n));k!==this.state.context&&ut(this,Ts,Ti).call(this,{type:"pending",context:k,variables:t,isPaused:i})}const E=await Q(this,Xo).start();return await((u=(c=Q(this,Kr).config).onSuccess)==null?void 0:u.call(c,E,t,this.state.context,this,n)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,E,t,this.state.context,n)),await((m=(f=Q(this,Kr).config).onSettled)==null?void 0:m.call(f,E,null,this.state.variables,this.state.context,this,n)),await((v=(g=this.options).onSettled)==null?void 0:v.call(g,E,null,t,this.state.context,n)),ut(this,Ts,Ti).call(this,{type:"success",data:E}),E}catch(E){try{await((b=(x=Q(this,Kr).config).onError)==null?void 0:b.call(x,E,t,this.state.context,this,n))}catch(k){Promise.reject(k)}try{await((C=(_=this.options).onError)==null?void 0:C.call(_,E,t,this.state.context,n))}catch(k){Promise.reject(k)}try{await((w=(S=Q(this,Kr).config).onSettled)==null?void 0:w.call(S,void 0,E,this.state.variables,this.state.context,this,n))}catch(k){Promise.reject(k)}try{await((N=(y=this.options).onSettled)==null?void 0:N.call(y,void 0,E,t,this.state.context,n))}catch(k){Promise.reject(k)}throw ut(this,Ts,Ti).call(this,{type:"error",error:E}),E}finally{Q(this,Kr).runNext(this)}}},uu=new WeakMap,As=new WeakMap,Kr=new WeakMap,Xo=new WeakMap,Ts=new WeakSet,Ti=function(t){const r=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=r(this.state),_r.batch(()=>{Q(this,As).forEach(n=>{n.onMutationUpdate(t)}),Q(this,Kr).notify({mutation:this,type:"updated",action:t})})},q2);function a3(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var oi,os,du,K2,l3=(K2=class extends jl{constructor(t={}){super();Ye(this,oi);Ye(this,os);Ye(this,du);this.config=t,Ae(this,oi,new Set),Ae(this,os,new Map),Ae(this,du,0)}build(t,r,n){const s=new W$({client:t,mutationCache:this,mutationId:++od(this,du)._,options:t.defaultMutationOptions(r),state:n});return this.add(s),s}add(t){Q(this,oi).add(t);const r=yd(t);if(typeof r=="string"){const n=Q(this,os).get(r);n?n.push(t):Q(this,os).set(r,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Q(this,oi).delete(t)){const r=yd(t);if(typeof r=="string"){const n=Q(this,os).get(r);if(n)if(n.length>1){const s=n.indexOf(t);s!==-1&&n.splice(s,1)}else n[0]===t&&Q(this,os).delete(r)}}this.notify({type:"removed",mutation:t})}canRun(t){const r=yd(t);if(typeof r=="string"){const n=Q(this,os).get(r),s=n==null?void 0:n.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){var n;const r=yd(t);if(typeof r=="string"){const s=(n=Q(this,os).get(r))==null?void 0:n.find(i=>i!==t&&i.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}else return Promise.resolve()}clear(){_r.batch(()=>{Q(this,oi).forEach(t=>{this.notify({type:"removed",mutation:t})}),Q(this,oi).clear(),Q(this,os).clear()})}getAll(){return Array.from(Q(this,oi))}find(t){const r={exact:!0,...t};return this.getAll().find(n=>l1(r,n))}findAll(t={}){return this.getAll().filter(r=>l1(t,r))}notify(t){_r.batch(()=>{this.listeners.forEach(r=>{r(t)})})}resumePausedMutations(){const t=this.getAll().filter(r=>r.state.isPaused);return _r.batch(()=>Promise.all(t.map(r=>r.continue().catch(ln))))}},oi=new WeakMap,os=new WeakMap,du=new WeakMap,K2);function yd(e){var t;return(t=e.options.scope)==null?void 0:t.id}var ai,Gi,xn,li,pi,rh,rg,V2,q$=(V2=class extends jl{constructor(r,n){super();Ye(this,pi);Ye(this,ai);Ye(this,Gi);Ye(this,xn);Ye(this,li);Ae(this,ai,r),this.setOptions(n),this.bindMethods(),ut(this,pi,rh).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var s;const n=this.options;this.options=Q(this,ai).defaultMutationOptions(r),Oh(this.options,n)||Q(this,ai).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Q(this,xn),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&na(n.mutationKey)!==na(this.options.mutationKey)?this.reset():((s=Q(this,xn))==null?void 0:s.state.status)==="pending"&&Q(this,xn).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Q(this,xn))==null||r.removeObserver(this)}onMutationUpdate(r){ut(this,pi,rh).call(this),ut(this,pi,rg).call(this,r)}getCurrentResult(){return Q(this,Gi)}reset(){var r;(r=Q(this,xn))==null||r.removeObserver(this),Ae(this,xn,void 0),ut(this,pi,rh).call(this),ut(this,pi,rg).call(this)}mutate(r,n){var s;return Ae(this,li,n),(s=Q(this,xn))==null||s.removeObserver(this),Ae(this,xn,Q(this,ai).getMutationCache().build(Q(this,ai),this.options)),Q(this,xn).addObserver(this),Q(this,xn).execute(r)}},ai=new WeakMap,Gi=new WeakMap,xn=new WeakMap,li=new WeakMap,pi=new WeakSet,rh=function(){var n;const r=((n=Q(this,xn))==null?void 0:n.state)??a3();Ae(this,Gi,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},rg=function(r){_r.batch(()=>{var n,s,i,a,l,c,u,d;if(Q(this,li)&&this.hasListeners()){const h=Q(this,Gi).variables,f=Q(this,Gi).context,m={client:Q(this,ai),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(s=(n=Q(this,li)).onSuccess)==null||s.call(n,r.data,h,f,m)}catch(g){Promise.reject(g)}try{(a=(i=Q(this,li)).onSettled)==null||a.call(i,r.data,null,h,f,m)}catch(g){Promise.reject(g)}}else if((r==null?void 0:r.type)==="error"){try{(c=(l=Q(this,li)).onError)==null||c.call(l,r.error,h,f,m)}catch(g){Promise.reject(g)}try{(d=(u=Q(this,li)).onSettled)==null||d.call(u,void 0,r.error,h,f,m)}catch(g){Promise.reject(g)}}}this.listeners.forEach(h=>{h(Q(this,Gi))})})},V2),Ds,G2,c3=(G2=class extends jl{constructor(t={}){super();Ye(this,Ds);this.config=t,Ae(this,Ds,new Map)}build(t,r,n){const s=r.queryKey,i=r.queryHash??Dx(s,r);let a=this.get(i);return a||(a=new $$({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(r),state:n,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){Q(this,Ds).has(t.queryHash)||(Q(this,Ds).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const r=Q(this,Ds).get(t.queryHash);r&&(t.destroy(),r===t&&Q(this,Ds).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){_r.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Q(this,Ds).get(t)}getAll(){return[...Q(this,Ds).values()]}find(t){const r={exact:!0,...t};return this.getAll().find(n=>a1(r,n))}findAll(t={}){const r=this.getAll();return Object.keys(t).length>0?r.filter(n=>a1(t,n)):r}notify(t){_r.batch(()=>{this.listeners.forEach(r=>{r(t)})})}onFocus(){_r.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){_r.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ds=new WeakMap,G2),Jt,Yi,Xi,ll,cl,Ji,ul,dl,Y2,K$=(Y2=class{constructor(e={}){Ye(this,Jt);Ye(this,Yi);Ye(this,Xi);Ye(this,ll);Ye(this,cl);Ye(this,Ji);Ye(this,ul);Ye(this,dl);Ae(this,Jt,e.queryCache||new c3),Ae(this,Yi,e.mutationCache||new l3),Ae(this,Xi,e.defaultOptions||{}),Ae(this,ll,new Map),Ae(this,cl,new Map),Ae(this,Ji,0)}mount(){od(this,Ji)._++,Q(this,Ji)===1&&(Ae(this,ul,$f.subscribe(async e=>{e&&(await this.resumePausedMutations(),Q(this,Jt).onFocus())})),Ae(this,dl,sa.subscribe(async e=>{e&&(await this.resumePausedMutations(),Q(this,Jt).onOnline())})))}unmount(){var e,t;od(this,Ji)._--,Q(this,Ji)===0&&((e=Q(this,ul))==null||e.call(this),Ae(this,ul,void 0),(t=Q(this,dl))==null||t.call(this),Ae(this,dl,void 0))}isFetching(e){return Q(this,Jt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return Q(this,Yi).findAll({...e,status:"pending"}).length}getQueryData(e){var r;const t=this.defaultQueryOptions({queryKey:e});return(r=Q(this,Jt).get(t.queryHash))==null?void 0:r.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),r=Q(this,Jt).build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(no(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return Q(this,Jt).findAll(e).map(({queryKey:t,state:r})=>{const n=r.data;return[t,n]})}setQueryData(e,t,r){const n=this.defaultQueryOptions({queryKey:e}),s=Q(this,Jt).get(n.queryHash),i=s==null?void 0:s.state.data,a=I$(t,i);if(a!==void 0)return Q(this,Jt).build(this,n).setData(a,{...r,manual:!0})}setQueriesData(e,t,r){return _r.batch(()=>Q(this,Jt).findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(e){var r;const t=this.defaultQueryOptions({queryKey:e});return(r=Q(this,Jt).get(t.queryHash))==null?void 0:r.state}removeQueries(e){const t=Q(this,Jt);_r.batch(()=>{t.findAll(e).forEach(r=>{t.remove(r)})})}resetQueries(e,t){const r=Q(this,Jt);return _r.batch(()=>(r.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const r={revert:!0,...t},n=_r.batch(()=>Q(this,Jt).findAll(e).map(s=>s.cancel(r)));return Promise.all(n).then(ln).catch(ln)}invalidateQueries(e,t={}){return _r.batch(()=>(Q(this,Jt).findAll(e).forEach(r=>{r.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const r={...t,cancelRefetch:t.cancelRefetch??!0},n=_r.batch(()=>Q(this,Jt).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,r);return r.throwOnError||(i=i.catch(ln)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(ln)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const r=Q(this,Jt).build(this,t);return r.isStaleByTime(no(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ln).catch(ln)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ln).catch(ln)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return sa.isOnline()?Q(this,Yi).resumePausedMutations():Promise.resolve()}getQueryCache(){return Q(this,Jt)}getMutationCache(){return Q(this,Yi)}getDefaultOptions(){return Q(this,Xi)}setDefaultOptions(e){Ae(this,Xi,e)}setQueryDefaults(e,t){Q(this,ll).set(na(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...Q(this,ll).values()],r={};return t.forEach(n=>{zc(e,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(e,t){Q(this,cl).set(na(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...Q(this,cl).values()],r={};return t.forEach(n=>{zc(e,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(e){if(e._defaulted)return e;const t={...Q(this,Xi).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Dx(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Px&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...Q(this,Xi).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){Q(this,Jt).clear(),Q(this,Yi).clear()}},Jt=new WeakMap,Yi=new WeakMap,Xi=new WeakMap,ll=new WeakMap,cl=new WeakMap,Ji=new WeakMap,ul=new WeakMap,dl=new WeakMap,Y2),u3=p.createContext(void 0),xs=e=>{const t=p.useContext(u3);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},V$=({client:e,children:t})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(u3.Provider,{value:e,children:t})),d3=p.createContext(!1),G$=()=>p.useContext(d3);d3.Provider;function Y$(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var X$=p.createContext(Y$()),J$=()=>p.useContext(X$),Q$=(e,t,r)=>{const n=r!=null&&r.state.error&&typeof e.throwOnError=="function"?Lx(e.throwOnError,[r.state.error,r]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||n)&&(t.isReset()||(e.retryOnMount=!1))},Z$=e=>{p.useEffect(()=>{e.clearReset()},[e])},ez=({result:e,errorResetBoundary:t,throwOnError:r,query:n,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(s&&e.data===void 0||Lx(r,[e.error,n])),tz=e=>{if(e.suspense){const r=s=>s==="static"?s:Math.max(s??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...s)=>r(n(...s)):r(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},rz=(e,t)=>e.isLoading&&e.isFetching&&!t,nz=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,m1=(e,t,r)=>t.fetchOptimistic(e).catch(()=>{r.clearReset()});function h3(e,t,r){var m,g,v,x;const n=G$(),s=J$(),i=xs(),a=i.defaultQueryOptions(e);(g=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||g.call(m,a);const l=i.getQueryCache().get(a.queryHash),c=e.subscribed!==!1;a._optimisticResults=n?"isRestoring":c?"optimistic":void 0,tz(a),Q$(a,s,l),Z$(s);const u=!i.getQueryCache().get(a.queryHash),[d]=p.useState(()=>new t(i,a)),h=d.getOptimisticResult(a),f=!n&&c;if(p.useSyncExternalStore(p.useCallback(b=>{const _=f?d.subscribe(_r.batchCalls(b)):ln;return d.updateResult(),_},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),p.useEffect(()=>{d.setOptions(a)},[a,d]),nz(a,h))throw m1(a,d,s);if(ez({result:h,errorResetBoundary:s,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw h.error;if((x=(v=i.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||x.call(v,a,h),a.experimental_prefetchInRender&&!Uc.isServer()&&rz(h,n)){const b=u?m1(a,d,s):l==null?void 0:l.promise;b==null||b.catch(ln).finally(()=>{d.updateResult()})}return a.notifyOnChangeProps?h:d.trackResult(h)}function Ct(e,t){return h3(e,i3)}function nr(e,t){const r=xs(),[n]=p.useState(()=>new q$(r,e));p.useEffect(()=>{n.setOptions(e)},[n,e]);const s=p.useSyncExternalStore(p.useCallback(a=>n.subscribe(_r.batchCalls(a)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=p.useCallback((a,l)=>{n.mutate(a,l).catch(ln)},[n]);if(s.error&&Lx(n.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function ia(e,t){return h3(e,H$)}const sz=15e3,iz=30*6e4;function ml(e){const t=e.apiBase.trim().replace(/\/+$/,"")||"same-origin";return`${e.connectionId??"web"}::${t}${e.generation===void 0?"":`::${e.generation}`}`}function f3({children:e,onUnauthorized:t,scope:r}){const n=p.useRef(new Map),s=p.useRef(t);s.current=t;let i=n.current.get(r);if(!i){const a=l=>{var c;l&&typeof l=="object"&&"status"in l&&l.status===401&&((c=s.current)==null||c.call(s))};i=new K$({mutationCache:new l3({onError:a}),queryCache:new c3({onError:a}),defaultOptions:{queries:{gcTime:iz,retry:!1,staleTime:sz},mutations:{retry:!1}}}),n.current.set(r,i)}return p.useEffect(()=>{const a=n.current;return()=>{for(const l of a.values())l.clear();a.clear()}},[]),o.jsx(V$,{client:i,children:e})}const p3={appearance:p.lazy(()=>Vr(()=>import("./appearance-BHYR2QUj.js"),__vite__mapDeps([0,1]))),notifications:p.lazy(()=>Vr(()=>import("./notifications-CTv1WVBh.js"),__vite__mapDeps([2,1]))),shortcuts:p.lazy(()=>Vr(()=>import("./shortcuts-BNrV46nh.js"),__vite__mapDeps([3,1]))),suiji:p.lazy(()=>Vr(()=>import("./suiji-DPDKlWVi.js"),__vite__mapDeps([4,1,5,6]))),access:p.lazy(()=>Vr(()=>import("./access-Bw9yaM2u.js"),__vite__mapDeps([7,1,8]))),monitoring:p.lazy(()=>Vr(()=>import("./monitoring-BaUd-PhH.js"),__vite__mapDeps([9,1]))),advanced:p.lazy(()=>Vr(()=>import("./advanced-BspSUvyf.js"),__vite__mapDeps([10,1]))),status:p.lazy(()=>Vr(()=>import("./status-BOcUUbE9.js"),__vite__mapDeps([11,1,8]))),desktop:p.lazy(()=>Vr(()=>import("./desktop-1jdcRQ7b.js"),__vite__mapDeps([12,1])))},oz=p.lazy(()=>Vr(()=>import("./connections-DsHGQRR2.js"),__vite__mapDeps([13,1,8])));function az({pageId:e,connections:t}){var i;const r=Fk(),n=p3[e],s=ml({apiBase:r.apiBase,connectionId:r.connectionId,generation:r.generation});return o.jsx(fB,{children:o.jsx(K5,{apiBase:r.apiBase,token:r.auth.token,connections:t,isElectron:((i=window.electronAPI)==null?void 0:i.isElectron)===!0,children:o.jsx(f3,{scope:s,onUnauthorized:r.auth.clearToken,children:o.jsx(Y5,{apiBase:r.apiBase,token:r.auth.token,connectionId:r.connectionId??s,notifications:!1,children:o.jsx(n,{})},`${s}:${r.auth.sessionId}`)})})})}function lz(e){var C,S,w;const t=sB(),r=ju(),n=Gt(),s=Cr(),i=rx(),a=oB(n.pathname.split("/")[2]??"appearance"),l=a.id==="connections"?null:p3[a.id],c=e.pageContent!==void 0,u=L0.find(y=>n.pathname===y.path||n.pathname.startsWith(y.path+"/")),d=c?(u==null?void 0:u.title)??(n.pathname.startsWith("/background-runs")?"后台运行":n.pathname==="/login"?"登录":"连接管理"):a.title,h=p.useRef((C=e.activeConnection)==null?void 0:C.id),f=new URLSearchParams(n.search),m=f.get("target")??h.current,g=e.connections.find(y=>y.id===m),v=hr(void 0,"window"),x=p.useRef(null),b=p.useRef(null);p.useEffect(()=>{var y,N;(y=x.current)==null||y.focus({preventScroll:!0}),(N=b.current)==null||N.scrollTo(0,0)},[d,n.search]),p.useEffect(()=>{!c&&n.pathname!==`/settings/${a.id}`&&s(`/settings/${a.id}${n.search}`,{replace:!0,state:n.state})},[c,n.pathname,n.search,n.state,s,a.id]);const _=()=>{const y=e.background??Ih(n);s(y?y.pathname+y.search+y.hash:"/terminal",{state:y==null?void 0:y.state})};return o.jsx(hB,{connection:g,activeConnection:e.activeConnection,workspaceAuth:e.workspaceAuth,webApiBase:e.webApiBase,children:o.jsx(Qr,{open:!0,children:o.jsxs(dx,{"aria-describedby":void 0,ref:v,className:"settings-screen",role:"dialog","aria-modal":"true",onEscapeKeyDown:y=>y.preventDefault(),onInteractOutside:y=>y.preventDefault(),children:[o.jsxs("aside",{className:"settings-sidebar",children:[o.jsxs("button",{className:"settings-back",title:(r==null?void 0:r.preparedLabel)??"返回当前终端",onClick:()=>r==null?void 0:r.exit(_),children:[o.jsx(xi,{className:"size-4"}),"返回终端"]}),(r==null?void 0:r.preparedLabel)&&o.jsx("p",{role:"status",className:"px-2 text-xs text-primary",children:"已准备会话,从上方返回终端"}),o.jsxs("nav",{"aria-label":"应用导航",className:"mt-2 shrink-0 border-b pb-2",children:[o.jsx("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:"应用导航"}),L0.map(y=>o.jsxs("button",{"aria-current":(u==null?void 0:u.path)===y.path?"page":void 0,className:`settings-nav ${(u==null?void 0:u.path)===y.path?"active":""}`,onClick:()=>s(y.path,{state:{settingsBackground:e.background}}),children:[o.jsx(y.icon,{className:"size-4"}),y.title]},y.path))]}),o.jsx("h2",{className:"px-2 pb-1 pt-2 text-sm font-semibold",children:"全局设置"}),o.jsx("nav",{"aria-label":"设置分类",className:"shrink-0",children:["本台应用","连接与服务","所选电脑","状态与诊断"].map(y=>{var N;return o.jsxs("div",{className:"mb-1",children:[o.jsx("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:y}),y==="所选电脑"&&((N=window.electronAPI)==null?void 0:N.isElectron)&&o.jsxs("select",{"aria-label":"所选电脑",className:"mb-1 h-7 w-full rounded-md border bg-background px-2 text-xs",value:(g==null?void 0:g.id)??"",onChange:E=>{const k=new URLSearchParams(n.search);k.set("target",E.target.value),s(`${n.pathname}?${k}`,{state:n.state})},children:[!g&&o.jsx("option",{value:"",children:"请选择电脑"}),e.connections.map(E=>o.jsx("option",{value:E.id,children:E.name},E.id))]}),M0.filter(E=>E.group===y).map(E=>o.jsxs("button",{"aria-current":!c&&E.id===a.id?"page":void 0,className:`settings-nav ${!c&&E.id===a.id?"active":""}`,onClick:()=>i(E.id),children:[o.jsx(E.icon,{className:"size-4"}),E.title]},E.id))]},y)})}),o.jsxs("div",{className:"mt-auto shrink-0 border-t pt-2",children:[o.jsxs("button",{className:"settings-nav text-rose-600 dark:text-rose-400 disabled:cursor-not-allowed disabled:opacity-50",disabled:!t,title:t?"退出工作区当前连接的登录":"请先保存修改或返回工作区放弃修改,并等待当前操作完成",onClick:()=>{t&&(e.workspaceAuth.clearToken(),s("/login"))},children:[o.jsx(bE,{className:"size-4"}),"退出登录"]}),o.jsxs("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:["工作区 · ",((S=e.activeConnection)==null?void 0:S.name)??"当前电脑"]})]})]}),o.jsx("main",{ref:b,className:"settings-content",children:o.jsxs("div",{className:`settings-wrap ${c?"management-wrap":""}`,children:[o.jsxs("header",{className:"mb-4 flex flex-wrap items-center justify-between gap-2",children:[o.jsx(Ur,{asChild:!0,children:o.jsx("h1",{ref:x,tabIndex:-1,className:"text-xl font-semibold outline-none",children:d})}),o.jsx("span",{className:"rounded border px-2 py-1 text-xs text-muted-foreground",children:c?`当前连接 · ${((w=e.activeConnection)==null?void 0:w.name)??"当前电脑"}`:a.scope==="computer"?`所选电脑 · ${(g==null?void 0:g.name)??"当前电脑"}`:a.scope==="account"?"随记账户":"本台应用"})]}),o.jsx(p.Suspense,{fallback:o.jsx("p",{role:"status",children:"正在加载…"}),children:c?o.jsx("div",{className:"management-content",children:e.pageContent}):a.scope==="computer"?o.jsx(az,{pageId:a.id,connections:e.connections},`${g==null?void 0:g.id}:${g==null?void 0:g.url}:${g==null?void 0:g.generation}:${e.workspaceAuth.sessionId}`):a.id==="connections"?o.jsx(oz,{...e}):l?o.jsx(l,{}):null})]})})]})})})}const m3=p.createContext(null);function zf({activeConnectionId:e,connectionName:t="当前电脑",apiBase:r,children:n,onAuthExpired:s,token:i,remote:a=null,connectionGeneration:l}){const c=ml({apiBase:r,connectionId:e??null,generation:(a==null?void 0:a.generation)??l}),u=p.useMemo(()=>({activeConnectionId:e??null,connectionName:t,apiBase:r,onAuthExpired:s,scope:c,token:i,remote:a}),[e,t,r,s,a,c,i]);return o.jsx(m3.Provider,{value:u,children:n})}function vt(){const e=p.useContext(m3);if(!e)throw new Error("TerminalRuntimeProvider is missing");return e}const g1=e=>Symbol.iterator in e,v1=e=>"entries"in e,x1=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[s,i]of r)if(!n.has(s)||!Object.is(i,n.get(s)))return!1;return!0},cz=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let s=r.next(),i=n.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=r.next(),i=n.next()}return!!s.done&&!!i.done};function uz(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:g1(e)&&g1(t)?v1(e)&&v1(t)?x1(e,t):cz(e,t):x1({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function An(e){const t=_t.useRef(void 0);return r=>{const n=e(r);return uz(t.current,n)?t.current:t.current=n}}function Ox(e){return`viewer.terminal.recent.${e}`}function oa(e){const t=ht.getItem(Ox(e));if(!t)return null;try{const r=JSON.parse(t);if(typeof r.projectId!="string")return null;const n=r.projectSessionIds&&typeof r.projectSessionIds=="object"&&!Array.isArray(r.projectSessionIds)?Object.fromEntries(Object.entries(r.projectSessionIds).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string")):{},s=r.contextProjectIdByParentProjectId&&typeof r.contextProjectIdByParentProjectId=="object"&&!Array.isArray(r.contextProjectIdByParentProjectId)?Object.fromEntries(Object.entries(r.contextProjectIdByParentProjectId).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string")):{[r.projectId]:r.projectId};if(typeof r.terminalSessionId=="string"){const i=s[r.projectId]??r.projectId;return{projectId:r.projectId,terminalSessionId:r.terminalSessionId,projectSessionIds:{[i]:r.terminalSessionId,...n},contextProjectIdByParentProjectId:s}}return r.terminalSessionId!==null?null:{projectId:r.projectId,terminalSessionId:null,projectSessionIds:n,contextProjectIdByParentProjectId:s}}catch{return null}}function dz(e,t){const r=oa(e),n={...(r==null?void 0:r.projectSessionIds)??{}};t.terminalSessionId&&(n[t.projectId]=t.terminalSessionId);const s={...(r==null?void 0:r.contextProjectIdByParentProjectId)??{},[t.parentProjectId]:t.projectId};ht.setItem(Ox(e),JSON.stringify({projectId:t.parentProjectId,terminalSessionId:t.terminalSessionId,projectSessionIds:n,contextProjectIdByParentProjectId:s}))}function hz(e,t,r){const n=oa(e);if(!n)return;const s={...n.projectSessionIds},i=s[r];delete s[r];const a={...n.contextProjectIdByParentProjectId};a[t]===r&&(a[t]=t),ht.setItem(Ox(e),JSON.stringify({projectId:n.projectId,terminalSessionId:n.terminalSessionId===i?null:n.terminalSessionId,projectSessionIds:s,contextProjectIdByParentProjectId:a}))}const jt={all:e=>["connection",e,"terminal"],projects:e=>[...jt.all(e),"projects"],projectContexts:(e,t)=>[...jt.all(e),"project-contexts",t],projectContextBranchStatuses:(e,t)=>[...jt.all(e),"project-context-branch-statuses",t],workspaceServices:(e,t,r)=>[...jt.all(e),"workspace-services",t,r],sessions:e=>[...jt.all(e),"sessions"],preview:(e,t)=>[...jt.all(e),"preview",t],previewFileSearch:e=>[...jt.preview(e.scope,e.projectId),"file-search",e.query],previewFile:e=>[...jt.preview(e.scope,e.projectId),"file",e.path],previewChanges:(e,t)=>[...jt.preview(e,t),"changes"],previewDiff:e=>[...jt.preview(e.scope,e.projectId),"diff",e.kind,e.path]},_o=[],bs=[],Uf=[];function fz(e){var r;return((r=e.state.data)==null?void 0:r.services.some(n=>n.status==="starting"||n.status==="stopping"))?1e3:3e3}function _s(){const{apiBase:e,scope:t,token:r}=vt();return Ct({queryKey:jt.projects(t),queryFn:()=>Hv(e,r)})}function Zn(){const{apiBase:e,scope:t,token:r}=vt();return Ct({queryKey:jt.sessions(t),queryFn:()=>_u(e,r)})}function Hf(e){var a;const{apiBase:t,scope:r,token:n}=vt(),i=((a=_s().data)==null?void 0:a.some(l=>l.projectId===e))??!1;return Ct({queryKey:jt.projectContexts(r,e??""),queryFn:()=>eE(t,n,e??""),enabled:!!(e&&i),refetchInterval:3e3,refetchOnWindowFocus:!0})}function pz(e,t,r=!0){var c;const{apiBase:n,scope:s,token:i}=vt(),l=((c=_s().data)==null?void 0:c.some(u=>u.projectId===e))??!1;return Ct({queryKey:jt.workspaceServices(s,e??"",t??""),queryFn:()=>rL(n,i,e??"",t??""),enabled:u=>r&&!!(e&&t&&l)&&!oE(u.state.error),refetchInterval:fz,refetchOnWindowFocus:!0,retry:!1})}function Al(){const e=xs(),{scope:t}=vt();return{queryClient:e,scope:t}}function om(e,t,r){e.setQueryData(jt.projects(t),n=>r(n??_o))}function Ga(e,t,r){e.setQueryData(jt.sessions(t),n=>r(n??bs))}const g3=6e5;function v3(e){return e.state!=="ready"||!e.checkedAt||Date.now()-Date.parse(e.checkedAt)>=g3}function mz(e,t,r){var u,d;const{apiBase:n,scope:s,token:i}=vt(),l=((d=(u=_s().data)==null?void 0:u.find(h=>h.projectId===e))==null?void 0:d.mainBranch)??null,c=t.filter(h=>h.availability==="available"&&h.path);return Ct({queryKey:[...jt.projectContextBranchStatuses(s,e??""),l,c.map(({projectId:h,path:f,head:m})=>[h,f,m])],queryFn:async()=>{const h=[];for(let f=0;f<c.length;f+=4){const m=await B6(n,i,e??"",{projectIds:c.slice(f,f+4).map(g=>g.projectId)});h.push(...m.statuses)}return h},enabled:r&&!!e&&c.length>0,staleTime:3e4,refetchInterval:h=>h.state.error||!h.state.data||h.state.data.some(f=>f.state!=="not-repository"&&v3(f))?3e4:g3,refetchOnWindowFocus:!0,retry:!1})}function x3(){const e=Zn().data??bs,t=tt(An(r=>({bellMarkers:r.bellMarkers,completionMarkers:r.completionMarkers,terminalStateBySessionId:r.terminalStateBySessionId})));return p.useMemo(()=>FO(t,e),[t,e])}var b3="AlertDialog",[gz]=bi(b3,[vk]),yi=vk(),_3=e=>{const{__scopeAlertDialog:t,...r}=e,n=yi(t);return o.jsx(lx,{...n,...r,modal:!0})};_3.displayName=b3;var vz="AlertDialogTrigger",y3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Dk,{...s,...n,ref:t})});y3.displayName=vz;var xz="AlertDialogPortal",w3=e=>{const{__scopeAlertDialog:t,...r}=e,n=yi(t);return o.jsx(cx,{...n,...r})};w3.displayName=xz;var bz="AlertDialogOverlay",S3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(ku,{...s,...n,ref:t})});S3.displayName=bz;var Ya="AlertDialogContent",[_z,yz]=gz(Ya),wz=K7("AlertDialogContent"),C3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,children:n,...s}=e,i=yi(r),a=p.useRef(null),l=wr(t,a),c=p.useRef(null);return o.jsx(Z9,{contentName:Ya,titleName:E3,docsSlug:"alert-dialog",children:o.jsx(_z,{scope:r,cancelRef:c,children:o.jsxs(Cl,{role:"alertdialog",...i,...s,ref:l,onOpenAutoFocus:st(s.onOpenAutoFocus,u=>{var d;u.preventDefault(),(d=c.current)==null||d.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[o.jsx(wz,{children:n}),o.jsx(Cz,{contentRef:a})]})})})});C3.displayName=Ya;var E3="AlertDialogTitle",k3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Iu,{...s,...n,ref:t})});k3.displayName=E3;var I3="AlertDialogDescription",N3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Nu,{...s,...n,ref:t})});N3.displayName=I3;var Sz="AlertDialogAction",R3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=yi(r);return o.jsx(Ru,{...s,...n,ref:t})});R3.displayName=Sz;var j3="AlertDialogCancel",A3=p.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,{cancelRef:s}=yz(j3,r),i=yi(r),a=wr(t,s);return o.jsx(Ru,{...i,...n,ref:a})});A3.displayName=j3;var Cz=({contentRef:e})=>{const t=`\`${Ya}\` requires a description for the component to be accessible for screen reader users.
|
|
491
491
|
|
|
492
492
|
You can add a description to the \`${Ya}\` by passing a \`${I3}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
|
|
493
493
|
|
|
494
494
|
Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${Ya}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
|
|
495
495
|
|
|
496
496
|
For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return p.useEffect(()=>{var n;document.getElementById((n=e.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},Ez=_3,kz=y3,Iz=w3,T3=S3,D3=C3,P3=R3,L3=A3,M3=k3,O3=N3;const B3=Zv("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-semibold tracking-[-0.01em] transition-all duration-300 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 active:scale-[0.985]",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-[0_16px_40px_-22px_hsl(var(--primary)/0.8)] hover:-translate-y-0.5 hover:shadow-[0_22px_50px_-24px_hsl(var(--primary)/0.82)]",secondary:"border border-border/60 bg-muted/78 text-foreground hover:bg-muted",ghost:"hover:bg-muted/72"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3"}},defaultVariants:{variant:"default",size:"default"}}),Tl=Ez,Nz=kz,Rz=Iz,F3=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"window");return o.jsx(T3,{ref:n,className:Xe("fixed inset-0 z-50 bg-black/45 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t})});F3.displayName=T3.displayName;const xa=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"intersection");return o.jsxs(Rz,{children:[o.jsx(F3,{}),o.jsx(D3,{ref:n,className:Xe("fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-[1.75rem] border border-slate-800/80 bg-slate-950 p-6 shadow-[0_34px_120px_-72px_rgba(15,23,42,0.92)] duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 sm:p-7",e),...t})]})});xa.displayName=D3.displayName;const Dl=({className:e,...t})=>o.jsx("div",{className:Xe("flex flex-col space-y-2 text-left",e),...t}),Pl=({className:e,...t})=>o.jsx("div",{className:Xe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t}),ba=p.forwardRef(({className:e,...t},r)=>o.jsx(M3,{ref:r,className:Xe("text-lg font-semibold text-slate-100",e),...t}));ba.displayName=M3.displayName;const _a=p.forwardRef(({className:e,...t},r)=>o.jsx(O3,{ref:r,className:Xe("text-sm text-slate-400",e),...t}));_a.displayName=O3.displayName;const Lu=p.forwardRef(({className:e,...t},r)=>o.jsx(P3,{ref:r,className:Xe(B3({size:"sm"}),"h-10 rounded-full px-4",e),...t}));Lu.displayName=P3.displayName;const ya=p.forwardRef(({className:e,...t},r)=>o.jsx(L3,{ref:r,className:Xe(B3({variant:"ghost",size:"sm"}),"h-10 rounded-full px-4 text-slate-300",e),...t}));ya.displayName=L3.displayName;function jz({pendingDeletion:e,sessionCount:t,deleting:r,deleteError:n,onDismiss:s,onConfirm:i}){return o.jsx(Tl,{open:e!==null,onOpenChange:a=>{!a&&!r&&s()},children:o.jsxs(xa,{"data-testid":"terminal-worktree-delete-dialog",children:[o.jsxs(Dl,{children:[o.jsx(ba,{children:"删除 Worktree"}),o.jsxs(_a,{children:[o.jsxs("span",{className:"block",children:["将删除“",e==null?void 0:e.name,"”的工作目录,并关闭其中的",t,"个 Terminal。"]}),o.jsxs("span",{className:"mt-2 block",children:["分支 ",(e==null?void 0:e.branch)??"detached HEAD"," 会被保留。"]}),o.jsx("span",{className:"mt-2 block",children:"会尝试停止关联的 Dev Session;清理失败仍会继续删除。"})]})]}),n?o.jsx("p",{role:"alert","data-testid":"terminal-worktree-delete-error",className:"rounded-lg border border-rose-900/70 bg-rose-950/40 px-3 py-2 text-sm text-rose-300",children:n}):null,o.jsxs(Pl,{children:[o.jsx(ya,{disabled:r,children:"取消"}),o.jsx(Lu,{disabled:r,"data-testid":"terminal-worktree-delete-confirm",className:"bg-rose-500 text-white hover:bg-rose-500/90 hover:shadow-[0_22px_50px_-24px_rgba(244,63,94,0.82)]",onClick:a=>{a.preventDefault(),i()},children:r?"删除中…":"删除"})]})]})})}function $3(e){const t=e+"CollectionProvider",[r,n]=bi(t),[s,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),a=v=>{const{scope:x,children:b}=v,_=_t.useRef(null),C=_t.useRef(new Map).current;return o.jsx(s,{scope:x,itemMap:C,collectionRef:_,children:b})};a.displayName=t;const l=e+"CollectionSlot",c=hl(l),u=_t.forwardRef((v,x)=>{const{scope:b,children:_}=v,C=i(l,b),S=wr(x,C.collectionRef);return o.jsx(c,{ref:S,children:_})});u.displayName=l;const d=e+"CollectionItemSlot",h="data-radix-collection-item",f=hl(d),m=_t.forwardRef((v,x)=>{const{scope:b,children:_,...C}=v,S=_t.useRef(null),w=wr(x,S),y=i(d,b);return _t.useEffect(()=>(y.itemMap.set(S,{ref:S,...C}),()=>void y.itemMap.delete(S))),o.jsx(f,{[h]:"",ref:w,children:_})});m.displayName=d;function g(v){const x=i(e+"CollectionConsumer",v);return _t.useCallback(()=>{const _=x.collectionRef.current;if(!_)return[];const C=Array.from(_.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((y,N)=>C.indexOf(y.ref.current)-C.indexOf(N.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:a,Slot:u,ItemSlot:m},g,n]}var Az=p.createContext(void 0);function z3(e){const t=p.useContext(Az);return e||t||"ltr"}var am="rovingFocusGroup.onEntryFocus",Tz={bubbles:!1,cancelable:!0},Mu="RovingFocusGroup",[ng,U3,Dz]=$3(Mu),[Pz,H3]=bi(Mu,[Dz]),[Lz,Mz]=Pz(Mu),W3=p.forwardRef((e,t)=>o.jsx(ng.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(ng.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Oz,{...e,ref:t})})}));W3.displayName=Mu;var Oz=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:s=!1,dir:i,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:u,preventScrollOnEntryFocus:d=!1,...h}=e,f=p.useRef(null),m=wr(t,f),g=z3(i),[v,x]=Su({prop:a,defaultProp:l??null,onChange:c,caller:Mu}),[b,_]=p.useState(!1),C=oo(u),S=U3(r),w=p.useRef(!1),[y,N]=p.useState(0);return p.useEffect(()=>{const E=f.current;if(E)return E.addEventListener(am,C),()=>E.removeEventListener(am,C)},[C]),o.jsx(Lz,{scope:r,orientation:n,dir:g,loop:s,currentTabStopId:v,onItemFocus:p.useCallback(E=>x(E),[x]),onItemShiftTab:p.useCallback(()=>_(!0),[]),onFocusableItemAdd:p.useCallback(()=>N(E=>E+1),[]),onFocusableItemRemove:p.useCallback(()=>N(E=>E-1),[]),children:o.jsx(or.div,{tabIndex:b||y===0?-1:0,"data-orientation":n,...h,ref:m,style:{outline:"none",...e.style},onMouseDown:st(e.onMouseDown,()=>{w.current=!0}),onFocus:st(e.onFocus,E=>{const k=!w.current;if(E.target===E.currentTarget&&k&&!b){const D=new CustomEvent(am,Tz);if(E.currentTarget.dispatchEvent(D),!D.defaultPrevented){const j=S().filter(P=>P.focusable),R=j.find(P=>P.active),I=j.find(P=>P.id===v),A=[R,I,...j].filter(Boolean).map(P=>P.ref.current);V3(A,d)}}w.current=!1}),onBlur:st(e.onBlur,()=>_(!1))})})}),q3="RovingFocusGroupItem",K3=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:s=!1,tabStopId:i,children:a,...l}=e,c=hi(),u=i||c,d=Mz(q3,r),h=d.currentTabStopId===u,f=U3(r),{onFocusableItemAdd:m,onFocusableItemRemove:g,currentTabStopId:v}=d;return p.useEffect(()=>{if(n)return m(),()=>g()},[n,m,g]),o.jsx(ng.ItemSlot,{scope:r,id:u,focusable:n,active:s,children:o.jsx(or.span,{tabIndex:h?0:-1,"data-orientation":d.orientation,...l,ref:t,onMouseDown:st(e.onMouseDown,x=>{n?d.onItemFocus(u):x.preventDefault()}),onFocus:st(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:st(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const b=$z(x,d.orientation,d.dir);if(b!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let C=f().filter(S=>S.focusable).map(S=>S.ref.current);if(b==="last")C.reverse();else if(b==="prev"||b==="next"){b==="prev"&&C.reverse();const S=C.indexOf(x.currentTarget);C=d.loop?zz(C,S+1):C.slice(S+1)}setTimeout(()=>V3(C))}}),children:typeof a=="function"?a({isCurrentTabStop:h,hasTabStop:v!=null}):a})})});K3.displayName=q3;var Bz={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Fz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function $z(e,t,r){const n=Fz(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return Bz[n]}function V3(e,t=!1){const r=document.activeElement;for(const n of e)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function zz(e,t){return e.map((r,n)=>e[(t+n)%e.length])}var Uz=W3,Hz=K3,sg=["Enter"," "],Wz=["ArrowDown","PageUp","Home"],G3=["ArrowUp","PageDown","End"],qz=[...Wz,...G3],Kz={ltr:[...sg,"ArrowRight"],rtl:[...sg,"ArrowLeft"]},Vz={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Ou="Menu",[Hc,Gz,Yz]=$3(Ou),[wa,Wf]=bi(Ou,[Yz,Mf,H3]),Bu=Mf(),Y3=H3(),[X3,yo]=wa(Ou),[Xz,Fu]=wa(Ou),J3=e=>{const{__scopeMenu:t,open:r=!1,children:n,dir:s,onOpenChange:i,modal:a=!0}=e,l=Bu(t),[c,u]=p.useState(null),d=p.useRef(!1),h=oo(i),f=z3(s);return p.useEffect(()=>{const m=()=>{d.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>d.current=!1;return document.addEventListener("keydown",m,{capture:!0}),()=>{document.removeEventListener("keydown",m,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),o.jsx(Cx,{...l,children:o.jsx(X3,{scope:t,open:r,onOpenChange:h,content:c,onContentChange:u,children:o.jsx(Xz,{scope:t,onClose:p.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:d,dir:f,modal:a,children:n})})})};J3.displayName=Ou;var Jz="MenuAnchor",Bx=p.forwardRef((e,t)=>{const{__scopeMenu:r,...n}=e,s=Bu(r);return o.jsx(Ex,{...s,...n,ref:t})});Bx.displayName=Jz;var Fx="MenuPortal",[Qz,Q3]=wa(Fx,{forceMount:void 0}),Z3=e=>{const{__scopeMenu:t,forceMount:r,children:n,container:s}=e,i=yo(Fx,t);return o.jsx(Qz,{scope:t,forceMount:r,children:o.jsx(Gs,{present:r||i.open,children:o.jsx(Nf,{asChild:!0,container:s,children:n})})})};Z3.displayName=Fx;var Yn="MenuContent",[Zz,$x]=wa(Yn),eI=p.forwardRef((e,t)=>{const r=Q3(Yn,e.__scopeMenu),{forceMount:n=r.forceMount,...s}=e,i=yo(Yn,e.__scopeMenu),a=Fu(Yn,e.__scopeMenu);return o.jsx(Hc.Provider,{scope:e.__scopeMenu,children:o.jsx(Gs,{present:n||i.open,children:o.jsx(Hc.Slot,{scope:e.__scopeMenu,children:a.modal?o.jsx(eU,{...s,ref:t}):o.jsx(tU,{...s,ref:t})})})})}),eU=p.forwardRef((e,t)=>{const r=yo(Yn,e.__scopeMenu),n=p.useRef(null),s=wr(t,n);return p.useEffect(()=>{const i=n.current;if(i)return jf(i)},[]),o.jsx(zx,{...e,ref:s,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:st(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),tU=p.forwardRef((e,t)=>{const r=yo(Yn,e.__scopeMenu);return o.jsx(zx,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),rU=hl("MenuContent.ScrollLock"),zx=p.forwardRef((e,t)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:h,onInteractOutside:f,onDismiss:m,disableOutsideScroll:g,...v}=e,x=yo(Yn,r),b=Fu(Yn,r),_=Bu(r),C=Y3(r),S=Gz(r),[w,y]=p.useState(null),N=p.useRef(null),E=wr(t,N,x.onContentChange),k=p.useRef(0),D=p.useRef(""),j=p.useRef(0),R=p.useRef(null),I=p.useRef("right"),T=p.useRef(0),A=g?Eu:p.Fragment,P=g?{as:rU,allowPinchZoom:!0}:void 0,O=B=>{var H,G;const M=D.current+B,$=S().filter(z=>!z.disabled),U=document.activeElement,F=(H=$.find(z=>z.ref.current===U))==null?void 0:H.textValue,K=$.map(z=>z.textValue),Y=pU(K,M,F),te=(G=$.find(z=>z.textValue===Y))==null?void 0:G.ref.current;(function z(ee){D.current=ee,window.clearTimeout(k.current),ee!==""&&(k.current=window.setTimeout(()=>z(""),1e3))})(M),te&&setTimeout(()=>te.focus())};p.useEffect(()=>()=>window.clearTimeout(k.current),[]),sx();const L=p.useCallback(B=>{var $,U;return I.current===(($=R.current)==null?void 0:$.side)&&gU(B,(U=R.current)==null?void 0:U.area)},[]);return o.jsx(Zz,{scope:r,searchRef:D,onItemEnter:p.useCallback(B=>{L(B)&&B.preventDefault()},[L]),onItemLeave:p.useCallback(B=>{var M;L(B)||((M=N.current)==null||M.focus(),y(null))},[L]),onTriggerLeave:p.useCallback(B=>{L(B)&&B.preventDefault()},[L]),pointerGraceTimerRef:j,onPointerGraceIntentChange:p.useCallback(B=>{R.current=B},[]),children:o.jsx(A,{...P,children:o.jsx(If,{asChild:!0,trapped:s,onMountAutoFocus:st(i,B=>{var M;B.preventDefault(),(M=N.current)==null||M.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:o.jsx(Cu,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:h,onInteractOutside:f,onDismiss:m,children:o.jsx(Uz,{asChild:!0,...C,dir:b.dir,orientation:"vertical",loop:n,currentTabStopId:w,onCurrentTabStopIdChange:y,onEntryFocus:st(c,B=>{b.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(k5,{role:"menu","aria-orientation":"vertical","data-state":vI(x.open),"data-radix-menu-content":"",dir:b.dir,..._,...v,ref:E,style:{outline:"none",...v.style},onKeyDown:st(v.onKeyDown,B=>{const $=B.target.closest("[data-radix-menu-content]")===B.currentTarget,U=B.ctrlKey||B.altKey||B.metaKey,F=B.key.length===1;$&&(B.key==="Tab"&&B.preventDefault(),!U&&F&&O(B.key));const K=N.current;if(B.target!==K||!qz.includes(B.key))return;B.preventDefault();const te=S().filter(H=>!H.disabled).map(H=>H.ref.current);G3.includes(B.key)&&te.reverse(),hU(te)}),onBlur:st(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(k.current),D.current="")}),onPointerMove:st(e.onPointerMove,Wc(B=>{const M=B.target,$=T.current!==B.clientX;if(B.currentTarget.contains(M)&&$){const U=B.clientX>T.current?"right":"left";I.current=U,T.current=B.clientX}}))})})})})})})});eI.displayName=Yn;var nU="MenuGroup",Ux=p.forwardRef((e,t)=>{const{__scopeMenu:r,...n}=e;return o.jsx(or.div,{role:"group",...n,ref:t})});Ux.displayName=nU;var sU="MenuLabel",tI=p.forwardRef((e,t)=>{const{__scopeMenu:r,...n}=e;return o.jsx(or.div,{...n,ref:t})});tI.displayName=sU;var Bh="MenuItem",b1="menu.itemSelect",qf=p.forwardRef((e,t)=>{const{disabled:r=!1,onSelect:n,...s}=e,i=p.useRef(null),a=Fu(Bh,e.__scopeMenu),l=$x(Bh,e.__scopeMenu),c=wr(t,i),u=p.useRef(!1),d=()=>{const h=i.current;if(!r&&h){const f=new CustomEvent(b1,{bubbles:!0,cancelable:!0});h.addEventListener(b1,m=>n==null?void 0:n(m),{once:!0}),J7(h,f),f.defaultPrevented?u.current=!1:a.onClose()}};return o.jsx(rI,{...s,ref:c,disabled:r,onClick:st(e.onClick,d),onPointerDown:h=>{var f;(f=e.onPointerDown)==null||f.call(e,h),u.current=!0},onPointerUp:st(e.onPointerUp,h=>{var f;u.current||(f=h.currentTarget)==null||f.click()}),onKeyDown:st(e.onKeyDown,h=>{const f=l.searchRef.current!=="";r||f&&h.key===" "||sg.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});qf.displayName=Bh;var rI=p.forwardRef((e,t)=>{const{__scopeMenu:r,disabled:n=!1,textValue:s,...i}=e,a=$x(Bh,r),l=Y3(r),c=p.useRef(null),u=wr(t,c),[d,h]=p.useState(!1),[f,m]=p.useState("");return p.useEffect(()=>{const g=c.current;g&&m((g.textContent??"").trim())},[i.children]),o.jsx(Hc.ItemSlot,{scope:r,disabled:n,textValue:s??f,children:o.jsx(Hz,{asChild:!0,...l,focusable:!n,children:o.jsx(or.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...i,ref:u,onPointerMove:st(e.onPointerMove,Wc(g=>{n?a.onItemLeave(g):(a.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:st(e.onPointerLeave,Wc(g=>a.onItemLeave(g))),onFocus:st(e.onFocus,()=>h(!0)),onBlur:st(e.onBlur,()=>h(!1))})})})}),iU="MenuCheckboxItem",nI=p.forwardRef((e,t)=>{const{checked:r=!1,onCheckedChange:n,...s}=e;return o.jsx(lI,{scope:e.__scopeMenu,checked:r,children:o.jsx(qf,{role:"menuitemcheckbox","aria-checked":Fh(r)?"mixed":r,...s,ref:t,"data-state":qx(r),onSelect:st(s.onSelect,()=>n==null?void 0:n(Fh(r)?!0:!r),{checkForDefaultPrevented:!1})})})});nI.displayName=iU;var sI="MenuRadioGroup",[oU,aU]=wa(sI,{value:void 0,onValueChange:()=>{}}),iI=p.forwardRef((e,t)=>{const{value:r,onValueChange:n,...s}=e,i=oo(n);return o.jsx(oU,{scope:e.__scopeMenu,value:r,onValueChange:i,children:o.jsx(Ux,{...s,ref:t})})});iI.displayName=sI;var oI="MenuRadioItem",aI=p.forwardRef((e,t)=>{const{value:r,...n}=e,s=aU(oI,e.__scopeMenu),i=r===s.value;return o.jsx(lI,{scope:e.__scopeMenu,checked:i,children:o.jsx(qf,{role:"menuitemradio","aria-checked":i,...n,ref:t,"data-state":qx(i),onSelect:st(n.onSelect,()=>{var a;return(a=s.onValueChange)==null?void 0:a.call(s,r)},{checkForDefaultPrevented:!1})})})});aI.displayName=oI;var Hx="MenuItemIndicator",[lI,lU]=wa(Hx,{checked:!1}),cI=p.forwardRef((e,t)=>{const{__scopeMenu:r,forceMount:n,...s}=e,i=lU(Hx,r);return o.jsx(Gs,{present:n||Fh(i.checked)||i.checked===!0,children:o.jsx(or.span,{...s,ref:t,"data-state":qx(i.checked)})})});cI.displayName=Hx;var cU="MenuSeparator",uI=p.forwardRef((e,t)=>{const{__scopeMenu:r,...n}=e;return o.jsx(or.div,{role:"separator","aria-orientation":"horizontal",...n,ref:t})});uI.displayName=cU;var uU="MenuArrow",dI=p.forwardRef((e,t)=>{const{__scopeMenu:r,...n}=e,s=Bu(r);return o.jsx(I5,{...s,...n,ref:t})});dI.displayName=uU;var Wx="MenuSub",[dU,hI]=wa(Wx),fI=e=>{const{__scopeMenu:t,children:r,open:n=!1,onOpenChange:s}=e,i=yo(Wx,t),a=Bu(t),[l,c]=p.useState(null),[u,d]=p.useState(null),h=oo(s);return p.useEffect(()=>(i.open===!1&&h(!1),()=>h(!1)),[i.open,h]),o.jsx(Cx,{...a,children:o.jsx(X3,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:d,children:o.jsx(dU,{scope:t,contentId:hi(),triggerId:hi(),trigger:l,onTriggerChange:c,children:r})})})};fI.displayName=Wx;var gc="MenuSubTrigger",pI=p.forwardRef((e,t)=>{const r=yo(gc,e.__scopeMenu),n=Fu(gc,e.__scopeMenu),s=hI(gc,e.__scopeMenu),i=$x(gc,e.__scopeMenu),a=p.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=i,u={__scopeMenu:e.__scopeMenu},d=p.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return p.useEffect(()=>d,[d]),p.useEffect(()=>{const h=l.current;return()=>{window.clearTimeout(h),c(null)}},[l,c]),o.jsx(Bx,{asChild:!0,...u,children:o.jsx(rI,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":s.contentId,"data-state":vI(r.open),...e,ref:kf(t,s.onTriggerChange),onClick:h=>{var f;(f=e.onClick)==null||f.call(e,h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:st(e.onPointerMove,Wc(h=>{i.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!r.open&&!a.current&&(i.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{r.onOpenChange(!0),d()},100))})),onPointerLeave:st(e.onPointerLeave,Wc(h=>{var m,g;d();const f=(m=r.content)==null?void 0:m.getBoundingClientRect();if(f){const v=(g=r.content)==null?void 0:g.dataset.side,x=v==="right",b=x?-5:5,_=f[x?"left":"right"],C=f[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+b,y:h.clientY},{x:_,y:f.top},{x:C,y:f.top},{x:C,y:f.bottom},{x:_,y:f.bottom}],side:v}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:st(e.onKeyDown,h=>{var m;const f=i.searchRef.current!=="";e.disabled||f&&h.key===" "||Kz[n.dir].includes(h.key)&&(r.onOpenChange(!0),(m=r.content)==null||m.focus(),h.preventDefault())})})})});pI.displayName=gc;var mI="MenuSubContent",gI=p.forwardRef((e,t)=>{const r=Q3(Yn,e.__scopeMenu),{forceMount:n=r.forceMount,...s}=e,i=yo(Yn,e.__scopeMenu),a=Fu(Yn,e.__scopeMenu),l=hI(mI,e.__scopeMenu),c=p.useRef(null),u=wr(t,c);return o.jsx(Hc.Provider,{scope:e.__scopeMenu,children:o.jsx(Gs,{present:n||i.open,children:o.jsx(Hc.Slot,{scope:e.__scopeMenu,children:o.jsx(zx,{id:l.contentId,"aria-labelledby":l.triggerId,...s,ref:u,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var h;a.isUsingKeyboardRef.current&&((h=c.current)==null||h.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:st(e.onFocusOutside,d=>{d.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:st(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:st(e.onKeyDown,d=>{var m;const h=d.currentTarget.contains(d.target),f=Vz[a.dir].includes(d.key);h&&f&&(i.onOpenChange(!1),(m=l.trigger)==null||m.focus(),d.preventDefault())})})})})})});gI.displayName=mI;function vI(e){return e?"open":"closed"}function Fh(e){return e==="indeterminate"}function qx(e){return Fh(e)?"indeterminate":e?"checked":"unchecked"}function hU(e){const t=document.activeElement;for(const r of e)if(r===t||(r.focus(),document.activeElement!==t))return}function fU(e,t){return e.map((r,n)=>e[(t+n)%e.length])}function pU(e,t,r){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=r?e.indexOf(r):-1;let a=fU(e,Math.max(i,0));s.length===1&&(a=a.filter(u=>u!==r));const c=a.find(u=>u.toLowerCase().startsWith(s.toLowerCase()));return c!==r?c:void 0}function mU(e,t){const{x:r,y:n}=e;let s=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const l=t[i],c=t[a],u=l.x,d=l.y,h=c.x,f=c.y;d>n!=f>n&&r<(h-u)*(n-d)/(f-d)+u&&(s=!s)}return s}function gU(e,t){if(!t)return!1;const r={x:e.clientX,y:e.clientY};return mU(r,t)}function Wc(e){return t=>t.pointerType==="mouse"?e(t):void 0}var xI=J3,bI=Bx,_I=Z3,yI=eI,wI=Ux,SI=tI,CI=qf,EI=nI,kI=iI,II=aI,NI=cI,RI=uI,jI=dI,vU=fI,AI=pI,TI=gI,Kx="ContextMenu",[xU]=bi(Kx,[Wf]),en=Wf(),[bU,DI]=xU(Kx),PI=e=>{const{__scopeContextMenu:t,children:r,onOpenChange:n,dir:s,modal:i=!0}=e,[a,l]=p.useState(!1),c=en(t),u=oo(n),d=p.useCallback(h=>{l(h),u(h)},[u]);return o.jsx(bU,{scope:t,open:a,onOpenChange:d,modal:i,children:o.jsx(xI,{...c,dir:s,open:a,onOpenChange:d,modal:i,children:r})})};PI.displayName=Kx;var LI="ContextMenuTrigger",MI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,disabled:n=!1,...s}=e,i=DI(LI,r),a=en(r),l=p.useRef({x:0,y:0}),c=p.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...l.current})}),u=p.useRef(0),d=p.useCallback(()=>window.clearTimeout(u.current),[]),h=f=>{l.current={x:f.clientX,y:f.clientY},i.onOpenChange(!0)};return p.useEffect(()=>d,[d]),p.useEffect(()=>void(n&&d()),[n,d]),o.jsxs(o.Fragment,{children:[o.jsx(bI,{...a,virtualRef:c}),o.jsx(or.span,{"data-state":i.open?"open":"closed","data-disabled":n?"":void 0,...s,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:n?e.onContextMenu:st(e.onContextMenu,f=>{d(),h(f),f.preventDefault()}),onPointerDown:n?e.onPointerDown:st(e.onPointerDown,wd(f=>{d(),u.current=window.setTimeout(()=>h(f),700)})),onPointerMove:n?e.onPointerMove:st(e.onPointerMove,wd(d)),onPointerCancel:n?e.onPointerCancel:st(e.onPointerCancel,wd(d)),onPointerUp:n?e.onPointerUp:st(e.onPointerUp,wd(d))})]})});MI.displayName=LI;var _U="ContextMenuPortal",OI=e=>{const{__scopeContextMenu:t,...r}=e,n=en(t);return o.jsx(_I,{...n,...r})};OI.displayName=_U;var BI="ContextMenuContent",FI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=DI(BI,r),i=en(r),a=p.useRef(!1);return o.jsx(yI,{...i,...n,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:l=>{var c;(c=e.onCloseAutoFocus)==null||c.call(e,l),!l.defaultPrevented&&a.current&&l.preventDefault(),a.current=!1},onInteractOutside:l=>{var c;(c=e.onInteractOutside)==null||c.call(e,l),!l.defaultPrevented&&!s.modal&&(a.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});FI.displayName=BI;var yU="ContextMenuGroup",$I=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(wI,{...s,...n,ref:t})});$I.displayName=yU;var wU="ContextMenuLabel",zI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(SI,{...s,...n,ref:t})});zI.displayName=wU;var SU="ContextMenuItem",UI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(CI,{...s,...n,ref:t})});UI.displayName=SU;var CU="ContextMenuCheckboxItem",HI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(EI,{...s,...n,ref:t})});HI.displayName=CU;var EU="ContextMenuRadioGroup",kU=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(kI,{...s,...n,ref:t})});kU.displayName=EU;var IU="ContextMenuRadioItem",WI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(II,{...s,...n,ref:t})});WI.displayName=IU;var NU="ContextMenuItemIndicator",qI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(NI,{...s,...n,ref:t})});qI.displayName=NU;var RU="ContextMenuSeparator",KI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(RI,{...s,...n,ref:t})});KI.displayName=RU;var jU="ContextMenuArrow",AU=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(jI,{...s,...n,ref:t})});AU.displayName=jU;var VI="ContextMenuSub",GI=e=>{const{__scopeContextMenu:t,children:r,onOpenChange:n,open:s,defaultOpen:i}=e,a=en(t),[l,c]=Su({prop:s,defaultProp:i??!1,onChange:n,caller:VI});return o.jsx(vU,{...a,open:l,onOpenChange:c,children:r})};GI.displayName=VI;var TU="ContextMenuSubTrigger",YI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(AI,{...s,...n,ref:t})});YI.displayName=TU;var DU="ContextMenuSubContent",XI=p.forwardRef((e,t)=>{const{__scopeContextMenu:r,...n}=e,s=en(r);return o.jsx(TI,{...s,...n,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XI.displayName=DU;function wd(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var PU=PI,LU=MI,MU=OI,JI=FI,OU=$I,QI=zI,ZI=UI,eN=HI,tN=WI,rN=qI,nN=KI,BU=GI,sN=YI,iN=XI;const Vx=PU,Gx=LU,FU=OU,$U=BU,oN=p.forwardRef(({className:e,inset:t,children:r,...n},s)=>o.jsxs(sN,{ref:s,className:Xe("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",t&&"pl-8",e),...n,children:[r,o.jsx(Jr,{className:"ml-auto h-4 w-4"})]}));oN.displayName=sN.displayName;const aN=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"intersection");return o.jsx(iN,{ref:n,className:Xe("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 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-context-menu-content-transform-origin]",e),...t})});aN.displayName=iN.displayName;const Kf=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"intersection");return o.jsx(MU,{children:o.jsx(JI,{ref:n,className:Xe("z-50 max-h-[--radix-context-menu-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 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-context-menu-content-transform-origin]",e),...t})})});Kf.displayName=JI.displayName;const Ps=p.forwardRef(({className:e,inset:t,...r},n)=>o.jsx(ZI,{ref:n,className:Xe("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));Ps.displayName=ZI.displayName;const zU=p.forwardRef(({className:e,children:t,checked:r,...n},s)=>o.jsxs(eN,{ref:s,className:Xe("relative flex 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",e),checked:r,...n,children:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(rN,{children:o.jsx(di,{className:"h-4 w-4"})})}),t]}));zU.displayName=eN.displayName;const UU=p.forwardRef(({className:e,children:t,...r},n)=>o.jsxs(tN,{ref:n,className:Xe("relative flex 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",e),...r,children:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(rN,{children:o.jsx(hE,{className:"h-2 w-2 fill-current"})})}),t]}));UU.displayName=tN.displayName;const lN=p.forwardRef(({className:e,inset:t,...r},n)=>o.jsx(QI,{ref:n,className:Xe("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",e),...r}));lN.displayName=QI.displayName;const HU=p.forwardRef(({className:e,...t},r)=>o.jsx(nN,{ref:r,className:Xe("-mx-1 my-1 h-px bg-border",e),...t}));HU.displayName=nN.displayName;function cN({className:e,invert:t=!1,...r}){return o.jsx("span",{className:Xe("shimmer",t&&"shimmer-invert",e),...r})}function uN({label:e,status:t,className:r,labelClassName:n}){const s=!!(t&TE),i=t&jE?"bell":t&AE?"completion":"none";return o.jsxs("span",{className:["inline-flex min-w-0 items-center gap-2",r].filter(Boolean).join(" "),children:[s?o.jsx(cN,{className:["shimmer-invert",n].filter(Boolean).join(" "),style:{"--shimmer-duration":"4000","--shimmer-repeat-delay":"300"},children:e}):o.jsx("span",{className:n,children:e}),o.jsx("span",{"aria-hidden":"true","data-terminal-event-status":i,className:["h-1.5 w-1.5 shrink-0 rounded-full",i==="bell"?"bg-amber-400":i==="completion"?"bg-emerald-400":"bg-transparent"].join(" ")})]})}const ig=10;function WU(e){return e>=ig?`最近 ${ig} 条`:`${e} 条`}function qU({status:e,failed:t}){if((e==null?void 0:e.state)==="not-repository")return null;const r=!e||t||v3(e),n=(e==null?void 0:e.baseBranch)!==void 0&&e.behind!==void 0,i=(n?e.behind>0?`${e.baseBranch} 待同步提交,${WU(e.behind)}`:`与 ${e.baseBranch} 无落差`:"分支状态待更新")+(r&&n?",待更新":"")+(e!=null&&e.checkedAt?`;上次更新:${new Date(e.checkedAt).toLocaleString()}`:"");return o.jsxs("span",{"data-testid":"terminal-worktree-branch-status","aria-label":i,title:i,className:["flex min-w-0 shrink-0 items-center gap-1 whitespace-nowrap text-[10px] tabular-nums",!r&&((e==null?void 0:e.behind)??0)>0?"text-amber-400":"text-slate-500"].join(" "),children:[n?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"max-w-12 truncate",children:e.baseBranch}),o.jsx("span",{children:e.behind>0?e.behind>=ig?"最近 10 条":`↓${e.behind}`:"✓"})]}):null,r?o.jsx("span",{children:"待更新"}):null]})}function KU({message:e,onDismiss:t}){return o.jsxs("div",{role:"status","data-testid":"terminal-worktree-cleanup-notice",className:"m-2 rounded border border-amber-800/60 bg-amber-950/30 p-2 text-xs text-amber-200",children:[o.jsx("p",{className:"break-words",children:e}),o.jsx("button",{type:"button",className:"mt-2 text-amber-300 underline hover:text-amber-100",onClick:t,children:"关闭提示"})]})}const VU=236,og=180,ag=420,_1=16;function lm(e){return`viewer.terminal.worktree-rail-collapsed.${e}`}function lg(e){return`viewer.terminal.worktree-rail-width.${e}`}function nh(e){return Math.min(ag,Math.max(og,e))}function y1(e){const t=Number.parseInt(ht.getItem(lg(e))??"",10);return Number.isFinite(t)?nh(t):VU}function w1(e){const t=e.branch??"detached";return e.availability==="missing"?`${t} · missing`:e.availability==="path_unavailable"?`${t} · unavailable`:t}function dN({parentProjectId:e,onSelectContext:t}){const{apiBase:r,onAuthExpired:n,scope:s,token:i}=vt(),{queryClient:a}=Al(),c=Hf(e).data??Uf,u=Zn().data??bs,{activeProjectId:d,selectProjectContext:h,setRequestError:f}=tt(An(H=>({activeProjectId:H.activeProjectId,selectProjectContext:H.selectProjectContext,setRequestError:H.setRequestError}))),m=Vt(H=>H.removeProjectPreview),{byContextProjectId:g}=x3(),[v,x]=p.useState(()=>ht.getItem(lm(s))==="true"),[b,_]=p.useState(()=>y1(s)),C=mz(e,c,!v&&c.length>0),[S,w]=p.useState(!1),[y,N]=p.useState(null),[E,k]=p.useState(null),[D,j]=p.useState(null),[R,I]=p.useState(!1),[T,A]=p.useState(null),[P,O]=p.useState(null);p.useEffect(()=>{O(null)},[s,e]);const L=p.useRef(null),B=W(H=>{const G=L.current;if(!G)return;const z=nh(Math.round(H.clientX-G.railLeft));G.width=z,_(z)}),M=W(()=>{const H=L.current;L.current=null,window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",M),window.removeEventListener("pointercancel",M),w(!1),H&&(document.body.style.cursor=H.previousCursor,document.body.style.userSelect=H.previousUserSelect,ht.setItem(lg(H.scope),String(H.width)))}),$=W(H=>{H.preventDefault();const G=H.currentTarget.closest("aside");G&&(L.current={railLeft:G.getBoundingClientRect().left,width:b,scope:s,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",w(!0),window.addEventListener("pointermove",B),window.addEventListener("pointerup",M),window.addEventListener("pointercancel",M))}),U=W(H=>{const G=H.key==="Home"?og:H.key==="End"?ag:H.key==="ArrowLeft"?nh(b-_1):H.key==="ArrowRight"?nh(b+_1):null;G!==null&&(H.preventDefault(),_(G),ht.setItem(lg(s),String(G)))});p.useEffect(()=>{M(),x(ht.getItem(lm(s))==="true"),_(y1(s))},[s,M]),p.useEffect(()=>M,[M]),p.useEffect(()=>{var z,ee,V,re;let H=!1;(ee=(z=window.electronAPI)==null?void 0:z.terminalBrowserGetProfilePreferences)==null||ee.call(z).then(oe=>{!H&&oe&&k(oe)});const G=(re=(V=window.electronAPI)==null?void 0:V.onTerminalBrowserProfileChanged)==null?void 0:re.call(V,oe=>{oe.kind==="preferences"&&k(oe.preferences)});return()=>{H=!0,G==null||G()}},[]);const F=W(()=>{x(H=>{const G=!H;return ht.setItem(lm(s),String(G)),G})}),K=W(async(H,G)=>{if(!(!e||y)){N(H);try{await O6(r,i,e,H,G),await a.invalidateQueries({queryKey:jt.projectContexts(s,e)}),f(null)}catch(z){f(String(z))}finally{N(null)}}}),Y=W(H=>{A(null),j(H)}),te=W(async()=>{const H=D;if(!(!H||R)){I(!0),A(null);try{const G=await F6(r,i,H.parentProjectId,H.projectId);if(m(H.projectId),hz(s,H.parentProjectId,H.projectId),a.removeQueries({queryKey:jt.preview(s,H.projectId)}),d===H.projectId){const z=u.find(ee=>ee.projectId===H.parentProjectId);h(H.parentProjectId,H.parentProjectId,(z==null?void 0:z.terminalSessionId)??null)}Promise.all([a.invalidateQueries({queryKey:jt.projectContexts(s,H.parentProjectId)}),a.invalidateQueries({queryKey:jt.sessions(s)})]).catch(z=>{f(String(z))}),f(null),j(null),G.cleanupWarnings.length>0?(O(`Worktree 已删除,部分服务未清理:${G.cleanupWarnings.map(z=>`${z.devSessionId??"Dev Session"}(${z.message})`).join(";")}`),x(!1)):O(null)}catch(G){if(G instanceof De&&G.status===401){n==null||n();return}A(G instanceof Error?G.message:String(G))}finally{I(!1)}}});return o.jsxs(o.Fragment,{children:[o.jsxs("aside",{"data-testid":"terminal-worktree-rail","data-collapsed":v?"true":"false","data-resizing":S?"true":"false",className:["relative flex min-h-0 shrink-0 flex-col border-r border-slate-800 bg-slate-950",S?"":"transition-[width] duration-150"].join(" "),style:{width:v?36:b},children:[o.jsxs("div",{className:["flex h-7 shrink-0 items-center border-b border-slate-800",v?"justify-center":"justify-between px-2"].join(" "),children:[v?null:o.jsxs("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500",children:["Worktrees ",c.length]}),o.jsx("button",{type:"button","aria-label":v?"Expand Worktrees":"Collapse Worktrees",title:v?"Expand Worktrees":"Collapse Worktrees",className:"flex h-6 w-6 items-center justify-center rounded text-slate-500 hover:bg-slate-900 hover:text-slate-200",onClick:F,children:v?o.jsx(Jr,{className:"h-3.5 w-3.5"}):o.jsx(uE,{className:"h-3.5 w-3.5"})})]}),P&&!v?o.jsx(KU,{message:P,onDismiss:()=>O(null)}):null,v?null:o.jsx("div",{className:"min-h-0 flex-1 space-y-1 overflow-y-auto px-2 py-3",children:c.map(H=>{var be;const G=H.projectId===d,z=H.availability!=="available",ee=g[H.projectId]??0,V=E==null?void 0:E.worktrees[H.projectId],re=(V==null?void 0:V.preferredProfileId)??(E==null?void 0:E.defaultProfileId),oe=re?`${re.replace("profile-","P")} · ${V!=null&&V.preferredProfileId?"bound":"global"}`:null,ce=o.jsxs("div",{"data-testid":"terminal-worktree-row","data-project-id":H.projectId,"data-active":G?"true":"false",className:["group flex min-h-12 items-center gap-2 rounded-md border px-2 py-1.5",G?"border-sky-900/70 bg-slate-900 text-slate-50":"border-transparent text-slate-300 hover:bg-slate-900/70"].join(" "),children:[o.jsx("button",{type:"button","aria-label":`${H.name}, ${H.branch??"detached"}`,className:"flex min-w-0 flex-1 items-center gap-2 text-left",onClick:()=>t(H.projectId),children:o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx(uN,{label:H.name,status:ee,className:"flex w-full",labelClassName:"min-w-0 flex-1 truncate text-xs font-semibold"}),o.jsxs("span",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{title:w1(H),className:["min-w-0 truncate text-[10px]",z?"text-amber-400":"text-slate-500"].join(" "),children:w1(H)}),z?null:o.jsx(qU,{status:(be=C.data)==null?void 0:be.find(ne=>ne.projectId===H.projectId&&ne.path===H.path&&ne.head===H.head),failed:C.isError})]}),oe?o.jsx("span",{"data-testid":"terminal-worktree-browser-profile",className:"block truncate text-[9px] text-slate-600",children:oe}):null]})}),H.isPrimary?o.jsx("span",{"aria-label":"Permanently pinned",title:"Permanently pinned",className:"flex h-6 w-6 shrink-0 items-center justify-center text-sky-400",children:o.jsx(E0,{className:"h-3.5 w-3.5 fill-current"})}):o.jsx("button",{type:"button","aria-label":H.pinned?"Unpin Worktree":"Pin Worktree",title:H.pinned?"Unpin Worktree":"Pin Worktree",disabled:y===H.projectId,className:["flex h-6 w-6 shrink-0 items-center justify-center rounded hover:bg-slate-800 hover:text-slate-100 disabled:opacity-40",H.pinned?"text-sky-400":"text-slate-600"].join(" "),onClick:()=>{K(H.projectId,!H.pinned)},children:o.jsx(E0,{className:["h-3.5 w-3.5",H.pinned?"fill-current":""].join(" ")})})]});return H.isPrimary?o.jsx(p.Fragment,{children:ce},H.projectId):o.jsxs(Vx,{children:[o.jsx(Gx,{asChild:!0,children:ce}),o.jsx(Kf,{className:"w-36",children:o.jsxs(Ps,{"data-testid":"terminal-worktree-delete-menu-item",className:"gap-2 text-rose-400 focus:text-rose-400",onSelect:()=>Y(H),children:[o.jsx(EE,{className:"h-4 w-4"}),"删除"]})})]},H.projectId)})}),v?null:o.jsx("div",{role:"separator",tabIndex:0,"aria-label":"Resize Worktrees panel","aria-orientation":"vertical","aria-valuemin":og,"aria-valuemax":ag,"aria-valuenow":b,className:"absolute right-0 top-0 z-20 h-full w-2 translate-x-1/2 touch-none cursor-col-resize before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors hover:before:bg-sky-400/60 focus-visible:before:bg-sky-400/60 data-[resizing=true]:before:w-0.5 data-[resizing=true]:before:bg-sky-400","data-resizing":S?"true":"false",onPointerDown:$,onKeyDown:U})]}),o.jsx(jz,{pendingDeletion:D,sessionCount:u.filter(H=>H.projectId===(D==null?void 0:D.projectId)).length,deleting:R,deleteError:T,onDismiss:()=>{A(null),j(null)},onConfirm:te})]})}function GU(e,t){const r=BO(e,t);if(!r)return;const n=tt.getState();n.selectProjectContext(r.parentProjectId,r.projectId,r.terminalSessionId),r.terminalSessionId&&r.panelId&&n.setActivePanelIdBySessionId(s=>({...s,[r.terminalSessionId]:r.panelId}))}function Sd(e,t,r){const n=tt.getState();return n.activeParentProjectId===e&&n.activeProjectId===t&&n.activeSessionId===r}function sh(e,t,r,n){var a;if(n){const l=r.find(c=>c.terminalSessionId===n);if(l)return l.terminalSessionId}const s=oa(e),i=(s==null?void 0:s.projectSessionIds[t])??(s==null?void 0:s.terminalSessionId);if(i){const l=r.find(c=>c.terminalSessionId===i);if(l)return l.terminalSessionId}return((a=r[0])==null?void 0:a.terminalSessionId)??null}function YU(e,t,r,n,s){var c,u;const i=s?(c=r.find(d=>d.terminalSessionId===s))==null?void 0:c.projectId:null,a=i?Tn(i):null;if(a&&t.some(d=>d.projectId===a))return a;if(n&&t.some(d=>d.projectId===n))return n;const l=oa(e);return l!=null&&l.projectId&&t.some(d=>d.projectId===l.projectId)?l.projectId:((u=t[0])==null?void 0:u.projectId)??null}function XU(e,t,r,n,s){return!r||!n?!1:s?e.some(i=>i.projectId===r)&&Tn(n)===r&&t.some(i=>i.projectId===n&&i.terminalSessionId===s):e.some(i=>i.projectId===r)&&Tn(n)===r&&!t.some(i=>i.projectId===n)}function hN({activeParentProjectId:e,projectId:t,sessions:r,scope:n,selectProjectContext:s}){if(!e)return;const i=r.filter(a=>a.projectId===t);s(e,t,sh(n,t,i))}function S1(e,t,r){return t<=0?-1:((e>=0?e:0)+r+t)%t}function JU({enabled:e,activeProjectId:t,activeSessionId:r,visibleProjects:n,visibleSessions:s,onSelectProject:i,onSelectSession:a}){p.useEffect(()=>{if(!e)return;const l=c=>{if(c.defaultPrevented||!c.altKey||c.ctrlKey||c.metaKey)return;const u=c.code==="BracketLeft"||c.key==="[",d=c.code==="BracketRight"||c.key==="]",h=!c.shiftKey&&u,f=!c.shiftKey&&d,m=c.shiftKey&&u,g=c.shiftKey&&d;if(!h&&!f&&!m&&!g)return;if(c.preventDefault(),c.stopPropagation(),h||f){if(n.length<=1)return;const b=n.findIndex(C=>C.projectId===t),_=n[S1(b,n.length,h?-1:1)];_&&i(_.projectId);return}if(s.length<=1)return;const v=s.findIndex(b=>b.terminalSessionId===r),x=s[S1(v,s.length,m?-1:1)];x&&a(x.terminalSessionId)};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l)}},[t,r,e,i,a,n,s])}function QU({sessions:e,historyTerminalSessionId:t,setCompletionMarkers:r,setBellMarkers:n,setHistoryDrawerOpen:s,setHistoryTerminalSessionId:i,setHistoryTerminalPanelId:a}){p.useEffect(()=>{const l=new Set(e.map(c=>c.terminalSessionId));r(c=>{let u=!1;const d=Object.entries(c).filter(([h,f])=>{const m=f&&l.has(h);return m||(u=!0),m});return u?Object.fromEntries(d):c})},[e,r]),p.useEffect(()=>{const l=new Set(e.map(c=>c.terminalSessionId));n(c=>{let u=!1;const d=Object.entries(c).filter(([h,f])=>{const m=f&&l.has(h);return m||(u=!0),m});return u?Object.fromEntries(d):c})},[e,n]),p.useEffect(()=>{t&&(e.some(l=>l.terminalSessionId===t)||(s(!1),i(null),a(null)))},[t,e,s,a,i])}function ZU({apiBase:e,activeParentProjectId:t,activeProjectId:r,activeSessionId:n,canPersist:s,requestError:i}){p.useEffect(()=>{!s||i||!t||!r||dz(e,{parentProjectId:t,projectId:r,terminalSessionId:n})},[t,r,n,e,s,i])}const Yx={busy:"使用中",free:"空闲",blocked:"待检查",unknown:"未知"},eH={busy:"text-sky-300 bg-sky-500/10",free:"text-slate-400 bg-slate-700/25",blocked:"text-amber-300 bg-amber-500/10",unknown:"text-amber-300 bg-amber-500/10"};function cg(e){return!e||!Number.isFinite(Date.parse(e))?"—":new Date(e).toLocaleString("zh-CN",{hour12:!1})}function tH(e,t){if(!e||!Number.isFinite(Date.parse(e)))return"—";const r=Math.max(0,Math.floor((Date.parse(t)-Date.parse(e))/6e4));return r>=60?`${Math.floor(r/60)} 小时 ${r%60} 分钟`:`${r} 分钟`}function C1({title:e,group:t,sessions:r=[],observedAt:n,filter:s,expanded:i,onToggle:a,onRelease:l,pending:c}){const u=[...t.resources,...r].filter(d=>s==="all"||d.state===s||s==="attention"&&["blocked","unknown"].includes(d.state));return o.jsxs("section",{"aria-label":`${e}资源`,className:"overflow-hidden rounded-lg border border-slate-800 bg-slate-900/60",children:[o.jsxs("header",{className:"flex items-center gap-3 border-b border-slate-800 p-4",children:[e==="桌面测试"?o.jsx(Cf,{className:"h-5 w-5 text-slate-400"}):o.jsx(SE,{className:"h-5 w-5 text-slate-400"}),o.jsxs("div",{className:"flex-1",children:[o.jsx("h2",{className:"font-semibold",children:e}),o.jsx("p",{className:"mt-1 text-xs text-slate-500",children:e==="桌面测试"?"Runweave Beta":"iOS Simulator"})]}),o.jsxs("span",{className:"text-xs text-slate-400",children:[t.counts.free??"—"," 空闲 / ",t.counts.total??"—"," 总计"]})]}),t.reason&&o.jsx("p",{role:t.sourceState==="ready"?"status":"alert",className:"border-b border-slate-800 px-4 py-3 text-sm text-amber-300",children:t.reason}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("div",{className:"min-w-[760px]",children:[o.jsxs("div",{className:"grid grid-cols-[1.3fr_0.6fr_1.6fr_0.8fr_1fr_24px] gap-4 px-4 py-3 text-xs text-slate-500",children:[o.jsx("span",{children:"资源"}),o.jsx("span",{children:"状态"}),o.jsx("span",{children:"占用任务 / 工作树"}),o.jsx("span",{children:"占用时长"}),o.jsx("span",{children:"最后活动"}),o.jsx("span",{})]}),u.map(d=>{var h,f,m,g,v,x,b,_;return o.jsxs("div",{"data-resource-id":d.id,className:"border-t border-slate-800",children:[o.jsxs("button",{type:"button",className:"grid w-full grid-cols-[1.3fr_0.6fr_1.6fr_0.8fr_1fr_24px] items-center gap-4 px-4 py-4 text-left hover:bg-slate-800/50","aria-label":`${d.label}详情`,"aria-expanded":i.has(d.id),onClick:()=>a(d.id),children:[o.jsxs("span",{className:"min-w-0",children:[o.jsx("span",{className:"block truncate text-sm",children:d.label}),o.jsx("span",{className:"mt-1 block truncate text-xs text-slate-500",children:d.kind==="desktop-session"?"非池 Session · 不计入槽位容量":d.details.deviceState??d.id})]}),o.jsx("span",{children:o.jsx("span",{className:`rounded px-2 py-1 text-xs ${eH[d.state]}`,children:Yx[d.state]})}),o.jsxs("span",{className:"min-w-0",children:[o.jsx("span",{className:"block truncate text-sm",children:((h=d.owner)==null?void 0:h.task)??(d.state==="free"?"没有占用任务":((f=d.owner)==null?void 0:f.id)??"占用者未知")}),o.jsx("span",{className:"mt-1 block truncate text-xs text-slate-500",children:(m=d.owner)==null?void 0:m.worktree})]}),o.jsx("span",{className:"text-xs text-slate-400",children:tH(((g=d.owner)==null?void 0:g.startedAt)??null,n)}),o.jsx("span",{className:"text-xs text-slate-400",children:cg(((v=d.owner)==null?void 0:v.lastActivityAt)??null)}),o.jsx(Jr,{className:`h-4 w-4 text-slate-500 ${i.has(d.id)?"rotate-90":""}`})]}),i.has(d.id)&&o.jsxs("div",{className:"space-y-4 bg-slate-950/50 p-4",children:[(d.reason||d.operation)&&o.jsxs("p",{className:"flex items-start gap-2 rounded border border-amber-500/20 bg-amber-500/10 p-3 text-sm text-amber-300",children:[o.jsx(pa,{className:"mt-0.5 h-4 w-4 shrink-0"}),((x=d.operation)==null?void 0:x.state)==="running"?"正在释放,请稍后手动刷新":d.reason??"上次操作结果尚未确认"]}),o.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[o.jsx("dl",{className:"space-y-2 text-xs",children:[["占用者",(b=d.owner)==null?void 0:b.id],["工作目录",d.details.path],["占用开始",cg(((_=d.owner)==null?void 0:_.startedAt)??null)],["端口",d.details.ports.join(" · ")],["设备 UDID",d.details.udid]].filter(([C])=>C!=="设备 UDID"||d.kind==="simulator").map(([C,S])=>o.jsxs("div",{className:"grid grid-cols-[80px_1fr] gap-2",children:[o.jsx("dt",{className:"text-slate-500",children:C}),o.jsx("dd",{className:"break-all font-mono text-slate-300",children:S||"—"})]},C))}),o.jsxs("div",{children:[o.jsx("p",{className:"mb-2 text-xs text-slate-500",children:"当前进程"}),d.details.processes.length?o.jsx("ul",{className:"space-y-2 text-xs",children:d.details.processes.map(C=>o.jsxs("li",{className:"flex justify-between gap-3",children:[o.jsxs("span",{children:[C.name," · ",C.pid,C.ownership==="shared"?" · 共享":C.ownership==="unknown"?" · 身份未知":""]}),o.jsxs("span",{className:"text-slate-400",children:[C.cpuPercent===null?"CPU —":`CPU ${C.cpuPercent.toFixed(1)}%`," ","·"," ",C.rssBytes===null?"内存 —":`${Math.round(C.rssBytes/1048576)} MB`]})]},C.pid))}):o.jsx("p",{className:"text-xs text-slate-400",children:d.state==="unknown"?"进程状态未知":"未发现存活的测试进程"})]})]}),d.state!=="free"&&o.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-slate-800 pt-4",children:[o.jsx("p",{className:"text-xs text-slate-400",children:d.release.disabledReason??(d.release.action==="stop-and-release"?"将停止当前测试并释放该资源":"核对归属后清理残留占用")}),o.jsx(Z,{size:"sm",variant:d.release.action==="stop-and-release"?"destructive":"outline",disabled:c||!d.release.action,onClick:()=>l(d),children:d.release.action==="stop-and-release"?"停止并释放":d.release.action==="release-occupancy"?"释放占用":"无法释放"})]})]})]},d.id)}),!u.length&&o.jsx("p",{className:"p-8 text-center text-sm text-slate-500",children:t.sourceState==="unavailable"||t.sourceState==="unsupported"?"当前资源状态未知":"没有符合条件的资源"})]})})]})}function rH(e,t,r){return me(e,"/api/dev-resources",{signal:r,cache:"no-store",headers:{Authorization:`Bearer ${t}`}})}function nH(e,t,r,n){return me(e,`/api/dev-resources/${encodeURIComponent(r)}/release`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}function E1({title:e,group:t,simulator:r=!1}){const n=t==null?void 0:t.counts,s=!n||n.unknown===null||n.unknown>0;return o.jsxs("section",{"aria-label":`${e}总览`,className:"rounded-lg border border-slate-800 bg-slate-900/70 p-5",children:[o.jsxs("p",{className:"flex items-center gap-2 text-sm text-slate-400",children:[r?o.jsx(SE,{className:"h-4 w-4"}):o.jsx(Cf,{className:"h-4 w-4"}),e]}),o.jsxs("p",{className:"my-4 flex items-baseline gap-2",children:[o.jsx("strong",{className:"text-3xl font-semibold",children:s||(n==null?void 0:n.busy)===null||(n==null?void 0:n.blocked)===null?"—":n.busy+n.blocked}),o.jsxs("span",{className:"text-lg text-slate-500",children:["/ ",(n==null?void 0:n.total)??"—"]}),o.jsx("span",{className:"text-xs text-slate-400",children:"已占用"})]}),o.jsx("div",{className:"flex flex-wrap gap-4 text-xs text-slate-400",children:["busy","blocked","free","unknown"].map(i=>o.jsxs("span",{children:[Yx[i]," ",(n==null?void 0:n[i])??"—"]},i))})]})}function sH({embedded:e=!1,apiBase:t,token:r,connectionName:n,onAuthExpired:s}){var M,$,U;const i=Cr(),{scope:a}=vt(),l=Zn().data??bs,c=tt(F=>F.selectProjectContext),u=tt(F=>F.activeParentProjectId),d=tt(F=>F.activeSessionId),[h,f]=p.useState(null),[m,g]=p.useState("all"),[v,x]=p.useState(new Set),[b,_]=p.useState(null),[C,S]=p.useState(!1),[w,y]=p.useState(!1),[N,E]=p.useState(null),[k,D]=p.useState(null),j=p.useRef(!1),R=p.useRef(null),I=p.useRef(!1),T=W(()=>i(d?`/terminal/${encodeURIComponent(d)}`:"/terminal")),A=W(F=>{hN({activeParentProjectId:u,projectId:F,sessions:l,scope:a,selectProjectContext:c});const K=tt.getState().activeSessionId;i(K?`/terminal/${encodeURIComponent(K)}`:"/terminal")}),P=W(async()=>{if(R.current||!j.current)return;const F=new AbortController;R.current=F,S(!0);try{const K=await rH(t,r,F.signal);!F.signal.aborted&&j.current&&(f(K),E(null))}catch(K){!F.signal.aborted&&j.current&&(f(null),E(K instanceof Error?K.message:"无法获取当前资源状态"),K instanceof De&&K.status===401&&s())}finally{R.current===F&&(R.current=null),j.current&&S(!1)}});p.useEffect(()=>{j.current=!0;let F=!1;return Promise.resolve().then(()=>{F||P()}),()=>{var K;F=!0,j.current=!1,(K=R.current)==null||K.abort(),R.current=null}},[P]);const O=W(async()=>{if(!(!(b!=null&&b.release.action)||!b.ownershipVersion||I.current)){I.current=!0,y(!0),D(null);try{const F=await nH(t,r,b.id,{action:b.release.action,expectedOwnershipVersion:b.ownershipVersion,idempotencyKey:crypto.randomUUID()});j.current&&D({error:F.state!=="released",text:F.state==="running"?"释放仍在进行,请稍后手动刷新查看结果":F.message})}catch(F){j.current&&(D({error:!0,text:F instanceof De?F.message:"释放结果尚未确认,请手动刷新核查"}),F instanceof De&&F.status===401&&s())}finally{j.current&&(_(null),await P(),y(!1)),I.current=!1}}}),L=W(F=>x(K=>{const Y=new Set(K);return Y.has(F)?Y.delete(F):Y.add(F),Y})),B=h?(h.desktop.counts.blocked??0)+(h.desktop.counts.unknown??0)+(h.simulators.counts.blocked??0)+(h.simulators.counts.unknown??0)+h.desktop.sessions.filter(F=>F.state==="blocked"||F.state==="unknown").length:null;return o.jsxs("main",{className:e?"flex flex-col":"flex h-dvh flex-col overflow-hidden bg-slate-950 text-slate-200",children:[!e&&o.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-3 border-b border-slate-800 px-4",children:[o.jsx(cs,{className:"h-4 w-4 text-sky-300"}),o.jsx("span",{className:"text-sm font-semibold",children:"Runweave"}),o.jsxs("span",{className:"ml-auto text-xs text-slate-400",children:[n??"当前连接"," ·"," ",(h==null?void 0:h.hostName)??"资源状态读取中"]})]}),o.jsxs("div",{className:"flex min-h-0 flex-1",children:[!e&&o.jsx(dN,{parentProjectId:u,onSelectContext:A}),o.jsx("div",{className:e?"min-w-0 flex-1":"min-w-0 flex-1 overflow-y-auto p-5 md:p-9",children:o.jsxs("div",{className:"w-full space-y-3",children:[o.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs text-slate-500",children:"当前连接电脑"}),!e&&o.jsx("h1",{className:"mt-2 text-2xl font-semibold",children:"开发资源"}),o.jsxs("p",{className:"mt-2 text-sm text-slate-400",children:[(h==null?void 0:h.hostName)??n??"当前连接"," / 测试环境"]})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[!e&&o.jsxs(Z,{variant:"ghost",size:"sm",onClick:T,children:[o.jsx(xi,{className:"mr-2 h-4 w-4"}),"返回终端"]}),o.jsx("span",{className:"text-xs text-slate-500","data-testid":"dev-resources-updated-at",children:C?"正在更新…":h?`更新于 ${cg(h.observedAt)}`:"未取得当前状态"}),o.jsxs(Z,{variant:"outline",size:"sm",disabled:C||w,onClick:()=>{D(null),P()},children:[o.jsx(Ws,{className:`mr-2 h-4 w-4 ${C?"animate-spin":""}`}),"刷新"]})]})]}),o.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[o.jsx(E1,{title:"桌面测试",group:h==null?void 0:h.desktop}),o.jsx(E1,{title:"模拟器测试",group:h==null?void 0:h.simulators,simulator:!0}),o.jsxs("section",{"aria-label":"待检查总览",className:"rounded-lg border border-amber-500/25 bg-amber-500/5 p-5",children:[o.jsxs("p",{className:"flex items-center gap-2 text-sm text-amber-300",children:[o.jsx(pa,{className:"h-4 w-4"}),"待检查"]}),o.jsx("p",{className:"my-4 text-3xl font-semibold",children:h&&h.desktop.sourceState!=="unavailable"&&h.simulators.sourceState!=="unavailable"?B:"—"}),o.jsx("button",{className:"text-xs text-amber-300 hover:underline",onClick:()=>g("attention"),children:"查看待检查资源"})]})]}),k&&o.jsx("p",{role:k.error?"alert":"status",className:`rounded-lg border p-3 text-sm ${k.error?"border-amber-500/30 text-amber-300":"border-emerald-500/30 text-emerald-300"}`,children:k.text}),N&&o.jsxs("p",{role:"alert",className:"rounded border border-amber-500/25 p-4 text-sm text-amber-300",children:["无法获取当前资源状态:",N,"。请手动刷新重试。"]}),h&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[o.jsx("p",{className:"text-sm text-slate-400",children:"资源列表"}),o.jsx("div",{className:"flex flex-wrap gap-1 rounded border border-slate-800 p-1","aria-label":"资源状态筛选",children:["all","busy","free","blocked","unknown"].map(F=>o.jsx("button",{className:`rounded px-3 py-1.5 text-xs ${m===F?"bg-slate-800 text-slate-100":"text-slate-400"}`,"aria-pressed":m===F,onClick:()=>g(F),children:F==="all"?"全部状态":Yx[F]},F))})]}),o.jsx(C1,{title:"桌面测试",group:h.desktop,sessions:h.desktop.sessions,observedAt:h.observedAt,filter:m,expanded:v,onToggle:L,onRelease:_,pending:C||w}),o.jsx(C1,{title:"模拟器测试",group:h.simulators,observedAt:h.observedAt,filter:m,expanded:v,onToggle:L,onRelease:_,pending:C||w})]}),!h&&!N&&o.jsx("p",{role:"status",className:"p-8 text-center text-sm text-slate-500",children:"正在读取当前资源…"}),o.jsx("p",{className:"text-xs text-slate-500",children:"当前快照"})]})})]}),o.jsx(Tl,{open:b!==null,onOpenChange:F=>{!F&&!w&&_(null)},children:o.jsxs(xa,{onEscapeKeyDown:F=>{w&&F.preventDefault()},className:"rounded-lg",children:[o.jsxs(Dl,{children:[o.jsx(ba,{children:(b==null?void 0:b.release.action)==="stop-and-release"?"停止并释放资源?":"释放资源占用?"}),o.jsx(_a,{asChild:!0,children:o.jsxs("div",{className:"space-y-4 text-sm text-slate-400",children:[o.jsx("p",{children:(b==null?void 0:b.release.action)==="stop-and-release"?"当前测试正在使用这个资源。继续操作会中断该测试。":"将重新核对占用归属并清理残留。"}),o.jsx("dl",{className:"space-y-2 rounded border border-slate-800 p-3",children:[["资源",b==null?void 0:b.label],["占用任务",((M=b==null?void 0:b.owner)==null?void 0:M.task)??(($=b==null?void 0:b.owner)==null?void 0:$.id)],["工作树",(U=b==null?void 0:b.owner)==null?void 0:U.worktree]].map(([F,K])=>o.jsxs("div",{className:"grid grid-cols-[80px_1fr] gap-3",children:[o.jsx("dt",{children:F}),o.jsx("dd",{className:"break-all text-slate-200",children:K??"—"})]},F))}),o.jsxs("p",{children:[(b==null?void 0:b.kind)==="simulator"?"将停止该任务的 Runner、关闭模拟器并释放占用。":"将清理该测试环境自有的服务和占用,保留共享服务。","归属核对或清理未完成时,资源仍保持占用。"]}),w&&o.jsx("p",{role:"status",children:"正在核对占用并释放资源…"})]})})]}),o.jsxs(Pl,{children:[o.jsx(ya,{disabled:w,children:"取消"}),o.jsx(Z,{variant:"destructive",disabled:w,onClick:()=>void O(),children:w?"释放中…":(b==null?void 0:b.release.action)==="stop-and-release"?"确认停止并释放":"确认释放占用"})]})]})})]})}function iH(e){return o.jsx(zf,{apiBase:e.apiBase,token:e.token,activeConnectionId:e.activeConnectionId,connectionGeneration:e.connectionGeneration,onAuthExpired:e.onAuthExpired,children:o.jsx(sH,{...e},`${e.activeConnectionId}:${e.apiBase}:${e.connectionGeneration}:${e.token}`)})}function oH(e){p.useEffect(()=>{const t=window.electronAPI;if(!(t!=null&&t.setTerminalBadgeConnections))return;const r=t.setTerminalBadgeConnections;let n="";const s=()=>{const a=e.map(c=>{var u;return{id:c.id,url:c.url,token:((u=yl(c.id))==null?void 0:u.accessToken)??null}}),l=JSON.stringify(a);n!==l&&(n=l,r(a).catch(()=>{n=""}))};s();const i=window.setInterval(s,1e3);return()=>window.clearInterval(i)},[e])}function aH({onOpen:e}){const t=Tx(),r=Gt(),n=t.notice;return!n||r.pathname==="/system-monitor"||!t.token?null:o.jsxs(eo,{kind:"resource",noticeKey:n,onDismiss:t.dismissNotice,className:"rounded-lg border border-amber-500/40 bg-card p-4 shadow-lg",children:[o.jsxs("strong",{className:"text-sm",children:[n.appName," ",n.ruleId==="energy"?"能耗影响较高":"内存占用较大"]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["近 5 分钟多次检测到高占用",n.ruleId==="memory"?";内存占用不代表耗电量":""]}),o.jsxs("div",{className:"mt-3 flex gap-2",children:[o.jsx(Z,{size:"sm",onClick:()=>{t.dismissNotice(),e(n.appKey)},children:"查看进程"}),o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>{t.snooze(n.alertId).then(()=>t.dismissNotice()).catch(()=>e(n.appKey))},children:"忽略 1 小时"})]})]})}async function lH(e){if(typeof e.arrayBuffer=="function"){const t=await e.arrayBuffer();return btoa(Array.from(new Uint8Array(t),r=>String.fromCharCode(r)).join(""))}return await new Promise((t,r)=>{const n=new FileReader;n.onerror=()=>{r(n.error??new Error("Failed to read image"))},n.onload=()=>{const s=n.result;if(typeof s!="string"){r(new Error("Failed to read image"));return}t(s.split(",",2)[1]??"")},n.readAsDataURL(e)})}function fN(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function cH(e){return!Number.isFinite(e)||!e||e<=0?null:Math.floor(e)}function uH(e){if(!e)return 0;let t=1;for(let r=0;r<e.length;r+=1)e.charCodeAt(r)===10&&(t+=1);return t}function dH(e){return e.replace(/\r?\n/g,`\r
|
|
497
|
-
`)}function hH({terminal:e,fitAddon:t,sourceCols:r}){const n=cH(r);if(n){const s=t.proposeDimensions();if(!s)return;e.resize(n,s.rows)}else t.fit();e.refresh(0,Math.max(e.rows-1,0))}function fH({terminal:e,output:t,syncSize:r}){if(r(),!t)return;const n=dH(t);e.write(n,()=>{r(),e.scrollToBottom()})}const pN=p.createContext(null),pH=pN.Provider;function mce(){const e=p.useRef(null),t=p.useContext(pN);return p.useLayoutEffect(()=>{var n;const r=(n=e.current)==null?void 0:n.closest(".rw-image-lightbox");if(r&&t)return t(r)},[t]),o.jsx("span",{ref:e,hidden:!0})}function mH(e){return e.type==="keydown"&&e.key==="Enter"&&e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey}const co="\\u001b",gH="\\u0007",vH=new RegExp(`${co}\\]1[01];rgb:[0-9a-f/]+(?:${gH}|${co}\\\\)`,"i"),xH=new RegExp(`${co}\\[\\?[0-9;]+\\$y`),bH=new RegExp(`${co}P[01]\\$r.*${co}\\\\`),_H=new RegExp(`${co}\\[[0-9;]+R`),yH=new RegExp(`${co}\\[(?:\\?|>)[0-9;]+c`),wH=new RegExp(`${co}\\[(?:I|O)$`);function SH(e){return e.startsWith("\x1B")?vH.test(e)||xH.test(e)||bH.test(e)||_H.test(e)||yH.test(e)||wH.test(e):!1}function mN(e,t=1){const r=Math.max(0,e.buffer.active.baseY-e.buffer.active.viewportY);return{isAtBottom:r<=t,bottomOffsetRows:r}}function k1(e,t=1){return mN(e,t).isAtBottom}function CH(e){e.scrollToBottom()}const EH=2,kH=250;function I1(e=!1){const t=e?1:5;let r=0,n=-1/0;const s=()=>{r=0,n=-1/0};return{reset:s,consume(i,a,l,c,u){if(!Number.isFinite(c)||c<=0)return s(),null;const d=i.deltaMode===1?c:i.deltaMode===2?c*l:1,h=i.deltaY*d*u*EH;if(!Number.isFinite(h)||h===0)return null;(i.timeStamp-n>kH||Math.sign(h)!==Math.sign(r))&&(r=0),n=i.timeStamp,r+=h;const f=c*t,m=Math.trunc(r/f);if(m===0)return null;r-=m*f;const g=(m<0?64:65)+(e?16:0),v=Math.max(1,Math.floor(a/2)),x=Math.max(1,Math.floor(l/2));return{input:`\x1B[<${g};${v};${x}M`.repeat(Math.abs(m)),rows:m*t}}}}function IH(e){let t="",r=null;const n=()=>{r!==null&&cancelAnimationFrame(r),r=null},s=()=>{n();const i=t;t="",i&&e(i)};return{enqueue(i){t+=i,r===null&&(r=requestAnimationFrame(s))},flush:s,reset(){n(),t=""}}}const NH=e=>sk(e,"window");function RH({children:e}){return o.jsx(pH,{value:NH,children:e})}const jH=300*1e3;function AH(e){return{protocolVersion:1,status:e,observedAt:null,sampleAgeMs:null,weekly:null,shortWindow:null}}function TH(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,r=["ok","unavailable","incompatible","unsupported","not_logged_in","error"];if(t.protocolVersion!==1||!r.includes(t.status)||!(t.observedAt===null||typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt)))||!(t.sampleAgeMs===null||typeof t.sampleAgeMs=="number"&&Number.isFinite(t.sampleAgeMs)&&t.sampleAgeMs>=0))return null;const n=a=>{if(a===null)return null;if(!a||typeof a!="object"||Array.isArray(a))return;const l=a;if(!(typeof l.usedPercent!="number"||!Number.isFinite(l.usedPercent)||l.usedPercent<0||l.usedPercent>100||typeof l.windowDurationMins!="number"||!Number.isFinite(l.windowDurationMins)||l.windowDurationMins<=0||!(l.resetsAt===null||typeof l.resetsAt=="number"&&Number.isFinite(l.resetsAt)&&l.resetsAt>=0&&l.resetsAt<=864e10)))return{usedPercent:l.usedPercent,windowDurationMins:l.windowDurationMins,resetsAt:l.resetsAt}},s=n(t.weekly),i=n(t.shortWindow);return s===void 0||i===void 0?null:{protocolVersion:1,status:t.status,observedAt:t.observedAt,sampleAgeMs:t.sampleAgeMs,weekly:s,shortWindow:i}}const N1={ok:"",unavailable:"App Server 暂不可用",incompatible:"当前服务版本不支持 Codex 额度,请更新后重试",unsupported:"当前版本或登录方式不支持 Codex 额度",not_logged_in:"请先在 App Server 所在电脑登录 Codex 的 ChatGPT 订阅",error:"额度更新失败,请稍后重试"};async function DH(e,t,r,n){var i;const s=await fetch(`${e.replace(/\/+$/u,"")}/api/codex/quota${r?"?refresh=1":""}`,{headers:{Authorization:`Bearer ${t}`},cache:"no-store",signal:AbortSignal.any([n,AbortSignal.timeout(7e4)])});if(s.status===404)throw new Error("当前 Backend 版本不支持 Codex 额度");if(s.status===401){const a=(i=s.headers.get("content-type"))!=null&&i.includes("application/json")?await s.json().catch(()=>null):null;throw a&&typeof a=="object"&&"message"in a&&a.message==="Unauthorized"?new De(401,"登录已失效,请重新登录当前连接"):new Error("连接访问被拒绝,请检查代理或网络认证")}if(!s.ok)throw new Error("额度更新失败,请稍后重试");return TH(await s.json())??AH("incompatible")}const gN=p.createContext(null);function vN(){return p.useContext(gN)}function R1({title:e,value:t}){return o.jsxs("section",{className:"space-y-2 rounded-lg border border-border/60 p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h3",{className:"text-sm",children:e}),o.jsx("strong",{className:"text-xl tabular-nums",children:t?`${Number((100-t.usedPercent).toFixed(1))}%`:"未知"})]}),t?o.jsxs(o.Fragment,{children:[o.jsx("progress",{"aria-label":e,max:100,value:100-t.usedPercent,className:"h-2 w-full accent-primary"}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["下次重置:",t.resetsAt===null?"未知":new Date(t.resetsAt*1e3).toLocaleString(),t.resetsAt!==null&&t.resetsAt*1e3<=Date.now()?"(已到期,请刷新确认)":""]})]}):o.jsx("p",{className:"text-xs text-muted-foreground",children:"上游未提供此窗口"})]})}function PH({children:e,apiBase:t,token:r,connectionName:n,onUnauthorized:s,embedded:i=!1}){const[a,l]=p.useState(i),[c,u]=p.useState(null),[d,h]=p.useState(!1),[f,m]=p.useState(null),g=p.useRef(null),v=p.useRef(0),x=W(async S=>{var y;if(!r)return;(y=g.current)==null||y.abort();const w=new AbortController;g.current=w,h(!0),m(null);try{const N=await DH(t,r,S,w.signal);if(w.signal.aborted)return;N.observedAt===null&&(N.status==="unavailable"||N.status==="incompatible")?m(N1[N.status]):(u(N),v.current=performance.now())}catch(N){if(w.signal.aborted)return;N instanceof De&&N.status===401?(u(null),l(!1),s()):m(N instanceof Error?N.message:"额度更新失败")}finally{w.signal.aborted||h(!1)}});p.useEffect(()=>(a&&x(!1),()=>{var S;return(S=g.current)==null?void 0:S.abort()}),[a,x]);const b=(c==null?void 0:c.sampleAgeMs)==null?null:c.sampleAgeMs+performance.now()-v.current,_=f??(c?N1[c.status]:null),C=o.jsxs("div",{className:"space-y-4","aria-busy":d,children:[o.jsx(R1,{title:"每周剩余",value:(c==null?void 0:c.weekly)??null}),c!=null&&c.shortWindow?o.jsx(R1,{title:"短周期剩余",value:c.shortWindow}):null,_?o.jsxs("p",{role:"status",className:"text-sm text-amber-600",children:[_,c!=null&&c.observedAt?";额度为上次记录":""]}):null,c!=null&&c.observedAt?o.jsxs("p",{className:"text-xs text-muted-foreground",children:["更新于 ",new Date(c.observedAt).toLocaleString(),b!==null&&b>=jH?"(旧记录)":""]}):null,o.jsx(Z,{onClick:()=>void x(!0),disabled:d,children:d?"正在更新…":"刷新"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"仅打开或手动刷新时查询,不会持续监控。"})]});return i?C:o.jsxs(gN.Provider,{value:r?()=>l(!0):null,children:[e,o.jsx(Pu,{open:a,onOpenChange:l,children:o.jsxs(Il,{className:"w-full sm:max-w-sm",children:[o.jsxs(Ff,{children:[o.jsx(Nl,{children:"Codex 额度"}),o.jsxs(Rl,{children:[n," · App Server 的 ChatGPT 订阅"]})]}),C]})})]})}const xN=p.createContext(null),LH=()=>p.useContext(xN);function MH({payload:e}){const t=p.useRef(null),[r,n]=p.useState(!1);return p.useEffect(()=>{let s=!1;return Vr(()=>import("./browser-CIEzmzuD.js").then(i=>i.b),__vite__mapDeps([14,1])).then(async i=>{!s&&t.current&&await i.toCanvas(t.current,e,{width:320,margin:4,errorCorrectionLevel:"L",color:{dark:"#000000",light:"#ffffff"}})}).catch(()=>{s||n(!0)}),()=>{s=!0}},[e]),r?o.jsx("p",{role:"alert",children:"地址过长,无法显示二维码。请使用较短的连接地址或手动登录。"}):o.jsx("canvas",{ref:t,width:320,height:320,className:"mx-auto min-h-[320px] min-w-[320px] bg-white","aria-label":"用 Runweave iOS 扫描登录二维码"})}const OH={waiting_scan:"请在 iOS App 的连接管理中点击「扫码连接电脑」",pending_approval:"等待你确认这台手机",approved:"正在完成手机登录",issuing:"正在完成手机登录",issued:"正在完成手机登录",completed:"手机已登录",cancelled:"已取消",rejected:"已拒绝手机登录",expired:"二维码已过期,请重新生成",unconfirmed:"未收到手机完成确认;已保存的手机登录仍可使用",failed:"登录凭据签发失败,请重新扫码"};function BH({controller:e,connectionName:t,embedded:r=!1}){var c,u,d;const n=e.status&&["approved","issuing","issued"].includes(e.status.state),s=r?"section":dn,i=r?"h2":Ur,a=r?"p":Zr,l=o.jsxs(s,{className:r?"space-y-5 rounded-xl border p-5":"sm:max-w-[460px]",children:[o.jsxs(Mn,{children:[o.jsxs(i,{children:["连接手机 · ",t]}),o.jsx(a,{children:"手机需能访问此电脑。扫码后,由你在这里确认登录。"})]}),e.addresses.length>0?o.jsxs("label",{className:"grid gap-2 text-sm",children:["连接地址",o.jsx("select",{className:"w-full rounded-md border bg-background p-2",value:e.address,disabled:e.busy||!!n,onChange:h=>e.generate(h.target.value),children:e.addresses.map(h=>o.jsx("option",{value:h,children:h},h))})]}):null,o.jsxs("div",{className:"grid min-h-[160px] content-center gap-4 py-2 text-center","aria-live":"polite",children:[e.qr&&((c=e.status)==null?void 0:c.state)==="waiting_scan"&&e.seconds>0&&!e.error?o.jsxs(o.Fragment,{children:[o.jsx(MH,{payload:JSON.stringify(e.qr)},e.qr.requestId),o.jsxs("p",{className:"text-sm text-muted-foreground",children:["剩余 ",e.seconds," 秒"]})]}):null,e.status?o.jsx("p",{children:OH[e.status.state]}):e.busy?o.jsx("p",{children:"正在准备连接…"}):null,((u=e.status)==null?void 0:u.state)==="pending_approval"?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"font-medium",children:[e.status.deviceName," 请求登录"]}),o.jsxs("div",{className:"flex justify-center gap-3",children:[o.jsx(Z,{disabled:e.busy||!!e.error,onClick:()=>void e.decide("approve"),children:"允许登录"}),o.jsx(Z,{variant:"outline",disabled:e.busy||!!e.error,onClick:()=>void e.decide("reject"),children:"拒绝"})]})]}):null,e.error?o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:e.error}):null]}),!n&&((d=e.status)==null?void 0:d.state)!=="completed"?o.jsx(Z,{variant:"outline",disabled:e.busy,onClick:()=>e.address?e.generate(e.address):void e.open(),children:"重新生成二维码"}):null,o.jsx("p",{className:"text-xs text-muted-foreground",children:"也可以在手机连接管理中手动填写地址,使用原有账号密码登录。"})]});return r?l:o.jsx(Qr,{open:e.opened,onOpenChange:h=>{h||e.close()},children:l})}class $h extends Error{constructor(t,r){super(t===404?"电脑端暂不支持扫码登录,或请求已失效。":t===410?"二维码已失效,请重新生成。":t===401?"当前登录已失效,请重新登录。":t===429?"请求较多,请稍后重试。":"连接请求未完成,请重试。"),this.status=t,this.retryAfter=r}}async function Vf(e,t,r,n){const s=await fetch(`${e.replace(/\/+$/,"")}/api/auth/mobile-login${r}`,{method:n===void 0?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",keepalive:r.endsWith("/cancel"),headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},...n===void 0?{}:{body:JSON.stringify(n)},signal:AbortSignal.timeout(15e3)});if(!s.ok)throw new $h(s.status,Number(s.headers.get("Retry-After"))||1);return s.json()}const FH=(e,t,r)=>Vf(e,t,"",r),$H=(e,t,r)=>Vf(e,t,`/${encodeURIComponent(r)}`),zH=(e,t,r,n)=>Vf(e,t,`/${encodeURIComponent(r)}/decision`,n),UH=(e,t,r)=>Vf(e,t,`/${encodeURIComponent(r)}/cancel`,{});function j1(e){if(new TextEncoder().encode(e).length>2048||e!==e.trim()||/[\\\s]/u.test(e))throw new Error("Invalid mobile connection address");const t=new URL(e),r=t.hostname.toLowerCase().replace(/\.$/,"");if(!/^https?:$/.test(t.protocol)||t.username||t.password||e.includes("?")||e.includes("#")||!r||r==="localhost"||r.endsWith(".localhost")||/^127\./.test(r)||r==="0.0.0.0"||r==="[::]"||r==="[::1]"||/^\[::ffff:(?:7f[0-9a-f]{2}:|0:0\])/i.test(r))throw new Error("Configure a phone-accessible HTTP(S) connection address");return t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}async function HH(e){var a,l,c;if(e.available===!1)throw new Error("电脑后端暂不可用,请恢复连接后重试。");if(e.id!==Vn||!e.isSystem)try{return[j1(e.url)]}catch{throw new Error("请配置手机可访问的连接地址;自定义本地转发地址不能用于扫码。")}const t=await((l=(a=window.electronAPI)==null?void 0:a.getRuntimeStatusReport)==null?void 0:l.call(a)),r=t==null?void 0:t.items.find(u=>u.id==="electron.packaged-backend"),n=(c=r==null?void 0:r.facts.find(u=>u.id==="electron.packaged-backend.address"))==null?void 0:c.value;if(!t||t.source.runtime!=="electron"||t.target.kind!=="local-host"||t.observedAt+t.validForMs<Date.now()||typeof n!="string"||n.replace(/\/+$/,"")!==e.url.replace(/\/+$/,""))throw new Error("暂时无法取得这台电脑的连接地址,请稍后重试。");const s=t.items.find(u=>u.id==="electron.local-network"),i=(s==null?void 0:s.state)==="healthy"?s.facts.filter(u=>u.id==="electron.local-network.primary"||u.id.startsWith("electron.local-network.candidate-")).flatMap(u=>{try{return[j1(String(u.value))]}catch{return[]}}):[];if(!i.length)throw new Error("未找到可分享的局域网地址,请检查网络或使用手动登录。");return[...new Set(i)]}const WH=["completed","cancelled","rejected","expired","unconfirmed","failed"],Cd=e=>e instanceof $h?e.message:"连接暂时失败,请重试。";function qH(e,t,r){const[n,s]=p.useState(!1),[i,a]=p.useState(e.name),l=p.useRef(e),[c,u]=p.useState([]),[d,h]=p.useState(""),[f,m]=p.useState(null),[g,v]=p.useState(null),[x,b]=p.useState(null),[_,C]=p.useState(!1),[S,w]=p.useState(Date.now()),y=p.useRef(0),N=p.useRef(null),E=p.useRef(t);E.current=t;const k=p.useRef(Promise.resolve()),D=p.useRef(!1),j=W(O=>{O instanceof $h&&O.status===401&&(r==null||r())}),R=W(O=>{O&&UH(e.url,E.current,O.qr.requestId).catch(()=>{})}),I=W(()=>{y.current+=1,R(N.current),N.current=null,s(!1),m(null),v(null),C(!1)}),T=W(O=>{const L=++y.current;R(N.current),N.current=null,h(O),m(null),v(null),b(null),C(!0),k.current=k.current.catch(()=>{}).then(async()=>{if(L===y.current)try{const B=await FH(e.url,E.current,{baseUrl:O,connectionName:l.current.name}),M={qr:B,generation:L};if(L!==y.current){R(M);return}N.current=M,m(B),v({requestId:B.requestId,state:"waiting_scan",expiresAt:B.expiresAt})}catch(B){L===y.current&&(b(Cd(B)),j(B))}finally{L===y.current&&C(!1)}})}),A=W(async()=>{const O=++y.current;l.current={...e},a(e.name),s(!0),C(!0),b(null),m(null),v(null);try{const L=await HH(e);if(O!==y.current)return;u(L),T(L[0])}catch(L){O===y.current&&(C(!1),b(L instanceof Error?L.message:Cd(L)))}}),P=W(async O=>{const L=N.current;if(!(!L||!(g!=null&&g.claimId)||g.state!=="pending_approval"||D.current)){D.current=!0,C(!0),b(null);try{const B=await zH(e.url,E.current,L.qr.requestId,{claimId:g.claimId,decision:O});L.generation===y.current&&v(B)}catch(B){L.generation===y.current&&(j(B),b(`${Cd(B)} 正在核对电脑端状态。`))}finally{D.current=!1,L.generation===y.current&&C(!1)}}});return p.useEffect(()=>{if(!n||!f)return;let O=!1,L=!1,B;const M=y.current,$=async()=>{if(O||L||document.hidden)return;if(D.current){B=setTimeout(()=>void $(),1e3);return}L=!0;let K=1e3,Y=!1;try{const te=await $H(e.url,E.current,f.requestId);!O&&M===y.current&&(v(te),b(null),Y=WH.includes(te.state))}catch(te){!O&&M===y.current&&(b(Cd(te)),j(te),te instanceof $h&&(K=Math.max(1e3,te.retryAfter*1e3),Y=[401,404,410].includes(te.status)))}finally{L=!1,!O&&!Y&&(B=setTimeout(()=>void $(),K))}},U=setInterval(()=>{document.hidden||w(Date.now())},1e3),F=()=>{clearTimeout(B),document.hidden||$()};return document.addEventListener("visibilitychange",F),$(),()=>{O=!0,clearTimeout(B),clearInterval(U),document.removeEventListener("visibilitychange",F)}},[n,f,e.url,j]),p.useEffect(()=>{const O=()=>{y.current+=1,R(N.current),N.current=null};return window.addEventListener("pagehide",O),()=>{window.removeEventListener("pagehide",O),O()}},[R]),{opened:n,open:A,close:I,connectionName:i,addresses:c,address:d,generate:T,qr:f,status:g,error:x,busy:_,decide:P,seconds:f?Math.max(0,Math.ceil((Date.parse(f.expiresAt)-S)/1e3)):0}}function KH({children:e,connection:t,token:r}){const n=qH(t,r);return o.jsxs(xN.Provider,{value:n.open,children:[e,o.jsx(BH,{controller:n,connectionName:n.connectionName})]})}const an="mt-1 h-9 w-full rounded-md border border-border bg-background px-3 text-sm";function A1(e){const t=e instanceof Error?e.message:String(e);return t.includes("BROWSER_BINDING_CONFLICT")?"此终端正在使用另一台桌面的浏览器。请先在原桌面断开浏览器通道,再重新选择。":t.includes("NEEDS_AUTH")?"远端登录已过期,请在「端口与隧道」中重新登录浏览器通道。":t.includes("DESKTOP_UNAVAILABLE")||t.includes("TUNNEL_CANCELLED")?"浏览器通道尚未就绪,请在「端口与隧道」中检查连接后重试。":"无法连接此终端的浏览器通道,请在「端口与隧道」中检查连接后重试。"}function bN(e){return(e instanceof Error?e.message:String(e)).replace(/^Error invoking remote method '[^']+': (?:Error: )?/,"").replace(/^REMOTE_DESKTOP_[A-Z_]+:\s*/,"")}const qc={disconnected:"未连接",connecting:"连接中",ready:"已建立",reconnecting:"正在重连",failed:"运行失败",disabled:"已关闭",waiting:"等待主机连接",starting:"启动中",needs_auth:"需要登录"};function VH({value:e,relayAddress:t,onChange:r,onReadyChange:n}){const s=e??{enabled:!1,listenAddress:t??"",port:15446,localAddress:"",localPort:48571,certificateFingerprint:""},[i,a]=p.useState(!1),[l,c]=p.useState(null),[u,d]=p.useState(!1),h=p.useRef(0),f=W(()=>s),m=W(()=>{++h.current}),g=W(async()=>{const v=++h.current;a(!0),d(!1),c(null),n(!1);try{const x=window.electronAPI;if(!(x!=null&&x.getLocalRemoteDesktopInfo))throw new Error("请更新 Runweave 桌面端以自动获取 RemoteDesk 信息。");const b=await x.getLocalRemoteDesktopInfo(),_=f();if(h.current!==v||!_.enabled)return;if(_.certificateFingerprint&&_.certificateFingerprint.toLowerCase()!==b.certificateFingerprint)throw new Error("本机 RemoteDesk 身份与原配置不符。请核对 Mac 并重新配对,不会自动替换原证书指纹。");r({..._,...b,autoDetectLocalHost:!0}),d(!0),n(!0)}catch(x){h.current===v&&c(bN(x))}finally{h.current===v&&a(!1)}});return p.useEffect(()=>(s.enabled?g():(d(!1),n(!1)),m),[s.enabled,g,m,n]),o.jsxs("fieldset",{className:"space-y-3 border-t border-border pt-3",children:[o.jsx("legend",{className:"font-medium",children:"RemoteDesk · 可选"}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:s.enabled,onChange:v=>r({...s,enabled:v.target.checked})}),"通过此主机远控本机 Mac"]}),s.enabled&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"保持 Runweave 和 RemoteDesk 共享服务运行。手机需接入中转服务器所在网络或 VPN,配对与控制权限仍由 RemoteDesk 管理。"}),o.jsxs("label",{className:"block",children:["中转服务器内网 IPv4 地址",o.jsx("input",{required:!0,className:an,value:s.listenAddress,onChange:v=>r({...s,listenAddress:v.target.value.trim()})})]}),o.jsxs("label",{className:"block",children:["手机远控端口",o.jsx("input",{required:!0,type:"number",min:1024,max:65535,className:an,value:s.port||"",onChange:v=>r({...s,port:Number(v.target.value)})})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"使用独立端口,不与 Runweave 远程访问共用。服务器需可通过 SSH 执行 Node.js 并允许端口转发。"}),o.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3","aria-live":"polite",children:[o.jsx("p",{className:"font-medium",children:"本机 RemoteDesk · 自动获取"}),i&&o.jsx("p",{className:"text-muted-foreground",children:"正在读取本机共享服务…"}),u&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["已自动获取:",s.localAddress,":",s.localPort]}),o.jsxs("details",{children:[o.jsx("summary",{className:"cursor-pointer text-muted-foreground",children:"查看证书指纹"}),o.jsx("p",{className:"break-all text-xs",children:s.certificateFingerprint})]})]}),l&&o.jsx("p",{role:"alert",className:"text-amber-600",children:l}),o.jsx(Z,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>void g(),children:i?"获取中…":"重新获取"})]})]})]})}function GH({host:e,runtime:t,busy:r,run:n}){var l,c;const s=e.remoteDesktop,i=t==null?void 0:t.remoteDesktop,a=(t==null?void 0:t.state)==="ready"&&(i==null?void 0:i.state)==="ready";return o.jsxs("div",{className:"space-y-2 border-t border-border pt-3","data-remote-desktop-state":(i==null?void 0:i.state)??"disabled",children:[o.jsx("h4",{className:"text-sm font-medium",children:"RemoteDesk"}),s!=null&&s.enabled?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm",children:a?"中转入口与 Host 证书已验证":(t==null?void 0:t.state)==="disconnected"?"主机已断开":qc[(i==null?void 0:i.state)??"waiting"]}),((t==null?void 0:t.error)||(i==null?void 0:i.error))&&o.jsx("p",{role:"alert",className:"text-sm text-amber-600",children:((l=t==null?void 0:t.error)==null?void 0:l.message)??((c=i==null?void 0:i.error)==null?void 0:c.message)}),o.jsxs("p",{className:"break-all text-sm",children:[s.listenAddress,":",s.port]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"先在局域网完成 Mac 配对,再在手机「Mac 桌面 → 编辑地址」启用 Runweave 隧道并填写此地址与端口。首次画面和控制需在手机确认。"}),(i==null?void 0:i.checkedAt)&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["最近检查:",new Date(i.checkedAt).toLocaleTimeString()]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:!a||r,onClick:()=>void n(()=>navigator.clipboard.writeText(i.address)),children:"复制远控地址"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:r,onClick:()=>void n(()=>window.electronAPI.retryTunnel(e.id,"remote-desktop")),children:"重新检测"})]})]}):o.jsx("p",{className:"text-xs text-muted-foreground",children:"未启用 · 编辑主机可配置手机远控中转。"})]})}function YH({value:e,onChange:t}){const r=e??{enabled:!1,listenAddress:"",port:15443};return o.jsxs("fieldset",{className:"space-y-3 border-t border-border pt-3",children:[o.jsx("legend",{className:"font-medium",children:"远程访问本机 · 可选"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"手机通过你的中转服务器访问这台 Mac,代码和 Agent 仍在本机运行。关闭时不建立此通道。"}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:r.enabled,onChange:n=>t({...r,enabled:n.target.checked})}),"启用远程访问本机"]}),r.enabled&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"block",children:["中转服务器内网 IPv4 地址",o.jsx("input",{required:!0,className:an,placeholder:"例如 192.168.1.10",value:r.listenAddress,onChange:n=>t({...r,listenAddress:n.target.value.trim()})})]}),o.jsxs("label",{className:"block",children:["手机访问端口",o.jsx("input",{required:!0,className:an,type:"number",min:1024,max:65535,value:r.port||"",onChange:n=>t({...r,port:Number(n.target.value)})})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"服务器需已安装 Node.js,SSH 可执行 node,且允许端口转发。Mac 和手机均需能访问此内网地址,必要时连接 VPN。保存后连接主机,桌面端会启动中转并检查入口。"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"重启后需先登录 Mac、启动 Runweave,并恢复网络和 SSH 认证;可勾选上方“启动桌面端时自动连接”。"})]})]})}function XH({host:e,runtime:t,busy:r,run:n}){var l,c;const s=e.remoteAccess,i=t==null?void 0:t.remoteAccess,a=(s==null?void 0:s.enabled)&&(t==null?void 0:t.state)==="ready"&&(i==null?void 0:i.state)==="ready";return o.jsxs("div",{className:"space-y-2 border-t border-border pt-3","data-remote-access-state":(i==null?void 0:i.state)??"disabled",children:[o.jsx("h4",{className:"text-sm font-medium",children:"远程访问本机"}),s!=null&&s.enabled?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm",children:a?"中转入口可用":(t==null?void 0:t.state)==="disconnected"?"主机已断开":qc[(i==null?void 0:i.state)??"waiting"]}),((t==null?void 0:t.error)||(i==null?void 0:i.error))&&o.jsx("p",{role:"alert",className:"text-sm text-amber-600",children:((l=t==null?void 0:t.error)==null?void 0:l.message)??((c=i==null?void 0:i.error)==null?void 0:c.message)}),o.jsxs("p",{className:"break-all text-sm",children:["http://",s.listenAddress,":",s.port]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"手机接入相同网络或 VPN 后,在连接管理中添加此地址,使用这台 Mac 的 Runweave 账号登录。"}),(i==null?void 0:i.checkedAt)&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["最近检查:",new Date(i.checkedAt).toLocaleTimeString()]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:!a||r,onClick:()=>void n(()=>navigator.clipboard.writeText(i.address)),children:"复制连接地址"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:r,onClick:()=>void n(()=>window.electronAPI.retryTunnel(e.id,"remote-access")),children:"重新检测"})]})]}):o.jsx("p",{className:"text-xs text-muted-foreground",children:"未启用 · 编辑主机可配置手机经中转访问这台电脑。"})]})}function Aa(e){const t=e.split(".");if(t.length!==4||t.some(s=>!/^(0|[1-9][0-9]{0,2})$/.test(s)||Number(s)>255))return!1;const[r,n]=t.map(Number);return r===10||r===172&&n>=16&&n<=31||r===192&&n===168}const cm=e=>typeof e=="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e),Ta=e=>Number.isInteger(e)&&Number(e)>0&&Number(e)<=65535,T1=e=>typeof e=="string"&&e.trim().length>0&&e.length<=120;function JH(e){if(!e||typeof e!="object")throw new Error("INVALID_TUNNEL_CONFIG");const t=e;if(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0||!Array.isArray(t.hosts)||t.hosts.length>64||!Array.isArray(t.backendEndpoints)||t.backendEndpoints.length>128)throw new Error("INVALID_TUNNEL_CONFIG");const r=t.hosts.map(s=>{if(!s||!cm(s.id)||!T1(s.name)||typeof s.sshTarget!="string"||!/^[a-zA-Z0-9_][a-zA-Z0-9_.@-]{0,254}$/.test(s.sshTarget)||typeof s.autoConnect!="boolean"||!Array.isArray(s.forwards)||s.forwards.length>64)throw new Error("INVALID_TUNNEL_HOST");const i=s.forwards.map(u=>{if(!u||!cm(u.id)||!T1(u.name)||!Ta(u.port)||typeof u.enabled!="boolean"||typeof u.path!="string"||u.path.length>2048||!u.path.startsWith("/")||u.path.startsWith("//")||u.path.includes("\\"))throw new Error("INVALID_TUNNEL_FORWARD");return{id:u.id,name:u.name.trim(),port:u.port,enabled:u.enabled,path:u.path}});if(new Set(i.map(u=>u.id)).size!==i.length||new Set(i.map(u=>u.port)).size!==i.length)throw new Error("DUPLICATE_TUNNEL_PORT");const a=s.remoteAccess;if(a&&(typeof a.enabled!="boolean"||typeof a.listenAddress!="string"||!Ta(a.port)||a.port<1024||(a.enabled||a.listenAddress!=="")&&!Aa(a.listenAddress)))throw new Error("远程访问需要有效的服务器内网 IPv4 地址及 1024–65535 端口");const l=s.remoteDesktop;if(l&&(typeof l.enabled!="boolean"||l.autoDetectLocalHost!==void 0&&typeof l.autoDetectLocalHost!="boolean"||typeof l.listenAddress!="string"||!Ta(l.port)||l.port<1024||typeof l.localAddress!="string"||!Ta(l.localPort)||typeof l.certificateFingerprint!="string"||(l.enabled?!Aa(l.listenAddress)||!Aa(l.localAddress)||!/^[a-fA-F0-9]{64}$/.test(l.certificateFingerprint):l.listenAddress!==""&&!Aa(l.listenAddress)||l.localAddress!==""&&!Aa(l.localAddress)||l.certificateFingerprint!==""&&!/^[a-fA-F0-9]{64}$/.test(l.certificateFingerprint))))throw new Error("RemoteDesk 需要有效的内网地址、端口和 Mac 的完整 SHA-256 证书指纹");if(l!=null&&l.enabled&&(a!=null&&a.enabled)&&l.listenAddress===a.listenAddress&&l.port===a.port)throw new Error("RemoteDesk 与 Runweave 远程访问需要不同的中转端口");const c=s.browser;if(!c||typeof c.enabled!="boolean"||!Ta(c.backendPort)||!WO(c.profileId)||!(c.approvedBrowserGroupId===null||typeof c.approvedBrowserGroupId=="string"&&c.approvedBrowserGroupId.length>0&&c.approvedBrowserGroupId.length<=512))throw new Error("INVALID_BROWSER_TUNNEL");return{id:s.id,name:s.name.trim(),sshTarget:s.sshTarget,...a?{remoteAccess:{enabled:a.enabled,listenAddress:a.listenAddress,port:a.port}}:{},...l?{remoteDesktop:{enabled:l.enabled,listenAddress:l.listenAddress,port:l.port,localAddress:l.localAddress,localPort:l.localPort,certificateFingerprint:l.certificateFingerprint.toLowerCase(),...l.autoDetectLocalHost!==void 0?{autoDetectLocalHost:l.autoDetectLocalHost}:{}}}:{},autoConnect:s.autoConnect,forwards:i,browser:{enabled:c.enabled,backendPort:c.backendPort,profileId:c.profileId,approvedBrowserGroupId:c.approvedBrowserGroupId}}});if(new Set(r.map(s=>s.id)).size!==r.length)throw new Error("DUPLICATE_TUNNEL_HOST");const n=t.backendEndpoints.map(s=>{if(!s||!cm(s.id)||!r.some(i=>i.id===s.hostId)||!Ta(s.remotePort))throw new Error("INVALID_BACKEND_ENDPOINT");return{id:s.id,hostId:s.hostId,remotePort:s.remotePort}});if(new Set(n.map(s=>s.id)).size!==n.length)throw new Error("DUPLICATE_BACKEND_ENDPOINT");return{expectedRevision:t.expectedRevision,hosts:r,backendEndpoints:n}}function QH({host:e,snapshot:t,onCancel:r,onSaved:n,embedded:s=!1}){var C,S;const[i,a]=p.useState(e),[l]=p.useState(()=>t.config.hosts.find(w=>w.id===e.id)??null),[c]=p.useState(()=>t.config.backendEndpoints.filter(w=>w.hostId===e.id)),[u,d]=p.useState(c),[h,f]=p.useState(null),[m,g]=p.useState(!1),[v,x]=p.useState(!1);va(s&&(JSON.stringify(i)!==JSON.stringify(e)||JSON.stringify(u)!==JSON.stringify(c)),s&&m);const b=w=>a({...i,...w}),_=W(async()=>{var w;if(!m){f(null),g(!0);try{let y=i;if((w=i.remoteDesktop)!=null&&w.enabled){if(!v)throw new Error("请先启动本机 RemoteDesk 并完成自动获取。");const D=await window.electronAPI.getLocalRemoteDesktopInfo();if(D.certificateFingerprint!==i.remoteDesktop.certificateFingerprint)throw new Error("本机 RemoteDesk 身份已改变,请核对并重新配对。");y={...i,remoteDesktop:{...i.remoteDesktop,...D,autoDetectLocalHost:!0}}}const N=t.config.hosts.find(D=>D.id===e.id)??null,E=t.config.backendEndpoints.filter(D=>D.hostId===e.id);if(JSON.stringify(N)!==JSON.stringify(l)||JSON.stringify(E)!==JSON.stringify(c))throw new Error("这台主机的配置已被其他操作修改,当前输入已保留。请重新打开编辑器核对后保存。");const k=JH({expectedRevision:t.config.revision,hosts:[...t.config.hosts.filter(D=>D.id!==e.id),y],backendEndpoints:[...t.config.backendEndpoints.filter(D=>D.hostId!==e.id),...u]});n(await window.electronAPI.saveTunnels(k))}catch(y){const N=bN(y);f(N.includes("CONFIG_REVISION_CONFLICT")?"配置刚被其他操作修改,当前输入已保留,请重试保存。":N)}finally{g(!1)}}});return o.jsx("form",{className:"space-y-3 rounded-xl border border-primary/40 p-4 text-sm",onSubmit:w=>{w.preventDefault(),_()},children:o.jsxs("fieldset",{disabled:m,className:"space-y-3",children:[o.jsx("h3",{className:"font-medium",children:t.config.hosts.some(w=>w.id===e.id)?"编辑主机":"添加主机"}),o.jsxs("label",{className:"block",children:["名称",o.jsx("input",{className:an,required:!0,value:i.name,onChange:w=>b({name:w.target.value})})]}),o.jsxs("label",{className:"block",children:["SSH 主机或配置别名",o.jsx("input",{className:an,required:!0,placeholder:"user@host 或 devbox",value:i.sshTarget,onChange:w=>b({sshTarget:w.target.value})})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"沿用本机 SSH 配置与密钥,请先确认终端中 SSH 可以连接。"}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:i.autoConnect,onChange:w=>b({autoConnect:w.target.checked})}),"启动桌面端时自动连接"]}),o.jsx(YH,{value:i.remoteAccess,onChange:w=>b({remoteAccess:w})}),o.jsx(VH,{value:i.remoteDesktop,relayAddress:(C=i.remoteAccess)==null?void 0:C.listenAddress,onChange:w=>b({remoteDesktop:w}),onReadyChange:x}),o.jsx("h4",{className:"border-t border-border pt-3 font-medium",children:"开发服务端口"}),i.forwards.map((w,y)=>o.jsxs("fieldset",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[o.jsxs("legend",{className:"sr-only",children:["端口 ",y+1]}),o.jsxs("label",{className:"block",children:["服务名称",o.jsx("input",{className:an,value:w.name,onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,name:N.target.value}:E)})})]}),o.jsxs("label",{className:"block",children:["端口(本地与远端相同)",o.jsx("input",{className:an,type:"number",min:"1",max:"65535",required:!0,value:w.port||"",onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,port:Number(N.target.value)}:E)})})]}),o.jsxs("label",{className:"block",children:["访问路径",o.jsx("input",{className:an,value:w.path,onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,path:N.target.value}:E)})})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:w.enabled,onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,enabled:N.target.checked}:E)})}),"启用转发"]}),o.jsx(Z,{type:"button",size:"sm",variant:"ghost",onClick:()=>b({forwards:i.forwards.filter(N=>N.id!==w.id)}),children:"移除端口"})]},w.id)),o.jsx(Z,{type:"button",size:"sm",variant:"outline",onClick:()=>b({forwards:[...i.forwards,{id:crypto.randomUUID(),name:"开发服务",port:3e3,path:"/",enabled:!0}]}),children:"添加端口"}),!s&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex items-center gap-2 border-t border-border pt-3",children:[o.jsx("input",{type:"checkbox",checked:i.browser.enabled,onChange:w=>b({browser:{...i.browser,enabled:w.target.checked}})}),"允许远端 Agent 使用本机 Browser"]}),i.browser.enabled&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"block",children:["远端 Backend 端口",o.jsx("input",{type:"number",className:an,min:"1",max:"65535",required:!0,value:i.browser.backendPort||"",onChange:w=>b({browser:{...i.browser,backendPort:Number(w.target.value)}})})]}),o.jsxs("label",{className:"block",children:["授权 Browser",o.jsx("select",{className:an,value:i.browser.profileId,onChange:w=>b({browser:{...i.browser,profileId:w.target.value}}),children:[1,2,3].map(w=>o.jsxs("option",{value:`profile-${w}`,children:["Browser ",w]},w))})]}),o.jsxs("label",{className:"block",children:["允许复用的工作组 ID(可选)",o.jsx("input",{className:an,value:i.browser.approvedBrowserGroupId??"",onChange:w=>b({browser:{...i.browser,approvedBrowserGroupId:w.target.value||null}})})]})]})]}),o.jsxs("details",{children:[o.jsx("summary",{className:"cursor-pointer text-muted-foreground",children:"高级 · Backend 访问入口"}),o.jsx("p",{className:"my-2 text-xs text-muted-foreground",children:"为只能通过 SSH 访问的 Backend 保留内部入口。删除入口后,引用它的连接将等待通道。"}),u.map(w=>o.jsxs("div",{className:"my-2 flex items-center gap-2",children:[o.jsxs("label",{children:["远端端口",o.jsx("input",{type:"number",min:"1",max:"65535",className:an,value:w.remotePort||"",onChange:y=>d(u.map(N=>N.id===w.id?{...N,remotePort:Number(y.target.value)}:N))})]}),o.jsx(Z,{type:"button",size:"sm",variant:"ghost",onClick:()=>d(u.filter(y=>y.id!==w.id)),children:"移除入口"})]},w.id)),o.jsx(Z,{type:"button",size:"sm",variant:"outline",onClick:()=>d([...u,{id:crypto.randomUUID(),hostId:e.id,remotePort:5001}]),children:"添加 Backend 入口"})]}),h&&o.jsx("p",{role:"alert",className:"text-red-500",children:h}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(Z,{type:"button",variant:"ghost",disabled:m,onClick:r,children:"取消"}),o.jsx(Z,{type:"submit",disabled:m||((S=i.remoteDesktop)==null?void 0:S.enabled)&&!v,children:m?"保存中…":"保存配置"})]})]})})}function ZH({host:e,runtime:t,run:r,busy:n}){const[s,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(!1),[d,h]=p.useState("");return o.jsxs("div",{className:"space-y-2 border-t border-border pt-3 text-sm",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx("h4",{className:"font-medium",children:"远端使用本机 Browser"}),o.jsx("span",{children:qc[(t==null?void 0:t.browser.state)??(e.browser.enabled?"waiting":"disabled")]})]}),e.browser.enabled&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Browser ",e.browser.profileId.slice(-1)," · 远端 Backend"," ",e.browser.backendPort]}),(t==null?void 0:t.browser.error)&&o.jsx("p",{role:"alert",className:"text-amber-600",children:t.browser.error.message}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:n||(t==null?void 0:t.state)!=="ready",onClick:()=>u(!c),children:"登录远端 Backend"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:n||(t==null?void 0:t.state)!=="ready",onClick:()=>void r(()=>window.electronAPI.retryTunnel(e.id)),children:"重试浏览器通道"}),(c||(t==null?void 0:t.browser.state)==="needs_auth")&&o.jsxs("form",{className:"space-y-2",onSubmit:f=>{f.preventDefault(),r(async()=>{try{const m=await window.electronAPI.loginTunnelBrowser({hostId:e.id,username:s,password:a});h(m.persistent?"登录已加密保存":"系统加密不可用,登录仅在本次运行有效"),u(!1)}finally{l("")}})},children:[o.jsxs("label",{className:"block",children:["用户名",o.jsx("input",{autoComplete:"username",className:an,value:s,onChange:f=>i(f.target.value)})]}),o.jsxs("label",{className:"block",children:["密码",o.jsx("input",{type:"password",autoComplete:"current-password",className:an,value:a,onChange:f=>l(f.target.value)})]}),o.jsx(Z,{size:"sm",type:"submit",disabled:n||(t==null?void 0:t.state)!=="ready",children:"登录并启用"})]}),d&&o.jsx("p",{role:"status",children:d})]})]})}function zh(e){const t=e.trim();if(!t)return{ok:!1,error:"Enter a URL"};if(/^https?:\/\//i.test(t))return Ed(t);if(/^\d+$/.test(t)){const r=Number(t);return!Number.isInteger(r)||r<1||r>65535?{ok:!1,error:"Port must be between 1 and 65535"}:Ed(`http://127.0.0.1:${t}`)}return/^(localhost|127(?:\.\d{1,3}){3}|\[::1\]):\d{1,5}(\/.*)?$/i.test(t)?Ed(`http://${t}`):Ed(`https://${t}`)}function Ed(e){try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:"Only http and https URLs are supported"}:t.port==="0"?{ok:!1,error:"Port must be between 1 and 65535"}:{ok:!0,url:t.toString()}}catch{return{ok:!1,error:"Enter a valid http or https URL"}}}async function Kc(e){var i,a,l,c,u,d;const t=zh(e.url);if(!t.ok)throw new Error(t.error);if(((i=window.electronAPI)==null?void 0:i.isElectron)!==!0||!window.electronAPI.terminalBrowserCreateTab)return window.open(t.url,"_blank","noopener,noreferrer"),null;const r=e.profileId?null:await((l=(a=window.electronAPI).terminalBrowserGetProfilePreferences)==null?void 0:l.call(a)),n=e.profileId??(e.projectId?(c=r==null?void 0:r.worktrees[e.projectId])==null?void 0:c.preferredProfileId:null)??(r==null?void 0:r.defaultProfileId)??PE;let s=e.placement;if(s.kind==="active-group"){const h=await((d=(u=window.electronAPI).terminalBrowserGetWorkspace)==null?void 0:d.call(u,n)),f=h==null?void 0:h.tabs.find(m=>m.tabId===h.activeTabId);s=f?{kind:"current-group",groupId:f.browserGroupId,openerTabId:f.tabId}:{kind:"new-group"}}return await window.electronAPI.terminalBrowserCreateTab(s.kind==="current-group"?{profileId:n,placement:"current-group",groupId:s.groupId,openerTabId:s.openerTabId,url:t.url,source:e.source}:{profileId:n,placement:"new-group",url:t.url,source:e.source}),n}const eW=()=>({id:crypto.randomUUID(),name:"",sshTarget:"",autoConnect:!1,forwards:[],browser:{enabled:!1,backendPort:5001,profileId:"profile-1",approvedBrowserGroupId:null}});function tW({embedded:e=!1}){var C;const{snapshot:t,open:r,error:n,notice:s,setOpen:i,setSnapshot:a,setError:l,setNotice:c}=Xr(),[u,d]=p.useState(null),[h,f]=p.useState(!1);p.useEffect(()=>{const S=window.electronAPI;if(!(S!=null&&S.isElectron)||e)return;let w=!1;const y=[S.onTunnelsChanged(a),S.onTunnelNotice(c),S.onOpenTunnels(()=>i(!0))];return S.listTunnels().then(N=>{w||a(N)}).catch(N=>{w||l(String(N))}),()=>{w=!0,y.forEach(N=>N())}},[e,a,l,c,i]);const m=W(async S=>{if(!h){f(!0),l(null);try{await S()}catch(w){l(w instanceof Error?w.message:String(w))}finally{f(!1)}}}),g=W(async S=>{!t||!window.confirm(`删除 ${S.name}?此主机的隧道将停止,远端任务不受影响。`)||await m(async()=>a(await window.electronAPI.saveTunnels({expectedRevision:t.config.revision,hosts:t.config.hosts.filter(w=>w.id!==S.id),backendEndpoints:t.config.backendEndpoints.filter(w=>w.hostId!==S.id)})))});if(!((C=window.electronAPI)!=null&&C.isElectron))return null;const v=e?"section":Il,x=e?"h2":Nl,b=e?"p":Rl,_=o.jsxs(v,{className:e?"space-y-3":"w-full overflow-y-auto sm:w-[560px]",children:[o.jsx(x,{children:"端口与隧道"}),o.jsx(b,{children:"管理这台电脑的 SSH 通道。切换连接或关闭面板不影响运行;退出桌面端后停止。"}),o.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:t!=null&&t.owner.devSessionId?"Dev Session · 独立配置":"本机用户配置"}),o.jsx(Z,{size:"sm",disabled:h||!t,onClick:()=>d(eW()),children:"添加 SSH 主机"})]}),n&&o.jsxs("div",{role:"alert",className:"rounded-lg border border-red-500/30 p-3 text-sm text-red-500",children:[n,o.jsx(Z,{variant:"ghost",size:"sm",onClick:()=>void m(async()=>a(await window.electronAPI.listTunnels())),children:"重新读取"})]}),s&&o.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:s}),u&&t?o.jsx(QH,{host:u,embedded:e,snapshot:t,onCancel:()=>d(null),onSaved:S=>{a(S),d(null),c("配置已保存,运行结果见各通道状态。")}},u.id):null,!t&&!n&&o.jsx("p",{children:"读取配置中…"}),(t==null?void 0:t.config.hosts.length)===0&&!u&&o.jsx("div",{className:"rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground",children:e?"添加 SSH 主机后,可配置开发服务端口、Backend 入口和手机远程接入。":"添加 SSH 主机后,可配置手机远程访问本机、转发开发服务端口,或允许远端 Agent 使用本机 Browser。"}),t==null?void 0:t.config.hosts.map(S=>{const w=t.hosts.find(y=>y.hostId===S.id);return o.jsxs("section",{className:"space-y-4 rounded-xl border border-border p-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"font-semibold",children:S.name}),o.jsx("p",{className:"text-xs text-muted-foreground",children:S.sshTarget}),o.jsx("p",{className:"mt-1 text-sm",children:qc[(w==null?void 0:w.state)??"disconnected"]})]}),o.jsxs("div",{className:"flex gap-1",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:h,onClick:()=>void m(()=>(w==null?void 0:w.state)==="ready"||(w==null?void 0:w.state)==="connecting"||(w==null?void 0:w.state)==="reconnecting"?window.electronAPI.disconnectTunnel(S.id):window.electronAPI.connectTunnel(S.id)),children:(w==null?void 0:w.state)==="ready"||(w==null?void 0:w.state)==="connecting"||(w==null?void 0:w.state)==="reconnecting"?"断开":"连接"}),o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>d(structuredClone(S)),children:"编辑"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:h,onClick:()=>void g(S),children:"删除"})]})]}),(w==null?void 0:w.error)&&o.jsx("p",{role:"alert",className:"text-sm text-amber-600",children:w.error.message}),o.jsxs("div",{className:"space-y-2 border-t border-border pt-3",children:[o.jsx("h4",{className:"text-sm font-medium",children:"开发服务端口"}),S.forwards.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"尚未配置"}):S.forwards.map(y=>{const N=w==null?void 0:w.forwards[y.id];return o.jsxs("div",{className:"rounded-lg bg-muted/40 p-3 text-sm",children:[o.jsxs("div",{className:"flex justify-between gap-2",children:[o.jsxs("span",{children:[y.name," · ",y.port," → ",y.port]}),o.jsx("span",{children:qc[(N==null?void 0:N.state)??(y.enabled?"waiting":"disabled")]})]}),o.jsxs("p",{className:"mt-1 break-all text-xs text-muted-foreground",children:["http://127.0.0.1:",y.port,y.path]}),(N==null?void 0:N.error)&&o.jsx("p",{role:"alert",className:"mt-2 text-amber-600",children:N.error.message}),(N==null?void 0:N.state)==="failed"&&o.jsx(Z,{size:"sm",variant:"ghost",disabled:h,onClick:()=>void m(()=>window.electronAPI.retryTunnel(S.id,y.id)),children:"重试转发"}),(N==null?void 0:N.state)==="ready"&&o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>void m(()=>Kc({url:`http://127.0.0.1:${y.port}${y.path}`,profileId:S.browser.profileId,placement:{kind:"new-group"}})),children:"打开网页"})]},y.id)})]}),o.jsx(XH,{host:S,runtime:w,run:m,busy:h}),o.jsx(GH,{host:S,runtime:w,busy:h,run:m}),!e&&o.jsx(ZH,{host:S,runtime:w,run:m,busy:h})]},S.id)})]});return e?_:o.jsxs(o.Fragment,{children:[s&&!r&&o.jsxs(eo,{kind:"tunnel",noticeKey:s,onDismiss:()=>c(null),className:"rounded-lg border border-border bg-background p-3 text-sm text-foreground shadow-lg",children:[o.jsx("p",{children:s}),o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>{i(!0),c(null)},children:"查看端口与隧道"})]}),o.jsx(Pu,{open:r,onOpenChange:i,children:_})]})}class ih extends Error{constructor(t,r){super(r.error.message),this.status=t,this.detail=r}get uncertain(){return![400,404,409,413].includes(this.status)||this.detail.error.code==="IDEMPOTENCY_KEY_REUSED"}}function _N(e){const t=new URL(e.trim());if(!["https:","http:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("请输入完整的随记服务地址");if(t.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("远程随记服务需要 HTTPS");return t.href.replace(/\/+$/,"")}class rW{constructor(t,r){St(this,"endpoint");St(this,"saved");St(this,"lifetime",new AbortController);St(this,"renewing");this.storage=r,this.endpoint=_N(t),this.saved=r.session}get active(){return!this.lifetime.signal.aborted}assertActive(){if(!this.active)throw new DOMException("服务连接已切换","AbortError")}cancel(){this.lifetime.abort()}async store(t){this.assertActive();const r={tokens:t,expiresAt:Date.now()+t.expiresIn*1e3};return await this.storage.persist(r),this.assertActive(),this.saved=r,r}async raw(t,r,n,s,i,a){var c;this.assertActive();const l=await fetch(this.endpoint+t,{method:r,body:n,cache:"no-store",credentials:"omit",redirect:"error",signal:AbortSignal.any([this.lifetime.signal,AbortSignal.timeout(3e4),...a?[a]:[]]),headers:{...n instanceof FormData?{}:{"Content-Type":"application/json"},...s?{Authorization:`Bearer ${s}`}:{},...i?{"Idempotency-Key":i}:{}}});if(this.assertActive(),!l.ok){const u=await l.json();throw(c=u==null?void 0:u.error)!=null&&c.message?new ih(l.status,u):new Error(`服务响应异常(${l.status}),请手动确认结果`)}return l}async login(t,r){const n=await this.raw("/api/auth/login","POST",JSON.stringify({username:t,password:r}));return await this.store(await n.json()),this.info()}refresh(){if(this.renewing)return this.renewing;const t=this.saved;return t?(this.renewing=(async()=>{let r;try{r=await this.raw("/api/auth/refresh","POST",JSON.stringify({refreshToken:t.tokens.refreshToken}))}catch(s){if(!(s instanceof ih)||s.status!==401||!this.storage.credentials)throw s;r=await this.raw("/api/auth/login","POST",JSON.stringify(this.storage.credentials))}const n=await r.json();if(n.ownerId!==t.tokens.ownerId||n.serverId!==t.tokens.serverId)throw new Error("服务身份已改变,请重新登录;原草稿仍保留");return this.store(n)})().finally(()=>{this.renewing=void 0}),this.renewing):Promise.reject(new Error("请登录随记"))}async authorized(t,r,n,s,i){let a=this.saved;if(!a)throw new Error("请登录随记");a.expiresAt<Date.now()+6e4&&(a=await this.refresh());try{return await this.raw(t,r,n,a.tokens.accessToken,s,i)}catch(l){if(!(l instanceof ih&&l.status===401&&r==="GET"))throw l;const c=await this.refresh();return this.raw(t,r,n,c.tokens.accessToken,s,i)}}async request(t,r="GET",n,s,i){const l=await(await this.authorized(t,r,n instanceof FormData?n:n===void 0?void 0:JSON.stringify(n),s,i)).json();return this.assertActive(),l}async file(t){const n=await(await this.authorized(`/api/suiji/v1/attachments/${encodeURIComponent(t)}/content`,"GET")).blob();return this.assertActive(),n}async restore(){if(!this.saved&&this.storage.credentials){const{username:t,password:r}=this.storage.credentials;return this.login(t,r)}return this.info()}async info(){var r,n;const t=await this.request("/api/suiji/v1/info");if(t.protocolVersion!==1||t.ownerId!==((r=this.saved)==null?void 0:r.tokens.ownerId)||t.serverId!==((n=this.saved)==null?void 0:n.tokens.serverId))throw new Error("服务身份或协议已改变,请重新登录;原草稿仍保留");return t}async logout(){const t=this.saved;if(this.cancel(),await this.storage.persist(void 0,!0),this.storage.credentials=void 0,this.saved=void 0,t)try{await fetch(this.endpoint+"/api/auth/logout",{method:"POST",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(5e3),headers:{Authorization:`Bearer ${t.tokens.accessToken}`}})}catch{}}}class nW{constructor(t,r,n="production"){St(this,"scope");St(this,"database");this.scope=JSON.stringify([...n==="development"?[n]:[],t,r.serverId,r.ownerId]),this.database=new Promise((s,i)=>{const a=indexedDB.open("suiji-local-v1",1);a.onupgradeneeded=()=>a.result.createObjectStore("drafts"),a.onerror=()=>i(new Error("无法打开本机草稿存储")),a.onsuccess=()=>s(a.result)})}async get(t){const r=await this.database;return new Promise((n,s)=>{const i=r.transaction("drafts","readonly").objectStore("drafts").get(this.scope+":"+t);i.onerror=()=>s(new Error("读取本机草稿失败")),i.onsuccess=()=>n(i.result)})}async set(t,r){const n=structuredClone(r),s=await this.database;await new Promise((i,a)=>{const l=s.transaction("drafts","readwrite");l.objectStore("drafts").put(n,this.scope+":"+t),l.oncomplete=()=>i(),l.onabort=l.onerror=()=>a(new Error("本机草稿未保存,可能空间不足,请保留页面并重试"))})}async remove(t){const r=await this.database;await new Promise((n,s)=>{const i=r.transaction("drafts","readwrite");i.objectStore("drafts").delete(this.scope+":"+t),i.oncomplete=()=>n(),i.onabort=i.onerror=()=>s(new Error("本机确认状态未保存,请手动重试"))})}close(){this.database.then(t=>t.close()).catch(()=>{})}}const gce=e=>e==="production"?"正式":"开发",Vc="suiji.accounts.v1",Xx=()=>{const e=window.electronAPI;if(!(e!=null&&e.loadSuijiState)||!e.saveSuijiProfile||!e.selectSuijiEnvironment)throw new Error("请更新桌面客户端以启用随记账户保存");return e};async function Ic(){var r;if((r=window.electronAPI)!=null&&r.isElectron)return Xx().loadSuijiState();const e=ht.getItem(Vc),t=e?JSON.parse(e):{active:"production",profiles:{production:{endpoint:ht.getItem("suiji.endpoint.v1")??"",username:""},development:{endpoint:"http://127.0.0.1:4783",username:""}}};for(const n of["production","development"]){const s=g0.getItem(`${Vc}:${n}`);s&&(t.profiles[n].session=JSON.parse(s))}return t}async function D1(e,t){var n;if((n=window.electronAPI)!=null&&n.isElectron)return Xx().saveSuijiProfile(e,t);const r=await Ic();r.profiles[e]=t,t.session?g0.setItem(`${Vc}:${e}`,JSON.stringify(t.session)):g0.removeItem(`${Vc}:${e}`),yN(r)}function yN(e){ht.setItem(Vc,JSON.stringify({...e,profiles:Object.fromEntries(Object.entries(e.profiles).map(([t,r])=>[t,{endpoint:r.endpoint,username:r.username}]))}))}async function sW(e){var r;if((r=window.electronAPI)!=null&&r.isElectron)return Xx().selectSuijiEnvironment(e);const t=await Ic();t.active=e,yN(t)}function iW(){const[e,t]=p.useState(),[r,n]=p.useState(""),[s,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(!0),[d,h]=p.useState(""),[f,m]=p.useState(!0),[g,v]=p.useState(),x=p.useRef(void 0),b=p.useRef(!0),_=p.useRef(0),C=I=>{n(I.endpoint),i(I.username),l(I.password??"")},S=W(async(I,T=!1)=>{var B;const A=++_.current;(B=x.current)==null||B.cancel(),v(void 0),u(!0),h("");const P=I.active;let O={...I.profiles[P]},L;try{if(T&&(O={endpoint:_N(r),username:s.trim(),password:a}),m(T||!O.session&&!O.password),!O.endpoint||!T&&!O.session&&!O.password)return;L=new rW(O.endpoint,{session:O.session,credentials:O.password?{username:O.username,password:O.password}:void 0,persist:async($,U)=>{if(!b.current||A!==_.current)throw new DOMException("连接已切换","AbortError");const F={...O,session:$,...U?{password:void 0}:{}};await D1(P,F),O=F,b.current&&A===_.current&&t(K=>K&&{...K,profiles:{...K.profiles,[P]:F}})}}),x.current=L;const M=T?await L.login(O.username,O.password):await L.restore();if(!b.current||A!==_.current)return;v({client:L,info:M,store:new nW(L.endpoint,M,P)}),C(O)}catch(M){b.current&&A===_.current&&(M instanceof ih&&M.status===401&&(m(!0),l("")),h(M instanceof Error?M.message:"连接失败"))}finally{b.current&&A===_.current&&u(!1)}}),w=p.useRef(null),y=W(async()=>{if(w.current)return w.current;const I=(async()=>{u(!0),h("");try{const T=await Ic();if(!b.current)return;t(T),C(T.profiles[T.active]),await S(T)}catch(T){b.current&&(h(T instanceof Error?T.message:"账户读取失败"),u(!1))}})();w.current=I;try{await I}finally{w.current===I&&(w.current=null)}}),N=W(()=>{var I;b.current=!1,++_.current,(I=x.current)==null||I.cancel(),w.current=null});p.useEffect(()=>(b.current=!0,N),[y,N]);const E=W(async I=>{var T;if(!(!e||c||I===e.active)){(T=x.current)==null||T.cancel(),++_.current,v(void 0),u(!0),h("");try{await sW(I);const A=await Ic();t(A),C(A.profiles[I]),await S(A)}catch(A){h(A instanceof Error?A.message:"环境切换失败"),u(!1)}}}),k=W(async()=>{if(!(!e||c)){u(!0),h("");try{const I=x.current;v(void 0),I?await I.logout():await D1(e.active,{endpoint:r,username:s}),++_.current,x.current=void 0,v(void 0),l(""),m(!0);const T=await Ic();t(T),C(T.profiles[T.active])}catch(I){h(I instanceof Error?I.message:"退出失败")}finally{u(!1)}}}),D=W(()=>e||w.current?w.current??Promise.resolve():y()),j=W(I=>b.current&&x.current===I&&I.active),R=W(()=>{var I;(I=x.current)==null||I.cancel(),++_.current,v(void 0),m(!0)});return{accounts:e,endpoint:r,setEndpoint:n,username:s,setUsername:i,password:a,setPassword:l,busy:c,message:d,connection:g,needsLogin:f,setNeedsLogin:m,ensure:D,initialize:y,connect:S,switchEnvironment:E,logout:k,editAccount:R,isCurrent:j}}const wN=p.createContext(null);function oW({children:e}){const t=iW();return o.jsx(wN.Provider,{value:t,children:e})}function aW(){const e=p.useContext(wN);if(!e)throw new Error("SuijiConnectionProvider is missing");return e}const $o=Qn(e=>({open:!1,opened:!1,revision:0,setOpen:t=>e(r=>({open:t,opened:r.opened||t,revision:r.revision+(r.open===t?0:1)}))}));function lW(e){const t=Gt(),r=p.useRef(t.key);r.current=t.key;const n=p.useRef(!0),s=p.useRef(!1),[i,a]=p.useState(null);p.useEffect(()=>(n.current=!0,()=>{n.current=!1}),[]);const l=W(async(u,d)=>{var v,x;if(s.current||!d())return;const h=r.current,f=()=>n.current&&h===r.current&&d(),m=zh(u);if(!m.ok){a({url:u,isCurrent:f,message:m.error});return}s.current=!0,a(null);let g=f;try{if(!((v=window.electronAPI)!=null&&v.terminalBrowserCreateTab)){if(!((x=window.electronAPI)!=null&&x.openExternal))throw new Error("当前桌面版本无法打开链接,请复制地址后继续。");await window.electronAPI.openExternal(m.url);return}const b=Vt.getState(),_=b.activeBrowserProfileId,C=b.browserActivationRevision;Yr.flushSync(()=>{e(),$o.getState().setOpen(!1)});const S=$o.getState().revision;if(g=()=>{const w=Vt.getState();return f()&&$o.getState().revision===S&&w.activeBrowserProfileId===_&&w.browserActivationRevision===C},!g())return;await Kc({url:m.url,profileId:_,placement:{kind:"new-group"}}),g()&&Vt.getState().activateBrowser(_,null)}catch(b){g()&&($o.getState().setOpen(!0),a({url:u,isCurrent:f,message:b instanceof Error?b.message:"打开网页失败,请主动重试。"}))}finally{s.current=!1}}),c=W(async()=>{var u;if(!(!(i!=null&&i.isCurrent())||!((u=window.electronAPI)!=null&&u.openExternal)||s.current)){s.current=!0;try{const d=zh(i.url);if(!d.ok)throw new Error(d.error);await window.electronAPI.openExternal(d.url),i.isCurrent()&&a(null)}catch(d){i.isCurrent()&&a({...i,message:d instanceof Error?d.message:"外部打开失败。"})}finally{s.current=!1}}});return{openLink:l,failure:i!=null&&i.isCurrent()?i:null,retry:()=>{i!=null&&i.isCurrent()&&l(i.url,i.isCurrent)},openExternal:c,dismissError:()=>a(null)}}const cW=p.lazy(()=>Vr(()=>import("./connection-DbcKyIr4.js"),__vite__mapDeps([5,1,6])));function uW(){var l;const{open:e,opened:t,setOpen:r}=$o(),n=p.useRef(null),s=hr(n,"window"),i=lW(()=>{var c;return(c=n.current)==null?void 0:c.close()}),a=Gt();return p.useEffect(()=>{a.pathname.startsWith("/terminal")||r(!1)},[a.pathname,r]),p.useEffect(()=>{var c,u;e?(c=n.current)==null||c.showModal():(u=n.current)==null||u.close()},[e]),o.jsx("dialog",{ref:s,"aria-label":"随记抽屉","aria-modal":"true",className:"suiji-drawer fixed inset-y-0 left-auto right-0 m-0 h-dvh max-h-none w-[480px] max-w-full overflow-hidden border-0 border-l bg-background p-0 text-foreground shadow-2xl backdrop:bg-black/30",onCancel:c=>{c.preventDefault(),r(!1)},onClick:c=>{c.target===c.currentTarget&&c.clientX<c.currentTarget.getBoundingClientRect().left&&r(!1)},children:o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i.failure?o.jsxs("div",{role:"alert",className:"shrink-0 space-y-2 border-b p-4 text-sm",children:[o.jsxs("p",{children:["打开网页失败:",i.failure.message]}),o.jsx("p",{children:"请求结果可能未确认,请先检查 Browser 中是否已打开。"}),o.jsxs("div",{className:"flex gap-3",children:[o.jsx("button",{type:"button",onClick:i.retry,children:"重试打开"}),(l=window.electronAPI)!=null&&l.openExternal?o.jsx("button",{type:"button",onClick:()=>void i.openExternal(),children:"在默认浏览器打开"}):null,o.jsx("button",{type:"button",onClick:i.dismissError,children:"关闭提示"})]})]}):null,o.jsx("div",{className:"min-h-0 flex-1",children:t?o.jsx(p.Suspense,{fallback:o.jsx("p",{role:"status",className:"p-5",children:"正在打开随记…"}),children:o.jsx(cW,{active:e,onClose:()=>r(!1),onOpenLink:i.openLink})}):null})]})})}function SN(e,t){return e===1013&&["Terminal output recovery required","Terminal initial output queue exceeded","Terminal recovery queue exceeded","Terminal recovery unavailable; reconnect"].includes((t==null?void 0:t.trim())??"")}const dW=1e3,Gc=5,hW=5e3,fW=250,pW=1012,mW=new Set([1e3,1008,1011,1013]),gW=new Set(["Terminal runtime not found"]);function vW(e){var r;if(e.terminalStatus==="exited"||(e.reconnectAttempt??0)>=Gc||mW.has(e.code)&&!SN(e.code,e.reason))return!1;if(e.code===pW)return!0;const t=(r=e.reason)==null?void 0:r.trim();return!(t&&gW.has(t))}function Uh(e){return Math.min(fW*2**Math.max(e,0),hW)}function CN(e){const t=e.trim();return t?t.startsWith("https://")?t.replace("https://","wss://"):t.startsWith("http://")?t.replace("http://","ws://"):t:window.location.origin.replace(/^http/,"ws")}function xW(e,t,r){const n=new URLSearchParams({token:t,after:r??""});return`${CN(e)}/ws/terminal-events?${n.toString()}`}function bW(e){let t=null;for(const r of e)(t===null||Number(r.id)>Number(t))&&(t=r.id);return t}function EN(e){const{apiBase:t,token:r,getCursor:n,setCursor:s,onAuthExpired:i,onResyncRequired:a,onTerminalEvents:l}=e,c=p.useRef(null),u=p.useRef(r),d=p.useRef(null),h=p.useRef(0),f=p.useRef(null),m=p.useRef(null),g=p.useRef(new Set),v=p.useRef(null),x=p.useRef(null),b=p.useRef(null),_=p.useRef(n),C=p.useRef(s),S=p.useRef(a),w=p.useRef(l),[y,N]=p.useState("connecting"),[E,k]=p.useState(null),[D,j]=p.useState(0),[R,I]=p.useState(null),[T,A]=p.useState(!1);p.useEffect(()=>{u.current=r},[r]),p.useEffect(()=>{_.current=n},[n]),p.useEffect(()=>{C.current=s},[s]),p.useEffect(()=>{S.current=a},[a]),p.useEffect(()=>{w.current=l},[l]),p.useEffect(()=>{b.current=null},[t]);const P=W((L,B)=>{const M=L.filter(U=>g.current.has(U.id)?!1:(g.current.add(U.id),!0));if(M.length===0)return;w.current(M,B);const $=bW(M);$&&(x.current=$,C.current($))}),O=W(()=>{g.current=new Set,x.current=null,C.current(null),S.current()});return p.useEffect(()=>{N("connecting"),k(null),A(!1),g.current=new Set,x.current=null;let L=!1;const B=()=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null)},M=()=>{if(f.current!==null)return;const Y=Date.now();f.current=Y,I(Y),B(),m.current=window.setTimeout(()=>{m.current=null,A(!0)},3e4)},$=()=>{f.current=null,I(null),A(!1),h.current=0,j(0),B(),N("connected")};M();const U=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},F=async()=>{if(!L){U(),N("connecting"),k(null);try{const Y=await Z6(t,u.current);if(L)return;let te=_.current()??x.current??Y.baselineEventId;b.current!==null&&b.current!==Y.streamId&&(O(),te=null),b.current=Y.streamId,x.current=te;const H=new WebSocket(xW(t,Y.ticket,te));c.current=H,H.addEventListener("open",()=>{c.current===H&&(v.current=null,N("connecting"))}),H.addEventListener("close",G=>{if(c.current===H){if(c.current=null,G.code===1008&&G.reason==="Unauthorized"){N("closed"),i==null||i();return}if(!L){M();const z=h.current;h.current=z+1,j(z+1),N("connecting"),U(),d.current=window.setTimeout(()=>{F()},Uh(z));return}N("closed"),(v.current||G.reason)&&k(v.current||G.reason||"Terminal events connection closed.")}}),H.addEventListener("message",G=>{if(c.current===H)try{const z=JSON.parse(String(G.data));if(z.type==="connected"){if(z.streamId!==b.current){b.current=z.streamId,O(),H.close(1012,"Terminal event stream changed");return}z.gap&&O(),$();return}if(z.type==="terminal-events"){P(z.events,z.delivery);return}if(z.type==="terminal-event"){P([z.event],z.delivery);return}z.type==="error"&&(v.current=z.message,k(z.message),z.message==="Unauthorized"&&(i==null||i()))}catch{v.current="Invalid terminal events message",k("Invalid terminal events message")}})}catch(Y){if(L)return;if(Y instanceof De&&Y.status===401){i==null||i();return}k(String(Y)),M();const te=h.current;h.current=te+1,j(te+1),U(),d.current=window.setTimeout(()=>{F()},Uh(te))}}},K=window.setTimeout(()=>{F()},0);return()=>{var Y;L=!0,window.clearTimeout(K),U(),h.current=0,f.current=null,B(),v.current=null,(Y=c.current)==null||Y.close(),c.current=null}},[t,P,i,O]),{connectionStatus:y,error:E,reconnectAttempt:D,failureSince:R,failureExpired:T}}function _W(e,t,r){return me(e,"/api/attention/slots",{headers:{Authorization:`Bearer ${t}`},cache:"no-store",signal:r})}function Jx(e){const{apiBase:t,token:r,connectionId:n,enabled:s=!0}=e,[i,a]=p.useState("checking"),[l,c]=p.useState(null);return p.useEffect(()=>{if(!s){c(null),a("checking");return}if(!t||!r||!n){c(null),a("disconnected");return}let u=!1,d=null;const h=()=>{d==null||d.abort(),d=new AbortController,_W(t,r,d.signal).then(m=>{u||(c(m),a("ready"))}).catch(()=>{!u&&!(d!=null&&d.signal.aborted)&&(c(null),a("disconnected"))})};a("checking"),h();const f=window.setInterval(h,4e3);return()=>{u=!0,window.clearInterval(f),d==null||d.abort()}},[t,n,s,r]),{state:i,snapshot:l}}function yW(e,t,r){return me(e,"/api/terminal/unread",{headers:{Authorization:`Bearer ${t}`},cache:"no-store",signal:r})}const kN=Qn(e=>({byId:{},update:(t,r)=>e(n=>({byId:{...n.byId,[t]:r}}))}));function IN(e){return JSON.stringify([e.url,e.generation??0])}function NN(e,t){const{id:r,url:n,available:s}=e,i=IN(e);p.useEffect(()=>{const a=kN.getState,l=()=>{const g=a().byId[r];return(g==null?void 0:g.source)===i?g.snapshot:null},c=(g,v)=>a().update(r,{source:i,snapshot:g,stale:v});if(!t){c(null,!1);return}if(!n||s===!1){c(l(),!0);return}let u=!1,d=null,h=!1;const f=async()=>{if(h)return;h=!0;const g=new AbortController;d=g;const v=window.setTimeout(()=>g.abort(),8e3);try{const x=await yW(n,t,g.signal);if(u)return;if(typeof x.hostId!="string"||!x.hostId||!Number.isSafeInteger(x.revision)||x.revision<0||!Number.isSafeInteger(x.count)||x.count<0)throw new Error("Invalid completion snapshot");const b=l();if((b==null?void 0:b.hostId)===x.hostId&&b.revision>x.revision)return;c(x,!1)}catch(x){if(!u){const b=x instanceof De&&[401,403].includes(x.status);c(b?null:l(),!0)}}finally{window.clearTimeout(v),h=!1}};f();const m=window.setInterval(()=>void f(),4e3);return()=>{u=!0,window.clearInterval(m),d==null||d.abort()}},[r,n,s,i,t])}function wW(e,t){const r=kN(n=>n.byId);return p.useMemo(()=>{var u,d;const n=h=>{const f=r[h.id];return(f==null?void 0:f.source)===IN(h)?f:void 0},s=new Map;for(const h of e){const f=n(h);if(!(f!=null&&f.snapshot))continue;const m=s.get(f.snapshot.hostId);(!m||m.snapshot.revision<f.snapshot.revision||m.snapshot.revision===f.snapshot.revision&&m.stale&&!f.stale)&&s.set(f.snapshot.hostId,f)}const i={};for(const h of e){const f=n(h);if(f!=null&&f.snapshot){const m=s.get(f.snapshot.hostId);i[h.id]={count:m.snapshot.count,stale:f.stale}}}const a=e.find(h=>h.id===t),l=a?(d=(u=n(a))==null?void 0:u.snapshot)==null?void 0:d.hostId:null,c=l?[...s.entries()].reduce((h,[f,m])=>h+(f===l?0:m.snapshot.count),0):0;return{byId:i,otherTotal:c}},[e,t,r])}const Gf=Qn(e=>({byConnectionId:{},update:(t,r)=>e(n=>({byConnectionId:{...n.byConnectionId,[t]:{projects:[],sessions:[],attention:null,observedAt:null,status:"checking",...n.byConnectionId[t],...r}}}))})),P1=new Map;function RN(e,t){var i,a;const r=P1.get(e.id),n=new Set(t.slots.map(l=>l.attentionId)),s=new Set([...r??[],...n]);for(;s.size>500;)s.delete(s.values().next().value);if(P1.set(e.id,s),!!r)for(const l of t.slots)r.has(l.attentionId)||l.state==="working"||(a=(i=window.electronAPI)==null?void 0:i.showAttentionNotification)==null||a.call(i,{connectionId:e.id,attentionId:l.attentionId,parentProjectId:l.parentProjectId,projectId:l.projectId,terminalSessionId:l.terminalSessionId,panelId:l.panelId,title:`${e.name} · ${l.projectName}`,body:l.title}).catch(()=>{})}function SW({connection:e,token:t,onAuthExpired:r}){const n=Gf(u=>u.update),s=Jx({apiBase:e.url,token:t,connectionId:e.id}),[i,a]=p.useState(0),l=p.useRef(null),c=EN({apiBase:e.url,token:t,getCursor:()=>l.current,setCursor:u=>{l.current=u},onAuthExpired:r,onResyncRequired:()=>a(u=>u+1),onTerminalEvents:()=>a(u=>u+1)});return p.useEffect(()=>{s.state==="ready"&&s.snapshot&&(n(e.id,{attention:s.snapshot}),RN(e,s.snapshot))},[s.snapshot,s.state,e,n]),p.useEffect(()=>{let u=!1;return Promise.all([Hv(e.url,t),_u(e.url,t)]).then(([d,h])=>{u||n(e.id,{projects:d,sessions:h,observedAt:new Date().toISOString(),status:"ready"})}).catch(()=>{u||n(e.id,{status:"disconnected"})}),()=>{u=!0}},[e.id,e.url,i,t,n]),p.useEffect(()=>{c.connectionStatus!=="connected"?n(e.id,{status:"disconnected"}):a(u=>u+1)},[e.id,c.connectionStatus,n]),null}function jN({connection:e,token:t,status:r,onAuthExpired:n}){NN(e,r==="authenticated"?t:null);const s=Gf(i=>i.update);return p.useEffect(()=>{!e.url||e.available===!1?s(e.id,{status:"disconnected"}):r==="checking"?s(e.id,{status:"checking"}):(r==="unauthenticated"||!t)&&s(e.id,{status:"needs_auth"})},[e.available,e.id,e.url,r,t,s]),!e.url||r!=="authenticated"||!t||e.available===!1?null:o.jsx(SW,{connection:e,token:t,onAuthExpired:n},`${e.id}:${e.generation??0}`)}function CW({connection:e}){const{token:t,status:r,clearToken:n}=hx({apiBase:e.url,connectionId:e.id,isElectron:!0,webStorageKey:"viewer.auth.token"});return o.jsx(jN,{connection:e,token:t,status:r,onAuthExpired:n})}function EW({connection:e,token:t}){NN(e,t);const r=Gf(s=>s.update),n=Jx({apiBase:e.url,token:t,connectionId:e.id,enabled:e.available!==!1});return p.useEffect(()=>{n.state==="ready"&&n.snapshot&&(r(e.id,{attention:n.snapshot}),RN(e,n.snapshot))},[n.snapshot,n.state,e,r]),null}function kW({connections:e,activeConnectionId:t,activeToken:r,activeAuthStatus:n,onActiveAuthExpired:s,observeActive:i}){return o.jsxs(o.Fragment,{children:[e.filter(a=>a.id!==t).map(a=>o.jsx(CW,{connection:a},a.id)),i&&e.filter(a=>a.id===t).map(a=>o.jsx(jN,{connection:a,token:r,status:n,onAuthExpired:s},`active:${a.id}`)),!i&&e.filter(a=>a.id===t).map(a=>o.jsx(EW,{connection:a,token:n==="authenticated"?r:null},`attention:${a.id}`))]})}var Yf="DropdownMenu",[IW]=bi(Yf,[Wf]),hn=Wf(),[NW,AN]=IW(Yf),TN=e=>{const{__scopeDropdownMenu:t,children:r,dir:n,open:s,defaultOpen:i,onOpenChange:a,modal:l=!0}=e,c=hn(t),u=p.useRef(null),[d,h]=Su({prop:s,defaultProp:i??!1,onChange:a,caller:Yf});return o.jsx(NW,{scope:t,triggerId:hi(),triggerRef:u,contentId:hi(),open:d,onOpenChange:h,onOpenToggle:p.useCallback(()=>h(f=>!f),[h]),modal:l,children:o.jsx(xI,{...c,open:d,onOpenChange:h,dir:n,modal:l,children:r})})};TN.displayName=Yf;var DN="DropdownMenuTrigger",PN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...s}=e,i=AN(DN,r),a=hn(r);return o.jsx(bI,{asChild:!0,...a,children:o.jsx(or.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...s,ref:kf(t,i.triggerRef),onPointerDown:st(e.onPointerDown,l=>{!n&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:st(e.onKeyDown,l=>{n||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});PN.displayName=DN;var RW="DropdownMenuPortal",LN=e=>{const{__scopeDropdownMenu:t,...r}=e,n=hn(t);return o.jsx(_I,{...n,...r})};LN.displayName=RW;var MN="DropdownMenuContent",ON=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=AN(MN,r),i=hn(r),a=p.useRef(!1);return o.jsx(yI,{id:s.contentId,"aria-labelledby":s.triggerId,...i,...n,ref:t,onCloseAutoFocus:st(e.onCloseAutoFocus,l=>{var c;a.current||(c=s.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:st(e.onInteractOutside,l=>{const c=l.detail.originalEvent,u=c.button===0&&c.ctrlKey===!0,d=c.button===2||u;(!s.modal||d)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ON.displayName=MN;var jW="DropdownMenuGroup",BN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(wI,{...s,...n,ref:t})});BN.displayName=jW;var AW="DropdownMenuLabel",FN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(SI,{...s,...n,ref:t})});FN.displayName=AW;var TW="DropdownMenuItem",$N=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(CI,{...s,...n,ref:t})});$N.displayName=TW;var DW="DropdownMenuCheckboxItem",zN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(EI,{...s,...n,ref:t})});zN.displayName=DW;var PW="DropdownMenuRadioGroup",LW=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(kI,{...s,...n,ref:t})});LW.displayName=PW;var MW="DropdownMenuRadioItem",UN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(II,{...s,...n,ref:t})});UN.displayName=MW;var OW="DropdownMenuItemIndicator",HN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(NI,{...s,...n,ref:t})});HN.displayName=OW;var BW="DropdownMenuSeparator",WN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(RI,{...s,...n,ref:t})});WN.displayName=BW;var FW="DropdownMenuArrow",$W=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(jI,{...s,...n,ref:t})});$W.displayName=FW;var zW="DropdownMenuSubTrigger",qN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(AI,{...s,...n,ref:t})});qN.displayName=zW;var UW="DropdownMenuSubContent",KN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(TI,{...s,...n,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});KN.displayName=UW;var HW=TN,WW=PN,qW=LN,VN=ON,KW=BN,GN=FN,YN=$N,XN=zN,JN=UN,QN=HN,ZN=WN,eR=qN,tR=KN;const $u=HW,zu=WW,VW=KW,GW=p.forwardRef(({className:e,inset:t,children:r,...n},s)=>o.jsxs(eR,{ref:s,className:Xe("flex cursor-default select-none items-center rounded-md px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted",t&&"pl-8",e),...n,children:[r,o.jsx(Jr,{className:"ml-auto h-4 w-4"})]}));GW.displayName=eR.displayName;const YW=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"intersection");return o.jsx(tR,{ref:n,className:Xe("z-50 min-w-[8rem] overflow-hidden rounded-xl border border-border/60 bg-popover p-1 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",e),...t})});YW.displayName=tR.displayName;const Ll=p.forwardRef(({className:e,sideOffset:t=8,...r},n)=>{const s=hr(n,"intersection");return o.jsx(qW,{children:o.jsx(VN,{ref:s,sideOffset:t,className:Xe("z-50 min-w-[14rem] overflow-hidden rounded-2xl border border-border/60 bg-popover/95 p-1.5 text-popover-foreground shadow-[0_24px_80px_-36px_rgba(17,24,39,0.8)] backdrop-blur-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...r})})});Ll.displayName=VN.displayName;const Bt=p.forwardRef(({className:e,inset:t,...r},n)=>o.jsx(YN,{ref:n,className:Xe("relative flex cursor-default select-none items-center gap-2 rounded-xl px-3 py-2.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));Bt.displayName=YN.displayName;const XW=p.forwardRef(({className:e,children:t,checked:r,...n},s)=>o.jsxs(XN,{ref:s,className:Xe("relative flex cursor-default select-none items-center rounded-xl py-2.5 pl-8 pr-3 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:r,...n,children:[o.jsx("span",{className:"absolute left-3 flex h-4 w-4 items-center justify-center",children:o.jsx(QN,{children:o.jsx(di,{className:"h-4 w-4"})})}),t]}));XW.displayName=XN.displayName;const JW=p.forwardRef(({className:e,children:t,...r},n)=>o.jsxs(JN,{ref:n,className:Xe("relative flex cursor-default select-none items-center rounded-xl py-2.5 pl-8 pr-3 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[o.jsx("span",{className:"absolute left-3 flex h-4 w-4 items-center justify-center",children:o.jsx(QN,{children:o.jsx(hE,{className:"h-2.5 w-2.5 fill-current"})})}),t]}));JW.displayName=JN.displayName;const rR=p.forwardRef(({className:e,inset:t,...r},n)=>o.jsx(GN,{ref:n,className:Xe("px-3 py-2 text-xs font-medium uppercase tracking-[0.22em] text-muted-foreground/75",t&&"pl-8",e),...r}));rR.displayName=GN.displayName;const nR=p.forwardRef(({className:e,...t},r)=>o.jsx(ZN,{ref:r,className:Xe("-mx-1 my-1 h-px bg-border/60",e),...t}));nR.displayName=ZN.displayName;function Xf({connections:e,activeConnectionId:t,activeConnectionName:r,onSelectConnection:n,onOpenConnectionManager:s,className:i}){var f;const[a,l]=p.useState(!1),c=wW(e,t),u=LH(),d=vN(),h=r??((f=e.find(m=>m.id===t))==null?void 0:f.name)??"未选择连接";return o.jsxs($u,{open:a,onOpenChange:l,children:[o.jsx(zu,{asChild:!0,children:o.jsxs(Z,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(m=>!m),className:`relative overflow-visible ${i??"rounded-full border border-border/60 bg-background/60 px-3 text-[0.72rem] text-muted-foreground backdrop-blur"}`,children:[o.jsx("span",{className:"mr-2 text-[0.62rem] uppercase tracking-[0.24em] text-muted-foreground/70",children:"当前连接"}),o.jsx("span",{className:"max-w-[14rem] truncate",children:h}),o.jsx(dE,{className:"ml-2 h-3.5 w-3.5 opacity-70"}),c.otherTotal>0?o.jsx("span",{className:"absolute -right-1.5 -top-1 inline-flex h-[19px] min-w-[19px] items-center justify-center rounded-full border-2 border-background bg-[#30d158] px-1 text-[11px] font-bold leading-none text-[#07140a] tabular-nums","aria-label":`其他连接 ${c.otherTotal} 个未读完成终端`,"data-testid":"connection-completion-total",children:c.otherTotal}):null]})}),o.jsxs(Ll,{align:"start",className:"w-[18rem]",children:[o.jsx(rR,{children:"切换连接"}),e.map(m=>{const g=m.id===t,v=c.byId[m.id];return o.jsxs(Bt,{className:g?"bg-slate-800/80":void 0,onSelect:()=>{n(m.id),l(!1)},children:[o.jsx(Cf,{className:"h-4 w-4 text-muted-foreground"}),o.jsxs("span",{className:"min-w-0 flex-1 py-1",children:[o.jsx("span",{className:"block truncate font-medium",children:m.name}),o.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:g?"当前连接":v!=null&&v.stale||m.available===!1?"离线 · 上次同步":v?"已连接":"尚未检测"})]}),v&&v.count>0?o.jsx("span",{className:"inline-flex h-[19px] min-w-[19px] items-center justify-center rounded-full bg-[#30d158] px-1 text-[11px] font-bold leading-none text-[#07140a] tabular-nums","aria-label":`${m.name} ${v.count} 个未读完成终端`,title:v.stale?"离线 · 上次同步":void 0,"data-testid":"connection-completion-count",children:v.count}):null,g?o.jsx(di,{className:"h-4 w-4 text-primary"}):null]},m.id)}),o.jsx(nR,{}),d?o.jsx(Bt,{onSelect:()=>{l(!1),d()},children:"Codex 额度"}):null,u?o.jsx(Bt,{onSelect:()=>{l(!1),u()},children:"连接手机"}):null,o.jsxs(Bt,{onSelect:()=>{s(),l(!1)},children:[o.jsx(BL,{className:"h-4 w-4 text-primary"}),o.jsx("span",{children:"连接管理"})]})]})]})}function L1({connection:e,connections:t,onSelectConnection:r,onOpenConnectionManager:n,onReconnect:s}){const i=Gf(l=>l.byConnectionId[e.id]),a=i!=null&&i.observedAt?new Date(i.observedAt).toLocaleString():null;return o.jsxs("main",{className:"flex min-h-screen flex-col gap-5 bg-slate-950 p-8 text-slate-100",children:[o.jsx(Xf,{connections:t,activeConnectionId:e.id,onSelectConnection:r,onOpenConnectionManager:n}),o.jsxs("section",{className:"max-w-lg space-y-3 rounded-xl border border-slate-700 p-5",children:[o.jsxs("h1",{className:"text-lg font-semibold",children:[e.name," · ",e.remoteStatus==="connecting"||e.remoteStatus==="reconnecting"?"正在重连":"连接不可用"]}),o.jsx("p",{className:"text-sm text-slate-300",children:e.statusMessage??"等待 SSH 通道,可在端口与隧道中连接主机"}),a?o.jsxs("p",{className:"text-xs text-slate-400",children:["上次终端状态更新:",a,"。下方为历史信息,不代表终端仍在运行。"]}):null,i?o.jsxs("p",{className:"text-sm text-slate-300",children:["已记录 ",i.projects.length," 个项目、",i.sessions.length," 个终端。"]}):null,o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{onClick:s,children:"打开端口与隧道"}),o.jsx(Z,{variant:"outline",onClick:n,children:"连接管理"})]})]})]})}const oh=new Map;function QW(e,t){return[...oh.values()].some(r=>r.apiBase===e&&r.terminalSessionId===t)}function ZW(e,t,r){const n=`/terminal/${encodeURIComponent(e)}`,s=Tn(t);return new Promise(i=>{let a=!1,l=null;const c=h=>{a||(a=!0,window.clearInterval(d),r.removeEventListener("abort",u),i(h))},u=()=>c(!1);r.addEventListener("abort",u,{once:!0});const d=window.setInterval(()=>{const h=tt.getState();if(!(window.location.pathname===n&&h.activeParentProjectId===s&&h.activeProjectId===t&&h.activeSessionId===e)){l=null;return}l??(l=performance.now()),performance.now()-l>=100&&c(!0)},25);r.aborted&&c(!1)})}function eq({activeConnectionId:e,apiBase:t,enabled:r,token:n}){const s=Cr();p.useEffect(()=>{var c,u,d,h;if(!r)return;const i=new Map,a=(u=(c=window.electronAPI)==null?void 0:c.onAttentionOpenCancelled)==null?void 0:u.call(c,f=>{var m;return(m=i.get(f))==null?void 0:m.abort()}),l=(h=(d=window.electronAPI)==null?void 0:d.onAttentionOpenIntent)==null?void 0:h.call(d,f=>{const m=new AbortController,g=m.signal;i.set(f.requestId,m),oh.set(f.requestId,{apiBase:t,terminalSessionId:f.terminalSessionId});const v=window.setTimeout(()=>m.abort(),Math.max(0,f.deadlineAt-Date.now()));let x=!1;(async()=>{var y,N;const b=async E=>{var k,D;g.aborted||await((D=(k=window.electronAPI)==null?void 0:k.reportAttentionOpenResult)==null?void 0:D.call(k,E))};if(!e||f.connectionId!==e||!n){await b({requestId:f.requestId,status:"connection_unavailable",message:"Connection changed before Slot opened"});return}const C=(await _u(t,n,g).catch(E=>{if(g.aborted)throw E;return[]})).find(E=>E.terminalSessionId===f.terminalSessionId);if(!C){await b({requestId:f.requestId,status:"session_not_found",message:"Terminal Session no longer exists"});return}if(Bo(window.location.pathname)){await b({requestId:f.requestId,status:"connection_unavailable",message:"请从管理页面左上角返回终端后再打开会话"});return}if(tt.getState().selectProjectContext(Tn(C.projectId),C.projectId,f.terminalSessionId),s(`/terminal/${encodeURIComponent(f.terminalSessionId)}`),!await ZW(f.terminalSessionId,C.projectId,g))return;g.throwIfAborted();let S=!1;f.panelId&&(S=await Uv(t,n,f.terminalSessionId,f.panelId,g).then(()=>!1).catch(E=>{if(g.aborted)throw E;return!0})),g.throwIfAborted(),g.throwIfAborted();const w=S?{requestId:f.requestId,status:"opened_with_panel_fallback",message:"Session opened; original Panel is unavailable"}:{requestId:f.requestId,status:"opened"};if(f.completionRevision!==null){if(x=await((N=(y=window.electronAPI)==null?void 0:y.authorizeAttentionCompletion)==null?void 0:N.call(y,w))===!0,!x)return;const E=await Fc(t,n,f.terminalSessionId,{acknowledgedCompletionRevision:f.completionRevision},g);tt.getState().setCompletionMarkers(k=>{const D=k[f.terminalSessionId];if(!D||D>E.acknowledgedCompletionRevision)return k;const j={...k};return delete j[f.terminalSessionId],j});return}g.throwIfAborted(),await b(w)})().catch(async b=>{var _,C;x||g.aborted||await((C=(_=window.electronAPI)==null?void 0:_.reportAttentionOpenResult)==null?void 0:C.call(_,{requestId:f.requestId,status:"session_not_found",message:b instanceof Error?b.message:"Slot open failed"}))}).finally(()=>{window.clearTimeout(v),i.get(f.requestId)===m&&(i.delete(f.requestId),oh.delete(f.requestId))})});return()=>{l==null||l(),a==null||a();for(const[f,m]of i)m.abort(),oh.delete(f);i.clear()}},[e,t,r,s,n])}function tq(e){const[t,r]=p.useState(!1),{snapshot:n,state:s}=Jx({apiBase:e.apiBase,token:e.token,connectionId:e.connectionId,enabled:e.enabled&&t});p.useEffect(()=>{const i=window.electronAPI;if(!e.enabled||!(i!=null&&i.getCompanionEnabled)||!i.onCompanionEnabledChanged)return;let a=!1;const l=i.onCompanionEnabledChanged(r);return i.getCompanionEnabled().then(c=>{a||r(c)}).catch(()=>{}),()=>{a=!0,l()}},[e.enabled]),p.useEffect(()=>{var i,a;!e.enabled||!t||(a=(i=window.electronAPI)==null?void 0:i.publishCompanionPresentation)==null||a.call(i,{connectionId:e.connectionId,snapshot:n,state:s}).catch(()=>{})},[t,e.connectionId,e.enabled,n,s])}function rq({children:e}){const[t,r]=p.useState(null),[n,s]=p.useState(!0);return p.useEffect(()=>{},[]),t?o.jsxs("main",{className:"min-h-screen bg-background p-6 text-foreground","data-testid":"dev-session-backend-mismatch",children:[o.jsx("h1",{className:"text-lg font-semibold",children:"Dev Session backend mismatch"}),o.jsxs("p",{className:"mt-2 text-sm",children:["Session: ","unknown"]}),o.jsx("p",{className:"mt-1 text-sm",children:t})]}):n?e:o.jsx("main",{className:"min-h-screen bg-background","data-testid":"dev-session-backend-checking"})}const M1=767;function nq({viewportWidth:e,coarsePointer:t,isElectron:r=!1,override:n=null}){return n==="desktop"||n==="mobile"?n:r?"desktop":e<=M1||t&&e<=M1?"mobile":"desktop"}function sq(e){const t=new URLSearchParams(e).get("clientMode");return t==="desktop"||t==="mobile"?t:null}function O1(e){return typeof window>"u"?"desktop":nq({viewportWidth:window.innerWidth,coarsePointer:window.matchMedia("(pointer: coarse)").matches,isElectron:e,override:sq(window.location.search)})}function iq(e){const[t,r]=p.useState(()=>O1(e));return p.useEffect(()=>{const n=window.matchMedia("(pointer: coarse)"),s=()=>{r(O1(e))};return s(),window.addEventListener("resize",s),n.addEventListener("change",s),()=>{window.removeEventListener("resize",s),n.removeEventListener("change",s)}},[e]),t}function si({align:e="center",children:t,className:r,content:n,side:s="bottom"}){const[i,a]=p.useState(!1),l=hr(void 0,"intersection",i);return o.jsxs("span",{className:Xe("relative inline-flex",r),onBlurCapture:()=>a(!1),onClickCapture:()=>a(!1),onFocusCapture:()=>a(!0),onPointerDownCapture:()=>a(!1),onPointerEnter:()=>a(!0),onPointerLeave:()=>a(!1),children:[t,o.jsx("span",{ref:l,role:"tooltip","aria-hidden":!i,className:Xe("pointer-events-none absolute z-[80] w-max max-w-64 rounded-md border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] font-normal leading-4 text-slate-200 shadow-lg transition-opacity delay-150",i?"visible opacity-100":"invisible opacity-0",e==="center"&&"left-1/2 -translate-x-1/2",e==="start"&&"left-0",e==="end"&&"right-0",s==="bottom"?"top-full mt-1.5":"bottom-full mb-1.5"),children:n})]})}const um={unhealthy:"border-red-500/50 bg-red-500/10 text-red-700 dark:text-red-200",recovering:"border-amber-500/50 bg-amber-500/10 text-amber-700 dark:text-amber-200",checking:"border-border/70 bg-background/70 text-muted-foreground",blocked:"border-border/70 bg-muted/60 text-muted-foreground",healthy:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-200",unconfigured:"border-border/70 bg-muted/60 text-muted-foreground",disabled:"border-border/70 bg-muted/60 text-muted-foreground",unsupported:"border-border/70 bg-muted/60 text-muted-foreground"};function Sa(e){const{overallState:t,unhealthyCapabilityIds:r,warningCapabilityIds:n,panelOpen:s,setPanelOpen:i}=Au(),a=r.length,l=n.length,c=a>0?"error":l>0?"warning":"none",u=`运行状态${a?` · ${a} 个异常服务`:""}${l?` · ${l} 个服务需关注`:""}`,d=c==="error"?um.unhealthy:c==="warning"?um.recovering:um[t],h=o.jsxs("button",{type:"button",className:Xe("inline-flex h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border px-2 text-xs shadow-sm transition hover:bg-black/5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",e.iconOnly&&"relative w-8 justify-center gap-0 rounded-md px-0",e.className,d),"data-runtime-status-state":t,"data-runtime-status-attention":c,"aria-label":`${u},点击查看详情`,"aria-haspopup":"dialog","aria-expanded":s,title:e.iconOnly?void 0:`${u},点击查看详情`,onClick:()=>i(!0),children:[c!=="none"?o.jsx(pa,{className:"h-3.5 w-3.5 shrink-0"}):o.jsx(cs,{className:"h-3.5 w-3.5 shrink-0"}),e.iconOnly?null:o.jsx("span",{children:c==="error"?"异常":c==="warning"?"Warning":"状态"}),[{count:a,kind:"error",tone:"bg-red-600",label:"异常服务"},{count:l,kind:"warning",tone:"bg-amber-600",label:"服务需关注"}].filter(({count:f})=>f>0).map(({count:f,kind:m,tone:g,label:v},x)=>o.jsx("span",{className:Xe("shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-semibold text-white",g,e.iconOnly&&"absolute -right-1 flex h-3 min-w-3 items-center justify-center px-0.5 text-[8px] leading-none",e.iconOnly&&(x===0?"-top-1":"-bottom-1")),"aria-label":`${f} 个${v}`,"data-runtime-status-badge":m,children:f},m))]});return e.iconOnly?o.jsx(si,{align:"end",content:u,children:h}):h}function oq({apiBase:e,connectionId:t,isElectron:r,connections:n=[],connectionName:s,onSwitchConnection:i,onOpenConnectionManager:a,onSuccess:l}){var E;const c=(E=ju())==null?void 0:E.active;$v();const[u,d]=p.useState("admin"),[h,f]=p.useState(""),[m,g]=p.useState(!1),[v,x]=p.useState(null),[b,_]=p.useState(!1),C=p.useRef(null),S=p.useRef(null),w=b&&!u?"Please enter your username.":null,y=b&&!h?"Please enter your password.":null,N=W(async()=>{var k;if(!m){if(_(!0),x(null),!u||!h){(k=(u?S:C).current)==null||k.focus();return}g(!0);try{const D=await Bk(e,{username:u,password:h},r?{clientType:"electron",connectionId:t}:{clientType:"web"});l(D)}catch(D){if(D instanceof De&&D.status===400){x("Please check your username and password and try again.");return}if(D instanceof De&&D.status===401){x("Incorrect username or password.");return}x(String(D))}finally{g(!1)}}});return o.jsxs("main",{className:c?"relative max-w-lg py-2":"relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-10 sm:px-6",children:[!c&&o.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(70,130,145,0.18),transparent_30%),radial-gradient(circle_at_bottom_left,rgba(195,172,135,0.16),transparent_35%)]"}),o.jsxs("section",{className:c?"relative w-full rounded-md border bg-card p-4":"animate-fade-rise relative w-full max-w-md rounded-[2rem] border border-border/60 bg-card/82 p-7 shadow-[0_34px_120px_-72px_rgba(17,24,39,0.82)] backdrop-blur-xl sm:p-9",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.38em] text-muted-foreground/70",children:"Runweave"}),o.jsx(Sa,{className:"max-w-56"}),r&&s&&i&&a?o.jsx(Xf,{connections:n,activeConnectionId:t??null,activeConnectionName:s,onSelectConnection:i,onOpenConnectionManager:a,className:"h-9 rounded-full border border-border/60 bg-background/60 px-3 text-[0.72rem] text-muted-foreground backdrop-blur"}):null]}),o.jsxs("form",{className:c?"mt-4 space-y-3":"mt-8 space-y-4",noValidate:!0,onSubmit:k=>{k.preventDefault(),N()},children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"username",children:"Username"}),o.jsx("input",{ref:C,id:"username",autoComplete:"username",required:!0,"aria-invalid":!!w,"aria-describedby":w?"username-error":void 0,value:u,onChange:k=>{d(k.target.value),x(null)},className:c?"h-8 w-full rounded-md border bg-background px-3 text-sm":"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"}),w?o.jsx("p",{id:"username-error",className:"text-sm text-red-500",role:"alert",children:w}):null]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"password",children:"Password"}),o.jsx("input",{ref:S,id:"password",type:"password",autoComplete:"current-password",required:!0,"aria-invalid":!!y,"aria-describedby":y?"password-error":void 0,value:h,onChange:k=>{f(k.target.value),x(null)},className:c?"h-8 w-full rounded-md border bg-background px-3 text-sm":"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"}),y?o.jsx("p",{id:"password-error",className:"text-sm text-red-500",role:"alert",children:y}):null]}),v&&o.jsx("p",{className:"text-sm text-red-500",role:"alert",children:v}),o.jsx(Z,{type:"submit",className:c?"mt-2 h-8 text-sm":"mt-2 h-12 w-full rounded-full text-sm",disabled:m,children:m?"Entering...":"Continue"})]})]})]})}function aq({returnTo:e="/terminal",apiBase:t,connectionId:r,isElectron:n,connections:s,connectionName:i,onSwitchConnection:a,onOpenConnectionManager:l,onSuccess:c}){const u=Cr();return o.jsx(o.Fragment,{children:o.jsx(oq,{apiBase:t,connectionId:r,isElectron:n,connections:s,connectionName:i,onSwitchConnection:a,onOpenConnectionManager:l,onSuccess:d=>{c(d),u(e,{replace:!0})}})})}function lq(){const[e,t]=p.useState(null);return p.useEffect(()=>{var l;const r=(l=window.electronAPI)==null?void 0:l.getTerminalBadgeStatus;if(!r)return;let n=!1,s=!1;const i=async()=>{if(!s){s=!0;try{const c=await r();n||t(c)}catch{n||t(null)}finally{s=!1}}};i();const a=window.setInterval(()=>{i()},2e3);return()=>{n=!0,window.clearInterval(a)}},[]),e?o.jsxs("p",{className:"mt-3 text-sm text-muted-foreground",role:"status",children:[e.state==="ready"?`未读已同步 · ${e.count} 个终端`:e.reason,e.state!=="ready"&&e.count!==null?` · 上次同步 ${e.count} 个终端`:""]}):null}function cq({embedded:e=!1,onManageTunnels:t,connections:r,activeId:n,onAdd:s,onRemove:i,onSelect:a,onEdit:l,onReconnect:c}){var B;const[u,d]=p.useState(r.length===0),[h,f]=p.useState(""),[m,g]=p.useState(""),[v,x]=p.useState(""),b=Xr(M=>M.snapshot),_=Xr(M=>M.setOpen),[C,S]=p.useState(!1),[w,y]=p.useState(null),[N,E]=p.useState(null),[k,D]=p.useState(""),[j,R]=p.useState(""),[I,T]=p.useState(null),A=async M=>{S(!0),y(null);try{const $=new AbortController,U=setTimeout(()=>$.abort(),5e3),F=await fetch(`${M.replace(/\/+$/,"")}/health`,{signal:$.signal});return clearTimeout(U),F.ok?(y("connected"),!0):(y("unreachable"),!1)}catch{return y("unreachable"),!1}finally{S(!1)}},P=async()=>{const M=h.trim(),$=m.trim();if(!M){T("请输入连接名称");return}if(v){s(M,"",v),f(""),x(""),d(!1);return}if(!$){T("请输入后端地址");return}T(null),await A($),s(M,$),f(""),g(""),d(!1),y(null)},O=M=>{M.canEdit!==!1&&(E(M.id),D(M.name),R(M.url))},L=()=>{if(!N)return;const M=k.trim(),$=j.trim();!M||!$||(l(N,{name:M,url:$}),E(null))};return va(e&&(!!N||u&&!!(h||m||v)),e&&C),o.jsxs("main",{className:e?"space-y-3":"relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-10 sm:px-6",children:[!e&&o.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(70,130,145,0.18),transparent_30%),radial-gradient(circle_at_bottom_left,rgba(195,172,135,0.16),transparent_35%)]"}),o.jsxs("section",{className:e?"w-full space-y-3 rounded-md border bg-card p-3":"animate-fade-rise relative w-full max-w-lg rounded-[2rem] border border-border/60 bg-card/82 p-7 shadow-[0_34px_120px_-72px_rgba(17,24,39,0.82)] backdrop-blur-xl sm:p-9",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.38em] text-muted-foreground/70",children:"连接管理"}),r.length>0&&!u&&o.jsx(Z,{size:"sm",className:"rounded-full px-4",onClick:()=>{d(!0),T(null),y(null)},children:"添加连接"})]}),o.jsx(Sa,{className:"mt-4 max-w-full"}),o.jsx(lq,{}),u&&o.jsxs("div",{className:e?"mt-3 space-y-3":"mt-6 space-y-4",children:[((B=window.electronAPI)==null?void 0:B.isElectron)&&o.jsx(Z,{type:"button",variant:"outline",onClick:()=>t?t():_(!0),children:"配置 SSH 主机与 Backend 入口"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"conn-name",children:"连接名称"}),o.jsx("input",{id:"conn-name",placeholder:"例如:本地开发",value:h,onChange:M=>f(M.target.value),className:"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"})]}),b!=null&&b.config.backendEndpoints.length?o.jsxs("label",{className:"block text-sm",children:["访问方式",o.jsxs("select",{className:"mt-2 h-10 w-full rounded-lg border border-border bg-background px-3",value:v,onChange:M=>x(M.target.value),children:[o.jsx("option",{value:"",children:"后端地址"}),b.config.backendEndpoints.map(M=>{var $;return o.jsxs("option",{value:M.id,children:[($=b.config.hosts.find(U=>U.id===M.hostId))==null?void 0:$.name," · Backend ",M.remotePort]},M.id)})]})]}):null,!v&&o.jsxs(o.Fragment,{children:[" ",o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"conn-url",children:"后端地址"}),o.jsx("input",{id:"conn-url",placeholder:"例如:http://192.168.1.100:5001",value:m,onChange:M=>g(M.target.value),onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),P())},className:"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"})]})]}),w==="connected"&&o.jsx("p",{className:"text-sm text-green-500",children:"✓ 连接成功"}),w==="unreachable"&&o.jsx("p",{className:"text-sm text-yellow-500",children:"⚠ 无法连接,但已保存(后端可能未启动)"}),I&&o.jsx("p",{className:"text-sm text-red-500",role:"alert",children:I}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{className:"h-12 flex-1 rounded-full text-sm",onClick:()=>void P(),disabled:C,children:C?"检测中...":"添加"}),r.length>0&&o.jsx(Z,{variant:"ghost",className:"h-12 rounded-full px-6 text-sm",onClick:()=>{d(!1),T(null),y(null)},children:"取消"})]})]}),r.length>0&&!u&&o.jsx("ul",{className:e?"mt-3 space-y-2":"mt-6 space-y-3",children:r.map(M=>o.jsx("li",{className:`group flex flex-wrap items-center justify-between border transition ${e?"rounded-md px-3 py-2":"rounded-2xl px-5 py-4"} ${M.id===n?"border-primary/40 bg-primary/5":"border-border/60 bg-background/60 hover:border-border"}`,children:N===M.id?o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx("input",{value:k,onChange:$=>D($.target.value),className:"h-9 w-full rounded-xl border border-border/60 bg-background/70 px-3 text-sm outline-none focus:border-primary/50"}),o.jsx("input",{value:j,onChange:$=>R($.target.value),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),L())},className:"h-9 w-full rounded-xl border border-border/60 bg-background/70 px-3 text-sm outline-none focus:border-primary/50"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",className:"rounded-full px-4",onClick:L,children:"保存"}),o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-4",onClick:()=>E(null),children:"取消"})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"flex-1 text-left",onClick:()=>a(M.id),children:[o.jsx("p",{className:"text-sm font-medium",children:M.name}),o.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:M.tunnelEndpointId?"通过独立 SSH 通道访问":M.url||"内置本地后端未连接"}),M.available===!1&&M.statusMessage?o.jsx("p",{className:"mt-1 text-xs text-amber-600",children:M.statusMessage}):null,M.browserMessage?o.jsxs("p",{className:"mt-1 text-xs text-amber-600",children:["Browser: ",M.browserMessage]}):null,M.isSystem&&M.runtimeSource?o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Runtime: ",M.runtimeSource,M.runtimeReleaseId?` ${M.runtimeReleaseId}`:""]}):null]}),(M.canEdit!==!1||M.canDelete!==!1)&&o.jsxs("div",{className:"flex items-center gap-1 opacity-0 transition group-hover:opacity-100",children:[M.canEdit!==!1&&o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-3 text-xs text-muted-foreground",onClick:$=>{$.stopPropagation(),O(M)},children:"编辑"}),M.canDelete!==!1&&o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-3 text-xs text-red-500 hover:text-red-600",onClick:$=>{$.stopPropagation(),(!e||window.confirm(`删除 ${M.name} 的连接配置?远端数据不会删除。`))&&i(M.id)},children:"删除"})]}),y6(M)&&c?o.jsx(Z,{variant:"secondary",size:"sm",className:"ml-2 rounded-full px-4",onClick:$=>{$.stopPropagation(),c(M.id)},children:"恢复"}):null]})},M.id))}),r.length===0&&!u&&o.jsxs("div",{className:"mt-8 text-center",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"暂无连接配置,请添加一个后端连接"}),o.jsx(Z,{className:"mt-4 rounded-full px-6",onClick:()=>d(!0),children:"添加连接"})]}),I&&!u?o.jsx("p",{className:"mt-4 text-sm text-red-500",role:"alert",children:I}):null]})]})}function uq({embedded:e=!1,connections:t,activeId:r,onAdd:n,onRemove:s,onSelect:i,onEdit:a,onReconnect:l}){const c=Cr();return o.jsx(o.Fragment,{children:o.jsx(cq,{embedded:e,connections:t,activeId:r,onAdd:(u,d,h)=>{n(u,d,h),e||c("/terminal",{replace:!0})},onRemove:s,onSelect:u=>{i(u),e||c("/terminal",{replace:!0})},onEdit:a,onReconnect:async u=>await(l==null?void 0:l(u))?(i(u),e||c("/terminal",{replace:!0}),!0):!1})})}function Hh(e){return e===null||!Number.isFinite(e)?"—":`${e.toFixed(e>=10?0:1)}%`}function $a(e){return Number.isFinite(e)?e>=1024?`${(e/1024).toFixed(e>=10*1024?1:2)} GiB`:`${Math.round(e)} MiB`:"—"}function B1(e){return e?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(e)):"—"}function dq(e){const t=e.displayName.trim();return t.length<=72?t:`${t.slice(0,69)}...`}function hq(e){const t=p.useMemo(()=>[...e.processes].sort((r,n)=>(e.sortKey==="energy"?(n.energyImpact??-1)-(r.energyImpact??-1):e.sortKey==="cpu"?(n.cpuPercent??-1)-(r.cpuPercent??-1):n.memoryMb-r.memoryMb)||(n.cpuPercent??-1)-(r.cpuPercent??-1)||n.memoryMb-r.memoryMb),[e.processes,e.sortKey]);return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{id:`resource-app-${e.app.appKey}`,className:e.app.isCurrentApp?"bg-[hsl(var(--primary))]/8":"",children:[o.jsx("td",{className:"min-w-0 px-4 py-3",children:o.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 text-left",onClick:e.onToggle,children:[e.expanded?o.jsx(Kv,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):o.jsx(Jr,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"truncate font-medium",children:e.app.appName}),e.app.isCurrentApp?o.jsx("span",{className:"rounded-full bg-[hsl(var(--primary))]/14 px-2 py-0.5 text-[0.68rem] font-medium text-[hsl(var(--primary))]",children:"Runweave"}):null]})}),o.jsxs("td",{className:"px-4 py-3 text-right tabular-nums",children:[e.app.energyImpact==null?"—":e.app.energyImpact.toFixed(1),e.app.coverage==="partial"?o.jsx("span",{className:"block text-[10px] text-muted-foreground",children:"覆盖不完整"}):null]}),o.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:Hh(e.app.coverage==="partial"?null:e.app.cpuPercent)}),o.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:$a(e.app.memoryMb)}),o.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:e.app.processCount})]}),e.expanded?o.jsx("tr",{children:o.jsx("td",{colSpan:5,className:"border-y border-border/60 bg-muted/35 px-4 py-3",children:t.length>0?o.jsx("div",{className:"overflow-hidden rounded-lg border border-border/70 bg-background/70",children:o.jsxs("table",{className:"w-full table-fixed text-xs",children:[o.jsx("thead",{className:"text-muted-foreground",children:o.jsxs("tr",{children:[o.jsx("th",{className:"w-24 px-3 py-2 text-left font-medium",children:"PID"}),o.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Process"}),o.jsx("th",{className:"w-24 px-3 py-2 text-right font-medium",children:"CPU Core"}),o.jsx("th",{className:"w-28 px-3 py-2 text-right font-medium",children:"RSS"}),o.jsx("th",{className:"w-40 px-3 py-2 text-right font-medium",children:"操作"})]})}),o.jsx("tbody",{children:t.slice(0,12).map(r=>o.jsxs("tr",{className:"border-t border-border/50",children:[o.jsx("td",{className:"px-3 py-2 tabular-nums text-muted-foreground",children:r.pid}),o.jsx("td",{className:"truncate px-3 py-2",children:dq(r)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Hh(r.coverage==="partial"?null:r.cpuPercent)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:$a(r.memoryMb)}),o.jsx("td",{className:"px-3 py-2 text-right",children:(()=>{const n=r.processInstanceId??String(r.pid),s=e.results[n],i=typeof s=="object"&&s.state!=="still_running";return o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s?o.jsx("span",{role:"status",className:i?"text-emerald-600 dark:text-emerald-400":"text-muted-foreground",children:typeof s=="string"?s:s.state==="still_running"?"仍在运行":s.state==="already_exited"?"进程已退出":"已结束"}):null,i?null:o.jsx(Z,{size:"sm",variant:"outline",className:"h-7 text-xs disabled:text-muted-foreground",title:r.actionReason,disabled:!!e.pending||!e.canTerminate||!r.processInstanceId||r.actionKind==="readonly",onClick:()=>e.onTerminate(r,typeof s=="object"&&s.forceAllowed),children:e.pending===n?"正在结束…":r.actionKind==="readonly"?"受保护":typeof s=="object"&&s.forceAllowed?"强制结束…":r.actionKind==="stop_service"?"停止服务":"结束进程"}),r.actionKind==="readonly"?o.jsx("span",{className:"text-[10px] text-muted-foreground",children:r.actionReason}):null]})})()})]},r.pid))})]})}):o.jsx("p",{className:"text-sm text-muted-foreground",children:"Process details are outside the current top process window."})})}):null]})}function fq({onSaved:e,embedded:t=!1}){var v,x,b;const r=Tx(),[n,s]=p.useState(t),[i,a]=p.useState(null),[l,c]=p.useState(!1),[u,d]=p.useState(null),h=W(()=>{if(!r.data)return;const _=r.data;a({monitor:_.settings.monitorEnabled,alerts:_.settings.alertsEnabled,revision:_.settings.revision,remote:_.remoteControl.enabled,remoteRevision:_.remoteControl.revision,mac:r.macNotifications}),d(null)});p.useEffect(()=>{t&&!i&&r.data&&h()},[i,t,h,r.data]);const f=!!i&&!!r.data&&(i.monitor!==r.data.settings.monitorEnabled||i.alerts!==r.data.settings.alertsEnabled||i.remote!==r.data.remoteControl.enabled||i.mac!==r.macNotifications);va(t&&f,t&&l);const m=W(async()=>{var C;if(!i||!r.token||l)return;c(!0),d(null);let _=!1;try{const S=Mh(r.apiBase,r.token),w=await S.settings({revision:i.revision,monitorEnabled:i.monitor,alertsEnabled:i.alerts});if(r.applySettings(w),_=!0,a(y=>y&&{...y,revision:w.revision}),(C=r.data)!=null&&C.canManageRemoteControl&&i.remote!==r.data.remoteControl.enabled){const y=await S.remoteControl({revision:i.remoteRevision,enabled:i.remote});r.applyRemoteControl(y),a(N=>N&&{...N,remoteRevision:y.revision})}r.setMacNotifications(i.mac),e(),t||s(!1)}catch(S){d(`${_?"监控设置已保存;其余设置未完成。":""}${S instanceof Error?S.message:String(S)}`)}finally{c(!1)}}),g=o.jsxs("div",{className:t?"space-y-3":"space-y-5","aria-busy":l,children:[i?o.jsxs("fieldset",{disabled:l,className:t?"space-y-3":"space-y-5",children:[[["monitor","后台资源监控"],["alerts","资源占用提醒"],["mac","Mac 系统通知"]].map(([_,C])=>{var S;return o.jsxs("label",{className:"flex items-center justify-between gap-3 border-b pb-4 text-sm",children:[C,o.jsx("input",{type:"checkbox",checked:i[_],disabled:_==="mac"&&!((S=window.electronAPI)!=null&&S.showResourceNotification),onChange:w=>a({...i,[_]:w.target.checked})})]},_)}),(v=r.data)!=null&&v.canManageRemoteControl?o.jsxs("label",{className:"flex items-center justify-between gap-3 text-sm",children:["允许远程结束进程",o.jsx("input",{type:"checkbox",checked:i.remote,onChange:_=>a({...i,remote:_.target.checked})})]}):o.jsxs("p",{className:"text-sm text-muted-foreground",children:["远程结束进程:",(x=r.data)!=null&&x.remoteControl.enabled?"已授权":"未授权","。仅电脑本机可修改授权。"]}),o.jsx("p",{className:"text-xs leading-6 text-muted-foreground",children:"后台每分钟采样,关闭页面后仍继续观察。允许远程控制后,普通结束和强制结束仍需分别确认;系统及 Runweave 控制进程受保护。"}),o.jsxs("p",{className:"text-xs leading-6 text-muted-foreground",children:["能耗影响 ≥ 100(仅电池供电),或 RSS 合计 ≥ 4 GiB;至少六次有效采样跨满五分钟。内存占用不代表耗电量。",(b=window.electronAPI)!=null&&b.showResourceNotification?"系统通知需要在 macOS 中允许 Runweave 发送通知。":"普通 Web 使用应用内提醒。"]})]}):o.jsx("p",{role:"status",children:r.error??"正在读取监控设置…"}),(u||r.notificationError)&&o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:u??r.notificationError}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(Z,{variant:"ghost",disabled:l,onClick:()=>{h(),t||s(!1)},children:"取消修改"}),o.jsx(Z,{disabled:l||!i||!r.token||!f,onClick:()=>void m(),children:l?"保存中…":"保存修改"})]})]});return t?g:o.jsxs(o.Fragment,{children:[o.jsxs(Z,{variant:"secondary",size:"sm",disabled:!r.data,onClick:()=>{h(),s(!0)},children:[o.jsx(lO,{className:"mr-2 h-4 w-4"}),"提醒设置"]}),o.jsx(Qr,{open:n,onOpenChange:_=>{l||s(_)},children:o.jsxs(dn,{children:[o.jsxs(Mn,{children:[o.jsx(Ur,{children:"资源提醒设置"}),o.jsx(Zr,{children:"后台资源监控与系统通知"})]}),g]})})]})}function pq(e){const t=Tx(),[r,n]=p.useState(null);return p.useEffect(()=>{var s;e||n(((s=t.data)==null?void 0:s.snapshot)??null)},[e,t.data]),{snapshot:r,resource:t}}const mq=50;function gq(e){const t=e.value===null||!Number.isFinite(e.value)?0:Math.max(0,Math.min(100,e.value)),r=e.tone==="warn"?"bg-amber-500":"bg-[hsl(var(--primary))]";return o.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:o.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${t}%`}})})}function kd(e){return o.jsxs("section",{className:"rounded-lg border border-border/70 bg-card/85 p-4 shadow-[0_18px_70px_-54px_rgba(17,24,39,0.75)]",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm font-medium text-muted-foreground",children:[e.icon,o.jsx("span",{className:"truncate",children:e.label})]}),o.jsx("strong",{className:"text-xl font-semibold tabular-nums text-foreground",children:e.value})]}),e.barValue!==void 0?o.jsx("div",{className:"mt-4",children:o.jsx(gq,{value:e.barValue,tone:e.tone})}):null,o.jsx("p",{className:"mt-3 truncate text-xs text-muted-foreground",children:e.detail})]})}function vq(e){return o.jsx("main",{className:"flex min-h-screen items-center justify-center bg-background px-6 py-10",children:o.jsxs("section",{className:"w-full max-w-lg rounded-lg border border-border/70 bg-card/90 p-8 text-center shadow-[0_24px_90px_-58px_rgba(17,24,39,0.75)]",children:[o.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full border border-border/70 bg-muted",children:o.jsx(cs,{className:"h-5 w-5 text-muted-foreground"})}),o.jsx("h1",{className:"mt-5 text-2xl font-semibold text-foreground",children:e.title}),o.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:e.body}),e.onNavigateTerminal?o.jsxs(Z,{className:"mt-6",onClick:e.onNavigateTerminal,children:[o.jsx(xi,{className:"mr-2 h-4 w-4"}),"Terminals"]}):null]})})}function xq(e){return e.memory.totalMb<=0?0:Math.round(e.memory.usedMb/e.memory.totalMb*100)}function bq(e,t){return[...e].sort((r,n)=>(t==="energy"?(n.energyImpact??-1)-(r.energyImpact??-1):t==="cpu"?(n.cpuPercent??-1)-(r.cpuPercent??-1):n.memoryMb-r.memoryMb)||(n.cpuPercent??-1)-(r.cpuPercent??-1)||n.memoryMb-r.memoryMb)}function _q({onNavigateTerminal:e,embedded:t=!1}){const[r,n]=p.useState(!1),[s,i]=p.useState("energy"),[a]=fa(),[l,c]=p.useState(a.get("app")),[u,d]=p.useState({}),[h,f]=p.useState(null),m=p.useRef(!1),[g,v]=p.useState(null),{snapshot:x,resource:b}=pq(r),{data:_,error:C,refresh:S}=b;p.useEffect(()=>{const k=a.get("app");k&&c(k)},[a]),p.useEffect(()=>{var k;l&&((k=document.getElementById(`resource-app-${l}`))==null||k.scrollIntoView({block:"nearest"}))},[l]);const w=W(async()=>{if(!g||!b.token||m.current||!g.process.processInstanceId)return;const k=g,D=k.process.processInstanceId;m.current=!0,f(D),v(null);try{const j=await Mh(b.apiBase,b.token).terminate(D,k.force,crypto.randomUUID());d(R=>({...R,[D]:j}))}catch(j){d(R=>({...R,[D]:j instanceof Error?j.message:String(j)}))}finally{m.current=!1,f(null)}});if((_==null?void 0:_.status)==="unsupported")return o.jsx(vq,{title:"需要 macOS Backend",body:"当前连接的电脑尚不支持资源采样。",onNavigateTerminal:e});const y=x?xq(x):0,N=x?bq(x.apps,s).slice(0,mq):[],E=new Map;for(const k of(x==null?void 0:x.processes)??[]){const D=E.get(k.appKey)??[];D.push(k),E.set(k.appKey,D)}return o.jsxs("main",{className:t?"text-foreground":"min-h-screen bg-background px-4 py-5 text-foreground md:px-6 lg:px-8",children:[o.jsxs("div",{className:"flex w-full flex-col gap-3",children:[o.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border/70 pb-4",children:[o.jsxs("div",{className:"min-w-0",children:[!t&&o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.28em] text-muted-foreground",children:"Runweave"}),!t&&o.jsx("h1",{className:"mt-1 text-3xl font-semibold tracking-normal",children:"系统监控"}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[(_==null?void 0:_.hostName)??"当前连接的电脑"," ·"," ",(_==null?void 0:_.status)==="ok"?`最近采样 ${B1((x==null?void 0:x.sampledAt)??null)}`:(_==null?void 0:_.status)==="disabled"?"后台资源监控已关闭":(_==null?void 0:_.status)==="stale"?"采样已过期":(_==null?void 0:_.status)==="error"?"采样失败,显示上次数据":"观察中"]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[!t&&o.jsx(Sa,{}),e?o.jsxs(Z,{variant:"ghost",size:"sm",onClick:e,children:[o.jsx(xi,{className:"mr-2 h-4 w-4"}),"Terminals"]}):null,o.jsx(fq,{onSaved:S}),o.jsxs(Z,{variant:"secondary",size:"sm",onClick:S,children:[o.jsx(Ws,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"刷新缓存"})]}),o.jsxs(Z,{variant:r?"default":"secondary",size:"sm",onClick:()=>n(k=>!k),children:[o.jsx("span",{className:"sr-only",children:r?"继续显示":"暂停显示"}),r?o.jsx(Sl,{className:"h-4 w-4"}):o.jsx(VM,{className:"h-4 w-4"})]})]})]}),C?o.jsx("p",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600 dark:text-red-300",children:C}):null,_!=null&&_.alerts[0]?o.jsxs("aside",{role:"status",className:"flex flex-wrap items-center justify-between gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 p-4",children:[o.jsxs("div",{children:[o.jsxs("strong",{children:[_.alerts[0].appName," ",_.alerts[0].ruleId==="energy"?"能耗影响较高":"内存占用较大"]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["近 5 分钟多次检测到高占用",_.alerts[0].ruleId==="memory"?";内存占用不代表耗电量":""]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",onClick:()=>c(_.alerts[0].appKey),children:"查看进程"}),o.jsx(Z,{size:"sm",variant:"outline",onClick:()=>{b.snooze(_.alerts[0].alertId).then(()=>{b.dismissNotice(),S()}).catch(()=>{})},children:"忽略 1 小时"})]})]}):null,l&&x&&!N.some(k=>k.appKey===l)?o.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"该提醒对应的应用已退出或不在当前列表中。"}):null,b.notificationError?o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:b.notificationError}):null,b.unsupportedBackend?o.jsx("p",{role:"alert",className:"text-sm text-muted-foreground",children:"当前 Backend 尚不支持资源监控,请更新 Backend。"}):null,o.jsxs("section",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[o.jsx(kd,{label:"CPU",value:x?Hh(x.cpu.totalPercent):"-",detail:x!=null&&x.cpu.warmingUp?"观察中":`${(x==null?void 0:x.cpu.coreCount)??0} 核心`,icon:o.jsx(GL,{className:"h-4 w-4"}),barValue:(x==null?void 0:x.cpu.totalPercent)??null}),o.jsx(kd,{label:"内存",value:x?`${y}%`:"-",detail:x?`${$a(x.memory.usedMb)} / ${$a(x.memory.totalMb)} · ${x.memory.pressure}`:"-",icon:o.jsx(CM,{className:"h-4 w-4"}),barValue:y,tone:(x==null?void 0:x.memory.pressure)==="warn"||(x==null?void 0:x.memory.pressure)==="critical"?"warn":"ok"}),o.jsx(kd,{label:"Swap",value:x?$a(x.memory.swapUsedMb):"-",detail:_!=null&&_.settings.monitorEnabled?"后台每分钟采样":"后台采样已关闭",icon:o.jsx(cs,{className:"h-4 w-4"})}),o.jsx(kd,{label:"电池",value:x!=null&&x.battery.available?`${x.battery.percent}%`:"未知",detail:x!=null&&x.battery.available?`${x.battery.powerSource==="ac"?"接电":x.battery.powerSource==="battery"?"电池供电":"供电未知"} · ${x.battery.dischargePowerW==null?"放电功率未知":`估算放电 ${x.battery.dischargePowerW.toFixed(1)} W`}`:"电池数据未知",icon:x!=null&&x.battery.available&&x.battery.charging?o.jsx(xL,{className:"h-4 w-4"}):o.jsx(_L,{className:"h-4 w-4"}),barValue:x!=null&&x.battery.available?x.battery.percent:null})]}),o.jsxs("section",{className:"flex flex-col rounded-lg border border-border/70 bg-card/85 shadow-[0_24px_90px_-58px_rgba(17,24,39,0.75)]",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border/70 px-4 py-3",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold",children:"高占用应用与进程"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["最近采样 ",B1((x==null?void 0:x.sampledAt)??null)]})]}),o.jsxs("div",{className:"flex rounded-lg border border-border/70 bg-background/70 p-1",children:[o.jsx(Z,{variant:s==="energy"?"default":"ghost",size:"sm",onClick:()=>i("energy"),children:"能耗影响"}),o.jsx(Z,{variant:s==="cpu"?"default":"ghost",size:"sm",onClick:()=>i("cpu"),children:"CPU Core"}),o.jsx(Z,{variant:s==="memory"?"default":"ghost",size:"sm",onClick:()=>i("memory"),children:"RSS Sum"})]})]}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full min-w-[720px] table-fixed text-sm",children:[o.jsx("thead",{className:"border-b border-border/70 text-xs uppercase text-muted-foreground",children:o.jsxs("tr",{children:[o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"App"}),o.jsx("th",{className:"w-28 px-4 py-3 text-right font-medium",children:"能耗影响"}),o.jsx("th",{className:"w-32 px-4 py-3 text-right font-medium",children:"CPU Core"}),o.jsx("th",{className:"w-36 px-4 py-3 text-right font-medium",children:"RSS Sum"}),o.jsx("th",{className:"w-28 px-4 py-3 text-right font-medium",children:"Procs"})]})}),o.jsx("tbody",{className:"divide-y divide-border/60",children:N.length>0?N.map(k=>o.jsx(hq,{app:k,results:u,pending:h,canTerminate:(_==null?void 0:_.canTerminate)===!0&&!C&&!r,onTerminate:(D,j)=>v({process:D,force:j}),processes:E.get(k.appKey)??[],expanded:l===k.appKey,sortKey:s,onToggle:()=>{c(D=>D===k.appKey?null:k.appKey)}},k.appKey)):o.jsx("tr",{children:o.jsx("td",{colSpan:5,className:"px-4 py-12 text-center text-muted-foreground",children:x?"暂无进程数据。":"正在等待 Backend 采样…"})})})]})}),o.jsxs("div",{className:"border-t border-border/70 px-4 py-3 text-xs text-muted-foreground",children:["能耗影响按 CPU 与唤醒次数估算,不能完整归因 GPU、网络等耗电,也不是应用瓦数。进程 CPU 的 100% 表示一个核心;RSS 合计可能重复计入共享页。采样覆盖"," ",(_==null?void 0:_.coverage.matchedProcesses)??0,"/",(_==null?void 0:_.coverage.knownProcesses)??0," 个进程,未知值显示「—」。",Object.values(u).some(k=>typeof k=="object"&&k.state!=="still_running")?o.jsx("p",{className:"mt-2",children:"只结束了选定进程;该应用仍可能有其他进程运行。电池功率将在下次后台采样更新。"}):null]})]})]}),o.jsx(Tl,{open:g!==null,onOpenChange:k=>{k||v(null)},children:o.jsxs(xa,{className:"rounded-lg border-border bg-card text-foreground",children:[o.jsxs(Dl,{children:[o.jsx(ba,{children:g!=null&&g.force?"强制结束这个进程?":(g==null?void 0:g.process.actionKind)==="stop_service"?"停止这个服务?":"结束这个进程?"}),o.jsx(_a,{asChild:!0,children:o.jsxs("div",{className:"space-y-3 text-muted-foreground",children:[o.jsxs("p",{children:[g==null?void 0:g.process.displayName," · PID ",g==null?void 0:g.process.pid," ·"," ",_==null?void 0:_.hostName]}),o.jsxs("p",{children:["CPU ",Hh((g==null?void 0:g.process.cpuPercent)??null)," · RSS"," ",$a((g==null?void 0:g.process.memoryMb)??0)]}),o.jsxs("p",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-foreground",children:["未保存的内容可能丢失。",(g==null?void 0:g.process.actionKind)==="stop_service"?`将停止 ${g.process.serviceName} 服务及其子进程;必要时按服务生命周期强制结束。`:"此操作只结束选中的进程。",g!=null&&g.force?"强制结束不会等待程序自行退出。":""]})]})})]}),o.jsxs(Pl,{children:[o.jsx(ya,{children:"取消"}),o.jsx(Z,{variant:"destructive",onClick:()=>void w(),children:g!=null&&g.force?"强制结束":(g==null?void 0:g.process.actionKind)==="stop_service"?"停止服务":"结束进程"})]})]})})]})}const yq=10;function wq({activeSessionId:e,cachedSessionIds:t,sessionIds:r,maxCachedSurfaces:n=yq}){if(n<=0)return[];const s=new Set(r),i=t.filter(a=>s.has(a)&&a!==e);return e&&s.has(e)&&i.push(e),i.slice(-n)}function F1(e){return e==="mobile"?"pty":"auto"}function Sq({apiBase:e,token:t,clientMode:r,removeProjectPreview:n,loadSessions:s,onAuthExpired:i}){const a=_s().data??_o,l=Zn().data??bs,{queryClient:c,scope:u}=Al(),{loading:d,activeProjectId:h,activeParentProjectId:f,activeSessionId:m}=tt(An(F=>({loading:F.loading,activeProjectId:F.activeProjectId,activeParentProjectId:F.activeParentProjectId,activeSessionId:F.activeSessionId}))),g=a.find(F=>F.projectId===f)??null,v=h?l.filter(F=>F.projectId===h):l,x=v.find(F=>F.terminalSessionId===m)??v[0]??null,{projectDialogMode:b,projectPendingDeletion:_,setLoading:C,setRequestError:S,setProjectDialogMode:w,setProjectDialogError:y,setProjectPendingDeletion:N,setHistoryDrawerOpen:E,setHistoryTerminalSessionId:k,setHistoryTerminalPanelId:D,selectProjectContext:j,setActiveSessionId:R}=tt(An(F=>({projectDialogMode:F.projectDialogMode,projectPendingDeletion:F.projectPendingDeletion,setLoading:F.setLoading,setRequestError:F.setRequestError,setProjectDialogMode:F.setProjectDialogMode,setProjectDialogError:F.setProjectDialogError,setProjectPendingDeletion:F.setProjectPendingDeletion,setHistoryDrawerOpen:F.setHistoryDrawerOpen,setHistoryTerminalSessionId:F.setHistoryTerminalSessionId,setHistoryTerminalPanelId:F.setHistoryTerminalPanelId,selectProjectContext:F.selectProjectContext,setActiveSessionId:F.setActiveSessionId}))),I=W(async()=>{C(!0);try{const F=await C0(e,t,{projectId:h??void 0,inheritFromTerminalSessionId:x==null?void 0:x.terminalSessionId,runtimePreference:F1(r)});S(null),await s(),R(F.terminalSessionId)}catch(F){if(F instanceof De&&F.status===401){i==null||i();return}S(String(F))}finally{C(!1)}}),T=W(async F=>{C(!0);try{await Y6(e,t,F),S(null),await s()}catch(K){if(K instanceof De&&K.status===401){i==null||i();return}S(String(K))}finally{C(!1)}}),A=W(async(F,K)=>{C(!0);try{const Y=await Fc(e,t,F,{alias:K.trim()||null});Ga(c,u,te=>te.map(H=>H.terminalSessionId===Y.terminalSessionId?Y:H)),S(null)}catch(Y){if(Y instanceof De&&Y.status===401){i==null||i();return}S(String(Y))}finally{C(!1)}}),P=W(async(F,K)=>{C(!0);try{await Fc(e,t,F,{projectId:K}),await s(),j(K,K,F),S(null)}catch(Y){if(Y instanceof De&&Y.status===401){i==null||i();return}S(String(Y))}finally{C(!1)}}),O=W(()=>{d||(y(null),w(null))}),L=W(async(F,K,Y)=>{const te=F.trim();if(!te){y("Project name is required.");return}const H=K.trim();C(!0),y(null);try{if(b==="edit"&&g){const G=await z6(e,t,g.projectId,{name:te,path:H||null,mainBranch:Y.trim()||null});om(c,u,z=>z.map(ee=>ee.projectId===G.projectId?G:ee))}else{const G=await M6(e,t,{name:te,path:H||null}),z=await C0(e,t,{projectId:G.projectId,runtimePreference:F1(r)});om(c,u,V=>[...V.filter(re=>re.projectId!==G.projectId),G]),j(G.projectId,G.projectId,z.terminalSessionId);const ee=new Date().toISOString();Ga(c,u,V=>[...V.filter(re=>re.terminalSessionId!==z.terminalSessionId),{terminalSessionId:z.terminalSessionId,projectId:G.projectId,command:"",args:[],cwd:"",activeCommand:null,completionRevision:0,acknowledgedCompletionRevision:0,status:"running",createdAt:ee,lastActivityAt:ee,panelSplitEnabled:!1}]),await s()}w(null)}catch(G){if(G instanceof De&&G.status===401){i==null||i();return}y(String(G))}finally{C(!1)}}),B=W(async()=>{const F=_??g;if(F){C(!0);try{await $6(e,t,F.projectId),S(null),y(null),j(null,null,null),n(F.projectId),N(null),await s()}catch(K){if(K instanceof De&&K.status===401){i==null||i();return}S(String(K))}finally{C(!1)}}}),M=W((F,K)=>{om(c,u,Y=>{const te=[...Y],[H]=te.splice(F,1);H&&te.splice(K,0,H);const G=te.map(z=>z.projectId);return U6(e,t,G).catch(()=>{s()}),te})}),$=W((F,K)=>{h&&Ga(c,u,Y=>{const H=[...Y.filter(V=>V.projectId===h)],[G]=H.splice(F,1);G&&H.splice(K,0,G);const z=H.map(V=>V.terminalSessionId);X6(e,t,h,z).catch(()=>{s()});let ee=0;return Y.map(V=>V.projectId===h?H[ee++]:V)})}),U=W(F=>{k(F),D(null),E(!0)});return{createSession:I,closeSession:T,updateSessionAlias:A,moveSession:P,closeProjectDialog:O,submitProjectDialog:L,removeProject:B,handleProjectReorder:M,handleSessionReorder:$,openHistoryDrawer:U}}function Cq(){if(typeof window>"u")return null;const e=window.AudioContext??window.webkitAudioContext;return e?new e:null}function Eq(e){var u;const{createContext:t=Cq,durationMs:r=120,frequency:n=1046,nativeBeep:s=typeof window>"u"||(u=window.electronAPI)==null?void 0:u.beep,volume:i=.12}={};let a=null,l=null;const c=async()=>(a??(a=t()),a?(a.state==="suspended"&&a.resume&&(l||(l=a.resume().then(()=>a).finally(()=>{l=null})),await l),a):null);return{async prepare(){s||await c()},play(){if(s)try{return s(),Promise.resolve()}catch{}return c().then(d=>{if(!d)return;const h=d.createOscillator(),f=d.createGain();h.type="sine",h.frequency.value=n,f.gain.value=i,h.connect(f),f.connect(d.destination),h.start(),h.stop(d.currentTime+r/1e3)}).catch(()=>{})}}}const kq=2e3,Iq=50;function Nq(e){return e.kind==="completion_acknowledged"||e.kind==="project_created"||e.kind==="project_deleted"||e.kind==="terminal_session_created"||e.kind==="terminal_session_moved"||e.kind==="terminal_session_deleted"}function Rq(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t];if((r==null?void 0:r.kind)==="terminal_session_created")return r}return null}function jq({apiBase:e,token:t,onAuthExpired:r,loadSessions:n}){const s=Zn().data??bs,{queryClient:i,scope:a}=Al(),{setTerminalStateBySessionId:l,setPanelWorkspaceBySessionId:c,setActivePanelIdBySessionId:u,setCompletionMarkers:d,selectProjectContext:h,setBellMarkers:f}=tt(An(k=>({setTerminalStateBySessionId:k.setTerminalStateBySessionId,setPanelWorkspaceBySessionId:k.setPanelWorkspaceBySessionId,setActivePanelIdBySessionId:k.setActivePanelIdBySessionId,setCompletionMarkers:k.setCompletionMarkers,selectProjectContext:k.selectProjectContext,setBellMarkers:k.setBellMarkers}))),m=p.useRef(null),g=p.useRef(null),v=p.useRef(null),x=W(()=>{m.current=null}),{run:b,cancel:_}=dC(()=>{const k=g.current;g.current=null,n().then(()=>{!k||tt.getState().activeSessionId||h(Tn(k.projectId),k.projectId,k.terminalSessionId)})},{wait:Iq});p.useEffect(()=>()=>{_()},[_]);const C=W((k,D)=>{var L;const j=k[k.length-1];j&&(m.current=j.id);const R=k.filter(B=>B.kind==="terminal_state_changed");if(R.length>0){l(M=>{let $=!1;const U={...M};for(const F of R){if(F.kind!=="terminal_state_changed")continue;const K=F.payload.next,Y=U[F.terminalSessionId];(Y==null?void 0:Y.state)===K.state&&Y.agent===K.agent||(U[F.terminalSessionId]=K,$=!0)}return $?U:M});const B=R.filter(M=>M.kind==="terminal_state_changed"&&M.payload.next.state==="agent_running").map(M=>M.terminalSessionId);B.length>0&&d(M=>{let $=!1;const U={...M};for(const F of B)U[F]!==void 0&&(delete U[F],$=!0);return $?U:M})}const I=k.filter(B=>B.kind==="terminal_panel_created"||B.kind==="terminal_panel_updated"||B.kind==="terminal_panel_deleted"||B.kind==="terminal_panel_focused"||B.kind==="terminal_panel_input_sent");I.length>0&&(c(B=>{let M=!1;const $={...B};for(const U of I){const F=U.payload.workspace,K=$[U.terminalSessionId],te=(K==null?void 0:K.panels.length)===F.panels.length&&F.panels.every(H=>K.panels.some(G=>G.panelId===H.panelId))?{...F,panels:F.panels.map(H=>{var G;return{...H,geometry:H.geometry??((G=K.panels.find(z=>z.panelId===H.panelId))==null?void 0:G.geometry)}})}:F;JSON.stringify(K)!==JSON.stringify(te)&&($[U.terminalSessionId]=te,M=!0)}return M?$:B}),u(B=>{let M=!1;const $={...B};for(const U of I){const F=U.payload.workspace.activePanelId;$[U.terminalSessionId]!==F&&($[U.terminalSessionId]=F,M=!0)}return M?$:B}));const T=new Map;for(const B of k)B.kind==="terminal_session_metadata_changed"&&T.set(B.terminalSessionId,B.payload.next);if(T.size>0&&Ga(i,a,B=>{let M=!1;const $=B.map(U=>{const F=T.get(U.terminalSessionId);return!F||U.cwd===F.cwd&&U.activeCommand===F.activeCommand?U:(M=!0,{...U,cwd:F.cwd,activeCommand:F.activeCommand})});return M?$:B}),k.some(Nq)){const B=Rq(k);B&&(g.current=B),b()}const A=new Set(s.map(B=>B.terminalSessionId));if(D==="live"){const B=tt.getState().activeSessionId,M=new Set(k.filter($=>$.kind==="terminal_bell").map($=>$.terminalSessionId).filter($=>$!==B&&A.has($)));if(M.size>0){f($=>{let U=!1;const F={...$};for(const K of M)F[K]||(F[K]=!0,U=!0);return U?F:$});for(const $ of M)window.setTimeout(()=>{f(U=>{if(!U[$])return U;const F={...U};return delete F[$],F})},kq)}}const P=k.filter(B=>B.kind==="completion_acknowledged");P.length&&d(B=>{const M={...B};for(const $ of P)(M[$.terminalSessionId]??0)<=$.payload.acknowledgedCompletionRevision&&delete M[$.terminalSessionId];return M});const O=k.filter(B=>B.kind==="completion").filter(B=>A.has(B.terminalSessionId)).filter(B=>!P.some(M=>M.terminalSessionId===B.terminalSessionId&&M.payload.acknowledgedCompletionRevision>=B.payload.completionRevision));O.length!==0&&(d(B=>{let M=!1;const $={...B};for(const U of O){const F=$[U.terminalSessionId]??0;U.payload.completionRevision<=F||($[U.terminalSessionId]=U.payload.completionRevision,M=!0)}return M?$:B}),D==="live"&&((L=window.electronAPI)==null?void 0:L.isElectron)===!0&&(v.current??(v.current=Eq()),v.current.play()))}),S=W(()=>m.current),w=W(k=>{m.current=k}),y=W(()=>{n()}),N=EN({apiBase:e,token:t,getCursor:S,setCursor:w,onAuthExpired:r,onResyncRequired:y,onTerminalEvents:C}),E=p.useMemo(()=>{const k=Date.now(),D=N.connectionStatus==="connected"?"healthy":N.failureExpired?"unhealthy":N.failureSince===null?"checking":"recovering";return{id:"frontend.terminal-events.websocket",capabilityId:"terminal",label:"Terminal events",state:D,summary:D==="healthy"?"Terminal 事件流已收到服务端 connected":D==="unhealthy"?N.error||"Terminal 事件流持续未连接":"等待 Terminal 事件流服务端确认",observedAt:k,dependsOn:["frontend.node.http","frontend.node.auth"],recovery:D==="recovering"||D==="unhealthy"?{startedAt:N.failureSince??k,attempt:N.reconnectAttempt,maxAttempts:null,nextAttemptAt:null,deadlineAt:(N.failureSince??k)+3e4}:null,facts:[],navigation:null}},[N.connectionStatus,N.error,N.failureExpired,N.failureSince,N.reconnectAttempt]);return Kk(E,E.id),{resetTerminalEventCursor:x}}const sR=e=>`/api/terminal/session/${encodeURIComponent(e)}/code-reviews`;function $1(e,t,r,n){return me(e,sR(r),{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}function Aq(e,t,r,n,s){return me(e,sR(r)+"",{headers:{Authorization:`Bearer ${t}`},signal:n})}function Tq(e,t,r,n){return me(e,`/api/terminal/code-reviews/${encodeURIComponent(r)}`,{headers:{Authorization:`Bearer ${t}`},signal:n})}function Dq(e,t,r){return me(e,`/api/terminal/code-reviews/${encodeURIComponent(r)}/close`,{method:"POST",headers:{Authorization:`Bearer ${t}`}})}function vce(e,t,r,n){return zv(e,`/api/terminal/code-reviews/${encodeURIComponent(r)}/artifacts/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${t}`}})}const ug=Qn(e=>({states:{},put:(t,r)=>e(n=>({states:{...n.states,[t]:r}}))})),Wh=(e,t)=>[...jt.all(e),"code-reviews",t],iR=e=>e instanceof De&&[404,501].includes(e.status)?"此电脑尚不支持代码 Review":e instanceof Error?e.message:String(e);function oR(e){const{scope:t}=vt();return ug(r=>r.states[JSON.stringify([t,e])])}function Pq(e){const t=vt(),r=xs();return W(async()=>{if(!e)return;const{scope:n,apiBase:s,token:i,onAuthExpired:a}=t,l=e.terminalSessionId,c=JSON.stringify([n,l]),u=ug.getState().states[c];if(u!=null&&u.pending)return;const d={requestId:crypto.randomUUID()},h=ug.getState().put;h(c,{pending:!0,error:null,request:d});try{try{await $1(s,i,l,d)}catch(f){if(f instanceof De)throw f;await $1(s,i,l,d)}h(c,{pending:!1,error:null,request:d}),await Promise.all([r.invalidateQueries({queryKey:Wh(n,l)}),r.invalidateQueries({queryKey:jt.sessions(n)})])}catch(f){h(c,{pending:!1,error:iR(f),request:d}),f instanceof De&&f.status===401&&(a==null||a())}})}function aR(e,t=!0){const{scope:r,apiBase:n,token:s,onAuthExpired:i}=vt(),a=Ct({queryKey:Wh(r,e),queryFn:({signal:l})=>Aq(n,s,e,l),enabled:!!e,retry:!1,staleTime:3e3,refetchInterval:l=>t&&!(l.state.error instanceof De&&[404,501].includes(l.state.error.status))?5e3:!1,refetchIntervalInBackground:!1});return p.useEffect(()=>{a.error instanceof De&&a.error.status===401&&(i==null||i())},[a.error,i]),a}function xce(e){const{scope:t,apiBase:r,token:n}=vt();return Ct({queryKey:[...jt.all(t),"code-review",e],queryFn:({signal:s})=>Tq(r,n,e,s),enabled:!!e,retry:!1,refetchInterval:s=>{var a;const i=(a=s.state.data)==null?void 0:a.run;return s.state.error||i&&!["preparing","starting","reviewing"].includes(i.phase)&&!["pending","writing"].includes(i.delivery)?!1:5e3}})}function Lq(e){const{scope:t,apiBase:r,token:n,onAuthExpired:s}=vt(),i=xs();return nr({mutationFn:a=>Dq(r,n,a),onSuccess:a=>{i.setQueryData(Wh(t,e),l=>l&&{...l,runs:l.runs.map(c=>c.caseId===a.caseId?{...c,caseStatus:a.caseStatus}:c)}),i.invalidateQueries({queryKey:Wh(t,e)}),i.invalidateQueries({queryKey:[...jt.all(t),"code-review"]})},onError:a=>{a instanceof De&&a.status===401&&(s==null||s())}})}function Mq({apiBase:e,token:t,terminalId:r}){const n=Xr(v=>v.snapshot),[s,i]=p.useState(null),[a,l]=p.useState(null),c=(n==null?void 0:n.hosts.filter(v=>v.browser.state==="ready").map(v=>`${v.hostId}:${v.installationId}:${v.bindingId}`).sort().join("|"))??"";p.useEffect(()=>{if(i(null),l(null),!window.electronAPI||!t)return;const v=new AbortController;let x;const b=async _=>{try{const C=await fetch(`${e}/api/remote/capabilities`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.any([v.signal,AbortSignal.timeout(5e3)])});if([401,403,404].includes(C.status))return;if(!C.ok)throw new Error(`HTTP ${C.status}`);const S=await C.json();if(typeof S.installationId!="string")return;v.signal.aborted||i({apiBase:e,token:t,id:S.installationId})}catch{!v.signal.aborted&&_<4&&(x=setTimeout(()=>void b(_+1),Math.min(1e3*2**_,5e3)))}};return b(0),()=>{v.abort(),clearTimeout(x)}},[e,t,c]);const u=(s==null?void 0:s.apiBase)===e&&s.token===t?s.id:null,d=u?(n==null?void 0:n.hosts.filter(v=>v.browser.state==="ready"&&v.installationId===u))??[]:[],h=W(async(v,x,b=()=>!0)=>{var _;!b()||!((_=window.electronAPI)!=null&&_.selectTunnelBrowser)||(await window.electronAPI.selectTunnelBrowser(v,x),b()&&l(v))}),f=d.length===1?d[0]:null,m=f==null?void 0:f.hostId,g=f==null?void 0:f.bindingId;return p.useEffect(()=>{let v=!1,x;const b=async _=>{if(!(v||!m||!r))try{await h(m,r,()=>!v)}catch(C){if(v)return;!/BROWSER_BINDING_CONFLICT|BROWSER_SCOPE_DENIED|NEEDS_AUTH|INVALID_TERMINAL/.test(String(C))&&_<4?x=setTimeout(()=>void b(_+1),Math.min(1e3*2**_,5e3)):Xr.getState().setNotice(A1(C))}};return b(0),()=>{v=!0,clearTimeout(x)}},[e,t,m,g,r,h]),!r||d.length<2?null:o.jsx(o.Fragment,{children:d.map(v=>{var x;return o.jsxs(Bt,{onSelect:()=>void h(v.hostId,r).catch(b=>Xr.getState().setNotice(A1(b))),children:["浏览器通道:",(x=n==null?void 0:n.config.hosts.find(b=>b.id===v.hostId))==null?void 0:x.name,a===v.hostId?" ✓":""]},v.hostId)})})}function lR(){const{scope:e}=vt(),t=Cr();return W((r="/scheduled-tasks")=>{const n=tt.getState();t(r,{state:{scope:e,workspace:{parentProjectId:n.activeParentProjectId,projectId:n.activeProjectId,terminalSessionId:n.activeSessionId,panelId:n.activeSessionId?n.activePanelIdBySessionId[n.activeSessionId]:void 0}}})})}function cR(){const{scope:e}=vt(),t=Gt(),r=Cr(),n=t.state,s=oa(e),i=(n==null?void 0:n.scope)===e?n.workspace:{parentProjectId:(s==null?void 0:s.projectId)??null,projectId:s?s.contextProjectIdByParentProjectId[s.projectId]??s.projectId:null,terminalSessionId:(s==null?void 0:s.terminalSessionId)??null},a=W(c=>r(c,{state:{scope:e,workspace:i}})),l=W(()=>{wu(e,i),r(i.terminalSessionId?`/terminal/${encodeURIComponent(i.terminalSessionId)}`:"/terminal")});return{workspace:i,go:a,back:l}}const Oq="/api/scheduled-tasks",wn=encodeURIComponent;function Uu(e,t){let r;async function n(s,i={}){s!=="/capabilities"&&(r??(r=n("/capabilities").then(()=>{}).catch(l=>{throw r=void 0,l})),await r);const a=await me(e,`${Oq}${s}`,{method:i.method,signal:i.signal,headers:{Authorization:`Bearer ${t}`,"X-Runweave-Task-Context-Version":"2",...i.body===void 0?{}:{"Content-Type":"application/json"},...i.key?{"Idempotency-Key":i.key}:{}},body:i.body===void 0?void 0:JSON.stringify(i.body)});if(s==="/capabilities"&&a.taskContextVersion!==2)throw new Error("此电脑的定时任务协议不兼容,请更新 Backend 和客户端。");return a}return{capabilities:s=>n("/capabilities",{signal:s}),list:(s,i)=>{const a=new URLSearchParams;for(const[l,c]of Object.entries(s))c!==void 0&&c!==""&&a.set(l,String(c));return n(`?${a}`,{signal:i})},task:(s,i)=>n(`/${wn(s)}`,{signal:i}),preview:(s,i)=>n("/preview",{method:"POST",body:{schedule:s},signal:i}),create:(s,i)=>n("",{method:"POST",body:s,key:i}),update:(s,i)=>n(`/${wn(s)}`,{method:"PATCH",body:i}),remove:(s,i)=>n(`/${wn(s)}`,{method:"DELETE",body:{expectedRevision:i}}),start:(s,i)=>n(`/${wn(s)}/runs`,{method:"POST",body:{},key:i}),runs:(s,i,a)=>n(`/${wn(s)}/runs${i?`?cursor=${wn(i)}`:""}`,{signal:a}),run:(s,i)=>n(`/runs/${wn(s)}`,{signal:i}),quickInputRuns:(s,i)=>{const a=new URLSearchParams;for(const[l,c]of Object.entries(s))c!==void 0&&a.set(l,String(c));return n(`/runs?${a}`,{signal:i})},output:(s,i,a)=>n(`/runs/${wn(s)}/output${i?`?cursor=${wn(i)}`:""}`,{signal:a}),continue:(s,i,a,l)=>n(`/runs/${wn(s)}/continue`,{method:"POST",body:{expectedRevision:i,...l!==void 0?{reply:l}:{}},key:a}),stop:s=>n(`/runs/${wn(s)}/stop`,{method:"POST"}),archive:s=>n(`/runs/${wn(s)}/archive`,{method:"POST",body:{}}),open:(s,i)=>n(`/runs/${wn(s)}/open-terminal`,{method:"POST",body:i})}}function Bq(){const{apiBase:e,token:t,scope:r}=vt();return Ct({queryKey:["connection",r,"agent-model-catalogs"],queryFn:({signal:n})=>Yk(e,t,n),staleTime:6e4})}const hs={all:e=>["connection",e,"scheduled-tasks"]},Hu=()=>$f.isFocused()&&sa.isOnline()?3e3:!1;function es(){const{apiBase:e,token:t,scope:r}=vt();return{api:p.useMemo(()=>Uu(e,t),[e,t]),scope:r}}function Fq(){const{api:e,scope:t}=es();return Ct({queryKey:[...hs.all(t),"capabilities"],queryFn:({signal:r})=>e.capabilities(r)})}function $q(e,t){const{api:r,scope:n}=es();return ia({queryKey:[...hs.all(n),"list",e],queryFn:({signal:s,pageParam:i})=>r.list({...e,cursor:i},s),initialPageParam:void 0,getNextPageParam:s=>s.nextCursor??void 0,refetchInterval:Hu,enabled:t})}function zq(e,t=!0){const{api:r,scope:n}=es();return Ct({queryKey:[...hs.all(n),"task",e],queryFn:({signal:s})=>r.task(e,s),enabled:t&&!!e,refetchInterval:Hu})}function Uq(e){const{api:t,scope:r}=es();return ia({queryKey:[...hs.all(r),"runs",e],queryFn:({signal:n,pageParam:s})=>t.runs(e,s,n),initialPageParam:void 0,getNextPageParam:n=>n.nextCursor??void 0,refetchInterval:Hu})}function Ml(e,t=!0){const{api:r,scope:n}=es();return Ct({queryKey:[...hs.all(n),"run",e],queryFn:({signal:s})=>r.run(e,s),enabled:!!e,refetchInterval:t?Hu:!1})}function Jf(){const{scope:e}=es(),t=xs();return()=>t.invalidateQueries({queryKey:hs.all(e)})}function uR(e){return`/background-runs/${encodeURIComponent(e)}`}function Qf(e){var t;return((t=e.snapshot.origin)==null?void 0:t.kind)==="quick-input"?uR(e.id):`/scheduled-tasks/${encodeURIComponent(e.taskId)}?run=${encodeURIComponent(e.id)}`}function Hq({source:e}){var n,s;const t=Ml(e.runId,!1),r=lR();return o.jsxs("button",{type:"button",className:"max-w-44 truncate rounded px-2 py-1 text-xs text-slate-300 hover:bg-slate-800",title:t.error?"无法读取来源名称,点击查看来源":(n=t.data)==null?void 0:n.snapshot.name,onClick:()=>{var i;return r(((i=t.data)==null?void 0:i.taskId)===e.taskId?Qf(t.data):`/scheduled-tasks/${encodeURIComponent(e.taskId)}?run=${encodeURIComponent(e.runId)}`)},children:["来源:",((s=t.data)==null?void 0:s.taskId)===e.taskId?t.data.snapshot.name:"定时任务"]})}const Wq=/^\/share\/terminal\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\?expires=([1-9][0-9]{0,15})&signature=([A-Za-z0-9_-]{43})$/;function qq(e){const t=Wq.exec(e);if(!t||t[0]!==e)return null;const r=Number(t[2]);return Number.isSafeInteger(r)?{snapshotId:t[1],expires:r,signature:t[3]}:null}function Kq(e){const t=new URL(e||window.location.origin,window.location.href);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("Terminal sharing requires an HTTP(S) connection");return t.username="",t.password="",t.search="",t.hash="",t.toString().replace(/\/+$/,"")}async function Vq(e,t,r,n){const s=Kq(e),i=await me(s,`/api/terminal/session/${encodeURIComponent(r)}/panels/${encodeURIComponent(n)}/shares`,{method:"POST",headers:{Authorization:`Bearer ${t}`}}),a=qq(i.sharePath);if(!a||a.expires!==Date.parse(i.expiresAt))throw new Error("Invalid terminal snapshot response");if(typeof i.shareUrl!="string")throw new Error("Public snapshot URL is missing");const l=new URL(i.shareUrl);if(l.protocol!=="https:"||l.username||l.password||l.hash||`${l.pathname}${l.search}`!==i.sharePath)throw new Error("Invalid public terminal snapshot URL");return{...i,url:l.href}}const Nc=Qn((e,t)=>({pending:!1,result:null,error:null,dismiss:()=>e({result:null,error:null}),createShare:async(r,n,s,i)=>{if(!t().pending){e({pending:!0,result:null,error:null});try{const a=await Vq(r,n,s,i);let l=!1;try{await navigator.clipboard.writeText(a.url),l=!0}catch{}e({result:{url:a.url,copied:l}})}catch(a){if(a instanceof De&&a.message==="Public snapshot publishing is not configured"){e({error:"当前 Backend 尚未配置公网分享服务,请配置后重试。"});return}e({error:a instanceof De?`创建终端快照失败(HTTP ${a.status})`:"创建终端快照失败,请检查 HTTP(S) 连接后重试。"})}finally{e({pending:!1})}}}})),Gq=new Set(["bash","fish","sh","zsh"]),Yq=new Set(["claude","codex","trae","traecli","traex","pi"]);function z1(e){const t=e==null?void 0:e.trim().replace(/[\\/]+$/,"");return t?t.split(/[\\/]/).filter(Boolean).at(-1)??t:null}function Ol(e){var n;const t=((n=e.alias)==null?void 0:n.trim())||z1(e.cwd)||"Terminal",r=z1(e.activeCommand??void 0);return!r||Gq.has(r)||!Yq.has(r)?t:`${t}(${r})`}function Xq(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return p.useMemo(()=>n=>{t.forEach(s=>s(n))},t)}const Zf=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Bl(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Qx(e){return"nodeType"in e}function fn(e){var t,r;return e?Bl(e)?e:Qx(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function Zx(e){const{Document:t}=fn(e);return e instanceof t}function Wu(e){return Bl(e)?!1:e instanceof fn(e).HTMLElement}function dR(e){return e instanceof fn(e).SVGElement}function Fl(e){return e?Bl(e)?e.document:Qx(e)?Zx(e)?e:Wu(e)||dR(e)?e.ownerDocument:document:document:document}const fs=Zf?p.useLayoutEffect:p.useEffect;function ep(e){const t=p.useRef(e);return fs(()=>{t.current=e}),p.useCallback(function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return t.current==null?void 0:t.current(...n)},[])}function Jq(){const e=p.useRef(null),t=p.useCallback((n,s)=>{e.current=setInterval(n,s)},[]),r=p.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,r]}function Yc(e,t){t===void 0&&(t=[e]);const r=p.useRef(e);return fs(()=>{r.current!==e&&(r.current=e)},t),r}function qu(e,t){const r=p.useRef();return p.useMemo(()=>{const n=e(r.current);return r.current=n,n},[...t])}function qh(e){const t=ep(e),r=p.useRef(null),n=p.useCallback(s=>{s!==r.current&&(t==null||t(s,r.current)),r.current=s},[]);return[r,n]}function Kh(e){const t=p.useRef();return p.useEffect(()=>{t.current=e},[e]),t.current}let dm={};function Ku(e,t){return p.useMemo(()=>{if(t)return t;const r=dm[e]==null?0:dm[e]+1;return dm[e]=r,e+"-"+r},[e,t])}function hR(e){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return n.reduce((i,a)=>{const l=Object.entries(a);for(const[c,u]of l){const d=i[c];d!=null&&(i[c]=d+e*u)}return i},{...t})}}const Xa=hR(1),Vh=hR(-1);function Qq(e){return"clientX"in e&&"clientY"in e}function tp(e){if(!e)return!1;const{KeyboardEvent:t}=fn(e.target);return t&&e instanceof t}function Zq(e){if(!e)return!1;const{TouchEvent:t}=fn(e.target);return t&&e instanceof t}function Gh(e){if(Zq(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:r}=e.touches[0];return{x:t,y:r}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:r}=e.changedTouches[0];return{x:t,y:r}}}return Qq(e)?{x:e.clientX,y:e.clientY}:null}const uo=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:r}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:r}=e;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(e){if(e)return[uo.Translate.toString(e),uo.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:n}=e;return t+" "+r+"ms "+n}}}),U1="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function eK(e){return e.matches(U1)?e:e.querySelector(U1)}const tK={display:"none"};function rK(e){let{id:t,value:r}=e;return _t.createElement("div",{id:t,style:tK},r)}function nK(e){let{id:t,announcement:r,ariaLiveType:n="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return _t.createElement("div",{id:t,style:s,role:"status","aria-live":n,"aria-atomic":!0},r)}function sK(){const[e,t]=p.useState("");return{announce:p.useCallback(n=>{n!=null&&t(n)},[]),announcement:e}}const fR=p.createContext(null);function iK(e){const t=p.useContext(fR);p.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function oK(){const[e]=p.useState(()=>new Set),t=p.useCallback(n=>(e.add(n),()=>e.delete(n)),[e]);return[p.useCallback(n=>{let{type:s,event:i}=n;e.forEach(a=>{var l;return(l=a[s])==null?void 0:l.call(a,i)})},[e]),t]}const aK={draggable:`
|
|
497
|
+
`)}function hH({terminal:e,fitAddon:t,sourceCols:r}){const n=cH(r);if(n){const s=t.proposeDimensions();if(!s)return;e.resize(n,s.rows)}else t.fit();e.refresh(0,Math.max(e.rows-1,0))}function fH({terminal:e,output:t,syncSize:r}){if(r(),!t)return;const n=dH(t);e.write(n,()=>{r(),e.scrollToBottom()})}const pN=p.createContext(null),pH=pN.Provider;function mce(){const e=p.useRef(null),t=p.useContext(pN);return p.useLayoutEffect(()=>{var n;const r=(n=e.current)==null?void 0:n.closest(".rw-image-lightbox");if(r&&t)return t(r)},[t]),o.jsx("span",{ref:e,hidden:!0})}function mH(e){return e.type==="keydown"&&e.key==="Enter"&&e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey}const co="\\u001b",gH="\\u0007",vH=new RegExp(`${co}\\]1[01];rgb:[0-9a-f/]+(?:${gH}|${co}\\\\)`,"i"),xH=new RegExp(`${co}\\[\\?[0-9;]+\\$y`),bH=new RegExp(`${co}P[01]\\$r.*${co}\\\\`),_H=new RegExp(`${co}\\[[0-9;]+R`),yH=new RegExp(`${co}\\[(?:\\?|>)[0-9;]+c`),wH=new RegExp(`${co}\\[(?:I|O)$`);function SH(e){return e.startsWith("\x1B")?vH.test(e)||xH.test(e)||bH.test(e)||_H.test(e)||yH.test(e)||wH.test(e):!1}function mN(e,t=1){const r=Math.max(0,e.buffer.active.baseY-e.buffer.active.viewportY);return{isAtBottom:r<=t,bottomOffsetRows:r}}function k1(e,t=1){return mN(e,t).isAtBottom}function CH(e){e.scrollToBottom()}const EH=2,kH=250;function I1(e=!1){const t=e?1:5;let r=0,n=-1/0;const s=()=>{r=0,n=-1/0};return{reset:s,consume(i,a,l,c,u){if(!Number.isFinite(c)||c<=0)return s(),null;const d=i.deltaMode===1?c:i.deltaMode===2?c*l:1,h=i.deltaY*d*u*EH;if(!Number.isFinite(h)||h===0)return null;(i.timeStamp-n>kH||Math.sign(h)!==Math.sign(r))&&(r=0),n=i.timeStamp,r+=h;const f=c*t,m=Math.trunc(r/f);if(m===0)return null;r-=m*f;const g=(m<0?64:65)+(e?16:0),v=Math.max(1,Math.floor(a/2)),x=Math.max(1,Math.floor(l/2));return{input:`\x1B[<${g};${v};${x}M`.repeat(Math.abs(m)),rows:m*t}}}}function IH(e){let t="",r=null;const n=()=>{r!==null&&cancelAnimationFrame(r),r=null},s=()=>{n();const i=t;t="",i&&e(i)};return{enqueue(i){t+=i,r===null&&(r=requestAnimationFrame(s))},flush:s,reset(){n(),t=""}}}const NH=e=>sk(e,"window");function RH({children:e}){return o.jsx(pH,{value:NH,children:e})}const jH=300*1e3;function AH(e){return{protocolVersion:1,status:e,observedAt:null,sampleAgeMs:null,weekly:null,shortWindow:null}}function TH(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,r=["ok","unavailable","incompatible","unsupported","not_logged_in","error"];if(t.protocolVersion!==1||!r.includes(t.status)||!(t.observedAt===null||typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt)))||!(t.sampleAgeMs===null||typeof t.sampleAgeMs=="number"&&Number.isFinite(t.sampleAgeMs)&&t.sampleAgeMs>=0))return null;const n=a=>{if(a===null)return null;if(!a||typeof a!="object"||Array.isArray(a))return;const l=a;if(!(typeof l.usedPercent!="number"||!Number.isFinite(l.usedPercent)||l.usedPercent<0||l.usedPercent>100||typeof l.windowDurationMins!="number"||!Number.isFinite(l.windowDurationMins)||l.windowDurationMins<=0||!(l.resetsAt===null||typeof l.resetsAt=="number"&&Number.isFinite(l.resetsAt)&&l.resetsAt>=0&&l.resetsAt<=864e10)))return{usedPercent:l.usedPercent,windowDurationMins:l.windowDurationMins,resetsAt:l.resetsAt}},s=n(t.weekly),i=n(t.shortWindow);return s===void 0||i===void 0?null:{protocolVersion:1,status:t.status,observedAt:t.observedAt,sampleAgeMs:t.sampleAgeMs,weekly:s,shortWindow:i}}const N1={ok:"",unavailable:"App Server 暂不可用",incompatible:"当前服务版本不支持 Codex 额度,请更新后重试",unsupported:"当前版本或登录方式不支持 Codex 额度",not_logged_in:"请先在 App Server 所在电脑登录 Codex 的 ChatGPT 订阅",error:"额度更新失败,请稍后重试"};async function DH(e,t,r,n){var i;const s=await fetch(`${e.replace(/\/+$/u,"")}/api/codex/quota${r?"?refresh=1":""}`,{headers:{Authorization:`Bearer ${t}`},cache:"no-store",signal:AbortSignal.any([n,AbortSignal.timeout(7e4)])});if(s.status===404)throw new Error("当前 Backend 版本不支持 Codex 额度");if(s.status===401){const a=(i=s.headers.get("content-type"))!=null&&i.includes("application/json")?await s.json().catch(()=>null):null;throw a&&typeof a=="object"&&"message"in a&&a.message==="Unauthorized"?new De(401,"登录已失效,请重新登录当前连接"):new Error("连接访问被拒绝,请检查代理或网络认证")}if(!s.ok)throw new Error("额度更新失败,请稍后重试");return TH(await s.json())??AH("incompatible")}const gN=p.createContext(null);function vN(){return p.useContext(gN)}function R1({title:e,value:t}){return o.jsxs("section",{className:"space-y-2 rounded-lg border border-border/60 p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h3",{className:"text-sm",children:e}),o.jsx("strong",{className:"text-xl tabular-nums",children:t?`${Number((100-t.usedPercent).toFixed(1))}%`:"未知"})]}),t?o.jsxs(o.Fragment,{children:[o.jsx("progress",{"aria-label":e,max:100,value:100-t.usedPercent,className:"h-2 w-full accent-primary"}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["下次重置:",t.resetsAt===null?"未知":new Date(t.resetsAt*1e3).toLocaleString(),t.resetsAt!==null&&t.resetsAt*1e3<=Date.now()?"(已到期,请刷新确认)":""]})]}):o.jsx("p",{className:"text-xs text-muted-foreground",children:"上游未提供此窗口"})]})}function PH({children:e,apiBase:t,token:r,connectionName:n,onUnauthorized:s,embedded:i=!1}){const[a,l]=p.useState(i),[c,u]=p.useState(null),[d,h]=p.useState(!1),[f,m]=p.useState(null),g=p.useRef(null),v=p.useRef(0),x=W(async S=>{var y;if(!r)return;(y=g.current)==null||y.abort();const w=new AbortController;g.current=w,h(!0),m(null);try{const N=await DH(t,r,S,w.signal);if(w.signal.aborted)return;N.observedAt===null&&(N.status==="unavailable"||N.status==="incompatible")?m(N1[N.status]):(u(N),v.current=performance.now())}catch(N){if(w.signal.aborted)return;N instanceof De&&N.status===401?(u(null),l(!1),s()):m(N instanceof Error?N.message:"额度更新失败")}finally{w.signal.aborted||h(!1)}});p.useEffect(()=>(a&&x(!1),()=>{var S;return(S=g.current)==null?void 0:S.abort()}),[a,x]);const b=(c==null?void 0:c.sampleAgeMs)==null?null:c.sampleAgeMs+performance.now()-v.current,_=f??(c?N1[c.status]:null),C=o.jsxs("div",{className:"space-y-4","aria-busy":d,children:[o.jsx(R1,{title:"每周剩余",value:(c==null?void 0:c.weekly)??null}),c!=null&&c.shortWindow?o.jsx(R1,{title:"短周期剩余",value:c.shortWindow}):null,_?o.jsxs("p",{role:"status",className:"text-sm text-amber-600",children:[_,c!=null&&c.observedAt?";额度为上次记录":""]}):null,c!=null&&c.observedAt?o.jsxs("p",{className:"text-xs text-muted-foreground",children:["更新于 ",new Date(c.observedAt).toLocaleString(),b!==null&&b>=jH?"(旧记录)":""]}):null,o.jsx(Z,{onClick:()=>void x(!0),disabled:d,children:d?"正在更新…":"刷新"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"仅打开或手动刷新时查询,不会持续监控。"})]});return i?C:o.jsxs(gN.Provider,{value:r?()=>l(!0):null,children:[e,o.jsx(Pu,{open:a,onOpenChange:l,children:o.jsxs(Il,{className:"w-full sm:max-w-sm",children:[o.jsxs(Ff,{children:[o.jsx(Nl,{children:"Codex 额度"}),o.jsxs(Rl,{children:[n," · App Server 的 ChatGPT 订阅"]})]}),C]})})]})}const xN=p.createContext(null),LH=()=>p.useContext(xN);function MH({payload:e}){const t=p.useRef(null),[r,n]=p.useState(!1);return p.useEffect(()=>{let s=!1;return Vr(()=>import("./browser-CIEzmzuD.js").then(i=>i.b),__vite__mapDeps([14,1])).then(async i=>{!s&&t.current&&await i.toCanvas(t.current,e,{width:320,margin:4,errorCorrectionLevel:"L",color:{dark:"#000000",light:"#ffffff"}})}).catch(()=>{s||n(!0)}),()=>{s=!0}},[e]),r?o.jsx("p",{role:"alert",children:"地址过长,无法显示二维码。请使用较短的连接地址或手动登录。"}):o.jsx("canvas",{ref:t,width:320,height:320,className:"mx-auto min-h-[320px] min-w-[320px] bg-white","aria-label":"用 Runweave iOS 扫描登录二维码"})}const OH={waiting_scan:"请在 iOS App 的连接管理中点击「扫码连接电脑」",pending_approval:"等待你确认这台手机",approved:"正在完成手机登录",issuing:"正在完成手机登录",issued:"正在完成手机登录",completed:"手机已登录",cancelled:"已取消",rejected:"已拒绝手机登录",expired:"二维码已过期,请重新生成",unconfirmed:"未收到手机完成确认;已保存的手机登录仍可使用",failed:"登录凭据签发失败,请重新扫码"};function BH({controller:e,connectionName:t,embedded:r=!1}){var c,u,d;const n=e.status&&["approved","issuing","issued"].includes(e.status.state),s=r?"section":dn,i=r?"h2":Ur,a=r?"p":Zr,l=o.jsxs(s,{className:r?"space-y-5 rounded-xl border p-5":"sm:max-w-[460px]",children:[o.jsxs(Mn,{children:[o.jsxs(i,{children:["连接手机 · ",t]}),o.jsx(a,{children:"手机需能访问此电脑。扫码后,由你在这里确认登录。"})]}),e.addresses.length>0?o.jsxs("label",{className:"grid gap-2 text-sm",children:["连接地址",o.jsx("select",{className:"w-full rounded-md border bg-background p-2",value:e.address,disabled:e.busy||!!n,onChange:h=>e.generate(h.target.value),children:e.addresses.map(h=>o.jsx("option",{value:h,children:h},h))})]}):null,o.jsxs("div",{className:"grid min-h-[160px] content-center gap-4 py-2 text-center","aria-live":"polite",children:[e.qr&&((c=e.status)==null?void 0:c.state)==="waiting_scan"&&e.seconds>0&&!e.error?o.jsxs(o.Fragment,{children:[o.jsx(MH,{payload:JSON.stringify(e.qr)},e.qr.requestId),o.jsxs("p",{className:"text-sm text-muted-foreground",children:["剩余 ",e.seconds," 秒"]})]}):null,e.status?o.jsx("p",{children:OH[e.status.state]}):e.busy?o.jsx("p",{children:"正在准备连接…"}):null,((u=e.status)==null?void 0:u.state)==="pending_approval"?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"font-medium",children:[e.status.deviceName," 请求登录"]}),o.jsxs("div",{className:"flex justify-center gap-3",children:[o.jsx(Z,{disabled:e.busy||!!e.error,onClick:()=>void e.decide("approve"),children:"允许登录"}),o.jsx(Z,{variant:"outline",disabled:e.busy||!!e.error,onClick:()=>void e.decide("reject"),children:"拒绝"})]})]}):null,e.error?o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:e.error}):null]}),!n&&((d=e.status)==null?void 0:d.state)!=="completed"?o.jsx(Z,{variant:"outline",disabled:e.busy,onClick:()=>e.address?e.generate(e.address):void e.open(),children:"重新生成二维码"}):null,o.jsx("p",{className:"text-xs text-muted-foreground",children:"也可以在手机连接管理中手动填写地址,使用原有账号密码登录。"})]});return r?l:o.jsx(Qr,{open:e.opened,onOpenChange:h=>{h||e.close()},children:l})}class $h extends Error{constructor(t,r){super(t===404?"电脑端暂不支持扫码登录,或请求已失效。":t===410?"二维码已失效,请重新生成。":t===401?"当前登录已失效,请重新登录。":t===429?"请求较多,请稍后重试。":"连接请求未完成,请重试。"),this.status=t,this.retryAfter=r}}async function Vf(e,t,r,n){const s=await fetch(`${e.replace(/\/+$/,"")}/api/auth/mobile-login${r}`,{method:n===void 0?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",keepalive:r.endsWith("/cancel"),headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},...n===void 0?{}:{body:JSON.stringify(n)},signal:AbortSignal.timeout(15e3)});if(!s.ok)throw new $h(s.status,Number(s.headers.get("Retry-After"))||1);return s.json()}const FH=(e,t,r)=>Vf(e,t,"",r),$H=(e,t,r)=>Vf(e,t,`/${encodeURIComponent(r)}`),zH=(e,t,r,n)=>Vf(e,t,`/${encodeURIComponent(r)}/decision`,n),UH=(e,t,r)=>Vf(e,t,`/${encodeURIComponent(r)}/cancel`,{});function j1(e){if(new TextEncoder().encode(e).length>2048||e!==e.trim()||/[\\\s]/u.test(e))throw new Error("Invalid mobile connection address");const t=new URL(e),r=t.hostname.toLowerCase().replace(/\.$/,"");if(!/^https?:$/.test(t.protocol)||t.username||t.password||e.includes("?")||e.includes("#")||!r||r==="localhost"||r.endsWith(".localhost")||/^127\./.test(r)||r==="0.0.0.0"||r==="[::]"||r==="[::1]"||/^\[::ffff:(?:7f[0-9a-f]{2}:|0:0\])/i.test(r))throw new Error("Configure a phone-accessible HTTP(S) connection address");return t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}async function HH(e){var a,l,c;if(e.available===!1)throw new Error("电脑后端暂不可用,请恢复连接后重试。");if(e.id!==Vn||!e.isSystem)try{return[j1(e.url)]}catch{throw new Error("请配置手机可访问的连接地址;自定义本地转发地址不能用于扫码。")}const t=await((l=(a=window.electronAPI)==null?void 0:a.getRuntimeStatusReport)==null?void 0:l.call(a)),r=t==null?void 0:t.items.find(u=>u.id==="electron.packaged-backend"),n=(c=r==null?void 0:r.facts.find(u=>u.id==="electron.packaged-backend.address"))==null?void 0:c.value;if(!t||t.source.runtime!=="electron"||t.target.kind!=="local-host"||t.observedAt+t.validForMs<Date.now()||typeof n!="string"||n.replace(/\/+$/,"")!==e.url.replace(/\/+$/,""))throw new Error("暂时无法取得这台电脑的连接地址,请稍后重试。");const s=t.items.find(u=>u.id==="electron.local-network"),i=(s==null?void 0:s.state)==="healthy"?s.facts.filter(u=>u.id==="electron.local-network.primary"||u.id.startsWith("electron.local-network.candidate-")).flatMap(u=>{try{return[j1(String(u.value))]}catch{return[]}}):[];if(!i.length)throw new Error("未找到可分享的局域网地址,请检查网络或使用手动登录。");return[...new Set(i)]}const WH=["completed","cancelled","rejected","expired","unconfirmed","failed"],Cd=e=>e instanceof $h?e.message:"连接暂时失败,请重试。";function qH(e,t,r){const[n,s]=p.useState(!1),[i,a]=p.useState(e.name),l=p.useRef(e),[c,u]=p.useState([]),[d,h]=p.useState(""),[f,m]=p.useState(null),[g,v]=p.useState(null),[x,b]=p.useState(null),[_,C]=p.useState(!1),[S,w]=p.useState(Date.now()),y=p.useRef(0),N=p.useRef(null),E=p.useRef(t);E.current=t;const k=p.useRef(Promise.resolve()),D=p.useRef(!1),j=W(O=>{O instanceof $h&&O.status===401&&(r==null||r())}),R=W(O=>{O&&UH(e.url,E.current,O.qr.requestId).catch(()=>{})}),I=W(()=>{y.current+=1,R(N.current),N.current=null,s(!1),m(null),v(null),C(!1)}),T=W(O=>{const L=++y.current;R(N.current),N.current=null,h(O),m(null),v(null),b(null),C(!0),k.current=k.current.catch(()=>{}).then(async()=>{if(L===y.current)try{const B=await FH(e.url,E.current,{baseUrl:O,connectionName:l.current.name}),M={qr:B,generation:L};if(L!==y.current){R(M);return}N.current=M,m(B),v({requestId:B.requestId,state:"waiting_scan",expiresAt:B.expiresAt})}catch(B){L===y.current&&(b(Cd(B)),j(B))}finally{L===y.current&&C(!1)}})}),A=W(async()=>{const O=++y.current;l.current={...e},a(e.name),s(!0),C(!0),b(null),m(null),v(null);try{const L=await HH(e);if(O!==y.current)return;u(L),T(L[0])}catch(L){O===y.current&&(C(!1),b(L instanceof Error?L.message:Cd(L)))}}),P=W(async O=>{const L=N.current;if(!(!L||!(g!=null&&g.claimId)||g.state!=="pending_approval"||D.current)){D.current=!0,C(!0),b(null);try{const B=await zH(e.url,E.current,L.qr.requestId,{claimId:g.claimId,decision:O});L.generation===y.current&&v(B)}catch(B){L.generation===y.current&&(j(B),b(`${Cd(B)} 正在核对电脑端状态。`))}finally{D.current=!1,L.generation===y.current&&C(!1)}}});return p.useEffect(()=>{if(!n||!f)return;let O=!1,L=!1,B;const M=y.current,$=async()=>{if(O||L||document.hidden)return;if(D.current){B=setTimeout(()=>void $(),1e3);return}L=!0;let K=1e3,Y=!1;try{const te=await $H(e.url,E.current,f.requestId);!O&&M===y.current&&(v(te),b(null),Y=WH.includes(te.state))}catch(te){!O&&M===y.current&&(b(Cd(te)),j(te),te instanceof $h&&(K=Math.max(1e3,te.retryAfter*1e3),Y=[401,404,410].includes(te.status)))}finally{L=!1,!O&&!Y&&(B=setTimeout(()=>void $(),K))}},U=setInterval(()=>{document.hidden||w(Date.now())},1e3),F=()=>{clearTimeout(B),document.hidden||$()};return document.addEventListener("visibilitychange",F),$(),()=>{O=!0,clearTimeout(B),clearInterval(U),document.removeEventListener("visibilitychange",F)}},[n,f,e.url,j]),p.useEffect(()=>{const O=()=>{y.current+=1,R(N.current),N.current=null};return window.addEventListener("pagehide",O),()=>{window.removeEventListener("pagehide",O),O()}},[R]),{opened:n,open:A,close:I,connectionName:i,addresses:c,address:d,generate:T,qr:f,status:g,error:x,busy:_,decide:P,seconds:f?Math.max(0,Math.ceil((Date.parse(f.expiresAt)-S)/1e3)):0}}function KH({children:e,connection:t,token:r}){const n=qH(t,r);return o.jsxs(xN.Provider,{value:n.open,children:[e,o.jsx(BH,{controller:n,connectionName:n.connectionName})]})}const an="mt-1 h-9 w-full rounded-md border border-border bg-background px-3 text-sm";function A1(e){const t=e instanceof Error?e.message:String(e);return t.includes("BROWSER_BINDING_CONFLICT")?"此终端正在使用另一台桌面的浏览器。请先在原桌面断开浏览器通道,再重新选择。":t.includes("NEEDS_AUTH")?"远端登录已过期,请在「端口与隧道」中重新登录浏览器通道。":t.includes("DESKTOP_UNAVAILABLE")||t.includes("TUNNEL_CANCELLED")?"浏览器通道尚未就绪,请在「端口与隧道」中检查连接后重试。":"无法连接此终端的浏览器通道,请在「端口与隧道」中检查连接后重试。"}function bN(e){return(e instanceof Error?e.message:String(e)).replace(/^Error invoking remote method '[^']+': (?:Error: )?/,"").replace(/^REMOTE_DESKTOP_[A-Z_]+:\s*/,"")}const qc={disconnected:"未连接",connecting:"连接中",ready:"已建立",reconnecting:"正在重连",failed:"运行失败",disabled:"已关闭",waiting:"等待主机连接",starting:"启动中",needs_auth:"需要登录"};function VH({value:e,relayAddress:t,onChange:r,onReadyChange:n}){const s=e??{enabled:!1,listenAddress:t??"",port:15446,localAddress:"",localPort:48571,certificateFingerprint:""},[i,a]=p.useState(!1),[l,c]=p.useState(null),[u,d]=p.useState(!1),h=p.useRef(0),f=W(()=>s),m=W(()=>{++h.current}),g=W(async()=>{const v=++h.current;a(!0),d(!1),c(null),n(!1);try{const x=window.electronAPI;if(!(x!=null&&x.getLocalRemoteDesktopInfo))throw new Error("请更新 Runweave 桌面端以自动获取 RemoteDesk 信息。");const b=await x.getLocalRemoteDesktopInfo(),_=f();if(h.current!==v||!_.enabled)return;if(_.certificateFingerprint&&_.certificateFingerprint.toLowerCase()!==b.certificateFingerprint)throw new Error("本机 RemoteDesk 身份与原配置不符。请核对 Mac 并重新配对,不会自动替换原证书指纹。");r({..._,...b,autoDetectLocalHost:!0}),d(!0),n(!0)}catch(x){h.current===v&&c(bN(x))}finally{h.current===v&&a(!1)}});return p.useEffect(()=>(s.enabled?g():(d(!1),n(!1)),m),[s.enabled,g,m,n]),o.jsxs("fieldset",{className:"space-y-3 border-t border-border pt-3",children:[o.jsx("legend",{className:"font-medium",children:"RemoteDesk · 可选"}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:s.enabled,onChange:v=>r({...s,enabled:v.target.checked})}),"通过此主机远控本机 Mac"]}),s.enabled&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"保持 Runweave 和 RemoteDesk 共享服务运行。手机需接入中转服务器所在网络或 VPN,配对与控制权限仍由 RemoteDesk 管理。"}),o.jsxs("label",{className:"block",children:["中转服务器内网 IPv4 地址",o.jsx("input",{required:!0,className:an,value:s.listenAddress,onChange:v=>r({...s,listenAddress:v.target.value.trim()})})]}),o.jsxs("label",{className:"block",children:["手机远控端口",o.jsx("input",{required:!0,type:"number",min:1024,max:65535,className:an,value:s.port||"",onChange:v=>r({...s,port:Number(v.target.value)})})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"使用独立端口,不与 Runweave 远程访问共用。服务器需可通过 SSH 执行 Node.js 并允许端口转发。"}),o.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3","aria-live":"polite",children:[o.jsx("p",{className:"font-medium",children:"本机 RemoteDesk · 自动获取"}),i&&o.jsx("p",{className:"text-muted-foreground",children:"正在读取本机共享服务…"}),u&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["已自动获取:",s.localAddress,":",s.localPort]}),o.jsxs("details",{children:[o.jsx("summary",{className:"cursor-pointer text-muted-foreground",children:"查看证书指纹"}),o.jsx("p",{className:"break-all text-xs",children:s.certificateFingerprint})]})]}),l&&o.jsx("p",{role:"alert",className:"text-amber-600",children:l}),o.jsx(Z,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>void g(),children:i?"获取中…":"重新获取"})]})]})]})}function GH({host:e,runtime:t,busy:r,run:n}){var l,c;const s=e.remoteDesktop,i=t==null?void 0:t.remoteDesktop,a=(t==null?void 0:t.state)==="ready"&&(i==null?void 0:i.state)==="ready";return o.jsxs("div",{className:"space-y-2 border-t border-border pt-3","data-remote-desktop-state":(i==null?void 0:i.state)??"disabled",children:[o.jsx("h4",{className:"text-sm font-medium",children:"RemoteDesk"}),s!=null&&s.enabled?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm",children:a?"中转入口与 Host 证书已验证":(t==null?void 0:t.state)==="disconnected"?"主机已断开":qc[(i==null?void 0:i.state)??"waiting"]}),((t==null?void 0:t.error)||(i==null?void 0:i.error))&&o.jsx("p",{role:"alert",className:"text-sm text-amber-600",children:((l=t==null?void 0:t.error)==null?void 0:l.message)??((c=i==null?void 0:i.error)==null?void 0:c.message)}),o.jsxs("p",{className:"break-all text-sm",children:[s.listenAddress,":",s.port]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"先在局域网完成 Mac 配对,再在手机「Mac 桌面 → 编辑地址」启用 Runweave 隧道并填写此地址与端口。首次画面和控制需在手机确认。"}),(i==null?void 0:i.checkedAt)&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["最近检查:",new Date(i.checkedAt).toLocaleTimeString()]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:!a||r,onClick:()=>void n(()=>navigator.clipboard.writeText(i.address)),children:"复制远控地址"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:r,onClick:()=>void n(()=>window.electronAPI.retryTunnel(e.id,"remote-desktop")),children:"重新检测"})]})]}):o.jsx("p",{className:"text-xs text-muted-foreground",children:"未启用 · 编辑主机可配置手机远控中转。"})]})}function YH({value:e,onChange:t}){const r=e??{enabled:!1,listenAddress:"",port:15443};return o.jsxs("fieldset",{className:"space-y-3 border-t border-border pt-3",children:[o.jsx("legend",{className:"font-medium",children:"远程访问本机 · 可选"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"手机通过你的中转服务器访问这台 Mac,代码和 Agent 仍在本机运行。关闭时不建立此通道。"}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:r.enabled,onChange:n=>t({...r,enabled:n.target.checked})}),"启用远程访问本机"]}),r.enabled&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"block",children:["中转服务器内网 IPv4 地址",o.jsx("input",{required:!0,className:an,placeholder:"例如 192.168.1.10",value:r.listenAddress,onChange:n=>t({...r,listenAddress:n.target.value.trim()})})]}),o.jsxs("label",{className:"block",children:["手机访问端口",o.jsx("input",{required:!0,className:an,type:"number",min:1024,max:65535,value:r.port||"",onChange:n=>t({...r,port:Number(n.target.value)})})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"服务器需已安装 Node.js,SSH 可执行 node,且允许端口转发。Mac 和手机均需能访问此内网地址,必要时连接 VPN。保存后连接主机,桌面端会启动中转并检查入口。"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"重启后需先登录 Mac、启动 Runweave,并恢复网络和 SSH 认证;可勾选上方“启动桌面端时自动连接”。"})]})]})}function XH({host:e,runtime:t,busy:r,run:n}){var l,c;const s=e.remoteAccess,i=t==null?void 0:t.remoteAccess,a=(s==null?void 0:s.enabled)&&(t==null?void 0:t.state)==="ready"&&(i==null?void 0:i.state)==="ready";return o.jsxs("div",{className:"space-y-2 border-t border-border pt-3","data-remote-access-state":(i==null?void 0:i.state)??"disabled",children:[o.jsx("h4",{className:"text-sm font-medium",children:"远程访问本机"}),s!=null&&s.enabled?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm",children:a?"中转入口可用":(t==null?void 0:t.state)==="disconnected"?"主机已断开":qc[(i==null?void 0:i.state)??"waiting"]}),((t==null?void 0:t.error)||(i==null?void 0:i.error))&&o.jsx("p",{role:"alert",className:"text-sm text-amber-600",children:((l=t==null?void 0:t.error)==null?void 0:l.message)??((c=i==null?void 0:i.error)==null?void 0:c.message)}),o.jsxs("p",{className:"break-all text-sm",children:["http://",s.listenAddress,":",s.port]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"手机接入相同网络或 VPN 后,在连接管理中添加此地址,使用这台 Mac 的 Runweave 账号登录。"}),(i==null?void 0:i.checkedAt)&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["最近检查:",new Date(i.checkedAt).toLocaleTimeString()]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:!a||r,onClick:()=>void n(()=>navigator.clipboard.writeText(i.address)),children:"复制连接地址"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:r,onClick:()=>void n(()=>window.electronAPI.retryTunnel(e.id,"remote-access")),children:"重新检测"})]})]}):o.jsx("p",{className:"text-xs text-muted-foreground",children:"未启用 · 编辑主机可配置手机经中转访问这台电脑。"})]})}function Aa(e){const t=e.split(".");if(t.length!==4||t.some(s=>!/^(0|[1-9][0-9]{0,2})$/.test(s)||Number(s)>255))return!1;const[r,n]=t.map(Number);return r===10||r===172&&n>=16&&n<=31||r===192&&n===168}const cm=e=>typeof e=="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e),Ta=e=>Number.isInteger(e)&&Number(e)>0&&Number(e)<=65535,T1=e=>typeof e=="string"&&e.trim().length>0&&e.length<=120;function JH(e){if(!e||typeof e!="object")throw new Error("INVALID_TUNNEL_CONFIG");const t=e;if(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0||!Array.isArray(t.hosts)||t.hosts.length>64||!Array.isArray(t.backendEndpoints)||t.backendEndpoints.length>128)throw new Error("INVALID_TUNNEL_CONFIG");const r=t.hosts.map(s=>{if(!s||!cm(s.id)||!T1(s.name)||typeof s.sshTarget!="string"||!/^[a-zA-Z0-9_][a-zA-Z0-9_.@-]{0,254}$/.test(s.sshTarget)||typeof s.autoConnect!="boolean"||!Array.isArray(s.forwards)||s.forwards.length>64)throw new Error("INVALID_TUNNEL_HOST");const i=s.forwards.map(u=>{if(!u||!cm(u.id)||!T1(u.name)||!Ta(u.port)||typeof u.enabled!="boolean"||typeof u.path!="string"||u.path.length>2048||!u.path.startsWith("/")||u.path.startsWith("//")||u.path.includes("\\"))throw new Error("INVALID_TUNNEL_FORWARD");return{id:u.id,name:u.name.trim(),port:u.port,enabled:u.enabled,path:u.path}});if(new Set(i.map(u=>u.id)).size!==i.length||new Set(i.map(u=>u.port)).size!==i.length)throw new Error("DUPLICATE_TUNNEL_PORT");const a=s.remoteAccess;if(a&&(typeof a.enabled!="boolean"||typeof a.listenAddress!="string"||!Ta(a.port)||a.port<1024||(a.enabled||a.listenAddress!=="")&&!Aa(a.listenAddress)))throw new Error("远程访问需要有效的服务器内网 IPv4 地址及 1024–65535 端口");const l=s.remoteDesktop;if(l&&(typeof l.enabled!="boolean"||l.autoDetectLocalHost!==void 0&&typeof l.autoDetectLocalHost!="boolean"||typeof l.listenAddress!="string"||!Ta(l.port)||l.port<1024||typeof l.localAddress!="string"||!Ta(l.localPort)||typeof l.certificateFingerprint!="string"||(l.enabled?!Aa(l.listenAddress)||!Aa(l.localAddress)||!/^[a-fA-F0-9]{64}$/.test(l.certificateFingerprint):l.listenAddress!==""&&!Aa(l.listenAddress)||l.localAddress!==""&&!Aa(l.localAddress)||l.certificateFingerprint!==""&&!/^[a-fA-F0-9]{64}$/.test(l.certificateFingerprint))))throw new Error("RemoteDesk 需要有效的内网地址、端口和 Mac 的完整 SHA-256 证书指纹");if(l!=null&&l.enabled&&(a!=null&&a.enabled)&&l.listenAddress===a.listenAddress&&l.port===a.port)throw new Error("RemoteDesk 与 Runweave 远程访问需要不同的中转端口");const c=s.browser;if(!c||typeof c.enabled!="boolean"||!Ta(c.backendPort)||!WO(c.profileId)||!(c.approvedBrowserGroupId===null||typeof c.approvedBrowserGroupId=="string"&&c.approvedBrowserGroupId.length>0&&c.approvedBrowserGroupId.length<=512))throw new Error("INVALID_BROWSER_TUNNEL");return{id:s.id,name:s.name.trim(),sshTarget:s.sshTarget,...a?{remoteAccess:{enabled:a.enabled,listenAddress:a.listenAddress,port:a.port}}:{},...l?{remoteDesktop:{enabled:l.enabled,listenAddress:l.listenAddress,port:l.port,localAddress:l.localAddress,localPort:l.localPort,certificateFingerprint:l.certificateFingerprint.toLowerCase(),...l.autoDetectLocalHost!==void 0?{autoDetectLocalHost:l.autoDetectLocalHost}:{}}}:{},autoConnect:s.autoConnect,forwards:i,browser:{enabled:c.enabled,backendPort:c.backendPort,profileId:c.profileId,approvedBrowserGroupId:c.approvedBrowserGroupId}}});if(new Set(r.map(s=>s.id)).size!==r.length)throw new Error("DUPLICATE_TUNNEL_HOST");const n=t.backendEndpoints.map(s=>{if(!s||!cm(s.id)||!r.some(i=>i.id===s.hostId)||!Ta(s.remotePort))throw new Error("INVALID_BACKEND_ENDPOINT");return{id:s.id,hostId:s.hostId,remotePort:s.remotePort}});if(new Set(n.map(s=>s.id)).size!==n.length)throw new Error("DUPLICATE_BACKEND_ENDPOINT");return{expectedRevision:t.expectedRevision,hosts:r,backendEndpoints:n}}function QH({host:e,snapshot:t,onCancel:r,onSaved:n,embedded:s=!1}){var C,S;const[i,a]=p.useState(e),[l]=p.useState(()=>t.config.hosts.find(w=>w.id===e.id)??null),[c]=p.useState(()=>t.config.backendEndpoints.filter(w=>w.hostId===e.id)),[u,d]=p.useState(c),[h,f]=p.useState(null),[m,g]=p.useState(!1),[v,x]=p.useState(!1);va(s&&(JSON.stringify(i)!==JSON.stringify(e)||JSON.stringify(u)!==JSON.stringify(c)),s&&m);const b=w=>a({...i,...w}),_=W(async()=>{var w;if(!m){f(null),g(!0);try{let y=i;if((w=i.remoteDesktop)!=null&&w.enabled){if(!v)throw new Error("请先启动本机 RemoteDesk 并完成自动获取。");const D=await window.electronAPI.getLocalRemoteDesktopInfo();if(D.certificateFingerprint!==i.remoteDesktop.certificateFingerprint)throw new Error("本机 RemoteDesk 身份已改变,请核对并重新配对。");y={...i,remoteDesktop:{...i.remoteDesktop,...D,autoDetectLocalHost:!0}}}const N=t.config.hosts.find(D=>D.id===e.id)??null,E=t.config.backendEndpoints.filter(D=>D.hostId===e.id);if(JSON.stringify(N)!==JSON.stringify(l)||JSON.stringify(E)!==JSON.stringify(c))throw new Error("这台主机的配置已被其他操作修改,当前输入已保留。请重新打开编辑器核对后保存。");const k=JH({expectedRevision:t.config.revision,hosts:[...t.config.hosts.filter(D=>D.id!==e.id),y],backendEndpoints:[...t.config.backendEndpoints.filter(D=>D.hostId!==e.id),...u]});n(await window.electronAPI.saveTunnels(k))}catch(y){const N=bN(y);f(N.includes("CONFIG_REVISION_CONFLICT")?"配置刚被其他操作修改,当前输入已保留,请重试保存。":N)}finally{g(!1)}}});return o.jsx("form",{className:"space-y-3 rounded-xl border border-primary/40 p-4 text-sm",onSubmit:w=>{w.preventDefault(),_()},children:o.jsxs("fieldset",{disabled:m,className:"space-y-3",children:[o.jsx("h3",{className:"font-medium",children:t.config.hosts.some(w=>w.id===e.id)?"编辑主机":"添加主机"}),o.jsxs("label",{className:"block",children:["名称",o.jsx("input",{className:an,required:!0,value:i.name,onChange:w=>b({name:w.target.value})})]}),o.jsxs("label",{className:"block",children:["SSH 主机或配置别名",o.jsx("input",{className:an,required:!0,placeholder:"user@host 或 devbox",value:i.sshTarget,onChange:w=>b({sshTarget:w.target.value})})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"沿用本机 SSH 配置与密钥,请先确认终端中 SSH 可以连接。"}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:i.autoConnect,onChange:w=>b({autoConnect:w.target.checked})}),"启动桌面端时自动连接"]}),o.jsx(YH,{value:i.remoteAccess,onChange:w=>b({remoteAccess:w})}),o.jsx(VH,{value:i.remoteDesktop,relayAddress:(C=i.remoteAccess)==null?void 0:C.listenAddress,onChange:w=>b({remoteDesktop:w}),onReadyChange:x}),o.jsx("h4",{className:"border-t border-border pt-3 font-medium",children:"开发服务端口"}),i.forwards.map((w,y)=>o.jsxs("fieldset",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[o.jsxs("legend",{className:"sr-only",children:["端口 ",y+1]}),o.jsxs("label",{className:"block",children:["服务名称",o.jsx("input",{className:an,value:w.name,onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,name:N.target.value}:E)})})]}),o.jsxs("label",{className:"block",children:["端口(本地与远端相同)",o.jsx("input",{className:an,type:"number",min:"1",max:"65535",required:!0,value:w.port||"",onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,port:Number(N.target.value)}:E)})})]}),o.jsxs("label",{className:"block",children:["访问路径",o.jsx("input",{className:an,value:w.path,onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,path:N.target.value}:E)})})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:w.enabled,onChange:N=>b({forwards:i.forwards.map(E=>E.id===w.id?{...E,enabled:N.target.checked}:E)})}),"启用转发"]}),o.jsx(Z,{type:"button",size:"sm",variant:"ghost",onClick:()=>b({forwards:i.forwards.filter(N=>N.id!==w.id)}),children:"移除端口"})]},w.id)),o.jsx(Z,{type:"button",size:"sm",variant:"outline",onClick:()=>b({forwards:[...i.forwards,{id:crypto.randomUUID(),name:"开发服务",port:3e3,path:"/",enabled:!0}]}),children:"添加端口"}),!s&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex items-center gap-2 border-t border-border pt-3",children:[o.jsx("input",{type:"checkbox",checked:i.browser.enabled,onChange:w=>b({browser:{...i.browser,enabled:w.target.checked}})}),"允许远端 Agent 使用本机 Browser"]}),i.browser.enabled&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"block",children:["远端 Backend 端口",o.jsx("input",{type:"number",className:an,min:"1",max:"65535",required:!0,value:i.browser.backendPort||"",onChange:w=>b({browser:{...i.browser,backendPort:Number(w.target.value)}})})]}),o.jsxs("label",{className:"block",children:["授权 Browser",o.jsx("select",{className:an,value:i.browser.profileId,onChange:w=>b({browser:{...i.browser,profileId:w.target.value}}),children:[1,2,3].map(w=>o.jsxs("option",{value:`profile-${w}`,children:["Browser ",w]},w))})]}),o.jsxs("label",{className:"block",children:["允许复用的工作组 ID(可选)",o.jsx("input",{className:an,value:i.browser.approvedBrowserGroupId??"",onChange:w=>b({browser:{...i.browser,approvedBrowserGroupId:w.target.value||null}})})]})]})]}),o.jsxs("details",{children:[o.jsx("summary",{className:"cursor-pointer text-muted-foreground",children:"高级 · Backend 访问入口"}),o.jsx("p",{className:"my-2 text-xs text-muted-foreground",children:"为只能通过 SSH 访问的 Backend 保留内部入口。删除入口后,引用它的连接将等待通道。"}),u.map(w=>o.jsxs("div",{className:"my-2 flex items-center gap-2",children:[o.jsxs("label",{children:["远端端口",o.jsx("input",{type:"number",min:"1",max:"65535",className:an,value:w.remotePort||"",onChange:y=>d(u.map(N=>N.id===w.id?{...N,remotePort:Number(y.target.value)}:N))})]}),o.jsx(Z,{type:"button",size:"sm",variant:"ghost",onClick:()=>d(u.filter(y=>y.id!==w.id)),children:"移除入口"})]},w.id)),o.jsx(Z,{type:"button",size:"sm",variant:"outline",onClick:()=>d([...u,{id:crypto.randomUUID(),hostId:e.id,remotePort:5001}]),children:"添加 Backend 入口"})]}),h&&o.jsx("p",{role:"alert",className:"text-red-500",children:h}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(Z,{type:"button",variant:"ghost",disabled:m,onClick:r,children:"取消"}),o.jsx(Z,{type:"submit",disabled:m||((S=i.remoteDesktop)==null?void 0:S.enabled)&&!v,children:m?"保存中…":"保存配置"})]})]})})}function ZH({host:e,runtime:t,run:r,busy:n}){const[s,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(!1),[d,h]=p.useState("");return o.jsxs("div",{className:"space-y-2 border-t border-border pt-3 text-sm",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx("h4",{className:"font-medium",children:"远端使用本机 Browser"}),o.jsx("span",{children:qc[(t==null?void 0:t.browser.state)??(e.browser.enabled?"waiting":"disabled")]})]}),e.browser.enabled&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Browser ",e.browser.profileId.slice(-1)," · 远端 Backend"," ",e.browser.backendPort]}),(t==null?void 0:t.browser.error)&&o.jsx("p",{role:"alert",className:"text-amber-600",children:t.browser.error.message}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:n||(t==null?void 0:t.state)!=="ready",onClick:()=>u(!c),children:"登录远端 Backend"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:n||(t==null?void 0:t.state)!=="ready",onClick:()=>void r(()=>window.electronAPI.retryTunnel(e.id)),children:"重试浏览器通道"}),(c||(t==null?void 0:t.browser.state)==="needs_auth")&&o.jsxs("form",{className:"space-y-2",onSubmit:f=>{f.preventDefault(),r(async()=>{try{const m=await window.electronAPI.loginTunnelBrowser({hostId:e.id,username:s,password:a});h(m.persistent?"登录已加密保存":"系统加密不可用,登录仅在本次运行有效"),u(!1)}finally{l("")}})},children:[o.jsxs("label",{className:"block",children:["用户名",o.jsx("input",{autoComplete:"username",className:an,value:s,onChange:f=>i(f.target.value)})]}),o.jsxs("label",{className:"block",children:["密码",o.jsx("input",{type:"password",autoComplete:"current-password",className:an,value:a,onChange:f=>l(f.target.value)})]}),o.jsx(Z,{size:"sm",type:"submit",disabled:n||(t==null?void 0:t.state)!=="ready",children:"登录并启用"})]}),d&&o.jsx("p",{role:"status",children:d})]})]})}function zh(e){const t=e.trim();if(!t)return{ok:!1,error:"Enter a URL"};if(/^https?:\/\//i.test(t))return Ed(t);if(/^\d+$/.test(t)){const r=Number(t);return!Number.isInteger(r)||r<1||r>65535?{ok:!1,error:"Port must be between 1 and 65535"}:Ed(`http://127.0.0.1:${t}`)}return/^(localhost|127(?:\.\d{1,3}){3}|\[::1\]):\d{1,5}(\/.*)?$/i.test(t)?Ed(`http://${t}`):Ed(`https://${t}`)}function Ed(e){try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,error:"Only http and https URLs are supported"}:t.port==="0"?{ok:!1,error:"Port must be between 1 and 65535"}:{ok:!0,url:t.toString()}}catch{return{ok:!1,error:"Enter a valid http or https URL"}}}async function Kc(e){var i,a,l,c,u,d;const t=zh(e.url);if(!t.ok)throw new Error(t.error);if(((i=window.electronAPI)==null?void 0:i.isElectron)!==!0||!window.electronAPI.terminalBrowserCreateTab)return window.open(t.url,"_blank","noopener,noreferrer"),null;const r=e.profileId?null:await((l=(a=window.electronAPI).terminalBrowserGetProfilePreferences)==null?void 0:l.call(a)),n=e.profileId??(e.projectId?(c=r==null?void 0:r.worktrees[e.projectId])==null?void 0:c.preferredProfileId:null)??(r==null?void 0:r.defaultProfileId)??PE;let s=e.placement;if(s.kind==="active-group"){const h=await((d=(u=window.electronAPI).terminalBrowserGetWorkspace)==null?void 0:d.call(u,n)),f=h==null?void 0:h.tabs.find(m=>m.tabId===h.activeTabId);s=f?{kind:"current-group",groupId:f.browserGroupId,openerTabId:f.tabId}:{kind:"new-group"}}return await window.electronAPI.terminalBrowserCreateTab(s.kind==="current-group"?{profileId:n,placement:"current-group",groupId:s.groupId,openerTabId:s.openerTabId,url:t.url,source:e.source}:{profileId:n,placement:"new-group",url:t.url,source:e.source}),n}const eW=()=>({id:crypto.randomUUID(),name:"",sshTarget:"",autoConnect:!1,forwards:[],browser:{enabled:!1,backendPort:5001,profileId:"profile-1",approvedBrowserGroupId:null}});function tW({embedded:e=!1}){var C;const{snapshot:t,open:r,error:n,notice:s,setOpen:i,setSnapshot:a,setError:l,setNotice:c}=Xr(),[u,d]=p.useState(null),[h,f]=p.useState(!1);p.useEffect(()=>{const S=window.electronAPI;if(!(S!=null&&S.isElectron)||e)return;let w=!1;const y=[S.onTunnelsChanged(a),S.onTunnelNotice(c),S.onOpenTunnels(()=>i(!0))];return S.listTunnels().then(N=>{w||a(N)}).catch(N=>{w||l(String(N))}),()=>{w=!0,y.forEach(N=>N())}},[e,a,l,c,i]);const m=W(async S=>{if(!h){f(!0),l(null);try{await S()}catch(w){l(w instanceof Error?w.message:String(w))}finally{f(!1)}}}),g=W(async S=>{!t||!window.confirm(`删除 ${S.name}?此主机的隧道将停止,远端任务不受影响。`)||await m(async()=>a(await window.electronAPI.saveTunnels({expectedRevision:t.config.revision,hosts:t.config.hosts.filter(w=>w.id!==S.id),backendEndpoints:t.config.backendEndpoints.filter(w=>w.hostId!==S.id)})))});if(!((C=window.electronAPI)!=null&&C.isElectron))return null;const v=e?"section":Il,x=e?"h2":Nl,b=e?"p":Rl,_=o.jsxs(v,{className:e?"space-y-3":"w-full overflow-y-auto sm:w-[560px]",children:[o.jsx(x,{children:"端口与隧道"}),o.jsx(b,{children:"管理这台电脑的 SSH 通道。切换连接或关闭面板不影响运行;退出桌面端后停止。"}),o.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:t!=null&&t.owner.devSessionId?"Dev Session · 独立配置":"本机用户配置"}),o.jsx(Z,{size:"sm",disabled:h||!t,onClick:()=>d(eW()),children:"添加 SSH 主机"})]}),n&&o.jsxs("div",{role:"alert",className:"rounded-lg border border-red-500/30 p-3 text-sm text-red-500",children:[n,o.jsx(Z,{variant:"ghost",size:"sm",onClick:()=>void m(async()=>a(await window.electronAPI.listTunnels())),children:"重新读取"})]}),s&&o.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:s}),u&&t?o.jsx(QH,{host:u,embedded:e,snapshot:t,onCancel:()=>d(null),onSaved:S=>{a(S),d(null),c("配置已保存,运行结果见各通道状态。")}},u.id):null,!t&&!n&&o.jsx("p",{children:"读取配置中…"}),(t==null?void 0:t.config.hosts.length)===0&&!u&&o.jsx("div",{className:"rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground",children:e?"添加 SSH 主机后,可配置开发服务端口、Backend 入口和手机远程接入。":"添加 SSH 主机后,可配置手机远程访问本机、转发开发服务端口,或允许远端 Agent 使用本机 Browser。"}),t==null?void 0:t.config.hosts.map(S=>{const w=t.hosts.find(y=>y.hostId===S.id);return o.jsxs("section",{className:"space-y-4 rounded-xl border border-border p-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"font-semibold",children:S.name}),o.jsx("p",{className:"text-xs text-muted-foreground",children:S.sshTarget}),o.jsx("p",{className:"mt-1 text-sm",children:qc[(w==null?void 0:w.state)??"disconnected"]})]}),o.jsxs("div",{className:"flex gap-1",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:h,onClick:()=>void m(()=>(w==null?void 0:w.state)==="ready"||(w==null?void 0:w.state)==="connecting"||(w==null?void 0:w.state)==="reconnecting"?window.electronAPI.disconnectTunnel(S.id):window.electronAPI.connectTunnel(S.id)),children:(w==null?void 0:w.state)==="ready"||(w==null?void 0:w.state)==="connecting"||(w==null?void 0:w.state)==="reconnecting"?"断开":"连接"}),o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>d(structuredClone(S)),children:"编辑"}),o.jsx(Z,{size:"sm",variant:"ghost",disabled:h,onClick:()=>void g(S),children:"删除"})]})]}),(w==null?void 0:w.error)&&o.jsx("p",{role:"alert",className:"text-sm text-amber-600",children:w.error.message}),o.jsxs("div",{className:"space-y-2 border-t border-border pt-3",children:[o.jsx("h4",{className:"text-sm font-medium",children:"开发服务端口"}),S.forwards.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"尚未配置"}):S.forwards.map(y=>{const N=w==null?void 0:w.forwards[y.id];return o.jsxs("div",{className:"rounded-lg bg-muted/40 p-3 text-sm",children:[o.jsxs("div",{className:"flex justify-between gap-2",children:[o.jsxs("span",{children:[y.name," · ",y.port," → ",y.port]}),o.jsx("span",{children:qc[(N==null?void 0:N.state)??(y.enabled?"waiting":"disabled")]})]}),o.jsxs("p",{className:"mt-1 break-all text-xs text-muted-foreground",children:["http://127.0.0.1:",y.port,y.path]}),(N==null?void 0:N.error)&&o.jsx("p",{role:"alert",className:"mt-2 text-amber-600",children:N.error.message}),(N==null?void 0:N.state)==="failed"&&o.jsx(Z,{size:"sm",variant:"ghost",disabled:h,onClick:()=>void m(()=>window.electronAPI.retryTunnel(S.id,y.id)),children:"重试转发"}),(N==null?void 0:N.state)==="ready"&&o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>void m(()=>Kc({url:`http://127.0.0.1:${y.port}${y.path}`,profileId:S.browser.profileId,placement:{kind:"new-group"}})),children:"打开网页"})]},y.id)})]}),o.jsx(XH,{host:S,runtime:w,run:m,busy:h}),o.jsx(GH,{host:S,runtime:w,busy:h,run:m}),!e&&o.jsx(ZH,{host:S,runtime:w,run:m,busy:h})]},S.id)})]});return e?_:o.jsxs(o.Fragment,{children:[s&&!r&&o.jsxs(eo,{kind:"tunnel",noticeKey:s,onDismiss:()=>c(null),className:"rounded-lg border border-border bg-background p-3 text-sm text-foreground shadow-lg",children:[o.jsx("p",{children:s}),o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>{i(!0),c(null)},children:"查看端口与隧道"})]}),o.jsx(Pu,{open:r,onOpenChange:i,children:_})]})}class ih extends Error{constructor(t,r){super(r.error.message),this.status=t,this.detail=r}get uncertain(){return![400,404,409,413].includes(this.status)||this.detail.error.code==="IDEMPOTENCY_KEY_REUSED"}}function _N(e){const t=new URL(e.trim());if(!["https:","http:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("请输入完整的随记服务地址");if(t.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("远程随记服务需要 HTTPS");return t.href.replace(/\/+$/,"")}class rW{constructor(t,r){St(this,"endpoint");St(this,"saved");St(this,"lifetime",new AbortController);St(this,"renewing");this.storage=r,this.endpoint=_N(t),this.saved=r.session}get active(){return!this.lifetime.signal.aborted}assertActive(){if(!this.active)throw new DOMException("服务连接已切换","AbortError")}cancel(){this.lifetime.abort()}async store(t){this.assertActive();const r={tokens:t,expiresAt:Date.now()+t.expiresIn*1e3};return await this.storage.persist(r),this.assertActive(),this.saved=r,r}async raw(t,r,n,s,i,a){var c;this.assertActive();const l=await fetch(this.endpoint+t,{method:r,body:n,cache:"no-store",credentials:"omit",redirect:"error",signal:AbortSignal.any([this.lifetime.signal,AbortSignal.timeout(3e4),...a?[a]:[]]),headers:{...n instanceof FormData?{}:{"Content-Type":"application/json"},...s?{Authorization:`Bearer ${s}`}:{},...i?{"Idempotency-Key":i}:{}}});if(this.assertActive(),!l.ok){const u=await l.json();throw(c=u==null?void 0:u.error)!=null&&c.message?new ih(l.status,u):new Error(`服务响应异常(${l.status}),请手动确认结果`)}return l}async login(t,r){const n=await this.raw("/api/auth/login","POST",JSON.stringify({username:t,password:r}));return await this.store(await n.json()),this.info()}refresh(){if(this.renewing)return this.renewing;const t=this.saved;return t?(this.renewing=(async()=>{let r;try{r=await this.raw("/api/auth/refresh","POST",JSON.stringify({refreshToken:t.tokens.refreshToken}))}catch(s){if(!(s instanceof ih)||s.status!==401||!this.storage.credentials)throw s;r=await this.raw("/api/auth/login","POST",JSON.stringify(this.storage.credentials))}const n=await r.json();if(n.ownerId!==t.tokens.ownerId||n.serverId!==t.tokens.serverId)throw new Error("服务身份已改变,请重新登录;原草稿仍保留");return this.store(n)})().finally(()=>{this.renewing=void 0}),this.renewing):Promise.reject(new Error("请登录随记"))}async authorized(t,r,n,s,i){let a=this.saved;if(!a)throw new Error("请登录随记");a.expiresAt<Date.now()+6e4&&(a=await this.refresh());try{return await this.raw(t,r,n,a.tokens.accessToken,s,i)}catch(l){if(!(l instanceof ih&&l.status===401&&r==="GET"))throw l;const c=await this.refresh();return this.raw(t,r,n,c.tokens.accessToken,s,i)}}async request(t,r="GET",n,s,i){const l=await(await this.authorized(t,r,n instanceof FormData?n:n===void 0?void 0:JSON.stringify(n),s,i)).json();return this.assertActive(),l}async file(t){const n=await(await this.authorized(`/api/suiji/v1/attachments/${encodeURIComponent(t)}/content`,"GET")).blob();return this.assertActive(),n}async restore(){if(!this.saved&&this.storage.credentials){const{username:t,password:r}=this.storage.credentials;return this.login(t,r)}return this.info()}async info(){var r,n;const t=await this.request("/api/suiji/v1/info");if(t.protocolVersion!==1||t.ownerId!==((r=this.saved)==null?void 0:r.tokens.ownerId)||t.serverId!==((n=this.saved)==null?void 0:n.tokens.serverId))throw new Error("服务身份或协议已改变,请重新登录;原草稿仍保留");return t}async logout(){const t=this.saved;if(this.cancel(),await this.storage.persist(void 0,!0),this.storage.credentials=void 0,this.saved=void 0,t)try{await fetch(this.endpoint+"/api/auth/logout",{method:"POST",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(5e3),headers:{Authorization:`Bearer ${t.tokens.accessToken}`}})}catch{}}}class nW{constructor(t,r,n="production"){St(this,"scope");St(this,"database");this.scope=JSON.stringify([...n==="development"?[n]:[],t,r.serverId,r.ownerId]),this.database=new Promise((s,i)=>{const a=indexedDB.open("suiji-local-v1",1);a.onupgradeneeded=()=>a.result.createObjectStore("drafts"),a.onerror=()=>i(new Error("无法打开本机草稿存储")),a.onsuccess=()=>s(a.result)})}async get(t){const r=await this.database;return new Promise((n,s)=>{const i=r.transaction("drafts","readonly").objectStore("drafts").get(this.scope+":"+t);i.onerror=()=>s(new Error("读取本机草稿失败")),i.onsuccess=()=>n(i.result)})}async set(t,r){const n=structuredClone(r),s=await this.database;await new Promise((i,a)=>{const l=s.transaction("drafts","readwrite");l.objectStore("drafts").put(n,this.scope+":"+t),l.oncomplete=()=>i(),l.onabort=l.onerror=()=>a(new Error("本机草稿未保存,可能空间不足,请保留页面并重试"))})}async remove(t){const r=await this.database;await new Promise((n,s)=>{const i=r.transaction("drafts","readwrite");i.objectStore("drafts").delete(this.scope+":"+t),i.oncomplete=()=>n(),i.onabort=i.onerror=()=>s(new Error("本机确认状态未保存,请手动重试"))})}close(){this.database.then(t=>t.close()).catch(()=>{})}}const gce=e=>e==="production"?"正式":"开发",Vc="suiji.accounts.v1",Xx=()=>{const e=window.electronAPI;if(!(e!=null&&e.loadSuijiState)||!e.saveSuijiProfile||!e.selectSuijiEnvironment)throw new Error("请更新桌面客户端以启用随记账户保存");return e};async function Ic(){var r;if((r=window.electronAPI)!=null&&r.isElectron)return Xx().loadSuijiState();const e=ht.getItem(Vc),t=e?JSON.parse(e):{active:"production",profiles:{production:{endpoint:ht.getItem("suiji.endpoint.v1")??"",username:""},development:{endpoint:"http://127.0.0.1:4783",username:""}}};for(const n of["production","development"]){const s=g0.getItem(`${Vc}:${n}`);s&&(t.profiles[n].session=JSON.parse(s))}return t}async function D1(e,t){var n;if((n=window.electronAPI)!=null&&n.isElectron)return Xx().saveSuijiProfile(e,t);const r=await Ic();r.profiles[e]=t,t.session?g0.setItem(`${Vc}:${e}`,JSON.stringify(t.session)):g0.removeItem(`${Vc}:${e}`),yN(r)}function yN(e){ht.setItem(Vc,JSON.stringify({...e,profiles:Object.fromEntries(Object.entries(e.profiles).map(([t,r])=>[t,{endpoint:r.endpoint,username:r.username}]))}))}async function sW(e){var r;if((r=window.electronAPI)!=null&&r.isElectron)return Xx().selectSuijiEnvironment(e);const t=await Ic();t.active=e,yN(t)}function iW(){const[e,t]=p.useState(),[r,n]=p.useState(""),[s,i]=p.useState(""),[a,l]=p.useState(""),[c,u]=p.useState(!0),[d,h]=p.useState(""),[f,m]=p.useState(!0),[g,v]=p.useState(),x=p.useRef(void 0),b=p.useRef(!0),_=p.useRef(0),C=I=>{n(I.endpoint),i(I.username),l(I.password??"")},S=W(async(I,T=!1)=>{var B;const A=++_.current;(B=x.current)==null||B.cancel(),v(void 0),u(!0),h("");const P=I.active;let O={...I.profiles[P]},L;try{if(T&&(O={endpoint:_N(r),username:s.trim(),password:a}),m(T||!O.session&&!O.password),!O.endpoint||!T&&!O.session&&!O.password)return;L=new rW(O.endpoint,{session:O.session,credentials:O.password?{username:O.username,password:O.password}:void 0,persist:async($,U)=>{if(!b.current||A!==_.current)throw new DOMException("连接已切换","AbortError");const F={...O,session:$,...U?{password:void 0}:{}};await D1(P,F),O=F,b.current&&A===_.current&&t(K=>K&&{...K,profiles:{...K.profiles,[P]:F}})}}),x.current=L;const M=T?await L.login(O.username,O.password):await L.restore();if(!b.current||A!==_.current)return;v({client:L,info:M,store:new nW(L.endpoint,M,P)}),C(O)}catch(M){b.current&&A===_.current&&(M instanceof ih&&M.status===401&&(m(!0),l("")),h(M instanceof Error?M.message:"连接失败"))}finally{b.current&&A===_.current&&u(!1)}}),w=p.useRef(null),y=W(async()=>{if(w.current)return w.current;const I=(async()=>{u(!0),h("");try{const T=await Ic();if(!b.current)return;t(T),C(T.profiles[T.active]),await S(T)}catch(T){b.current&&(h(T instanceof Error?T.message:"账户读取失败"),u(!1))}})();w.current=I;try{await I}finally{w.current===I&&(w.current=null)}}),N=W(()=>{var I;b.current=!1,++_.current,(I=x.current)==null||I.cancel(),w.current=null});p.useEffect(()=>(b.current=!0,N),[y,N]);const E=W(async I=>{var T;if(!(!e||c||I===e.active)){(T=x.current)==null||T.cancel(),++_.current,v(void 0),u(!0),h("");try{await sW(I);const A=await Ic();t(A),C(A.profiles[I]),await S(A)}catch(A){h(A instanceof Error?A.message:"环境切换失败"),u(!1)}}}),k=W(async()=>{if(!(!e||c)){u(!0),h("");try{const I=x.current;v(void 0),I?await I.logout():await D1(e.active,{endpoint:r,username:s}),++_.current,x.current=void 0,v(void 0),l(""),m(!0);const T=await Ic();t(T),C(T.profiles[T.active])}catch(I){h(I instanceof Error?I.message:"退出失败")}finally{u(!1)}}}),D=W(()=>e||w.current?w.current??Promise.resolve():y()),j=W(I=>b.current&&x.current===I&&I.active),R=W(()=>{var I;(I=x.current)==null||I.cancel(),++_.current,v(void 0),m(!0)});return{accounts:e,endpoint:r,setEndpoint:n,username:s,setUsername:i,password:a,setPassword:l,busy:c,message:d,connection:g,needsLogin:f,setNeedsLogin:m,ensure:D,initialize:y,connect:S,switchEnvironment:E,logout:k,editAccount:R,isCurrent:j}}const wN=p.createContext(null);function oW({children:e}){const t=iW();return o.jsx(wN.Provider,{value:t,children:e})}function aW(){const e=p.useContext(wN);if(!e)throw new Error("SuijiConnectionProvider is missing");return e}const $o=Qn(e=>({open:!1,opened:!1,revision:0,setOpen:t=>e(r=>({open:t,opened:r.opened||t,revision:r.revision+(r.open===t?0:1)}))}));function lW(e){const t=Gt(),r=p.useRef(t.key);r.current=t.key;const n=p.useRef(!0),s=p.useRef(!1),[i,a]=p.useState(null);p.useEffect(()=>(n.current=!0,()=>{n.current=!1}),[]);const l=W(async(u,d)=>{var v,x;if(s.current||!d())return;const h=r.current,f=()=>n.current&&h===r.current&&d(),m=zh(u);if(!m.ok){a({url:u,isCurrent:f,message:m.error});return}s.current=!0,a(null);let g=f;try{if(!((v=window.electronAPI)!=null&&v.terminalBrowserCreateTab)){if(!((x=window.electronAPI)!=null&&x.openExternal))throw new Error("当前桌面版本无法打开链接,请复制地址后继续。");await window.electronAPI.openExternal(m.url);return}const b=Vt.getState(),_=b.activeBrowserProfileId,C=b.browserActivationRevision;Yr.flushSync(()=>{e(),$o.getState().setOpen(!1)});const S=$o.getState().revision;if(g=()=>{const w=Vt.getState();return f()&&$o.getState().revision===S&&w.activeBrowserProfileId===_&&w.browserActivationRevision===C},!g())return;await Kc({url:m.url,profileId:_,placement:{kind:"new-group"}}),g()&&Vt.getState().activateBrowser(_,null)}catch(b){g()&&($o.getState().setOpen(!0),a({url:u,isCurrent:f,message:b instanceof Error?b.message:"打开网页失败,请主动重试。"}))}finally{s.current=!1}}),c=W(async()=>{var u;if(!(!(i!=null&&i.isCurrent())||!((u=window.electronAPI)!=null&&u.openExternal)||s.current)){s.current=!0;try{const d=zh(i.url);if(!d.ok)throw new Error(d.error);await window.electronAPI.openExternal(d.url),i.isCurrent()&&a(null)}catch(d){i.isCurrent()&&a({...i,message:d instanceof Error?d.message:"外部打开失败。"})}finally{s.current=!1}}});return{openLink:l,failure:i!=null&&i.isCurrent()?i:null,retry:()=>{i!=null&&i.isCurrent()&&l(i.url,i.isCurrent)},openExternal:c,dismissError:()=>a(null)}}const cW=p.lazy(()=>Vr(()=>import("./connection-CINMNAPm.js"),__vite__mapDeps([5,1,6])));function uW(){var l;const{open:e,opened:t,setOpen:r}=$o(),n=p.useRef(null),s=hr(n,"window"),i=lW(()=>{var c;return(c=n.current)==null?void 0:c.close()}),a=Gt();return p.useEffect(()=>{a.pathname.startsWith("/terminal")||r(!1)},[a.pathname,r]),p.useEffect(()=>{var c,u;e?(c=n.current)==null||c.showModal():(u=n.current)==null||u.close()},[e]),o.jsx("dialog",{ref:s,"aria-label":"随记抽屉","aria-modal":"true",className:"suiji-drawer fixed inset-y-0 left-auto right-0 m-0 h-dvh max-h-none w-[480px] max-w-full overflow-hidden border-0 border-l bg-background p-0 text-foreground shadow-2xl backdrop:bg-black/30",onCancel:c=>{c.preventDefault(),r(!1)},onClick:c=>{c.target===c.currentTarget&&c.clientX<c.currentTarget.getBoundingClientRect().left&&r(!1)},children:o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i.failure?o.jsxs("div",{role:"alert",className:"shrink-0 space-y-2 border-b p-4 text-sm",children:[o.jsxs("p",{children:["打开网页失败:",i.failure.message]}),o.jsx("p",{children:"请求结果可能未确认,请先检查 Browser 中是否已打开。"}),o.jsxs("div",{className:"flex gap-3",children:[o.jsx("button",{type:"button",onClick:i.retry,children:"重试打开"}),(l=window.electronAPI)!=null&&l.openExternal?o.jsx("button",{type:"button",onClick:()=>void i.openExternal(),children:"在默认浏览器打开"}):null,o.jsx("button",{type:"button",onClick:i.dismissError,children:"关闭提示"})]})]}):null,o.jsx("div",{className:"min-h-0 flex-1",children:t?o.jsx(p.Suspense,{fallback:o.jsx("p",{role:"status",className:"p-5",children:"正在打开随记…"}),children:o.jsx(cW,{active:e,onClose:()=>r(!1),onOpenLink:i.openLink})}):null})]})})}function SN(e,t){return e===1013&&["Terminal output recovery required","Terminal host connection lost","Terminal initial output queue exceeded","Terminal recovery queue exceeded","Terminal recovery unavailable; reconnect"].includes((t==null?void 0:t.trim())??"")}const dW=1e3,Gc=5,hW=5e3,fW=250,pW=1012,mW=new Set([1e3,1008,1011,1013]),gW=new Set(["Terminal runtime not found"]);function vW(e){var r;if(e.terminalStatus==="exited"||(e.reconnectAttempt??0)>=Gc||mW.has(e.code)&&!SN(e.code,e.reason))return!1;if(e.code===pW)return!0;const t=(r=e.reason)==null?void 0:r.trim();return!(t&&gW.has(t))}function Uh(e){return Math.min(fW*2**Math.max(e,0),hW)}function CN(e){const t=e.trim();return t?t.startsWith("https://")?t.replace("https://","wss://"):t.startsWith("http://")?t.replace("http://","ws://"):t:window.location.origin.replace(/^http/,"ws")}function xW(e,t,r){const n=new URLSearchParams({token:t,after:r??""});return`${CN(e)}/ws/terminal-events?${n.toString()}`}function bW(e){let t=null;for(const r of e)(t===null||Number(r.id)>Number(t))&&(t=r.id);return t}function EN(e){const{apiBase:t,token:r,getCursor:n,setCursor:s,onAuthExpired:i,onResyncRequired:a,onTerminalEvents:l}=e,c=p.useRef(null),u=p.useRef(r),d=p.useRef(null),h=p.useRef(0),f=p.useRef(null),m=p.useRef(null),g=p.useRef(new Set),v=p.useRef(null),x=p.useRef(null),b=p.useRef(null),_=p.useRef(n),C=p.useRef(s),S=p.useRef(a),w=p.useRef(l),[y,N]=p.useState("connecting"),[E,k]=p.useState(null),[D,j]=p.useState(0),[R,I]=p.useState(null),[T,A]=p.useState(!1);p.useEffect(()=>{u.current=r},[r]),p.useEffect(()=>{_.current=n},[n]),p.useEffect(()=>{C.current=s},[s]),p.useEffect(()=>{S.current=a},[a]),p.useEffect(()=>{w.current=l},[l]),p.useEffect(()=>{b.current=null},[t]);const P=W((L,B)=>{const M=L.filter(U=>g.current.has(U.id)?!1:(g.current.add(U.id),!0));if(M.length===0)return;w.current(M,B);const $=bW(M);$&&(x.current=$,C.current($))}),O=W(()=>{g.current=new Set,x.current=null,C.current(null),S.current()});return p.useEffect(()=>{N("connecting"),k(null),A(!1),g.current=new Set,x.current=null;let L=!1;const B=()=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null)},M=()=>{if(f.current!==null)return;const Y=Date.now();f.current=Y,I(Y),B(),m.current=window.setTimeout(()=>{m.current=null,A(!0)},3e4)},$=()=>{f.current=null,I(null),A(!1),h.current=0,j(0),B(),N("connected")};M();const U=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},F=async()=>{if(!L){U(),N("connecting"),k(null);try{const Y=await Z6(t,u.current);if(L)return;let te=_.current()??x.current??Y.baselineEventId;b.current!==null&&b.current!==Y.streamId&&(O(),te=null),b.current=Y.streamId,x.current=te;const H=new WebSocket(xW(t,Y.ticket,te));c.current=H,H.addEventListener("open",()=>{c.current===H&&(v.current=null,N("connecting"))}),H.addEventListener("close",G=>{if(c.current===H){if(c.current=null,G.code===1008&&G.reason==="Unauthorized"){N("closed"),i==null||i();return}if(!L){M();const z=h.current;h.current=z+1,j(z+1),N("connecting"),U(),d.current=window.setTimeout(()=>{F()},Uh(z));return}N("closed"),(v.current||G.reason)&&k(v.current||G.reason||"Terminal events connection closed.")}}),H.addEventListener("message",G=>{if(c.current===H)try{const z=JSON.parse(String(G.data));if(z.type==="connected"){if(z.streamId!==b.current){b.current=z.streamId,O(),H.close(1012,"Terminal event stream changed");return}z.gap&&O(),$();return}if(z.type==="terminal-events"){P(z.events,z.delivery);return}if(z.type==="terminal-event"){P([z.event],z.delivery);return}z.type==="error"&&(v.current=z.message,k(z.message),z.message==="Unauthorized"&&(i==null||i()))}catch{v.current="Invalid terminal events message",k("Invalid terminal events message")}})}catch(Y){if(L)return;if(Y instanceof De&&Y.status===401){i==null||i();return}k(String(Y)),M();const te=h.current;h.current=te+1,j(te+1),U(),d.current=window.setTimeout(()=>{F()},Uh(te))}}},K=window.setTimeout(()=>{F()},0);return()=>{var Y;L=!0,window.clearTimeout(K),U(),h.current=0,f.current=null,B(),v.current=null,(Y=c.current)==null||Y.close(),c.current=null}},[t,P,i,O]),{connectionStatus:y,error:E,reconnectAttempt:D,failureSince:R,failureExpired:T}}function _W(e,t,r){return me(e,"/api/attention/slots",{headers:{Authorization:`Bearer ${t}`},cache:"no-store",signal:r})}function Jx(e){const{apiBase:t,token:r,connectionId:n,enabled:s=!0}=e,[i,a]=p.useState("checking"),[l,c]=p.useState(null);return p.useEffect(()=>{if(!s){c(null),a("checking");return}if(!t||!r||!n){c(null),a("disconnected");return}let u=!1,d=null;const h=()=>{d==null||d.abort(),d=new AbortController,_W(t,r,d.signal).then(m=>{u||(c(m),a("ready"))}).catch(()=>{!u&&!(d!=null&&d.signal.aborted)&&(c(null),a("disconnected"))})};a("checking"),h();const f=window.setInterval(h,4e3);return()=>{u=!0,window.clearInterval(f),d==null||d.abort()}},[t,n,s,r]),{state:i,snapshot:l}}function yW(e,t,r){return me(e,"/api/terminal/unread",{headers:{Authorization:`Bearer ${t}`},cache:"no-store",signal:r})}const kN=Qn(e=>({byId:{},update:(t,r)=>e(n=>({byId:{...n.byId,[t]:r}}))}));function IN(e){return JSON.stringify([e.url,e.generation??0])}function NN(e,t){const{id:r,url:n,available:s}=e,i=IN(e);p.useEffect(()=>{const a=kN.getState,l=()=>{const g=a().byId[r];return(g==null?void 0:g.source)===i?g.snapshot:null},c=(g,v)=>a().update(r,{source:i,snapshot:g,stale:v});if(!t){c(null,!1);return}if(!n||s===!1){c(l(),!0);return}let u=!1,d=null,h=!1;const f=async()=>{if(h)return;h=!0;const g=new AbortController;d=g;const v=window.setTimeout(()=>g.abort(),8e3);try{const x=await yW(n,t,g.signal);if(u)return;if(typeof x.hostId!="string"||!x.hostId||!Number.isSafeInteger(x.revision)||x.revision<0||!Number.isSafeInteger(x.count)||x.count<0)throw new Error("Invalid completion snapshot");const b=l();if((b==null?void 0:b.hostId)===x.hostId&&b.revision>x.revision)return;c(x,!1)}catch(x){if(!u){const b=x instanceof De&&[401,403].includes(x.status);c(b?null:l(),!0)}}finally{window.clearTimeout(v),h=!1}};f();const m=window.setInterval(()=>void f(),4e3);return()=>{u=!0,window.clearInterval(m),d==null||d.abort()}},[r,n,s,i,t])}function wW(e,t){const r=kN(n=>n.byId);return p.useMemo(()=>{var u,d;const n=h=>{const f=r[h.id];return(f==null?void 0:f.source)===IN(h)?f:void 0},s=new Map;for(const h of e){const f=n(h);if(!(f!=null&&f.snapshot))continue;const m=s.get(f.snapshot.hostId);(!m||m.snapshot.revision<f.snapshot.revision||m.snapshot.revision===f.snapshot.revision&&m.stale&&!f.stale)&&s.set(f.snapshot.hostId,f)}const i={};for(const h of e){const f=n(h);if(f!=null&&f.snapshot){const m=s.get(f.snapshot.hostId);i[h.id]={count:m.snapshot.count,stale:f.stale}}}const a=e.find(h=>h.id===t),l=a?(d=(u=n(a))==null?void 0:u.snapshot)==null?void 0:d.hostId:null,c=l?[...s.entries()].reduce((h,[f,m])=>h+(f===l?0:m.snapshot.count),0):0;return{byId:i,otherTotal:c}},[e,t,r])}const Gf=Qn(e=>({byConnectionId:{},update:(t,r)=>e(n=>({byConnectionId:{...n.byConnectionId,[t]:{projects:[],sessions:[],attention:null,observedAt:null,status:"checking",...n.byConnectionId[t],...r}}}))})),P1=new Map;function RN(e,t){var i,a;const r=P1.get(e.id),n=new Set(t.slots.map(l=>l.attentionId)),s=new Set([...r??[],...n]);for(;s.size>500;)s.delete(s.values().next().value);if(P1.set(e.id,s),!!r)for(const l of t.slots)r.has(l.attentionId)||l.state==="working"||(a=(i=window.electronAPI)==null?void 0:i.showAttentionNotification)==null||a.call(i,{connectionId:e.id,attentionId:l.attentionId,parentProjectId:l.parentProjectId,projectId:l.projectId,terminalSessionId:l.terminalSessionId,panelId:l.panelId,title:`${e.name} · ${l.projectName}`,body:l.title}).catch(()=>{})}function SW({connection:e,token:t,onAuthExpired:r}){const n=Gf(u=>u.update),s=Jx({apiBase:e.url,token:t,connectionId:e.id}),[i,a]=p.useState(0),l=p.useRef(null),c=EN({apiBase:e.url,token:t,getCursor:()=>l.current,setCursor:u=>{l.current=u},onAuthExpired:r,onResyncRequired:()=>a(u=>u+1),onTerminalEvents:()=>a(u=>u+1)});return p.useEffect(()=>{s.state==="ready"&&s.snapshot&&(n(e.id,{attention:s.snapshot}),RN(e,s.snapshot))},[s.snapshot,s.state,e,n]),p.useEffect(()=>{let u=!1;return Promise.all([Hv(e.url,t),_u(e.url,t)]).then(([d,h])=>{u||n(e.id,{projects:d,sessions:h,observedAt:new Date().toISOString(),status:"ready"})}).catch(()=>{u||n(e.id,{status:"disconnected"})}),()=>{u=!0}},[e.id,e.url,i,t,n]),p.useEffect(()=>{c.connectionStatus!=="connected"?n(e.id,{status:"disconnected"}):a(u=>u+1)},[e.id,c.connectionStatus,n]),null}function jN({connection:e,token:t,status:r,onAuthExpired:n}){NN(e,r==="authenticated"?t:null);const s=Gf(i=>i.update);return p.useEffect(()=>{!e.url||e.available===!1?s(e.id,{status:"disconnected"}):r==="checking"?s(e.id,{status:"checking"}):(r==="unauthenticated"||!t)&&s(e.id,{status:"needs_auth"})},[e.available,e.id,e.url,r,t,s]),!e.url||r!=="authenticated"||!t||e.available===!1?null:o.jsx(SW,{connection:e,token:t,onAuthExpired:n},`${e.id}:${e.generation??0}`)}function CW({connection:e}){const{token:t,status:r,clearToken:n}=hx({apiBase:e.url,connectionId:e.id,isElectron:!0,webStorageKey:"viewer.auth.token"});return o.jsx(jN,{connection:e,token:t,status:r,onAuthExpired:n})}function EW({connection:e,token:t}){NN(e,t);const r=Gf(s=>s.update),n=Jx({apiBase:e.url,token:t,connectionId:e.id,enabled:e.available!==!1});return p.useEffect(()=>{n.state==="ready"&&n.snapshot&&(r(e.id,{attention:n.snapshot}),RN(e,n.snapshot))},[n.snapshot,n.state,e,r]),null}function kW({connections:e,activeConnectionId:t,activeToken:r,activeAuthStatus:n,onActiveAuthExpired:s,observeActive:i}){return o.jsxs(o.Fragment,{children:[e.filter(a=>a.id!==t).map(a=>o.jsx(CW,{connection:a},a.id)),i&&e.filter(a=>a.id===t).map(a=>o.jsx(jN,{connection:a,token:r,status:n,onAuthExpired:s},`active:${a.id}`)),!i&&e.filter(a=>a.id===t).map(a=>o.jsx(EW,{connection:a,token:n==="authenticated"?r:null},`attention:${a.id}`))]})}var Yf="DropdownMenu",[IW]=bi(Yf,[Wf]),hn=Wf(),[NW,AN]=IW(Yf),TN=e=>{const{__scopeDropdownMenu:t,children:r,dir:n,open:s,defaultOpen:i,onOpenChange:a,modal:l=!0}=e,c=hn(t),u=p.useRef(null),[d,h]=Su({prop:s,defaultProp:i??!1,onChange:a,caller:Yf});return o.jsx(NW,{scope:t,triggerId:hi(),triggerRef:u,contentId:hi(),open:d,onOpenChange:h,onOpenToggle:p.useCallback(()=>h(f=>!f),[h]),modal:l,children:o.jsx(xI,{...c,open:d,onOpenChange:h,dir:n,modal:l,children:r})})};TN.displayName=Yf;var DN="DropdownMenuTrigger",PN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...s}=e,i=AN(DN,r),a=hn(r);return o.jsx(bI,{asChild:!0,...a,children:o.jsx(or.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...s,ref:kf(t,i.triggerRef),onPointerDown:st(e.onPointerDown,l=>{!n&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:st(e.onKeyDown,l=>{n||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});PN.displayName=DN;var RW="DropdownMenuPortal",LN=e=>{const{__scopeDropdownMenu:t,...r}=e,n=hn(t);return o.jsx(_I,{...n,...r})};LN.displayName=RW;var MN="DropdownMenuContent",ON=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=AN(MN,r),i=hn(r),a=p.useRef(!1);return o.jsx(yI,{id:s.contentId,"aria-labelledby":s.triggerId,...i,...n,ref:t,onCloseAutoFocus:st(e.onCloseAutoFocus,l=>{var c;a.current||(c=s.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:st(e.onInteractOutside,l=>{const c=l.detail.originalEvent,u=c.button===0&&c.ctrlKey===!0,d=c.button===2||u;(!s.modal||d)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ON.displayName=MN;var jW="DropdownMenuGroup",BN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(wI,{...s,...n,ref:t})});BN.displayName=jW;var AW="DropdownMenuLabel",FN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(SI,{...s,...n,ref:t})});FN.displayName=AW;var TW="DropdownMenuItem",$N=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(CI,{...s,...n,ref:t})});$N.displayName=TW;var DW="DropdownMenuCheckboxItem",zN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(EI,{...s,...n,ref:t})});zN.displayName=DW;var PW="DropdownMenuRadioGroup",LW=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(kI,{...s,...n,ref:t})});LW.displayName=PW;var MW="DropdownMenuRadioItem",UN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(II,{...s,...n,ref:t})});UN.displayName=MW;var OW="DropdownMenuItemIndicator",HN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(NI,{...s,...n,ref:t})});HN.displayName=OW;var BW="DropdownMenuSeparator",WN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(RI,{...s,...n,ref:t})});WN.displayName=BW;var FW="DropdownMenuArrow",$W=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(jI,{...s,...n,ref:t})});$W.displayName=FW;var zW="DropdownMenuSubTrigger",qN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(AI,{...s,...n,ref:t})});qN.displayName=zW;var UW="DropdownMenuSubContent",KN=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:r,...n}=e,s=hn(r);return o.jsx(TI,{...s,...n,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});KN.displayName=UW;var HW=TN,WW=PN,qW=LN,VN=ON,KW=BN,GN=FN,YN=$N,XN=zN,JN=UN,QN=HN,ZN=WN,eR=qN,tR=KN;const $u=HW,zu=WW,VW=KW,GW=p.forwardRef(({className:e,inset:t,children:r,...n},s)=>o.jsxs(eR,{ref:s,className:Xe("flex cursor-default select-none items-center rounded-md px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted",t&&"pl-8",e),...n,children:[r,o.jsx(Jr,{className:"ml-auto h-4 w-4"})]}));GW.displayName=eR.displayName;const YW=p.forwardRef(({className:e,...t},r)=>{const n=hr(r,"intersection");return o.jsx(tR,{ref:n,className:Xe("z-50 min-w-[8rem] overflow-hidden rounded-xl border border-border/60 bg-popover p-1 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",e),...t})});YW.displayName=tR.displayName;const Ll=p.forwardRef(({className:e,sideOffset:t=8,...r},n)=>{const s=hr(n,"intersection");return o.jsx(qW,{children:o.jsx(VN,{ref:s,sideOffset:t,className:Xe("z-50 min-w-[14rem] overflow-hidden rounded-2xl border border-border/60 bg-popover/95 p-1.5 text-popover-foreground shadow-[0_24px_80px_-36px_rgba(17,24,39,0.8)] backdrop-blur-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...r})})});Ll.displayName=VN.displayName;const Bt=p.forwardRef(({className:e,inset:t,...r},n)=>o.jsx(YN,{ref:n,className:Xe("relative flex cursor-default select-none items-center gap-2 rounded-xl px-3 py-2.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));Bt.displayName=YN.displayName;const XW=p.forwardRef(({className:e,children:t,checked:r,...n},s)=>o.jsxs(XN,{ref:s,className:Xe("relative flex cursor-default select-none items-center rounded-xl py-2.5 pl-8 pr-3 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:r,...n,children:[o.jsx("span",{className:"absolute left-3 flex h-4 w-4 items-center justify-center",children:o.jsx(QN,{children:o.jsx(di,{className:"h-4 w-4"})})}),t]}));XW.displayName=XN.displayName;const JW=p.forwardRef(({className:e,children:t,...r},n)=>o.jsxs(JN,{ref:n,className:Xe("relative flex cursor-default select-none items-center rounded-xl py-2.5 pl-8 pr-3 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[o.jsx("span",{className:"absolute left-3 flex h-4 w-4 items-center justify-center",children:o.jsx(QN,{children:o.jsx(hE,{className:"h-2.5 w-2.5 fill-current"})})}),t]}));JW.displayName=JN.displayName;const rR=p.forwardRef(({className:e,inset:t,...r},n)=>o.jsx(GN,{ref:n,className:Xe("px-3 py-2 text-xs font-medium uppercase tracking-[0.22em] text-muted-foreground/75",t&&"pl-8",e),...r}));rR.displayName=GN.displayName;const nR=p.forwardRef(({className:e,...t},r)=>o.jsx(ZN,{ref:r,className:Xe("-mx-1 my-1 h-px bg-border/60",e),...t}));nR.displayName=ZN.displayName;function Xf({connections:e,activeConnectionId:t,activeConnectionName:r,onSelectConnection:n,onOpenConnectionManager:s,className:i}){var f;const[a,l]=p.useState(!1),c=wW(e,t),u=LH(),d=vN(),h=r??((f=e.find(m=>m.id===t))==null?void 0:f.name)??"未选择连接";return o.jsxs($u,{open:a,onOpenChange:l,children:[o.jsx(zu,{asChild:!0,children:o.jsxs(Z,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(m=>!m),className:`relative overflow-visible ${i??"rounded-full border border-border/60 bg-background/60 px-3 text-[0.72rem] text-muted-foreground backdrop-blur"}`,children:[o.jsx("span",{className:"mr-2 text-[0.62rem] uppercase tracking-[0.24em] text-muted-foreground/70",children:"当前连接"}),o.jsx("span",{className:"max-w-[14rem] truncate",children:h}),o.jsx(dE,{className:"ml-2 h-3.5 w-3.5 opacity-70"}),c.otherTotal>0?o.jsx("span",{className:"absolute -right-1.5 -top-1 inline-flex h-[19px] min-w-[19px] items-center justify-center rounded-full border-2 border-background bg-[#30d158] px-1 text-[11px] font-bold leading-none text-[#07140a] tabular-nums","aria-label":`其他连接 ${c.otherTotal} 个未读完成终端`,"data-testid":"connection-completion-total",children:c.otherTotal}):null]})}),o.jsxs(Ll,{align:"start",className:"w-[18rem]",children:[o.jsx(rR,{children:"切换连接"}),e.map(m=>{const g=m.id===t,v=c.byId[m.id];return o.jsxs(Bt,{className:g?"bg-slate-800/80":void 0,onSelect:()=>{n(m.id),l(!1)},children:[o.jsx(Cf,{className:"h-4 w-4 text-muted-foreground"}),o.jsxs("span",{className:"min-w-0 flex-1 py-1",children:[o.jsx("span",{className:"block truncate font-medium",children:m.name}),o.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:g?"当前连接":v!=null&&v.stale||m.available===!1?"离线 · 上次同步":v?"已连接":"尚未检测"})]}),v&&v.count>0?o.jsx("span",{className:"inline-flex h-[19px] min-w-[19px] items-center justify-center rounded-full bg-[#30d158] px-1 text-[11px] font-bold leading-none text-[#07140a] tabular-nums","aria-label":`${m.name} ${v.count} 个未读完成终端`,title:v.stale?"离线 · 上次同步":void 0,"data-testid":"connection-completion-count",children:v.count}):null,g?o.jsx(di,{className:"h-4 w-4 text-primary"}):null]},m.id)}),o.jsx(nR,{}),d?o.jsx(Bt,{onSelect:()=>{l(!1),d()},children:"Codex 额度"}):null,u?o.jsx(Bt,{onSelect:()=>{l(!1),u()},children:"连接手机"}):null,o.jsxs(Bt,{onSelect:()=>{s(),l(!1)},children:[o.jsx(BL,{className:"h-4 w-4 text-primary"}),o.jsx("span",{children:"连接管理"})]})]})]})}function L1({connection:e,connections:t,onSelectConnection:r,onOpenConnectionManager:n,onReconnect:s}){const i=Gf(l=>l.byConnectionId[e.id]),a=i!=null&&i.observedAt?new Date(i.observedAt).toLocaleString():null;return o.jsxs("main",{className:"flex min-h-screen flex-col gap-5 bg-slate-950 p-8 text-slate-100",children:[o.jsx(Xf,{connections:t,activeConnectionId:e.id,onSelectConnection:r,onOpenConnectionManager:n}),o.jsxs("section",{className:"max-w-lg space-y-3 rounded-xl border border-slate-700 p-5",children:[o.jsxs("h1",{className:"text-lg font-semibold",children:[e.name," · ",e.remoteStatus==="connecting"||e.remoteStatus==="reconnecting"?"正在重连":"连接不可用"]}),o.jsx("p",{className:"text-sm text-slate-300",children:e.statusMessage??"等待 SSH 通道,可在端口与隧道中连接主机"}),a?o.jsxs("p",{className:"text-xs text-slate-400",children:["上次终端状态更新:",a,"。下方为历史信息,不代表终端仍在运行。"]}):null,i?o.jsxs("p",{className:"text-sm text-slate-300",children:["已记录 ",i.projects.length," 个项目、",i.sessions.length," 个终端。"]}):null,o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{onClick:s,children:"打开端口与隧道"}),o.jsx(Z,{variant:"outline",onClick:n,children:"连接管理"})]})]})]})}const oh=new Map;function QW(e,t){return[...oh.values()].some(r=>r.apiBase===e&&r.terminalSessionId===t)}function ZW(e,t,r){const n=`/terminal/${encodeURIComponent(e)}`,s=Tn(t);return new Promise(i=>{let a=!1,l=null;const c=h=>{a||(a=!0,window.clearInterval(d),r.removeEventListener("abort",u),i(h))},u=()=>c(!1);r.addEventListener("abort",u,{once:!0});const d=window.setInterval(()=>{const h=tt.getState();if(!(window.location.pathname===n&&h.activeParentProjectId===s&&h.activeProjectId===t&&h.activeSessionId===e)){l=null;return}l??(l=performance.now()),performance.now()-l>=100&&c(!0)},25);r.aborted&&c(!1)})}function eq({activeConnectionId:e,apiBase:t,enabled:r,token:n}){const s=Cr();p.useEffect(()=>{var c,u,d,h;if(!r)return;const i=new Map,a=(u=(c=window.electronAPI)==null?void 0:c.onAttentionOpenCancelled)==null?void 0:u.call(c,f=>{var m;return(m=i.get(f))==null?void 0:m.abort()}),l=(h=(d=window.electronAPI)==null?void 0:d.onAttentionOpenIntent)==null?void 0:h.call(d,f=>{const m=new AbortController,g=m.signal;i.set(f.requestId,m),oh.set(f.requestId,{apiBase:t,terminalSessionId:f.terminalSessionId});const v=window.setTimeout(()=>m.abort(),Math.max(0,f.deadlineAt-Date.now()));let x=!1;(async()=>{var y,N;const b=async E=>{var k,D;g.aborted||await((D=(k=window.electronAPI)==null?void 0:k.reportAttentionOpenResult)==null?void 0:D.call(k,E))};if(!e||f.connectionId!==e||!n){await b({requestId:f.requestId,status:"connection_unavailable",message:"Connection changed before Slot opened"});return}const C=(await _u(t,n,g).catch(E=>{if(g.aborted)throw E;return[]})).find(E=>E.terminalSessionId===f.terminalSessionId);if(!C){await b({requestId:f.requestId,status:"session_not_found",message:"Terminal Session no longer exists"});return}if(Bo(window.location.pathname)){await b({requestId:f.requestId,status:"connection_unavailable",message:"请从管理页面左上角返回终端后再打开会话"});return}if(tt.getState().selectProjectContext(Tn(C.projectId),C.projectId,f.terminalSessionId),s(`/terminal/${encodeURIComponent(f.terminalSessionId)}`),!await ZW(f.terminalSessionId,C.projectId,g))return;g.throwIfAborted();let S=!1;f.panelId&&(S=await Uv(t,n,f.terminalSessionId,f.panelId,g).then(()=>!1).catch(E=>{if(g.aborted)throw E;return!0})),g.throwIfAborted(),g.throwIfAborted();const w=S?{requestId:f.requestId,status:"opened_with_panel_fallback",message:"Session opened; original Panel is unavailable"}:{requestId:f.requestId,status:"opened"};if(f.completionRevision!==null){if(x=await((N=(y=window.electronAPI)==null?void 0:y.authorizeAttentionCompletion)==null?void 0:N.call(y,w))===!0,!x)return;const E=await Fc(t,n,f.terminalSessionId,{acknowledgedCompletionRevision:f.completionRevision},g);tt.getState().setCompletionMarkers(k=>{const D=k[f.terminalSessionId];if(!D||D>E.acknowledgedCompletionRevision)return k;const j={...k};return delete j[f.terminalSessionId],j});return}g.throwIfAborted(),await b(w)})().catch(async b=>{var _,C;x||g.aborted||await((C=(_=window.electronAPI)==null?void 0:_.reportAttentionOpenResult)==null?void 0:C.call(_,{requestId:f.requestId,status:"session_not_found",message:b instanceof Error?b.message:"Slot open failed"}))}).finally(()=>{window.clearTimeout(v),i.get(f.requestId)===m&&(i.delete(f.requestId),oh.delete(f.requestId))})});return()=>{l==null||l(),a==null||a();for(const[f,m]of i)m.abort(),oh.delete(f);i.clear()}},[e,t,r,s,n])}function tq(e){const[t,r]=p.useState(!1),{snapshot:n,state:s}=Jx({apiBase:e.apiBase,token:e.token,connectionId:e.connectionId,enabled:e.enabled&&t});p.useEffect(()=>{const i=window.electronAPI;if(!e.enabled||!(i!=null&&i.getCompanionEnabled)||!i.onCompanionEnabledChanged)return;let a=!1;const l=i.onCompanionEnabledChanged(r);return i.getCompanionEnabled().then(c=>{a||r(c)}).catch(()=>{}),()=>{a=!0,l()}},[e.enabled]),p.useEffect(()=>{var i,a;!e.enabled||!t||(a=(i=window.electronAPI)==null?void 0:i.publishCompanionPresentation)==null||a.call(i,{connectionId:e.connectionId,snapshot:n,state:s}).catch(()=>{})},[t,e.connectionId,e.enabled,n,s])}function rq({children:e}){const[t,r]=p.useState(null),[n,s]=p.useState(!0);return p.useEffect(()=>{},[]),t?o.jsxs("main",{className:"min-h-screen bg-background p-6 text-foreground","data-testid":"dev-session-backend-mismatch",children:[o.jsx("h1",{className:"text-lg font-semibold",children:"Dev Session backend mismatch"}),o.jsxs("p",{className:"mt-2 text-sm",children:["Session: ","unknown"]}),o.jsx("p",{className:"mt-1 text-sm",children:t})]}):n?e:o.jsx("main",{className:"min-h-screen bg-background","data-testid":"dev-session-backend-checking"})}const M1=767;function nq({viewportWidth:e,coarsePointer:t,isElectron:r=!1,override:n=null}){return n==="desktop"||n==="mobile"?n:r?"desktop":e<=M1||t&&e<=M1?"mobile":"desktop"}function sq(e){const t=new URLSearchParams(e).get("clientMode");return t==="desktop"||t==="mobile"?t:null}function O1(e){return typeof window>"u"?"desktop":nq({viewportWidth:window.innerWidth,coarsePointer:window.matchMedia("(pointer: coarse)").matches,isElectron:e,override:sq(window.location.search)})}function iq(e){const[t,r]=p.useState(()=>O1(e));return p.useEffect(()=>{const n=window.matchMedia("(pointer: coarse)"),s=()=>{r(O1(e))};return s(),window.addEventListener("resize",s),n.addEventListener("change",s),()=>{window.removeEventListener("resize",s),n.removeEventListener("change",s)}},[e]),t}function si({align:e="center",children:t,className:r,content:n,side:s="bottom"}){const[i,a]=p.useState(!1),l=hr(void 0,"intersection",i);return o.jsxs("span",{className:Xe("relative inline-flex",r),onBlurCapture:()=>a(!1),onClickCapture:()=>a(!1),onFocusCapture:()=>a(!0),onPointerDownCapture:()=>a(!1),onPointerEnter:()=>a(!0),onPointerLeave:()=>a(!1),children:[t,o.jsx("span",{ref:l,role:"tooltip","aria-hidden":!i,className:Xe("pointer-events-none absolute z-[80] w-max max-w-64 rounded-md border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] font-normal leading-4 text-slate-200 shadow-lg transition-opacity delay-150",i?"visible opacity-100":"invisible opacity-0",e==="center"&&"left-1/2 -translate-x-1/2",e==="start"&&"left-0",e==="end"&&"right-0",s==="bottom"?"top-full mt-1.5":"bottom-full mb-1.5"),children:n})]})}const um={unhealthy:"border-red-500/50 bg-red-500/10 text-red-700 dark:text-red-200",recovering:"border-amber-500/50 bg-amber-500/10 text-amber-700 dark:text-amber-200",checking:"border-border/70 bg-background/70 text-muted-foreground",blocked:"border-border/70 bg-muted/60 text-muted-foreground",healthy:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-200",unconfigured:"border-border/70 bg-muted/60 text-muted-foreground",disabled:"border-border/70 bg-muted/60 text-muted-foreground",unsupported:"border-border/70 bg-muted/60 text-muted-foreground"};function Sa(e){const{overallState:t,unhealthyCapabilityIds:r,warningCapabilityIds:n,panelOpen:s,setPanelOpen:i}=Au(),a=r.length,l=n.length,c=a>0?"error":l>0?"warning":"none",u=`运行状态${a?` · ${a} 个异常服务`:""}${l?` · ${l} 个服务需关注`:""}`,d=c==="error"?um.unhealthy:c==="warning"?um.recovering:um[t],h=o.jsxs("button",{type:"button",className:Xe("inline-flex h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border px-2 text-xs shadow-sm transition hover:bg-black/5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",e.iconOnly&&"relative w-8 justify-center gap-0 rounded-md px-0",e.className,d),"data-runtime-status-state":t,"data-runtime-status-attention":c,"aria-label":`${u},点击查看详情`,"aria-haspopup":"dialog","aria-expanded":s,title:e.iconOnly?void 0:`${u},点击查看详情`,onClick:()=>i(!0),children:[c!=="none"?o.jsx(pa,{className:"h-3.5 w-3.5 shrink-0"}):o.jsx(cs,{className:"h-3.5 w-3.5 shrink-0"}),e.iconOnly?null:o.jsx("span",{children:c==="error"?"异常":c==="warning"?"Warning":"状态"}),[{count:a,kind:"error",tone:"bg-red-600",label:"异常服务"},{count:l,kind:"warning",tone:"bg-amber-600",label:"服务需关注"}].filter(({count:f})=>f>0).map(({count:f,kind:m,tone:g,label:v},x)=>o.jsx("span",{className:Xe("shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-semibold text-white",g,e.iconOnly&&"absolute -right-1 flex h-3 min-w-3 items-center justify-center px-0.5 text-[8px] leading-none",e.iconOnly&&(x===0?"-top-1":"-bottom-1")),"aria-label":`${f} 个${v}`,"data-runtime-status-badge":m,children:f},m))]});return e.iconOnly?o.jsx(si,{align:"end",content:u,children:h}):h}function oq({apiBase:e,connectionId:t,isElectron:r,connections:n=[],connectionName:s,onSwitchConnection:i,onOpenConnectionManager:a,onSuccess:l}){var E;const c=(E=ju())==null?void 0:E.active;$v();const[u,d]=p.useState("admin"),[h,f]=p.useState(""),[m,g]=p.useState(!1),[v,x]=p.useState(null),[b,_]=p.useState(!1),C=p.useRef(null),S=p.useRef(null),w=b&&!u?"Please enter your username.":null,y=b&&!h?"Please enter your password.":null,N=W(async()=>{var k;if(!m){if(_(!0),x(null),!u||!h){(k=(u?S:C).current)==null||k.focus();return}g(!0);try{const D=await Bk(e,{username:u,password:h},r?{clientType:"electron",connectionId:t}:{clientType:"web"});l(D)}catch(D){if(D instanceof De&&D.status===400){x("Please check your username and password and try again.");return}if(D instanceof De&&D.status===401){x("Incorrect username or password.");return}x(String(D))}finally{g(!1)}}});return o.jsxs("main",{className:c?"relative max-w-lg py-2":"relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-10 sm:px-6",children:[!c&&o.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(70,130,145,0.18),transparent_30%),radial-gradient(circle_at_bottom_left,rgba(195,172,135,0.16),transparent_35%)]"}),o.jsxs("section",{className:c?"relative w-full rounded-md border bg-card p-4":"animate-fade-rise relative w-full max-w-md rounded-[2rem] border border-border/60 bg-card/82 p-7 shadow-[0_34px_120px_-72px_rgba(17,24,39,0.82)] backdrop-blur-xl sm:p-9",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.38em] text-muted-foreground/70",children:"Runweave"}),o.jsx(Sa,{className:"max-w-56"}),r&&s&&i&&a?o.jsx(Xf,{connections:n,activeConnectionId:t??null,activeConnectionName:s,onSelectConnection:i,onOpenConnectionManager:a,className:"h-9 rounded-full border border-border/60 bg-background/60 px-3 text-[0.72rem] text-muted-foreground backdrop-blur"}):null]}),o.jsxs("form",{className:c?"mt-4 space-y-3":"mt-8 space-y-4",noValidate:!0,onSubmit:k=>{k.preventDefault(),N()},children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"username",children:"Username"}),o.jsx("input",{ref:C,id:"username",autoComplete:"username",required:!0,"aria-invalid":!!w,"aria-describedby":w?"username-error":void 0,value:u,onChange:k=>{d(k.target.value),x(null)},className:c?"h-8 w-full rounded-md border bg-background px-3 text-sm":"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"}),w?o.jsx("p",{id:"username-error",className:"text-sm text-red-500",role:"alert",children:w}):null]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"password",children:"Password"}),o.jsx("input",{ref:S,id:"password",type:"password",autoComplete:"current-password",required:!0,"aria-invalid":!!y,"aria-describedby":y?"password-error":void 0,value:h,onChange:k=>{f(k.target.value),x(null)},className:c?"h-8 w-full rounded-md border bg-background px-3 text-sm":"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"}),y?o.jsx("p",{id:"password-error",className:"text-sm text-red-500",role:"alert",children:y}):null]}),v&&o.jsx("p",{className:"text-sm text-red-500",role:"alert",children:v}),o.jsx(Z,{type:"submit",className:c?"mt-2 h-8 text-sm":"mt-2 h-12 w-full rounded-full text-sm",disabled:m,children:m?"Entering...":"Continue"})]})]})]})}function aq({returnTo:e="/terminal",apiBase:t,connectionId:r,isElectron:n,connections:s,connectionName:i,onSwitchConnection:a,onOpenConnectionManager:l,onSuccess:c}){const u=Cr();return o.jsx(o.Fragment,{children:o.jsx(oq,{apiBase:t,connectionId:r,isElectron:n,connections:s,connectionName:i,onSwitchConnection:a,onOpenConnectionManager:l,onSuccess:d=>{c(d),u(e,{replace:!0})}})})}function lq(){const[e,t]=p.useState(null);return p.useEffect(()=>{var l;const r=(l=window.electronAPI)==null?void 0:l.getTerminalBadgeStatus;if(!r)return;let n=!1,s=!1;const i=async()=>{if(!s){s=!0;try{const c=await r();n||t(c)}catch{n||t(null)}finally{s=!1}}};i();const a=window.setInterval(()=>{i()},2e3);return()=>{n=!0,window.clearInterval(a)}},[]),e?o.jsxs("p",{className:"mt-3 text-sm text-muted-foreground",role:"status",children:[e.state==="ready"?`未读已同步 · ${e.count} 个终端`:e.reason,e.state!=="ready"&&e.count!==null?` · 上次同步 ${e.count} 个终端`:""]}):null}function cq({embedded:e=!1,onManageTunnels:t,connections:r,activeId:n,onAdd:s,onRemove:i,onSelect:a,onEdit:l,onReconnect:c}){var B;const[u,d]=p.useState(r.length===0),[h,f]=p.useState(""),[m,g]=p.useState(""),[v,x]=p.useState(""),b=Xr(M=>M.snapshot),_=Xr(M=>M.setOpen),[C,S]=p.useState(!1),[w,y]=p.useState(null),[N,E]=p.useState(null),[k,D]=p.useState(""),[j,R]=p.useState(""),[I,T]=p.useState(null),A=async M=>{S(!0),y(null);try{const $=new AbortController,U=setTimeout(()=>$.abort(),5e3),F=await fetch(`${M.replace(/\/+$/,"")}/health`,{signal:$.signal});return clearTimeout(U),F.ok?(y("connected"),!0):(y("unreachable"),!1)}catch{return y("unreachable"),!1}finally{S(!1)}},P=async()=>{const M=h.trim(),$=m.trim();if(!M){T("请输入连接名称");return}if(v){s(M,"",v),f(""),x(""),d(!1);return}if(!$){T("请输入后端地址");return}T(null),await A($),s(M,$),f(""),g(""),d(!1),y(null)},O=M=>{M.canEdit!==!1&&(E(M.id),D(M.name),R(M.url))},L=()=>{if(!N)return;const M=k.trim(),$=j.trim();!M||!$||(l(N,{name:M,url:$}),E(null))};return va(e&&(!!N||u&&!!(h||m||v)),e&&C),o.jsxs("main",{className:e?"space-y-3":"relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-10 sm:px-6",children:[!e&&o.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(70,130,145,0.18),transparent_30%),radial-gradient(circle_at_bottom_left,rgba(195,172,135,0.16),transparent_35%)]"}),o.jsxs("section",{className:e?"w-full space-y-3 rounded-md border bg-card p-3":"animate-fade-rise relative w-full max-w-lg rounded-[2rem] border border-border/60 bg-card/82 p-7 shadow-[0_34px_120px_-72px_rgba(17,24,39,0.82)] backdrop-blur-xl sm:p-9",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.38em] text-muted-foreground/70",children:"连接管理"}),r.length>0&&!u&&o.jsx(Z,{size:"sm",className:"rounded-full px-4",onClick:()=>{d(!0),T(null),y(null)},children:"添加连接"})]}),o.jsx(Sa,{className:"mt-4 max-w-full"}),o.jsx(lq,{}),u&&o.jsxs("div",{className:e?"mt-3 space-y-3":"mt-6 space-y-4",children:[((B=window.electronAPI)==null?void 0:B.isElectron)&&o.jsx(Z,{type:"button",variant:"outline",onClick:()=>t?t():_(!0),children:"配置 SSH 主机与 Backend 入口"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"conn-name",children:"连接名称"}),o.jsx("input",{id:"conn-name",placeholder:"例如:本地开发",value:h,onChange:M=>f(M.target.value),className:"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"})]}),b!=null&&b.config.backendEndpoints.length?o.jsxs("label",{className:"block text-sm",children:["访问方式",o.jsxs("select",{className:"mt-2 h-10 w-full rounded-lg border border-border bg-background px-3",value:v,onChange:M=>x(M.target.value),children:[o.jsx("option",{value:"",children:"后端地址"}),b.config.backendEndpoints.map(M=>{var $;return o.jsxs("option",{value:M.id,children:[($=b.config.hosts.find(U=>U.id===M.hostId))==null?void 0:$.name," · Backend ",M.remotePort]},M.id)})]})]}):null,!v&&o.jsxs(o.Fragment,{children:[" ",o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-muted-foreground/70",htmlFor:"conn-url",children:"后端地址"}),o.jsx("input",{id:"conn-url",placeholder:"例如:http://192.168.1.100:5001",value:m,onChange:M=>g(M.target.value),onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),P())},className:"h-12 w-full rounded-[1.25rem] border border-border/60 bg-background/70 px-4 text-sm outline-none transition focus:border-primary/50"})]})]}),w==="connected"&&o.jsx("p",{className:"text-sm text-green-500",children:"✓ 连接成功"}),w==="unreachable"&&o.jsx("p",{className:"text-sm text-yellow-500",children:"⚠ 无法连接,但已保存(后端可能未启动)"}),I&&o.jsx("p",{className:"text-sm text-red-500",role:"alert",children:I}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{className:"h-12 flex-1 rounded-full text-sm",onClick:()=>void P(),disabled:C,children:C?"检测中...":"添加"}),r.length>0&&o.jsx(Z,{variant:"ghost",className:"h-12 rounded-full px-6 text-sm",onClick:()=>{d(!1),T(null),y(null)},children:"取消"})]})]}),r.length>0&&!u&&o.jsx("ul",{className:e?"mt-3 space-y-2":"mt-6 space-y-3",children:r.map(M=>o.jsx("li",{className:`group flex flex-wrap items-center justify-between border transition ${e?"rounded-md px-3 py-2":"rounded-2xl px-5 py-4"} ${M.id===n?"border-primary/40 bg-primary/5":"border-border/60 bg-background/60 hover:border-border"}`,children:N===M.id?o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx("input",{value:k,onChange:$=>D($.target.value),className:"h-9 w-full rounded-xl border border-border/60 bg-background/70 px-3 text-sm outline-none focus:border-primary/50"}),o.jsx("input",{value:j,onChange:$=>R($.target.value),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),L())},className:"h-9 w-full rounded-xl border border-border/60 bg-background/70 px-3 text-sm outline-none focus:border-primary/50"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",className:"rounded-full px-4",onClick:L,children:"保存"}),o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-4",onClick:()=>E(null),children:"取消"})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"flex-1 text-left",onClick:()=>a(M.id),children:[o.jsx("p",{className:"text-sm font-medium",children:M.name}),o.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:M.tunnelEndpointId?"通过独立 SSH 通道访问":M.url||"内置本地后端未连接"}),M.available===!1&&M.statusMessage?o.jsx("p",{className:"mt-1 text-xs text-amber-600",children:M.statusMessage}):null,M.browserMessage?o.jsxs("p",{className:"mt-1 text-xs text-amber-600",children:["Browser: ",M.browserMessage]}):null,M.isSystem&&M.runtimeSource?o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Runtime: ",M.runtimeSource,M.runtimeReleaseId?` ${M.runtimeReleaseId}`:""]}):null]}),(M.canEdit!==!1||M.canDelete!==!1)&&o.jsxs("div",{className:"flex items-center gap-1 opacity-0 transition group-hover:opacity-100",children:[M.canEdit!==!1&&o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-3 text-xs text-muted-foreground",onClick:$=>{$.stopPropagation(),O(M)},children:"编辑"}),M.canDelete!==!1&&o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-3 text-xs text-red-500 hover:text-red-600",onClick:$=>{$.stopPropagation(),(!e||window.confirm(`删除 ${M.name} 的连接配置?远端数据不会删除。`))&&i(M.id)},children:"删除"})]}),y6(M)&&c?o.jsx(Z,{variant:"secondary",size:"sm",className:"ml-2 rounded-full px-4",onClick:$=>{$.stopPropagation(),c(M.id)},children:"恢复"}):null]})},M.id))}),r.length===0&&!u&&o.jsxs("div",{className:"mt-8 text-center",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"暂无连接配置,请添加一个后端连接"}),o.jsx(Z,{className:"mt-4 rounded-full px-6",onClick:()=>d(!0),children:"添加连接"})]}),I&&!u?o.jsx("p",{className:"mt-4 text-sm text-red-500",role:"alert",children:I}):null]})]})}function uq({embedded:e=!1,connections:t,activeId:r,onAdd:n,onRemove:s,onSelect:i,onEdit:a,onReconnect:l}){const c=Cr();return o.jsx(o.Fragment,{children:o.jsx(cq,{embedded:e,connections:t,activeId:r,onAdd:(u,d,h)=>{n(u,d,h),e||c("/terminal",{replace:!0})},onRemove:s,onSelect:u=>{i(u),e||c("/terminal",{replace:!0})},onEdit:a,onReconnect:async u=>await(l==null?void 0:l(u))?(i(u),e||c("/terminal",{replace:!0}),!0):!1})})}function Hh(e){return e===null||!Number.isFinite(e)?"—":`${e.toFixed(e>=10?0:1)}%`}function $a(e){return Number.isFinite(e)?e>=1024?`${(e/1024).toFixed(e>=10*1024?1:2)} GiB`:`${Math.round(e)} MiB`:"—"}function B1(e){return e?new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(e)):"—"}function dq(e){const t=e.displayName.trim();return t.length<=72?t:`${t.slice(0,69)}...`}function hq(e){const t=p.useMemo(()=>[...e.processes].sort((r,n)=>(e.sortKey==="energy"?(n.energyImpact??-1)-(r.energyImpact??-1):e.sortKey==="cpu"?(n.cpuPercent??-1)-(r.cpuPercent??-1):n.memoryMb-r.memoryMb)||(n.cpuPercent??-1)-(r.cpuPercent??-1)||n.memoryMb-r.memoryMb),[e.processes,e.sortKey]);return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{id:`resource-app-${e.app.appKey}`,className:e.app.isCurrentApp?"bg-[hsl(var(--primary))]/8":"",children:[o.jsx("td",{className:"min-w-0 px-4 py-3",children:o.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 text-left",onClick:e.onToggle,children:[e.expanded?o.jsx(Kv,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):o.jsx(Jr,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"truncate font-medium",children:e.app.appName}),e.app.isCurrentApp?o.jsx("span",{className:"rounded-full bg-[hsl(var(--primary))]/14 px-2 py-0.5 text-[0.68rem] font-medium text-[hsl(var(--primary))]",children:"Runweave"}):null]})}),o.jsxs("td",{className:"px-4 py-3 text-right tabular-nums",children:[e.app.energyImpact==null?"—":e.app.energyImpact.toFixed(1),e.app.coverage==="partial"?o.jsx("span",{className:"block text-[10px] text-muted-foreground",children:"覆盖不完整"}):null]}),o.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:Hh(e.app.coverage==="partial"?null:e.app.cpuPercent)}),o.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:$a(e.app.memoryMb)}),o.jsx("td",{className:"px-4 py-3 text-right tabular-nums",children:e.app.processCount})]}),e.expanded?o.jsx("tr",{children:o.jsx("td",{colSpan:5,className:"border-y border-border/60 bg-muted/35 px-4 py-3",children:t.length>0?o.jsx("div",{className:"overflow-hidden rounded-lg border border-border/70 bg-background/70",children:o.jsxs("table",{className:"w-full table-fixed text-xs",children:[o.jsx("thead",{className:"text-muted-foreground",children:o.jsxs("tr",{children:[o.jsx("th",{className:"w-24 px-3 py-2 text-left font-medium",children:"PID"}),o.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Process"}),o.jsx("th",{className:"w-24 px-3 py-2 text-right font-medium",children:"CPU Core"}),o.jsx("th",{className:"w-28 px-3 py-2 text-right font-medium",children:"RSS"}),o.jsx("th",{className:"w-40 px-3 py-2 text-right font-medium",children:"操作"})]})}),o.jsx("tbody",{children:t.slice(0,12).map(r=>o.jsxs("tr",{className:"border-t border-border/50",children:[o.jsx("td",{className:"px-3 py-2 tabular-nums text-muted-foreground",children:r.pid}),o.jsx("td",{className:"truncate px-3 py-2",children:dq(r)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Hh(r.coverage==="partial"?null:r.cpuPercent)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:$a(r.memoryMb)}),o.jsx("td",{className:"px-3 py-2 text-right",children:(()=>{const n=r.processInstanceId??String(r.pid),s=e.results[n],i=typeof s=="object"&&s.state!=="still_running";return o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s?o.jsx("span",{role:"status",className:i?"text-emerald-600 dark:text-emerald-400":"text-muted-foreground",children:typeof s=="string"?s:s.state==="still_running"?"仍在运行":s.state==="already_exited"?"进程已退出":"已结束"}):null,i?null:o.jsx(Z,{size:"sm",variant:"outline",className:"h-7 text-xs disabled:text-muted-foreground",title:r.actionReason,disabled:!!e.pending||!e.canTerminate||!r.processInstanceId||r.actionKind==="readonly",onClick:()=>e.onTerminate(r,typeof s=="object"&&s.forceAllowed),children:e.pending===n?"正在结束…":r.actionKind==="readonly"?"受保护":typeof s=="object"&&s.forceAllowed?"强制结束…":r.actionKind==="stop_service"?"停止服务":"结束进程"}),r.actionKind==="readonly"?o.jsx("span",{className:"text-[10px] text-muted-foreground",children:r.actionReason}):null]})})()})]},r.pid))})]})}):o.jsx("p",{className:"text-sm text-muted-foreground",children:"Process details are outside the current top process window."})})}):null]})}function fq({onSaved:e,embedded:t=!1}){var v,x,b;const r=Tx(),[n,s]=p.useState(t),[i,a]=p.useState(null),[l,c]=p.useState(!1),[u,d]=p.useState(null),h=W(()=>{if(!r.data)return;const _=r.data;a({monitor:_.settings.monitorEnabled,alerts:_.settings.alertsEnabled,revision:_.settings.revision,remote:_.remoteControl.enabled,remoteRevision:_.remoteControl.revision,mac:r.macNotifications}),d(null)});p.useEffect(()=>{t&&!i&&r.data&&h()},[i,t,h,r.data]);const f=!!i&&!!r.data&&(i.monitor!==r.data.settings.monitorEnabled||i.alerts!==r.data.settings.alertsEnabled||i.remote!==r.data.remoteControl.enabled||i.mac!==r.macNotifications);va(t&&f,t&&l);const m=W(async()=>{var C;if(!i||!r.token||l)return;c(!0),d(null);let _=!1;try{const S=Mh(r.apiBase,r.token),w=await S.settings({revision:i.revision,monitorEnabled:i.monitor,alertsEnabled:i.alerts});if(r.applySettings(w),_=!0,a(y=>y&&{...y,revision:w.revision}),(C=r.data)!=null&&C.canManageRemoteControl&&i.remote!==r.data.remoteControl.enabled){const y=await S.remoteControl({revision:i.remoteRevision,enabled:i.remote});r.applyRemoteControl(y),a(N=>N&&{...N,remoteRevision:y.revision})}r.setMacNotifications(i.mac),e(),t||s(!1)}catch(S){d(`${_?"监控设置已保存;其余设置未完成。":""}${S instanceof Error?S.message:String(S)}`)}finally{c(!1)}}),g=o.jsxs("div",{className:t?"space-y-3":"space-y-5","aria-busy":l,children:[i?o.jsxs("fieldset",{disabled:l,className:t?"space-y-3":"space-y-5",children:[[["monitor","后台资源监控"],["alerts","资源占用提醒"],["mac","Mac 系统通知"]].map(([_,C])=>{var S;return o.jsxs("label",{className:"flex items-center justify-between gap-3 border-b pb-4 text-sm",children:[C,o.jsx("input",{type:"checkbox",checked:i[_],disabled:_==="mac"&&!((S=window.electronAPI)!=null&&S.showResourceNotification),onChange:w=>a({...i,[_]:w.target.checked})})]},_)}),(v=r.data)!=null&&v.canManageRemoteControl?o.jsxs("label",{className:"flex items-center justify-between gap-3 text-sm",children:["允许远程结束进程",o.jsx("input",{type:"checkbox",checked:i.remote,onChange:_=>a({...i,remote:_.target.checked})})]}):o.jsxs("p",{className:"text-sm text-muted-foreground",children:["远程结束进程:",(x=r.data)!=null&&x.remoteControl.enabled?"已授权":"未授权","。仅电脑本机可修改授权。"]}),o.jsx("p",{className:"text-xs leading-6 text-muted-foreground",children:"后台每分钟采样,关闭页面后仍继续观察。允许远程控制后,普通结束和强制结束仍需分别确认;系统及 Runweave 控制进程受保护。"}),o.jsxs("p",{className:"text-xs leading-6 text-muted-foreground",children:["能耗影响 ≥ 100(仅电池供电),或 RSS 合计 ≥ 4 GiB;至少六次有效采样跨满五分钟。内存占用不代表耗电量。",(b=window.electronAPI)!=null&&b.showResourceNotification?"系统通知需要在 macOS 中允许 Runweave 发送通知。":"普通 Web 使用应用内提醒。"]})]}):o.jsx("p",{role:"status",children:r.error??"正在读取监控设置…"}),(u||r.notificationError)&&o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:u??r.notificationError}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(Z,{variant:"ghost",disabled:l,onClick:()=>{h(),t||s(!1)},children:"取消修改"}),o.jsx(Z,{disabled:l||!i||!r.token||!f,onClick:()=>void m(),children:l?"保存中…":"保存修改"})]})]});return t?g:o.jsxs(o.Fragment,{children:[o.jsxs(Z,{variant:"secondary",size:"sm",disabled:!r.data,onClick:()=>{h(),s(!0)},children:[o.jsx(lO,{className:"mr-2 h-4 w-4"}),"提醒设置"]}),o.jsx(Qr,{open:n,onOpenChange:_=>{l||s(_)},children:o.jsxs(dn,{children:[o.jsxs(Mn,{children:[o.jsx(Ur,{children:"资源提醒设置"}),o.jsx(Zr,{children:"后台资源监控与系统通知"})]}),g]})})]})}function pq(e){const t=Tx(),[r,n]=p.useState(null);return p.useEffect(()=>{var s;e||n(((s=t.data)==null?void 0:s.snapshot)??null)},[e,t.data]),{snapshot:r,resource:t}}const mq=50;function gq(e){const t=e.value===null||!Number.isFinite(e.value)?0:Math.max(0,Math.min(100,e.value)),r=e.tone==="warn"?"bg-amber-500":"bg-[hsl(var(--primary))]";return o.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:o.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${t}%`}})})}function kd(e){return o.jsxs("section",{className:"rounded-lg border border-border/70 bg-card/85 p-4 shadow-[0_18px_70px_-54px_rgba(17,24,39,0.75)]",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm font-medium text-muted-foreground",children:[e.icon,o.jsx("span",{className:"truncate",children:e.label})]}),o.jsx("strong",{className:"text-xl font-semibold tabular-nums text-foreground",children:e.value})]}),e.barValue!==void 0?o.jsx("div",{className:"mt-4",children:o.jsx(gq,{value:e.barValue,tone:e.tone})}):null,o.jsx("p",{className:"mt-3 truncate text-xs text-muted-foreground",children:e.detail})]})}function vq(e){return o.jsx("main",{className:"flex min-h-screen items-center justify-center bg-background px-6 py-10",children:o.jsxs("section",{className:"w-full max-w-lg rounded-lg border border-border/70 bg-card/90 p-8 text-center shadow-[0_24px_90px_-58px_rgba(17,24,39,0.75)]",children:[o.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full border border-border/70 bg-muted",children:o.jsx(cs,{className:"h-5 w-5 text-muted-foreground"})}),o.jsx("h1",{className:"mt-5 text-2xl font-semibold text-foreground",children:e.title}),o.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:e.body}),e.onNavigateTerminal?o.jsxs(Z,{className:"mt-6",onClick:e.onNavigateTerminal,children:[o.jsx(xi,{className:"mr-2 h-4 w-4"}),"Terminals"]}):null]})})}function xq(e){return e.memory.totalMb<=0?0:Math.round(e.memory.usedMb/e.memory.totalMb*100)}function bq(e,t){return[...e].sort((r,n)=>(t==="energy"?(n.energyImpact??-1)-(r.energyImpact??-1):t==="cpu"?(n.cpuPercent??-1)-(r.cpuPercent??-1):n.memoryMb-r.memoryMb)||(n.cpuPercent??-1)-(r.cpuPercent??-1)||n.memoryMb-r.memoryMb)}function _q({onNavigateTerminal:e,embedded:t=!1}){const[r,n]=p.useState(!1),[s,i]=p.useState("energy"),[a]=fa(),[l,c]=p.useState(a.get("app")),[u,d]=p.useState({}),[h,f]=p.useState(null),m=p.useRef(!1),[g,v]=p.useState(null),{snapshot:x,resource:b}=pq(r),{data:_,error:C,refresh:S}=b;p.useEffect(()=>{const k=a.get("app");k&&c(k)},[a]),p.useEffect(()=>{var k;l&&((k=document.getElementById(`resource-app-${l}`))==null||k.scrollIntoView({block:"nearest"}))},[l]);const w=W(async()=>{if(!g||!b.token||m.current||!g.process.processInstanceId)return;const k=g,D=k.process.processInstanceId;m.current=!0,f(D),v(null);try{const j=await Mh(b.apiBase,b.token).terminate(D,k.force,crypto.randomUUID());d(R=>({...R,[D]:j}))}catch(j){d(R=>({...R,[D]:j instanceof Error?j.message:String(j)}))}finally{m.current=!1,f(null)}});if((_==null?void 0:_.status)==="unsupported")return o.jsx(vq,{title:"需要 macOS Backend",body:"当前连接的电脑尚不支持资源采样。",onNavigateTerminal:e});const y=x?xq(x):0,N=x?bq(x.apps,s).slice(0,mq):[],E=new Map;for(const k of(x==null?void 0:x.processes)??[]){const D=E.get(k.appKey)??[];D.push(k),E.set(k.appKey,D)}return o.jsxs("main",{className:t?"text-foreground":"min-h-screen bg-background px-4 py-5 text-foreground md:px-6 lg:px-8",children:[o.jsxs("div",{className:"flex w-full flex-col gap-3",children:[o.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border/70 pb-4",children:[o.jsxs("div",{className:"min-w-0",children:[!t&&o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.28em] text-muted-foreground",children:"Runweave"}),!t&&o.jsx("h1",{className:"mt-1 text-3xl font-semibold tracking-normal",children:"系统监控"}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[(_==null?void 0:_.hostName)??"当前连接的电脑"," ·"," ",(_==null?void 0:_.status)==="ok"?`最近采样 ${B1((x==null?void 0:x.sampledAt)??null)}`:(_==null?void 0:_.status)==="disabled"?"后台资源监控已关闭":(_==null?void 0:_.status)==="stale"?"采样已过期":(_==null?void 0:_.status)==="error"?"采样失败,显示上次数据":"观察中"]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[!t&&o.jsx(Sa,{}),e?o.jsxs(Z,{variant:"ghost",size:"sm",onClick:e,children:[o.jsx(xi,{className:"mr-2 h-4 w-4"}),"Terminals"]}):null,o.jsx(fq,{onSaved:S}),o.jsxs(Z,{variant:"secondary",size:"sm",onClick:S,children:[o.jsx(Ws,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"刷新缓存"})]}),o.jsxs(Z,{variant:r?"default":"secondary",size:"sm",onClick:()=>n(k=>!k),children:[o.jsx("span",{className:"sr-only",children:r?"继续显示":"暂停显示"}),r?o.jsx(Sl,{className:"h-4 w-4"}):o.jsx(VM,{className:"h-4 w-4"})]})]})]}),C?o.jsx("p",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600 dark:text-red-300",children:C}):null,_!=null&&_.alerts[0]?o.jsxs("aside",{role:"status",className:"flex flex-wrap items-center justify-between gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 p-4",children:[o.jsxs("div",{children:[o.jsxs("strong",{children:[_.alerts[0].appName," ",_.alerts[0].ruleId==="energy"?"能耗影响较高":"内存占用较大"]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["近 5 分钟多次检测到高占用",_.alerts[0].ruleId==="memory"?";内存占用不代表耗电量":""]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",onClick:()=>c(_.alerts[0].appKey),children:"查看进程"}),o.jsx(Z,{size:"sm",variant:"outline",onClick:()=>{b.snooze(_.alerts[0].alertId).then(()=>{b.dismissNotice(),S()}).catch(()=>{})},children:"忽略 1 小时"})]})]}):null,l&&x&&!N.some(k=>k.appKey===l)?o.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"该提醒对应的应用已退出或不在当前列表中。"}):null,b.notificationError?o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:b.notificationError}):null,b.unsupportedBackend?o.jsx("p",{role:"alert",className:"text-sm text-muted-foreground",children:"当前 Backend 尚不支持资源监控,请更新 Backend。"}):null,o.jsxs("section",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[o.jsx(kd,{label:"CPU",value:x?Hh(x.cpu.totalPercent):"-",detail:x!=null&&x.cpu.warmingUp?"观察中":`${(x==null?void 0:x.cpu.coreCount)??0} 核心`,icon:o.jsx(GL,{className:"h-4 w-4"}),barValue:(x==null?void 0:x.cpu.totalPercent)??null}),o.jsx(kd,{label:"内存",value:x?`${y}%`:"-",detail:x?`${$a(x.memory.usedMb)} / ${$a(x.memory.totalMb)} · ${x.memory.pressure}`:"-",icon:o.jsx(CM,{className:"h-4 w-4"}),barValue:y,tone:(x==null?void 0:x.memory.pressure)==="warn"||(x==null?void 0:x.memory.pressure)==="critical"?"warn":"ok"}),o.jsx(kd,{label:"Swap",value:x?$a(x.memory.swapUsedMb):"-",detail:_!=null&&_.settings.monitorEnabled?"后台每分钟采样":"后台采样已关闭",icon:o.jsx(cs,{className:"h-4 w-4"})}),o.jsx(kd,{label:"电池",value:x!=null&&x.battery.available?`${x.battery.percent}%`:"未知",detail:x!=null&&x.battery.available?`${x.battery.powerSource==="ac"?"接电":x.battery.powerSource==="battery"?"电池供电":"供电未知"} · ${x.battery.dischargePowerW==null?"放电功率未知":`估算放电 ${x.battery.dischargePowerW.toFixed(1)} W`}`:"电池数据未知",icon:x!=null&&x.battery.available&&x.battery.charging?o.jsx(xL,{className:"h-4 w-4"}):o.jsx(_L,{className:"h-4 w-4"}),barValue:x!=null&&x.battery.available?x.battery.percent:null})]}),o.jsxs("section",{className:"flex flex-col rounded-lg border border-border/70 bg-card/85 shadow-[0_24px_90px_-58px_rgba(17,24,39,0.75)]",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border/70 px-4 py-3",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold",children:"高占用应用与进程"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["最近采样 ",B1((x==null?void 0:x.sampledAt)??null)]})]}),o.jsxs("div",{className:"flex rounded-lg border border-border/70 bg-background/70 p-1",children:[o.jsx(Z,{variant:s==="energy"?"default":"ghost",size:"sm",onClick:()=>i("energy"),children:"能耗影响"}),o.jsx(Z,{variant:s==="cpu"?"default":"ghost",size:"sm",onClick:()=>i("cpu"),children:"CPU Core"}),o.jsx(Z,{variant:s==="memory"?"default":"ghost",size:"sm",onClick:()=>i("memory"),children:"RSS Sum"})]})]}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full min-w-[720px] table-fixed text-sm",children:[o.jsx("thead",{className:"border-b border-border/70 text-xs uppercase text-muted-foreground",children:o.jsxs("tr",{children:[o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"App"}),o.jsx("th",{className:"w-28 px-4 py-3 text-right font-medium",children:"能耗影响"}),o.jsx("th",{className:"w-32 px-4 py-3 text-right font-medium",children:"CPU Core"}),o.jsx("th",{className:"w-36 px-4 py-3 text-right font-medium",children:"RSS Sum"}),o.jsx("th",{className:"w-28 px-4 py-3 text-right font-medium",children:"Procs"})]})}),o.jsx("tbody",{className:"divide-y divide-border/60",children:N.length>0?N.map(k=>o.jsx(hq,{app:k,results:u,pending:h,canTerminate:(_==null?void 0:_.canTerminate)===!0&&!C&&!r,onTerminate:(D,j)=>v({process:D,force:j}),processes:E.get(k.appKey)??[],expanded:l===k.appKey,sortKey:s,onToggle:()=>{c(D=>D===k.appKey?null:k.appKey)}},k.appKey)):o.jsx("tr",{children:o.jsx("td",{colSpan:5,className:"px-4 py-12 text-center text-muted-foreground",children:x?"暂无进程数据。":"正在等待 Backend 采样…"})})})]})}),o.jsxs("div",{className:"border-t border-border/70 px-4 py-3 text-xs text-muted-foreground",children:["能耗影响按 CPU 与唤醒次数估算,不能完整归因 GPU、网络等耗电,也不是应用瓦数。进程 CPU 的 100% 表示一个核心;RSS 合计可能重复计入共享页。采样覆盖"," ",(_==null?void 0:_.coverage.matchedProcesses)??0,"/",(_==null?void 0:_.coverage.knownProcesses)??0," 个进程,未知值显示「—」。",Object.values(u).some(k=>typeof k=="object"&&k.state!=="still_running")?o.jsx("p",{className:"mt-2",children:"只结束了选定进程;该应用仍可能有其他进程运行。电池功率将在下次后台采样更新。"}):null]})]})]}),o.jsx(Tl,{open:g!==null,onOpenChange:k=>{k||v(null)},children:o.jsxs(xa,{className:"rounded-lg border-border bg-card text-foreground",children:[o.jsxs(Dl,{children:[o.jsx(ba,{children:g!=null&&g.force?"强制结束这个进程?":(g==null?void 0:g.process.actionKind)==="stop_service"?"停止这个服务?":"结束这个进程?"}),o.jsx(_a,{asChild:!0,children:o.jsxs("div",{className:"space-y-3 text-muted-foreground",children:[o.jsxs("p",{children:[g==null?void 0:g.process.displayName," · PID ",g==null?void 0:g.process.pid," ·"," ",_==null?void 0:_.hostName]}),o.jsxs("p",{children:["CPU ",Hh((g==null?void 0:g.process.cpuPercent)??null)," · RSS"," ",$a((g==null?void 0:g.process.memoryMb)??0)]}),o.jsxs("p",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-foreground",children:["未保存的内容可能丢失。",(g==null?void 0:g.process.actionKind)==="stop_service"?`将停止 ${g.process.serviceName} 服务及其子进程;必要时按服务生命周期强制结束。`:"此操作只结束选中的进程。",g!=null&&g.force?"强制结束不会等待程序自行退出。":""]})]})})]}),o.jsxs(Pl,{children:[o.jsx(ya,{children:"取消"}),o.jsx(Z,{variant:"destructive",onClick:()=>void w(),children:g!=null&&g.force?"强制结束":(g==null?void 0:g.process.actionKind)==="stop_service"?"停止服务":"结束进程"})]})]})})]})}const yq=10;function wq({activeSessionId:e,cachedSessionIds:t,sessionIds:r,maxCachedSurfaces:n=yq}){if(n<=0)return[];const s=new Set(r),i=t.filter(a=>s.has(a)&&a!==e);return e&&s.has(e)&&i.push(e),i.slice(-n)}function F1(e){return e==="mobile"?"pty":"auto"}function Sq({apiBase:e,token:t,clientMode:r,removeProjectPreview:n,loadSessions:s,onAuthExpired:i}){const a=_s().data??_o,l=Zn().data??bs,{queryClient:c,scope:u}=Al(),{loading:d,activeProjectId:h,activeParentProjectId:f,activeSessionId:m}=tt(An(F=>({loading:F.loading,activeProjectId:F.activeProjectId,activeParentProjectId:F.activeParentProjectId,activeSessionId:F.activeSessionId}))),g=a.find(F=>F.projectId===f)??null,v=h?l.filter(F=>F.projectId===h):l,x=v.find(F=>F.terminalSessionId===m)??v[0]??null,{projectDialogMode:b,projectPendingDeletion:_,setLoading:C,setRequestError:S,setProjectDialogMode:w,setProjectDialogError:y,setProjectPendingDeletion:N,setHistoryDrawerOpen:E,setHistoryTerminalSessionId:k,setHistoryTerminalPanelId:D,selectProjectContext:j,setActiveSessionId:R}=tt(An(F=>({projectDialogMode:F.projectDialogMode,projectPendingDeletion:F.projectPendingDeletion,setLoading:F.setLoading,setRequestError:F.setRequestError,setProjectDialogMode:F.setProjectDialogMode,setProjectDialogError:F.setProjectDialogError,setProjectPendingDeletion:F.setProjectPendingDeletion,setHistoryDrawerOpen:F.setHistoryDrawerOpen,setHistoryTerminalSessionId:F.setHistoryTerminalSessionId,setHistoryTerminalPanelId:F.setHistoryTerminalPanelId,selectProjectContext:F.selectProjectContext,setActiveSessionId:F.setActiveSessionId}))),I=W(async()=>{C(!0);try{const F=await C0(e,t,{projectId:h??void 0,inheritFromTerminalSessionId:x==null?void 0:x.terminalSessionId,runtimePreference:F1(r)});S(null),await s(),R(F.terminalSessionId)}catch(F){if(F instanceof De&&F.status===401){i==null||i();return}S(String(F))}finally{C(!1)}}),T=W(async F=>{C(!0);try{await Y6(e,t,F),S(null),await s()}catch(K){if(K instanceof De&&K.status===401){i==null||i();return}S(String(K))}finally{C(!1)}}),A=W(async(F,K)=>{C(!0);try{const Y=await Fc(e,t,F,{alias:K.trim()||null});Ga(c,u,te=>te.map(H=>H.terminalSessionId===Y.terminalSessionId?Y:H)),S(null)}catch(Y){if(Y instanceof De&&Y.status===401){i==null||i();return}S(String(Y))}finally{C(!1)}}),P=W(async(F,K)=>{C(!0);try{await Fc(e,t,F,{projectId:K}),await s(),j(K,K,F),S(null)}catch(Y){if(Y instanceof De&&Y.status===401){i==null||i();return}S(String(Y))}finally{C(!1)}}),O=W(()=>{d||(y(null),w(null))}),L=W(async(F,K,Y)=>{const te=F.trim();if(!te){y("Project name is required.");return}const H=K.trim();C(!0),y(null);try{if(b==="edit"&&g){const G=await z6(e,t,g.projectId,{name:te,path:H||null,mainBranch:Y.trim()||null});om(c,u,z=>z.map(ee=>ee.projectId===G.projectId?G:ee))}else{const G=await M6(e,t,{name:te,path:H||null}),z=await C0(e,t,{projectId:G.projectId,runtimePreference:F1(r)});om(c,u,V=>[...V.filter(re=>re.projectId!==G.projectId),G]),j(G.projectId,G.projectId,z.terminalSessionId);const ee=new Date().toISOString();Ga(c,u,V=>[...V.filter(re=>re.terminalSessionId!==z.terminalSessionId),{terminalSessionId:z.terminalSessionId,projectId:G.projectId,command:"",args:[],cwd:"",activeCommand:null,completionRevision:0,acknowledgedCompletionRevision:0,status:"running",createdAt:ee,lastActivityAt:ee,panelSplitEnabled:!1}]),await s()}w(null)}catch(G){if(G instanceof De&&G.status===401){i==null||i();return}y(String(G))}finally{C(!1)}}),B=W(async()=>{const F=_??g;if(F){C(!0);try{await $6(e,t,F.projectId),S(null),y(null),j(null,null,null),n(F.projectId),N(null),await s()}catch(K){if(K instanceof De&&K.status===401){i==null||i();return}S(String(K))}finally{C(!1)}}}),M=W((F,K)=>{om(c,u,Y=>{const te=[...Y],[H]=te.splice(F,1);H&&te.splice(K,0,H);const G=te.map(z=>z.projectId);return U6(e,t,G).catch(()=>{s()}),te})}),$=W((F,K)=>{h&&Ga(c,u,Y=>{const H=[...Y.filter(V=>V.projectId===h)],[G]=H.splice(F,1);G&&H.splice(K,0,G);const z=H.map(V=>V.terminalSessionId);X6(e,t,h,z).catch(()=>{s()});let ee=0;return Y.map(V=>V.projectId===h?H[ee++]:V)})}),U=W(F=>{k(F),D(null),E(!0)});return{createSession:I,closeSession:T,updateSessionAlias:A,moveSession:P,closeProjectDialog:O,submitProjectDialog:L,removeProject:B,handleProjectReorder:M,handleSessionReorder:$,openHistoryDrawer:U}}function Cq(){if(typeof window>"u")return null;const e=window.AudioContext??window.webkitAudioContext;return e?new e:null}function Eq(e){var u;const{createContext:t=Cq,durationMs:r=120,frequency:n=1046,nativeBeep:s=typeof window>"u"||(u=window.electronAPI)==null?void 0:u.beep,volume:i=.12}={};let a=null,l=null;const c=async()=>(a??(a=t()),a?(a.state==="suspended"&&a.resume&&(l||(l=a.resume().then(()=>a).finally(()=>{l=null})),await l),a):null);return{async prepare(){s||await c()},play(){if(s)try{return s(),Promise.resolve()}catch{}return c().then(d=>{if(!d)return;const h=d.createOscillator(),f=d.createGain();h.type="sine",h.frequency.value=n,f.gain.value=i,h.connect(f),f.connect(d.destination),h.start(),h.stop(d.currentTime+r/1e3)}).catch(()=>{})}}}const kq=2e3,Iq=50;function Nq(e){return e.kind==="completion_acknowledged"||e.kind==="project_created"||e.kind==="project_deleted"||e.kind==="terminal_session_created"||e.kind==="terminal_session_moved"||e.kind==="terminal_session_deleted"}function Rq(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t];if((r==null?void 0:r.kind)==="terminal_session_created")return r}return null}function jq({apiBase:e,token:t,onAuthExpired:r,loadSessions:n}){const s=Zn().data??bs,{queryClient:i,scope:a}=Al(),{setTerminalStateBySessionId:l,setPanelWorkspaceBySessionId:c,setActivePanelIdBySessionId:u,setCompletionMarkers:d,selectProjectContext:h,setBellMarkers:f}=tt(An(k=>({setTerminalStateBySessionId:k.setTerminalStateBySessionId,setPanelWorkspaceBySessionId:k.setPanelWorkspaceBySessionId,setActivePanelIdBySessionId:k.setActivePanelIdBySessionId,setCompletionMarkers:k.setCompletionMarkers,selectProjectContext:k.selectProjectContext,setBellMarkers:k.setBellMarkers}))),m=p.useRef(null),g=p.useRef(null),v=p.useRef(null),x=W(()=>{m.current=null}),{run:b,cancel:_}=dC(()=>{const k=g.current;g.current=null,n().then(()=>{!k||tt.getState().activeSessionId||h(Tn(k.projectId),k.projectId,k.terminalSessionId)})},{wait:Iq});p.useEffect(()=>()=>{_()},[_]);const C=W((k,D)=>{var L;const j=k[k.length-1];j&&(m.current=j.id);const R=k.filter(B=>B.kind==="terminal_state_changed");if(R.length>0){l(M=>{let $=!1;const U={...M};for(const F of R){if(F.kind!=="terminal_state_changed")continue;const K=F.payload.next,Y=U[F.terminalSessionId];(Y==null?void 0:Y.state)===K.state&&Y.agent===K.agent||(U[F.terminalSessionId]=K,$=!0)}return $?U:M});const B=R.filter(M=>M.kind==="terminal_state_changed"&&M.payload.next.state==="agent_running").map(M=>M.terminalSessionId);B.length>0&&d(M=>{let $=!1;const U={...M};for(const F of B)U[F]!==void 0&&(delete U[F],$=!0);return $?U:M})}const I=k.filter(B=>B.kind==="terminal_panel_created"||B.kind==="terminal_panel_updated"||B.kind==="terminal_panel_deleted"||B.kind==="terminal_panel_focused"||B.kind==="terminal_panel_input_sent");I.length>0&&(c(B=>{let M=!1;const $={...B};for(const U of I){const F=U.payload.workspace,K=$[U.terminalSessionId],te=(K==null?void 0:K.panels.length)===F.panels.length&&F.panels.every(H=>K.panels.some(G=>G.panelId===H.panelId))?{...F,panels:F.panels.map(H=>{var G;return{...H,geometry:H.geometry??((G=K.panels.find(z=>z.panelId===H.panelId))==null?void 0:G.geometry)}})}:F;JSON.stringify(K)!==JSON.stringify(te)&&($[U.terminalSessionId]=te,M=!0)}return M?$:B}),u(B=>{let M=!1;const $={...B};for(const U of I){const F=U.payload.workspace.activePanelId;$[U.terminalSessionId]!==F&&($[U.terminalSessionId]=F,M=!0)}return M?$:B}));const T=new Map;for(const B of k)B.kind==="terminal_session_metadata_changed"&&T.set(B.terminalSessionId,B.payload.next);if(T.size>0&&Ga(i,a,B=>{let M=!1;const $=B.map(U=>{const F=T.get(U.terminalSessionId);return!F||U.cwd===F.cwd&&U.activeCommand===F.activeCommand?U:(M=!0,{...U,cwd:F.cwd,activeCommand:F.activeCommand})});return M?$:B}),k.some(Nq)){const B=Rq(k);B&&(g.current=B),b()}const A=new Set(s.map(B=>B.terminalSessionId));if(D==="live"){const B=tt.getState().activeSessionId,M=new Set(k.filter($=>$.kind==="terminal_bell").map($=>$.terminalSessionId).filter($=>$!==B&&A.has($)));if(M.size>0){f($=>{let U=!1;const F={...$};for(const K of M)F[K]||(F[K]=!0,U=!0);return U?F:$});for(const $ of M)window.setTimeout(()=>{f(U=>{if(!U[$])return U;const F={...U};return delete F[$],F})},kq)}}const P=k.filter(B=>B.kind==="completion_acknowledged");P.length&&d(B=>{const M={...B};for(const $ of P)(M[$.terminalSessionId]??0)<=$.payload.acknowledgedCompletionRevision&&delete M[$.terminalSessionId];return M});const O=k.filter(B=>B.kind==="completion").filter(B=>A.has(B.terminalSessionId)).filter(B=>!P.some(M=>M.terminalSessionId===B.terminalSessionId&&M.payload.acknowledgedCompletionRevision>=B.payload.completionRevision));O.length!==0&&(d(B=>{let M=!1;const $={...B};for(const U of O){const F=$[U.terminalSessionId]??0;U.payload.completionRevision<=F||($[U.terminalSessionId]=U.payload.completionRevision,M=!0)}return M?$:B}),D==="live"&&((L=window.electronAPI)==null?void 0:L.isElectron)===!0&&(v.current??(v.current=Eq()),v.current.play()))}),S=W(()=>m.current),w=W(k=>{m.current=k}),y=W(()=>{n()}),N=EN({apiBase:e,token:t,getCursor:S,setCursor:w,onAuthExpired:r,onResyncRequired:y,onTerminalEvents:C}),E=p.useMemo(()=>{const k=Date.now(),D=N.connectionStatus==="connected"?"healthy":N.failureExpired?"unhealthy":N.failureSince===null?"checking":"recovering";return{id:"frontend.terminal-events.websocket",capabilityId:"terminal",label:"Terminal events",state:D,summary:D==="healthy"?"Terminal 事件流已收到服务端 connected":D==="unhealthy"?N.error||"Terminal 事件流持续未连接":"等待 Terminal 事件流服务端确认",observedAt:k,dependsOn:["frontend.node.http","frontend.node.auth"],recovery:D==="recovering"||D==="unhealthy"?{startedAt:N.failureSince??k,attempt:N.reconnectAttempt,maxAttempts:null,nextAttemptAt:null,deadlineAt:(N.failureSince??k)+3e4}:null,facts:[],navigation:null}},[N.connectionStatus,N.error,N.failureExpired,N.failureSince,N.reconnectAttempt]);return Kk(E,E.id),{resetTerminalEventCursor:x}}const sR=e=>`/api/terminal/session/${encodeURIComponent(e)}/code-reviews`;function $1(e,t,r,n){return me(e,sR(r),{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}function Aq(e,t,r,n,s){return me(e,sR(r)+"",{headers:{Authorization:`Bearer ${t}`},signal:n})}function Tq(e,t,r,n){return me(e,`/api/terminal/code-reviews/${encodeURIComponent(r)}`,{headers:{Authorization:`Bearer ${t}`},signal:n})}function Dq(e,t,r){return me(e,`/api/terminal/code-reviews/${encodeURIComponent(r)}/close`,{method:"POST",headers:{Authorization:`Bearer ${t}`}})}function vce(e,t,r,n){return zv(e,`/api/terminal/code-reviews/${encodeURIComponent(r)}/artifacts/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${t}`}})}const ug=Qn(e=>({states:{},put:(t,r)=>e(n=>({states:{...n.states,[t]:r}}))})),Wh=(e,t)=>[...jt.all(e),"code-reviews",t],iR=e=>e instanceof De&&[404,501].includes(e.status)?"此电脑尚不支持代码 Review":e instanceof Error?e.message:String(e);function oR(e){const{scope:t}=vt();return ug(r=>r.states[JSON.stringify([t,e])])}function Pq(e){const t=vt(),r=xs();return W(async()=>{if(!e)return;const{scope:n,apiBase:s,token:i,onAuthExpired:a}=t,l=e.terminalSessionId,c=JSON.stringify([n,l]),u=ug.getState().states[c];if(u!=null&&u.pending)return;const d={requestId:crypto.randomUUID()},h=ug.getState().put;h(c,{pending:!0,error:null,request:d});try{try{await $1(s,i,l,d)}catch(f){if(f instanceof De)throw f;await $1(s,i,l,d)}h(c,{pending:!1,error:null,request:d}),await Promise.all([r.invalidateQueries({queryKey:Wh(n,l)}),r.invalidateQueries({queryKey:jt.sessions(n)})])}catch(f){h(c,{pending:!1,error:iR(f),request:d}),f instanceof De&&f.status===401&&(a==null||a())}})}function aR(e,t=!0){const{scope:r,apiBase:n,token:s,onAuthExpired:i}=vt(),a=Ct({queryKey:Wh(r,e),queryFn:({signal:l})=>Aq(n,s,e,l),enabled:!!e,retry:!1,staleTime:3e3,refetchInterval:l=>t&&!(l.state.error instanceof De&&[404,501].includes(l.state.error.status))?5e3:!1,refetchIntervalInBackground:!1});return p.useEffect(()=>{a.error instanceof De&&a.error.status===401&&(i==null||i())},[a.error,i]),a}function xce(e){const{scope:t,apiBase:r,token:n}=vt();return Ct({queryKey:[...jt.all(t),"code-review",e],queryFn:({signal:s})=>Tq(r,n,e,s),enabled:!!e,retry:!1,refetchInterval:s=>{var a;const i=(a=s.state.data)==null?void 0:a.run;return s.state.error||i&&!["preparing","starting","reviewing"].includes(i.phase)&&!["pending","writing"].includes(i.delivery)?!1:5e3}})}function Lq(e){const{scope:t,apiBase:r,token:n,onAuthExpired:s}=vt(),i=xs();return nr({mutationFn:a=>Dq(r,n,a),onSuccess:a=>{i.setQueryData(Wh(t,e),l=>l&&{...l,runs:l.runs.map(c=>c.caseId===a.caseId?{...c,caseStatus:a.caseStatus}:c)}),i.invalidateQueries({queryKey:Wh(t,e)}),i.invalidateQueries({queryKey:[...jt.all(t),"code-review"]})},onError:a=>{a instanceof De&&a.status===401&&(s==null||s())}})}function Mq({apiBase:e,token:t,terminalId:r}){const n=Xr(v=>v.snapshot),[s,i]=p.useState(null),[a,l]=p.useState(null),c=(n==null?void 0:n.hosts.filter(v=>v.browser.state==="ready").map(v=>`${v.hostId}:${v.installationId}:${v.bindingId}`).sort().join("|"))??"";p.useEffect(()=>{if(i(null),l(null),!window.electronAPI||!t)return;const v=new AbortController;let x;const b=async _=>{try{const C=await fetch(`${e}/api/remote/capabilities`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.any([v.signal,AbortSignal.timeout(5e3)])});if([401,403,404].includes(C.status))return;if(!C.ok)throw new Error(`HTTP ${C.status}`);const S=await C.json();if(typeof S.installationId!="string")return;v.signal.aborted||i({apiBase:e,token:t,id:S.installationId})}catch{!v.signal.aborted&&_<4&&(x=setTimeout(()=>void b(_+1),Math.min(1e3*2**_,5e3)))}};return b(0),()=>{v.abort(),clearTimeout(x)}},[e,t,c]);const u=(s==null?void 0:s.apiBase)===e&&s.token===t?s.id:null,d=u?(n==null?void 0:n.hosts.filter(v=>v.browser.state==="ready"&&v.installationId===u))??[]:[],h=W(async(v,x,b=()=>!0)=>{var _;!b()||!((_=window.electronAPI)!=null&&_.selectTunnelBrowser)||(await window.electronAPI.selectTunnelBrowser(v,x),b()&&l(v))}),f=d.length===1?d[0]:null,m=f==null?void 0:f.hostId,g=f==null?void 0:f.bindingId;return p.useEffect(()=>{let v=!1,x;const b=async _=>{if(!(v||!m||!r))try{await h(m,r,()=>!v)}catch(C){if(v)return;!/BROWSER_BINDING_CONFLICT|BROWSER_SCOPE_DENIED|NEEDS_AUTH|INVALID_TERMINAL/.test(String(C))&&_<4?x=setTimeout(()=>void b(_+1),Math.min(1e3*2**_,5e3)):Xr.getState().setNotice(A1(C))}};return b(0),()=>{v=!0,clearTimeout(x)}},[e,t,m,g,r,h]),!r||d.length<2?null:o.jsx(o.Fragment,{children:d.map(v=>{var x;return o.jsxs(Bt,{onSelect:()=>void h(v.hostId,r).catch(b=>Xr.getState().setNotice(A1(b))),children:["浏览器通道:",(x=n==null?void 0:n.config.hosts.find(b=>b.id===v.hostId))==null?void 0:x.name,a===v.hostId?" ✓":""]},v.hostId)})})}function lR(){const{scope:e}=vt(),t=Cr();return W((r="/scheduled-tasks")=>{const n=tt.getState();t(r,{state:{scope:e,workspace:{parentProjectId:n.activeParentProjectId,projectId:n.activeProjectId,terminalSessionId:n.activeSessionId,panelId:n.activeSessionId?n.activePanelIdBySessionId[n.activeSessionId]:void 0}}})})}function cR(){const{scope:e}=vt(),t=Gt(),r=Cr(),n=t.state,s=oa(e),i=(n==null?void 0:n.scope)===e?n.workspace:{parentProjectId:(s==null?void 0:s.projectId)??null,projectId:s?s.contextProjectIdByParentProjectId[s.projectId]??s.projectId:null,terminalSessionId:(s==null?void 0:s.terminalSessionId)??null},a=W(c=>r(c,{state:{scope:e,workspace:i}})),l=W(()=>{wu(e,i),r(i.terminalSessionId?`/terminal/${encodeURIComponent(i.terminalSessionId)}`:"/terminal")});return{workspace:i,go:a,back:l}}const Oq="/api/scheduled-tasks",wn=encodeURIComponent;function Uu(e,t){let r;async function n(s,i={}){s!=="/capabilities"&&(r??(r=n("/capabilities").then(()=>{}).catch(l=>{throw r=void 0,l})),await r);const a=await me(e,`${Oq}${s}`,{method:i.method,signal:i.signal,headers:{Authorization:`Bearer ${t}`,"X-Runweave-Task-Context-Version":"2",...i.body===void 0?{}:{"Content-Type":"application/json"},...i.key?{"Idempotency-Key":i.key}:{}},body:i.body===void 0?void 0:JSON.stringify(i.body)});if(s==="/capabilities"&&a.taskContextVersion!==2)throw new Error("此电脑的定时任务协议不兼容,请更新 Backend 和客户端。");return a}return{capabilities:s=>n("/capabilities",{signal:s}),list:(s,i)=>{const a=new URLSearchParams;for(const[l,c]of Object.entries(s))c!==void 0&&c!==""&&a.set(l,String(c));return n(`?${a}`,{signal:i})},task:(s,i)=>n(`/${wn(s)}`,{signal:i}),preview:(s,i)=>n("/preview",{method:"POST",body:{schedule:s},signal:i}),create:(s,i)=>n("",{method:"POST",body:s,key:i}),update:(s,i)=>n(`/${wn(s)}`,{method:"PATCH",body:i}),remove:(s,i)=>n(`/${wn(s)}`,{method:"DELETE",body:{expectedRevision:i}}),start:(s,i)=>n(`/${wn(s)}/runs`,{method:"POST",body:{},key:i}),runs:(s,i,a)=>n(`/${wn(s)}/runs${i?`?cursor=${wn(i)}`:""}`,{signal:a}),run:(s,i)=>n(`/runs/${wn(s)}`,{signal:i}),quickInputRuns:(s,i)=>{const a=new URLSearchParams;for(const[l,c]of Object.entries(s))c!==void 0&&a.set(l,String(c));return n(`/runs?${a}`,{signal:i})},output:(s,i,a)=>n(`/runs/${wn(s)}/output${i?`?cursor=${wn(i)}`:""}`,{signal:a}),continue:(s,i,a,l)=>n(`/runs/${wn(s)}/continue`,{method:"POST",body:{expectedRevision:i,...l!==void 0?{reply:l}:{}},key:a}),stop:s=>n(`/runs/${wn(s)}/stop`,{method:"POST"}),archive:s=>n(`/runs/${wn(s)}/archive`,{method:"POST",body:{}}),open:(s,i)=>n(`/runs/${wn(s)}/open-terminal`,{method:"POST",body:i})}}function Bq(){const{apiBase:e,token:t,scope:r}=vt();return Ct({queryKey:["connection",r,"agent-model-catalogs"],queryFn:({signal:n})=>Yk(e,t,n),staleTime:6e4})}const hs={all:e=>["connection",e,"scheduled-tasks"]},Hu=()=>$f.isFocused()&&sa.isOnline()?3e3:!1;function es(){const{apiBase:e,token:t,scope:r}=vt();return{api:p.useMemo(()=>Uu(e,t),[e,t]),scope:r}}function Fq(){const{api:e,scope:t}=es();return Ct({queryKey:[...hs.all(t),"capabilities"],queryFn:({signal:r})=>e.capabilities(r)})}function $q(e,t){const{api:r,scope:n}=es();return ia({queryKey:[...hs.all(n),"list",e],queryFn:({signal:s,pageParam:i})=>r.list({...e,cursor:i},s),initialPageParam:void 0,getNextPageParam:s=>s.nextCursor??void 0,refetchInterval:Hu,enabled:t})}function zq(e,t=!0){const{api:r,scope:n}=es();return Ct({queryKey:[...hs.all(n),"task",e],queryFn:({signal:s})=>r.task(e,s),enabled:t&&!!e,refetchInterval:Hu})}function Uq(e){const{api:t,scope:r}=es();return ia({queryKey:[...hs.all(r),"runs",e],queryFn:({signal:n,pageParam:s})=>t.runs(e,s,n),initialPageParam:void 0,getNextPageParam:n=>n.nextCursor??void 0,refetchInterval:Hu})}function Ml(e,t=!0){const{api:r,scope:n}=es();return Ct({queryKey:[...hs.all(n),"run",e],queryFn:({signal:s})=>r.run(e,s),enabled:!!e,refetchInterval:t?Hu:!1})}function Jf(){const{scope:e}=es(),t=xs();return()=>t.invalidateQueries({queryKey:hs.all(e)})}function uR(e){return`/background-runs/${encodeURIComponent(e)}`}function Qf(e){var t;return((t=e.snapshot.origin)==null?void 0:t.kind)==="quick-input"?uR(e.id):`/scheduled-tasks/${encodeURIComponent(e.taskId)}?run=${encodeURIComponent(e.id)}`}function Hq({source:e}){var n,s;const t=Ml(e.runId,!1),r=lR();return o.jsxs("button",{type:"button",className:"max-w-44 truncate rounded px-2 py-1 text-xs text-slate-300 hover:bg-slate-800",title:t.error?"无法读取来源名称,点击查看来源":(n=t.data)==null?void 0:n.snapshot.name,onClick:()=>{var i;return r(((i=t.data)==null?void 0:i.taskId)===e.taskId?Qf(t.data):`/scheduled-tasks/${encodeURIComponent(e.taskId)}?run=${encodeURIComponent(e.runId)}`)},children:["来源:",((s=t.data)==null?void 0:s.taskId)===e.taskId?t.data.snapshot.name:"定时任务"]})}const Wq=/^\/share\/terminal\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\?expires=([1-9][0-9]{0,15})&signature=([A-Za-z0-9_-]{43})$/;function qq(e){const t=Wq.exec(e);if(!t||t[0]!==e)return null;const r=Number(t[2]);return Number.isSafeInteger(r)?{snapshotId:t[1],expires:r,signature:t[3]}:null}function Kq(e){const t=new URL(e||window.location.origin,window.location.href);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("Terminal sharing requires an HTTP(S) connection");return t.username="",t.password="",t.search="",t.hash="",t.toString().replace(/\/+$/,"")}async function Vq(e,t,r,n){const s=Kq(e),i=await me(s,`/api/terminal/session/${encodeURIComponent(r)}/panels/${encodeURIComponent(n)}/shares`,{method:"POST",headers:{Authorization:`Bearer ${t}`}}),a=qq(i.sharePath);if(!a||a.expires!==Date.parse(i.expiresAt))throw new Error("Invalid terminal snapshot response");if(typeof i.shareUrl!="string")throw new Error("Public snapshot URL is missing");const l=new URL(i.shareUrl);if(l.protocol!=="https:"||l.username||l.password||l.hash||`${l.pathname}${l.search}`!==i.sharePath)throw new Error("Invalid public terminal snapshot URL");return{...i,url:l.href}}const Nc=Qn((e,t)=>({pending:!1,result:null,error:null,dismiss:()=>e({result:null,error:null}),createShare:async(r,n,s,i)=>{if(!t().pending){e({pending:!0,result:null,error:null});try{const a=await Vq(r,n,s,i);let l=!1;try{await navigator.clipboard.writeText(a.url),l=!0}catch{}e({result:{url:a.url,copied:l}})}catch(a){if(a instanceof De&&a.message==="Public snapshot publishing is not configured"){e({error:"当前 Backend 尚未配置公网分享服务,请配置后重试。"});return}e({error:a instanceof De?`创建终端快照失败(HTTP ${a.status})`:"创建终端快照失败,请检查 HTTP(S) 连接后重试。"})}finally{e({pending:!1})}}}})),Gq=new Set(["bash","fish","sh","zsh"]),Yq=new Set(["claude","codex","trae","traecli","traex","pi"]);function z1(e){const t=e==null?void 0:e.trim().replace(/[\\/]+$/,"");return t?t.split(/[\\/]/).filter(Boolean).at(-1)??t:null}function Ol(e){var n;const t=((n=e.alias)==null?void 0:n.trim())||z1(e.cwd)||"Terminal",r=z1(e.activeCommand??void 0);return!r||Gq.has(r)||!Yq.has(r)?t:`${t}(${r})`}function Xq(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return p.useMemo(()=>n=>{t.forEach(s=>s(n))},t)}const Zf=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Bl(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Qx(e){return"nodeType"in e}function fn(e){var t,r;return e?Bl(e)?e:Qx(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function Zx(e){const{Document:t}=fn(e);return e instanceof t}function Wu(e){return Bl(e)?!1:e instanceof fn(e).HTMLElement}function dR(e){return e instanceof fn(e).SVGElement}function Fl(e){return e?Bl(e)?e.document:Qx(e)?Zx(e)?e:Wu(e)||dR(e)?e.ownerDocument:document:document:document}const fs=Zf?p.useLayoutEffect:p.useEffect;function ep(e){const t=p.useRef(e);return fs(()=>{t.current=e}),p.useCallback(function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return t.current==null?void 0:t.current(...n)},[])}function Jq(){const e=p.useRef(null),t=p.useCallback((n,s)=>{e.current=setInterval(n,s)},[]),r=p.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,r]}function Yc(e,t){t===void 0&&(t=[e]);const r=p.useRef(e);return fs(()=>{r.current!==e&&(r.current=e)},t),r}function qu(e,t){const r=p.useRef();return p.useMemo(()=>{const n=e(r.current);return r.current=n,n},[...t])}function qh(e){const t=ep(e),r=p.useRef(null),n=p.useCallback(s=>{s!==r.current&&(t==null||t(s,r.current)),r.current=s},[]);return[r,n]}function Kh(e){const t=p.useRef();return p.useEffect(()=>{t.current=e},[e]),t.current}let dm={};function Ku(e,t){return p.useMemo(()=>{if(t)return t;const r=dm[e]==null?0:dm[e]+1;return dm[e]=r,e+"-"+r},[e,t])}function hR(e){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return n.reduce((i,a)=>{const l=Object.entries(a);for(const[c,u]of l){const d=i[c];d!=null&&(i[c]=d+e*u)}return i},{...t})}}const Xa=hR(1),Vh=hR(-1);function Qq(e){return"clientX"in e&&"clientY"in e}function tp(e){if(!e)return!1;const{KeyboardEvent:t}=fn(e.target);return t&&e instanceof t}function Zq(e){if(!e)return!1;const{TouchEvent:t}=fn(e.target);return t&&e instanceof t}function Gh(e){if(Zq(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:r}=e.touches[0];return{x:t,y:r}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:r}=e.changedTouches[0];return{x:t,y:r}}}return Qq(e)?{x:e.clientX,y:e.clientY}:null}const uo=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:r}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:r}=e;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(e){if(e)return[uo.Translate.toString(e),uo.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:n}=e;return t+" "+r+"ms "+n}}}),U1="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function eK(e){return e.matches(U1)?e:e.querySelector(U1)}const tK={display:"none"};function rK(e){let{id:t,value:r}=e;return _t.createElement("div",{id:t,style:tK},r)}function nK(e){let{id:t,announcement:r,ariaLiveType:n="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return _t.createElement("div",{id:t,style:s,role:"status","aria-live":n,"aria-atomic":!0},r)}function sK(){const[e,t]=p.useState("");return{announce:p.useCallback(n=>{n!=null&&t(n)},[]),announcement:e}}const fR=p.createContext(null);function iK(e){const t=p.useContext(fR);p.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function oK(){const[e]=p.useState(()=>new Set),t=p.useCallback(n=>(e.add(n),()=>e.delete(n)),[e]);return[p.useCallback(n=>{let{type:s,event:i}=n;e.forEach(a=>{var l;return(l=a[s])==null?void 0:l.call(a,i)})},[e]),t]}const aK={draggable:`
|
|
498
498
|
To pick up a draggable item, press the space bar.
|
|
499
499
|
While dragging, use the arrow keys to move the item.
|
|
500
500
|
Press space again to drop the item in its new position, or press escape to cancel.
|
|
@@ -701,6 +701,6 @@ WARNING: This link could potentially be dangerous`)){let r=window.open();if(r){t
|
|
|
701
701
|
|
|
702
702
|
`}),a.addRule("clipboardImage",{filter:"img",replacement:(c,u)=>{const d=Number(u.getAttribute("data-rich-image")),h=n[d];return i?"":h!=null&&h.path?` ${fN(h.path)} `:`[图片 ${d+1} 未准备好]`}}),e.html?a.turndown(r):[e.plainText,...Array.from(r.querySelectorAll("img")).map(c=>a.turndown(c.outerHTML))].filter(Boolean).join(`
|
|
703
703
|
|
|
704
|
-
`)}}}async function bse(e,t,r,n){let s=0,i=[...t.values()].reduce((u,d)=>u+d.bytes,0);const a=new Map,l=new Map,c=async u=>{var v;if(u.path)return;if(!n())throw new Error("粘贴已取消");let d;if(u.source instanceof File)d=u.source;else if(/^data:image\/(png|jpeg|gif|webp);base64,/i.test(u.source)){if(u.source.length>28*1024*1024)throw new Error("图片超过 20 MiB");d=await(await fetch(u.source)).blob()}else if(/^https?:\/\//i.test(u.source)){if(!((v=window.electronAPI)!=null&&v.downloadClipboardImage))throw new Error("当前客户端不支持网络图片,请更新桌面端");const x=await window.electronAPI.downloadClipboardImage(u.source);d=await(await fetch(`data:${x.mimeType};base64,${x.dataBase64}`)).blob()}else throw new Error("无法取得图片内容,请复制图片本身后重试");if(d.size>20*1024*1024)throw new Error("图片超过 20 MiB");if(!["image/png","image/jpeg","image/gif","image/webp"].includes(d.type))throw new Error("不支持的图片格式");const h=await d.arrayBuffer(),f=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",h))).map(x=>x.toString(16).padStart(2,"0")).join(""),m=t.get(f);if(m){u.path=m.path;return}let g=l.get(f);if(!g){if(i+=d.size,i>100*1024*1024)throw new Error("图文图片总计超过 100 MiB");g=(async()=>{if(!n())throw new Error("粘贴已取消");const x=await r(d.type,await lH(new File([d],"clipboard",{type:d.type})));return t.set(f,{path:x,bytes:d.size}),x})(),l.set(f,g)}u.path=await g};if(await Promise.all(Array.from({length:Math.min(3,e.images.length)},async()=>{var u;for(;s<e.images.length;){const d=e.images[s++];d.error=void 0;try{const h=a.get(d.source);if(h)await h,d.path=(u=e.images.find(f=>f.source===d.source&&f.path))==null?void 0:u.path;else{const f=c(d);a.set(d.source,f),await f}}catch(h){d.error=h instanceof Error?h.message:"图片准备失败"}}})),e.images.some(u=>!u.path))throw new Error("部分图片未准备好,内容已保留")}const Ao=new Map,_se=[];function yse(e){const t=JSON.stringify([e.apiBase,e.sessionId,e.panelId]),r=p.useRef(e);r.current=e;const n=p.useRef(0),s=JSON.stringify([t,e.token,e.threadId,e.active]),i=p.useRef(s);i.current!==s&&(i.current=s,n.current++);const[,a]=p.useState(0),l=W(()=>a(m=>m+1)),c=W(()=>{n.current++});p.useEffect(()=>()=>{n.current++},[]),p.useEffect(()=>{const m=g=>{[...Ao.values()].flat().some(v=>v.status!=="inserted")&&(g.preventDefault(),g.returnValue="")};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[]);const u=W(async(m,g,v=!1)=>{var k,D;if(r.current.sending||!r.current.active)return;const x={...r.current},b=i.current,_=++n.current,C=++m.attempt,S=g?{value:g.value,start:g.selectionStart,end:g.selectionEnd}:null,w=()=>(Ao.get(t)??[]).includes(m)&&m.attempt===C,y=()=>w()&&i.current===b&&n.current===_&&r.current.active,N=()=>y()&&(!S||!!(g!=null&&g.isConnected&&g.value===S.value&&g.selectionStart===S.start&&g.selectionEnd===S.end));m.status="pending",m.message="正在准备图文…",m.autoCloseAt=void 0,l();const E=j=>{var I;if(!w())return;const R=j&&!((I=m.document)!=null&&I.images.some(T=>T.error));m.autoCloseAt=R?Date.now()+3e3:m.purpose==="tui"?Date.now()+6e4:void 0,R&&(m.message=m.purpose==="tui"?"图文已插入":"图文已添加"),l()};try{if(m.purpose==="composer"&&!g)throw new Error("请打开 Input 后重新插入");if(!x.panelId)throw new Error("终端目标尚未就绪,内容已保留");const j=m.purpose==="tui"?await Mi(x.apiBase,x.token,x.sessionId,"/prepare","POST",{panelId:x.panelId}):void 0;if(!m.document&&!v&&(m.document=xse(m.snapshot)),!v&&m.document&&await bse(m.document,m.cache,async(I,T)=>(await eL(x.apiBase,x.token,x.sessionId,{mimeType:I,dataBase64:T},AbortSignal.timeout(2e4))).filePath,w),!w())return;const R=v?m.snapshot.plainText||((k=m.document)==null?void 0:k.markdown(!0))||"":m.document.markdown();if(!R)throw new Error("剪贴板没有可插入的文字或图片");if(!N()){m.status="ready",m.message="目标或输入已变化,内容已保留;可重新插入",E(!1),l();return}if(m.purpose==="tui"){if(!r.current.captureText(R,"tui",j.preparationId,E))throw new Error("终端目标不可用,内容已保留");m.message="图文已准备,投递结果见终端附件提示"}else if(r.current.captureText(R,"composer",void 0,E))m.message="已添加为长文本附件";else if(g&&S){const I=S.value.slice(0,S.start)+R+S.value.slice(S.end);r.current.onDraftChange(I);const T=S.start+R.length;requestAnimationFrame(()=>{g.isConnected&&g.value===I&&(g.focus(),g.setSelectionRange(T,T))}),m.message=`已插入图文${(D=m.document)!=null&&D.images.length?`(${m.document.images.length} 张图片)`:""}`,E(!0)}m.status="inserted",l()}catch(j){if(!w())return;m.status="error",m.message=j instanceof Error?j.message:"图文准备失败,内容已保留",E(!1),l()}}),d=W((m,g)=>{if(!m.clipboardData)return!1;const v=vse(m.clipboardData);if(!v)return!1;m.preventDefault(),m.stopPropagation(),"nativeEvent"in m?m.nativeEvent.stopImmediatePropagation():m.stopImmediatePropagation();const x={id:crypto.randomUUID(),purpose:g,snapshot:v,status:"ready",message:"",cache:new Map,attempt:0},b=Ao.get(t)??[];if(Ao.set(t,[...b.filter(C=>C.status!=="inserted"),x]),r.current.sending)return x.status="error",x.message="正在发送,图文已保留",x.autoCloseAt=g==="tui"?Date.now()+6e4:void 0,l(),!0;const _=g==="composer"?m.currentTarget:null;return u(x,_),!0}),h=W(m=>{m.attempt++,Ao.set(t,(Ao.get(t)??[]).filter(g=>g!==m)),l()}),f=Ao.get(t)??_se;return p.useEffect(()=>{const m=f.flatMap(g=>g.autoCloseAt===void 0?[]:[window.setTimeout(()=>h(g),Math.max(0,g.autoCloseAt-Date.now()))]);return()=>m.forEach(g=>window.clearTimeout(g))}),{items:f,capture:d,run:u,remove:h,markInput:c,blocked:f.some(m=>m.purpose==="composer"&&m.status!=="inserted")}}const $d={threshold:5e3,maxBytes:1024*1024,sessionMaxBytes:100*1024*1024,maxDraftAttachments:20},ks=e=>JSON.stringify([e.apiBase,e.sessionId,e.panelId,e.inputContextKey??"legacy"]),wse=new Map,i0=new Set;function Sse(e,t){const r=p.useRef(e),n=p.useRef(0),s=p.useRef(""),i=ks(e),a=JSON.stringify([i,e.token,e.active]);s.current!==a&&(s.current=a,n.current++),p.useEffect(()=>()=>{n.current++},[]);const l=p.useRef(wse),[,c]=p.useState(0),[u,d]=p.useState(null),h=W(()=>c(N=>N+1)),f=l.current.get(ks(e))??[],m=e.threadId;r.current={...e,threadId:m};const g=e.active&&!!e.panelId,v=g&&(u==null?void 0:u.context)===a&&u.value.enabled;p.useEffect(()=>{let N=!1;if(!e.panelId||!e.active)return;const E=()=>{Mi(e.apiBase,e.token,e.sessionId,`/capability?panelId=${encodeURIComponent(e.panelId)}`).then(D=>{N||d({context:a,scopeId:i,value:D})}).catch(()=>{N||d({context:a,scopeId:i,value:{enabled:!1,provider:null,threadId:null,executionHost:null,reason:"附件能力未确认",limits:$d}})})};E();const k=window.setInterval(E,5e3);return()=>{N=!0,window.clearInterval(k)}},[e.apiBase,e.token,e.sessionId,e.panelId,e.active,a,i]);const x=W((N=!1)=>{n.current++,N&&(i0.delete(ks(r.current)),h())}),b=W(N=>{const E=ks(r.current);l.current.set(E,(l.current.get(E)??[]).filter(k=>k!==N)),h(),N.purpose==="composer"&&N.attachment&&N.attachment.state==="draft"&&Wp(r.current.apiBase,r.current.token,r.current.sessionId,N.attachment.id,"release").catch(()=>{})}),_=W(async N=>N.attachment?tL(r.current.apiBase,r.current.token,r.current.sessionId,N.attachment):N.text),C=W((N,E,k,D)=>{if(!g||!k&&N.length<$d.threshold)return!1;const j={...r.current},R=ks(j),I=n.current,T=l.current.get(R)??[],A={key:crypto.randomUUID(),operationId:crypto.randomUUID(),richPaste:!!k,text:N,purpose:E,status:"pending"};if(l.current.set(R,[...T,A]),h(),T.filter(B=>B.status==="pending"||B.status==="saved").length>=$d.maxDraftAttachments)return A.status="error",A.reason="草稿最多保存 20 份附件,原文已保留",h(),D==null||D(!1),!0;const P=()=>(l.current.get(R)??[]).includes(A),O=()=>ks(r.current)===R&&r.current.active&&n.current===I,L=async B=>Mi(j.apiBase,j.token,j.sessionId,`/operations/${encodeURIComponent(B)}`);return(async()=>{try{if(!v){const $=await Mi(j.apiBase,j.token,j.sessionId,`/capability?panelId=${encodeURIComponent(j.panelId)}`);if(!$.enabled)throw new Error($.reason??"附件能力未确认,原文已保留");if(!P()||!O()){A.status="not-inserted",A.reason="目标或输入已变化,原文已保留",h();return}}let B;try{B=await Mi(j.apiBase,j.token,j.sessionId,"","POST",{operationId:A.operationId,panelId:j.panelId,expectedThreadId:j.threadId,purpose:E,text:N,...k?{preparationId:k}:{}})}catch($){const U=await L(A.operationId).catch(()=>null);if((U==null?void 0:U.status)!=="saved")throw $;B=await Mi(j.apiBase,j.token,j.sessionId,`/${U.attachmentIds[0]}`)}if(!P()&&E==="composer"){await Wp(j.apiBase,j.token,j.sessionId,B.id,"release").catch(()=>{});return}if(A.attachment=B,A.status="saved",h(),E==="composer")return;if(!O()){A.status="not-inserted",A.reason="目标或输入已变化,未插入路径",h();return}i0.add(R),t(),h();let M;try{M=await Mi(j.apiBase,j.token,j.sessionId,`/${B.id}/insert`,"POST",{operationId:B.insertOperationId,...k&&N.length<$d.threshold?{inline:!0}:{},panelId:j.panelId,expectedThreadId:j.threadId})}catch($){if($ instanceof De&&[400,409,410,413,507].includes($.status)){A.status="not-inserted",A.reason=$.message,h();return}const U=await L(B.insertOperationId).catch(()=>null);if(!U){A.status="unknown",A.reason="路径交付未确认,请核对终端",h();return}M=U}A.status=M.status==="accepted"?"inserted":M.status==="rejected"?"not-inserted":"unknown",A.reason=M.reason,A.richPaste&&A.status==="inserted"&&!A.reason&&(A.autoCloseAt=Date.now()+3e3),M.status!=="rejected"&&(B.state="referenced"),M.status==="accepted"&&ks(r.current)===R&&n.current++,h()}catch(B){P()&&(A.status="error",A.reason=B instanceof Error?B.message:"保存失败,原文已保留",h())}finally{D==null||D(P()&&(A.status==="inserted"||E==="composer"&&A.status==="saved")&&!A.reason)}})(),!0});p.useEffect(()=>{const N=f.flatMap(E=>E.autoCloseAt===void 0?[]:[window.setTimeout(()=>b(E),Math.max(0,E.autoCloseAt-Date.now()))]);return()=>N.forEach(E=>window.clearTimeout(E))});const S=W((N,E)=>{const k=N.clipboardData;return!k||Array.from(k.items).some(D=>D.kind==="file")||!C(k.getData("text/plain"),E)?!1:(N.preventDefault(),"nativeEvent"in N?N.nativeEvent.stopImmediatePropagation():N.stopImmediatePropagation(),N.stopPropagation(),!0)});p.useEffect(()=>{const N=()=>{var k;for(const D of l.current.get(ks(r.current))??[])((k=D.attachment)==null?void 0:k.state)==="draft"&&Wp(r.current.apiBase,r.current.token,r.current.sessionId,D.attachment.id,"retain").catch(j=>{D.status="error",D.reason=j instanceof Error?j.message:"附件续期失败",h()})};N();const E=window.setInterval(N,1440*60*1e3);return()=>window.clearInterval(E)},[a,h]),p.useEffect(()=>{const N=E=>{[...l.current.values()].flat().some(k=>!k.attachment)&&(E.preventDefault(),E.returnValue="")};return window.addEventListener("beforeunload",N),()=>window.removeEventListener("beforeunload",N)},[]);const w=f.filter(N=>N.purpose==="composer"),y=W(N=>{for(const E of l.current.values())for(const k of N){const D=E.indexOf(k);D!==-1&&E.splice(D,1)}h()});return{items:f,enabled:v,capabilityReason:(u==null?void 0:u.value.reason)??null,mirrorUnreliable:i0.has(ks(e)),composerItems:w,capture:S,captureText:C,markInput:x,remove:b,read:_,consume:y,blocked:w.some(N=>N.status!=="saved"),ids:w.flatMap(N=>N.attachment?[N.attachment.id]:[]),threadId:m,panelId:e.panelId,scopeId:ks(e)}}function Cse(e){const[t,r]=p.useState(null),n=JSON.stringify([e.apiBase,e.sessionId]);return p.useEffect(()=>{if(e.workspace||!e.active)return;let s=!1;const i=async()=>{const{listTerminalPanels:l}=await Vr(async()=>{const{listTerminalPanels:c}=await Promise.resolve().then(()=>L6);return{listTerminalPanels:c}},void 0);try{const c=await l(e.apiBase,e.token,e.sessionId);s||r({key:n,workspace:c})}catch{s||r(null)}};i();const a=window.setInterval(()=>{i()},5e3);return()=>{s=!0,window.clearInterval(a)}},[n,e.apiBase,e.sessionId,e.token,e.active,e.workspace]),e.workspace??((t==null?void 0:t.key)===n?t.workspace:null)}const mv="runweave:handoff-input";function Qce(e){const t={...e};if(window.dispatchEvent(new CustomEvent(mv,{detail:t})),!t.release)throw new Error(t.message??"终端输入尚未就绪,请在终端中继续。");return t.release}function Ese({apiBase:e,available:t,error:r,onSent:n,panelId:s,codexInputContext:i,requestScopeRef:a,sendPendingRef:l,setSending:c,terminalSessionId:u,token:d}){const[h,f]=p.useState(!1),[m,g]=p.useState(null);p.useEffect(()=>{f(!1),g(null)},[e,s,u]),p.useEffect(()=>{t||(f(!1),g(null))},[t]);const v=W(()=>{f(!1),g(null)}),x=W(()=>{f(!0)}),b=W(async _=>{if(l.current||!t)return;if(r){g({message:"终端连接不可用,请重连后再发送。",tone:"error"}),f(!0);return}const C=a.current;l.current=!0,c(!0),g(null);try{if(!C||a.current!==C||(await yf(e,d,u,{data:_,mode:"prompt_replace",submit:!0,recordQuickInput:!1,codexInputContext:i,...s?{panelId:s}:{}},AbortSignal.timeout(2e4)),a.current!==C))return;n(),g({message:`已发送「${_}」`,tone:"success"})}catch(S){if(a.current!==C)return;$t("terminal.instant_reply.send.failed",{terminalSessionId:u,error:String(S)}),g({message:"发送结果未确认,请先核对终端结果;不会自动重发。",tone:"error"}),f(!0)}finally{a.current===C&&(l.current=!1,c(!1))}});return{available:t,feedback:m,onClose:v,onOpen:x,onSend:b,open:h}}const kse=150;function Ise({active:e,activeCommand:t,apiBase:r,bufferType:n,clientMode:s,error:i,paneWorkspace:a,searchOpen:l,scrollToBottom:c,sessionStatus:u,showScrollToBottomControl:d,terminalAtBottom:h,terminalSessionId:f,terminalState:m,token:g}){const v=p.useRef(""),x=p.useRef(""),b=p.useRef(!1),_=p.useRef(!1),C=p.useRef(!1),S=p.useRef(null),[w,y]=p.useState(!1),[N,E]=p.useState(""),[k,D]=p.useState(!0),j=p.useRef(!1),[R,I]=p.useState(!1),[T,A]=p.useState(!1),[P,O]=p.useState(null),L=p.useRef(null),B=Hne(N,T,L),M=p.useRef(P);M.current=P;const $=p.useRef(new Map),U=a==null?void 0:a.panels.find(ye=>ye.panelId===a.activePanelId),F=U==null?void 0:U.codexContext,K=F===void 0?"legacy":`${(F==null?void 0:F.generation)??"unknown"}:${(F==null?void 0:F.displayedThreadId)??"unknown"}`;p.useEffect(()=>{VS(S);const ye=JSON.stringify([r,f,a==null?void 0:a.activePanelId,K]),ae=$.current,le=ae.get(ye);return L.current={},x.current=(le==null?void 0:le.draft)??"",v.current=(le==null?void 0:le.synced)??"",b.current=(le==null?void 0:le.dirty)??!1,_.current=!1,j.current=(le==null?void 0:le.mirrorUnreliable)??!1,D(!j.current),C.current=!1,E(x.current),O((le==null?void 0:le.error)??null),y(!!(le!=null&&le.dirty||le!=null&&le.error)),A(!1),I(!1),()=>{ae.set(ye,{draft:x.current,synced:v.current,dirty:b.current,mirrorUnreliable:j.current,error:_.current?"发送结果未确认,草稿已保留。请先检查终端,再决定是否重新发送。":M.current}),L.current=null}},[r,f,a==null?void 0:a.activePanelId,K]);const Y=a?(U==null?void 0:U.activeCommand)??null:t,te=a?U==null?void 0:U.terminalState:m,H=F&&te?{...te,state:F.displayedRunning?"agent_running":"agent_idle"}:te,G=a?(U==null?void 0:U.status)==="running":u==="running",z=(F===void 0||!!(F!=null&&F.inputReady&&F.displayedThreadId))&&BQ({activeCommand:Y,bufferType:n,clientMode:s,searchOpen:l,sessionRunning:G,terminalState:H}),ee=Cse({apiBase:r,token:g,sessionId:f,active:e,workspace:a}),V=ee==null?void 0:ee.panels.find(ye=>ye.panelId===ee.activePanelId),re=Sse({apiBase:r,token:g,sessionId:f,panelId:(ee==null?void 0:ee.activePanelId)??"",inputContextKey:K,threadId:F!==void 0?(F==null?void 0:F.displayedThreadId)??null:(V==null?void 0:V.threadId)??((V==null?void 0:V.lastThreadStatus)==="idle"?V.lastThreadId:null)??null,active:e},()=>{j.current=!0,ne(),I(!1),D(!1),O("TUI 路径投递后,光标草稿无法可靠镜像;请核对终端并在那里继续编辑、提交。")}),oe=yse({apiBase:r,token:g,sessionId:f,panelId:re.panelId,threadId:re.threadId,active:e,sending:T,captureText:re.captureText,onDraftChange:ye=>Ge(ye)}),ce=k&&!re.mirrorUnreliable,be=PQ({activeCommand:Y,terminalState:H}),ne=W(()=>{VS(S)}),Te=W(()=>{ne()}),Ve=W(ye=>{if(F!==void 0&&ye==="")return;if(oe.markInput(),re.markInput(ye==="\r"||ye===""),j.current||re.mirrorUnreliable)if(ye==="\r"||ye==="")j.current=!1,v.current="",b.current||(x.current="",E("")),D(!0),O(null);else return;if(!z||!ce)return;const ae=v.current,le=FQ(ae,ye);if(!le.supported){ne(),v.current&&D(!1);return}if(v.current=le.draft,!(b.current||_.current)&&(x.current=le.draft,E(le.draft),F===void 0)){if(!le.draft){ne(),I(!1);return}le.draft===ae||C.current||S.current!==null||(S.current=window.setTimeout(()=>{S.current=null,!(!x.current||!z||!ce)&&(I(!0),y(!0))},kse))}}),Ge=W(ye=>{oe.markInput(),re.markInput(),x.current=ye,E(ye),b.current=ye!==v.current}),we=Une({eligible:z,draftMirrorSupported:ce,floatingDraftSyncPendingRef:_,floatingDraftRef:x,setSendError:O,setFloatingComposerOpen:y,handleDraftChange:Ge}),de=W(async(ye={})=>{const ae=B();if(_.current||re.blocked||oe.blocked||j.current||re.mirrorUnreliable)return ae.reject();const le=[...re.composerItems],je=[...re.ids],Me=b.current||je.length>0;if(je.length&&ye.submit!==!0)return ae.reject();const ot=ye.submit===!0;if(!Me&&!ot)return ae.noop();if(i)return O("终端连接不可用,草稿已保留;重连后再发送。"),y(!0),ae.reject();if(F!==void 0&&(!(F!=null&&F.inputReady)||!F.displayedThreadId))return O("Codex 会话身份尚未就绪,草稿已保留,请在原终端继续。"),ae.reject();const ct=x.current,yt=L.current,Dt=je.length?re.panelId:a==null?void 0:a.activePanelId,Ft=ae.id;re.markInput(),_.current=!0,A(!0),O(null);try{return!yt||L.current!==yt||(await yf(r,g,f,{data:ct,mode:"prompt_replace",...F!=null&&F.displayedThreadId?{codexInputContext:{generation:F.generation,revision:F.revision,threadId:F.displayedThreadId}}:{},...je.length?{operationId:Ft,textAttachmentIds:je,expectedThreadId:re.threadId??void 0,recordQuickInput:!1}:{},submit:ot,...ye.submitKey?{submitKey:ye.submitKey}:{},...Dt?{panelId:Dt}:{}},AbortSignal.timeout(2e4),ae),je.length&&re.consume(le),L.current!==yt)||(v.current=ot?"":ct,x.current!==ct)?!1:(b.current=!1,ot&&(x.current="",E("")),ae.stateUpdated(ot),!0)}catch(Mt){if(je.length){const Ze=await Mi(r,g,f,`/operations/${Ft}`).catch(()=>null);if((Ze==null?void 0:Ze.status)==="accepted")return ae.stage("confirmed"),re.consume(le),L.current===yt&&x.current===ct&&(x.current="",v.current="",b.current=!1,E(""),ae.stateUpdated(!0)),!0;if((Ze==null?void 0:Ze.status)==="unknown"||(Ze==null?void 0:Ze.status)==="dispatching"||!Ze)for(const xt of le)xt.status="unknown",xt.reason="提交结果未确认,请核对终端;不会自动重发"}return L.current!==yt||($t("terminal.floating_composer.sync.failed",{terminalSessionId:f,error:String(Mt)}),b.current=!0,O("发送结果未确认,草稿已保留。请先检查终端,再决定是否重新发送。"),y(!0)),!1}finally{L.current===yt&&(_.current=!1,A(!1))}}),he=z&&(ce||!!P||re.composerItems.length>0)&&(d||R||w||T||!!P),ge=he&&w,Pe=he&&!w,Le=W(()=>{v.current="",b.current=x.current.length>0,b.current&&y(!0)}),_e=Ese({codexInputContext:F!=null&&F.displayedThreadId?{generation:F.generation,revision:F.revision,threadId:F.displayedThreadId}:void 0,apiBase:r,available:z&&ce&&!oe.blocked,error:i,onSent:Le,panelId:a==null?void 0:a.activePanelId,requestScopeRef:L,sendPendingRef:_,setSending:A,terminalSessionId:f,token:g}),et=W(async()=>{!N&&!re.ids.length||await de({submit:!0})&&(ne(),I(!1),y(!1),c())}),it=W(async()=>{!x.current&&!re.ids.length||!be||await de({submit:!0,submitKey:be})&&(ne(),I(!1),y(!0))});p.useEffect(()=>{const ye=C.current;if(C.current=ge,!ye&&ge&&!b.current&&!_.current){const ae=v.current;x.current=ae,b.current=!1,E(ae);return}ye&&!ge&&F===void 0&&b.current&&!_.current&&!P&&de()},[de,P,ge,F]),p.useEffect(()=>{h&&!j.current&&D(!0)},[h]),p.useEffect(()=>{j.current||D(!0),ne(),I(!1)},[Y,ne,f,H==null?void 0:H.agent,H==null?void 0:H.state]),p.useEffect(()=>{z||(ne(),I(!1),y(!1))},[ne,z]),p.useEffect(()=>()=>{ne()},[ne]);const ue=W(ye=>{const ae=ye.detail;if(!(ae.apiBase!==r||ae.terminalSessionId!==f||ae.panelId!==((a==null?void 0:a.activePanelId)??null))){if(oe.blocked||!z||!ce||i||_.current){ae.message="终端输入未就绪或正在发送,请稍后再试。";return}if(x.current.trim()||v.current.trim()){ae.message="终端中有未发送的草稿,请先处理草稿,再继续验收。";return}_.current=!0,A(!0),ae.release=()=>{_.current=!1,A(!1)}}});p.useEffect(()=>(window.addEventListener(mv,ue),()=>window.removeEventListener(mv,ue)),[ue]);const Ie=W(()=>{oe.markInput(),ne(),I(!1),y(!1)});return{richPaste:oe,textAttachments:re,draft:N,sending:T,sendError:P,draftMirrorSupported:ce,eligible:z,handleOutputReceived:Te,handleDraftChange:Ge,insertDraft:we,handleSend:et,handleQueue:it,queueKey:be,handleUserInputData:Ve,inputLagFallbackActive:R,instantReplyAvailable:_e.available,instantReplyFeedback:_e.feedback,instantReplyOpen:_e.open,onClose:Ie,onInstantReplyClose:_e.onClose,onInstantReplyOpen:_e.onOpen,onInstantReplySend:_e.onSend,onOpen:()=>y(!0),showTrigger:Pe,visible:ge}}function Nse({active:e,activeCommand:t,apiBase:r,clientMode:n,error:s,paneWorkspace:i,searchOpen:a,sessionStatus:l,scroll:c,terminalRef:u,terminalSessionId:d,terminalState:h,token:f}){const[m,g]=p.useState(void 0),v=Ise({active:e,activeCommand:t,apiBase:r,bufferType:m,clientMode:n,error:s,paneWorkspace:i,searchOpen:a,scrollToBottom:c.scrollToBottom,sessionStatus:l,showScrollToBottomControl:c.showScrollToBottomControl,terminalAtBottom:c.terminalAtBottom,terminalSessionId:d,terminalState:h,token:f}),x=v.eligible,b=v.visible,_=v.showTrigger,S=b&&(!c.terminalAtBottom||c.tmuxScrollbackActive)?"floating":c.showScrollToBottomControl&&!b?"legacy":"none",w={activeCommand:t,bottomOffsetRows:c.bottomOffsetRows,bufferType:m,draftMirrorSupported:v.draftMirrorSupported,eligible:x,inputLagFallbackActive:v.inputLagFallbackActive,sessionStatus:l,terminalAgent:(h==null?void 0:h.agent)??null,terminalAtBottom:c.terminalAtBottom,terminalState:(h==null?void 0:h.state)??null,tmuxScrollbackActive:c.tmuxScrollbackActive},y=W(()=>{v.onClose(),requestAnimationFrame(()=>{var E;return(E=u.current)==null?void 0:E.focus()})}),N=W(()=>{v.onInstantReplyClose(),requestAnimationFrame(()=>{var E;return(E=u.current)==null?void 0:E.focus()})});return{diagnostics:w,textAttachments:v.textAttachments,richPaste:v.richPaste,draft:v.draft,sending:v.sending,sendError:v.sendError,handleBottomStateChange:c.handleBottomStateChange,handleOutputReceived:v.handleOutputReceived,handleUserInputData:v.handleUserInputData,hasNewOutputBelow:c.hasNewOutputBelow,instantReplyAvailable:v.instantReplyAvailable,instantReplyFeedback:v.instantReplyFeedback,instantReplyOpen:v.instantReplyOpen,onClose:y,onDraftChange:v.handleDraftChange,insertDraft:v.insertDraft,onInstantReplyClose:N,onInstantReplyOpen:v.onInstantReplyOpen,onInstantReplySend:v.onInstantReplySend,onOpen:v.onOpen,onScrollToBottom:c.scrollToBottom,onSend:v.handleSend,onQueue:v.handleQueue,queueKey:v.queueKey,onTmuxExitCopyModeRequest:c.requestTmuxExitCopyMode,scrollButtonMode:S,setBufferType:g,setHasNewOutputBelow:c.setHasNewOutputBelow,setTerminalAtBottom:c.setTerminalAtBottom,setTmuxScrollbackActive:c.setTmuxScrollbackActive,showTrigger:_,visible:b}}const Rse=1e3;function jse({active:e,apiBase:t,runtimeKindRef:r,terminalRef:n,terminalSessionId:s,token:i,resetScrollInput:a}){const l=p.useRef(0),[c,u]=p.useState(0),[d,h]=p.useState(!0),[f,m]=p.useState(!1),[g,v]=p.useState(!1),x=W(()=>{a==null||a();const S=Date.now();if(S-l.current<Rse)return;l.current=S;const w=()=>{yf(t,i,s,{data:"",mode:"tmux_exit_copy_mode"})};w(),window.setTimeout(w,250),window.setTimeout(w,800)}),b=W(()=>{const S=n.current;S&&(r.current==="tmux"&&x(),CH(S),h(!0),u(0),m(!1),v(!1),S.focus())}),_=W(S=>{h(S.isAtBottom),u(S.bottomOffsetRows),S.isAtBottom&&m(!1)});return{bottomOffsetRows:c,handleBottomStateChange:_,hasNewOutputBelow:f,requestTmuxExitCopyMode:x,scrollToBottom:b,setHasNewOutputBelow:m,setTerminalAtBottom:h,setTmuxScrollbackActive:v,showScrollToBottomControl:e&&(!d||f||g),terminalAtBottom:d,tmuxScrollbackActive:g}}const mT="\x1B",Ase=new RegExp(`${mT}\\[\\?[\\d;]+\\$p`,"g"),Tse=new Set(["1000","1002","1003","1005","1006","1015"]),Dse=new RegExp(`${mT}\\[\\?([\\d;]+)([hl])`,"g");function XS(e){return e.replace(Ase,"").replace(Dse,(t,r)=>r.split(";").every(s=>Tse.has(s))?"":t)}const Pse="\x1B[?2026h",Lse="\x1B[?2026l",Mse="\x1B[?2004h",Ose="\x1B[?2004l";function o0(e){return`${Pse}${e}${Lse}`}function JS(e,t,r){var l,c,u;const n=(l=e.element)==null?void 0:l.querySelector(".xterm-screen"),s=n==null?void 0:n.querySelector(".xterm-rows:not([data-terminal-frame-overlay])");s!=null&&s.textContent&&(r.current=s.cloneNode(!0));const i=s!=null&&s.textContent?s:r.current;if(!n||!(i!=null&&i.textContent))return $t("terminal.frame.preserve.skipped",{terminalSessionId:t,hasScreen:!!n,rowTextLength:((c=s==null?void 0:s.textContent)==null?void 0:c.length)??0}),()=>{};const a=i.cloneNode(!0);return a.dataset.terminalFrameOverlay="true",a.setAttribute("aria-hidden","true"),Object.assign(a.style,{position:"absolute",inset:"0",zIndex:"4",width:"100%",height:"100%",overflow:"hidden",pointerEvents:"none",backgroundColor:((u=e.options.theme)==null?void 0:u.background)??"#0b1220"}),n.appendChild(a),$t("terminal.frame.preserved",{terminalSessionId:t,rowTextLength:i.textContent.length}),()=>{a.remove()}}function QS(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}function Bse({onLocalReset:e,activeRef:t,deferredOutputRef:r,deferredSnapshotRef:n,hasDeferredOutputRef:s,hasRenderedSnapshotRef:i,lastInputSentAtRef:a,outputSequenceRef:l,onOutputReceived:c,refreshTerminalViewportRef:u,requiresSnapshotRestoreRef:d,setHasNewOutputBelow:h,setTerminalAtBottom:f,setTmuxScrollbackActive:m,terminalRef:g,terminalFrameRef:v,terminalSessionId:x,websocketContentVersionRef:b}){const _=p.useRef(Promise.resolve()),C=W(j=>{_.current=_.current.then(j,j)}),S=W(j=>{C(()=>new Promise(R=>{const I=g.current;if(!I){R();return}I.write("",()=>{try{j()}finally{R()}})}))}),w=W((j,R,I)=>{I||e();const T=XS(j),A=g.current;if(!A){I==null||I.commit(!1);return}f(!0),h(!1),m(!1),$t("terminal.snapshot.received",{terminalSessionId:x,...bn(T)}),i.current=!0,s.current=!1,r.current="",n.current=null,d.current=!1;const P=JS(A,x,v),O=(R==null?void 0:R.bracketedPasteMode)??A.modes.bracketedPasteMode;A.reset();const L={cols:A.cols,rows:A.rows};I!=null&&I.cols&&I.rows&&A.resize(I.cols,I.rows);const B=performance.now();A.write(`${o0(T)}${O?Mse:Ose}`,()=>{var M;I!=null&&I.cols&&I.rows&&I.resizeMode!=="ordered"&&A.resize(L.cols,L.rows),I==null||I.commit(),$t("terminal.snapshot.rendered",{terminalSessionId:x,renderDurationMs:Number((performance.now()-B).toFixed(2)),...bn(T)}),A.scrollToBottom(),f(!0),h(!1),m(!1),(M=u.current)==null||M.call(u),QS(P)})}),y=W(j=>{const R=g.current;if(!R){r.current+=j;return}const I=n.current,T=`${r.current}${j}`;r.current="",n.current=null,s.current=!1,I!==null&&w(I.data,I.modes);const A=performance.now();R.write(o0(T),()=>{$t("terminal.background-output.rendered",{terminalSessionId:x,renderDurationMs:Number((performance.now()-A).toFixed(2)),...bn(T)})})}),N=W(j=>{if(s.current=!0,!d.current){if(r.current.length+j.length>Rne){y(j);return}r.current+=j}}),E=W(()=>{const j=g.current,R=n.current,I=r.current;if(!j||R===null&&I.length===0)return!1;if(r.current="",n.current=null,s.current=!1,R!==null&&w(R.data,R.modes),!I)return!0;const T=JS(j,x,v),A=performance.now();return j.write(o0(I),()=>{var P;$t("terminal.deferred-output.rendered",{terminalSessionId:x,renderDurationMs:Number((performance.now()-A).toFixed(2)),...bn(I)}),(P=u.current)==null||P.call(u),QS(T)}),!0}),k=W((j,R,I)=>{if(b.current+=1,I){C(()=>new Promise(T=>{const A=g.current;if(!A){I.commit(!1),T();return}A.write("",()=>w(j,R,{...I,commit:P=>{I.commit(P),T()}}))}));return}if(!t.current){n.current={data:j,modes:R},r.current="",s.current=!0,d.current=!1;return}w(j,R)}),D=W((j,R)=>{const I=XS(j);if(R){b.current+=1,I&&(c==null||c()),C(()=>new Promise(B=>{const M=g.current;if(!M||d.current){R.commit(!1),B();return}if(R.resizeMode==="ordered"&&R.cols&&R.rows){M.resize(R.cols,R.rows),R.commit(),B();return}k1(M)||h(!0),M.write(I,()=>{R.commit(),B()})}));return}if(!I)return;c==null||c(),b.current+=1;const T=Date.now();l.current+=1;const A=l.current;if($t("terminal.output.received",{terminalSessionId:x,seq:A,sinceLastInputMs:a.current===null?null:T-a.current,...bn(I)}),bh("terminal.output.received",I,{terminalSessionId:x,seq:A,sinceLastInputMs:a.current===null?null:T-a.current,...bn(I)}),!t.current){N(I);return}const P=g.current;if(!P)return;k1(P)||h(!0);const L=performance.now();P.write(I,()=>{const B=performance.now(),M=a.current===null?null:Date.now()-a.current;$t("terminal.output.rendered",{terminalSessionId:x,seq:A,sinceLastInputMs:M,renderDurationMs:Number((B-L).toFixed(2)),...bn(I)}),bh("terminal.output.rendered",I,{terminalSessionId:x,seq:A,sinceLastInputMs:M,renderDurationMs:Number((B-L).toFixed(2)),...bn(I)}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{const $=Number((performance.now()-B).toFixed(2)),U=a.current===null?null:Date.now()-a.current;bh("terminal.output.painted",I,{terminalSessionId:x,seq:A,sinceLastInputMs:U,paintDelayMs:$,...bn(I)})})})})});return{enqueueResize:S,onOutput:D,onSnapshot:k,renderTerminalSnapshot:w,replayDeferredOutput:E}}function Fse({active:e,apiBase:t,deferredSnapshotRef:r,hasDeferredOutputRef:n,hasRenderedSnapshotRef:s,onAuthExpiredRef:i,renderTerminalSnapshot:a,replayDeferredOutput:l,requiresSnapshotRestoreRef:c,restoreSnapshotRequestRef:u,terminalRef:d,terminalSessionId:h,tokenRef:f,websocketContentVersionRef:m}){p.useEffect(()=>{if(!e||!d.current)return;let g=!1;const v=u.current+1;u.current=v;const x=async b=>{var C;const _=m.current;try{const S=await _f(t,f.current,h);if(g||u.current!==v)return;if(m.current!==_){if(c.current&&b<2){await x(b+1);return}if(!c.current)return}a(S.scrollback)}catch(S){if(g)return;n.current=!0,c.current=!0,S instanceof De&&S.status===401&&((C=i.current)==null||C.call(i))}};return s.current&&!n.current&&!c.current?()=>{g=!0}:!c.current&&(s.current||r.current!==null)?l()?()=>{g=!0}:(n.current=!1,()=>{g=!0}):(x(0),()=>{g=!0})},[e,t,r,n,s,i,a,l,c,u,d,h,f,m])}function $se(e){var l,c;const t=tt(u=>u.completionMarkers[e.terminalSessionId]??0),r=Zn(),n=Math.max(t,((c=(l=r.data)==null?void 0:l.find(u=>u.terminalSessionId===e.terminalSessionId))==null?void 0:c.completionRevision)??0),s=p.useRef(""),i=p.useRef(!1),a=W(async()=>{var m;if(!e.active||!e.atBottom||!e.connected||!n||i.current||document.visibilityState!=="visible"||!document.hasFocus())return;const u=(m=e.terminalRef.current)==null?void 0:m.element;if(!u)return;const d=u.getBoundingClientRect();if(d.width<=0||d.height<=0)return;const h=document.elementFromPoint(d.left+d.width/2,d.top+d.height/2);if(!h||!u.contains(h))return;const f=JSON.stringify([e.apiBase,e.terminalSessionId,e.panelId,n]);if(s.current!==f){i.current=!0;try{await V6(e.apiBase,e.token,e.terminalSessionId,{completionRevision:n,panelIds:e.panelId?[e.panelId]:[]}),s.current=f}catch{}finally{i.current=!1}}});p.useEffect(()=>{if(!e.active||!e.atBottom||!e.connected||!n)return;const u=window.setInterval(()=>{a()},1e3);return()=>window.clearInterval(u)},[e.active,e.atBottom,e.connected,n,a])}function zse({active:e,obscured:t=!1,terminalSessionId:r,activeCommand:n=null,clientMode:s="desktop",layoutVersion:i="default",paneWorkspace:a=null,activePanelId:l=null,sessionStatus:c="running",terminalState:u,onResizePane:d,onViewportResize:h,onOpenFileLink:f}){const{apiBase:m,onAuthExpired:g,token:v}=vt(),x=NQ(r),b=p.useRef(null),_=p.useRef(null),C=Vt(Ke=>Ke.createBrowserTab),S=Vt(Ke=>Ke.openBrowser),w=Vt(Ke=>Ke.activeBrowserProfileId),y=xQ(e,r),N=Nj(Ke=>Ke.consumeInsertion),E=p.useRef(null),k=p.useRef(e),D=p.useRef(e&&!t),j=p.useRef(h),R=p.useRef(g),I=p.useRef(()=>{}),T=W((Ke,q,J)=>{var xe,Be,$e;if(!e||!f)return;const se=wg(Ke);if(!se){we("This file link is not supported on the connected backend");return}let fe;if(a&&a.panels.length>1){const He=(Be=(xe=_.current)==null?void 0:xe.element)==null?void 0:Be.querySelector(".xterm-screen"),Fe=He==null?void 0:He.getBoundingClientRect(),Ne=_.current;if(!Fe||!Ne)return;const Je=Math.floor((q.clientX-Fe.left)*Ne.cols/Fe.width),ze=Math.floor((q.clientY-Fe.top)*Ne.rows/Fe.height);if(fe=($e=a.panels.find(({geometry:rt})=>rt&&Je>=rt.paneLeft&&Je<rt.paneLeft+rt.paneWidth&&ze>=rt.paneTop&&ze<rt.paneTop+rt.paneHeight))==null?void 0:$e.panelId,!fe){we("Cannot determine the source terminal panel. Refresh the terminal and try again.");return}}f({...se,context:J},fe)}),A=p.useRef(a);A.current=a;const P=p.useRef(T),O=p.useRef(v),L=p.useRef(null),B=p.useRef(null),M=W(()=>{var Ke;return(Ke=B.current)==null?void 0:Ke.call(B)}),$=p.useRef(null),U=p.useRef(0),F=p.useRef(0),K=p.useRef(0),Y=p.useRef(null),te=p.useRef(null),H=p.useRef(null),G=p.useRef(!1),z=p.useRef(""),ee=p.useRef(null),V=p.useRef(null),re=p.useRef(!1),oe=p.useRef(!1),ce=p.useRef(0),be=p.useRef(0),ne=p.useRef(null),Te=p.useRef(()=>{}),Ve=p.useRef(()=>{}),[Ge,we]=p.useState(null),[de,he]=p.useState(!1),ge=qQ({active:e&&!t,clientMode:s,terminalRef:_}),Pe=jse({resetScrollInput:M,active:e,apiBase:m,runtimeKindRef:L,terminalRef:_,terminalSessionId:r,token:v}),Le=Pe.requestTmuxExitCopyMode,_e=Pe.tmuxScrollbackActive,{enqueueResize:et,onOutput:it,onSnapshot:ue,renderTerminalSnapshot:Ie,replayDeferredOutput:ye}=Bse({onLocalReset:()=>Ve.current(),activeRef:D,deferredOutputRef:z,deferredSnapshotRef:ee,hasDeferredOutputRef:G,hasRenderedSnapshotRef:oe,lastInputSentAtRef:Y,outputSequenceRef:F,onOutputReceived:()=>Te.current(),refreshTerminalViewportRef:E,requiresSnapshotRestoreRef:re,setHasNewOutputBelow:Pe.setHasNewOutputBelow,setTerminalAtBottom:Pe.setTerminalAtBottom,setTmuxScrollbackActive:Pe.setTmuxScrollbackActive,terminalRef:_,terminalFrameRef:V,terminalSessionId:r,websocketContentVersionRef:be});p.useLayoutEffect(()=>{D.current=e&&!t,e&&!t&&ye()},[e,t,ye]);const{invalidateOutputRecovery:ae,connectionStatus:le,error:je,notice:Me,failureSince:ot,lastCloseReason:ct,reconnectAttempt:yt,sendInput:Dt,sendResize:Ft,runtimeKind:Mt,singleRowScrollRef:Ze,orderedResizeRef:xt,terminalStatus:Ut}=UQ({apiBase:m,terminalSessionId:r,token:v,onAuthExpired:g,onSnapshot:ue,onOutput:it});Ve.current=ae,$se({apiBase:m,token:v,terminalSessionId:r,panelId:a==null?void 0:a.activePanelId,active:e&&!t,atBottom:Pe.terminalAtBottom&&!Pe.tmuxScrollbackActive&&!Pe.hasNewOutputBelow,connected:le==="connected",terminalRef:_});const fr=p.useMemo(()=>{const Ke=Date.now(),q=c==="exited"||Ut==="exited",J=q?"disabled":le==="connected"?"healthy":le==="closed"?"unhealthy":"recovering";return{id:`frontend.terminal.websocket:${r}`,capabilityId:"terminal",label:`Terminal ${r.slice(0,8)}`,state:J,summary:q?"Terminal 已正常退出":J==="healthy"?"Terminal WebSocket 已连接":J==="unhealthy"?ct||(yt>=Gc?"Terminal WebSocket 重试已耗尽":"Terminal WebSocket 已关闭"):"Terminal WebSocket 正在重连",observedAt:Ke,dependsOn:["frontend.node.http","frontend.node.auth"],recovery:J==="recovering"||J==="unhealthy"?{startedAt:ot??Ke,attempt:yt,maxAttempts:Gc,nextAttemptAt:null,deadlineAt:null}:null,facts:[],navigation:null}},[le,ot,ct,yt,Ut,c,r]);Kk(fr,fr.id);const dt=W(Ke=>{const q=performance.now(),J=te.current;if(J&&Ke===J.data&&q-J.at<=eT){if(J.forwarded)return;J.forwarded=!0}U.current+=1,Y.current=Date.now(),$t("terminal.input.captured",{terminalSessionId:r,seq:U.current,...bn(Ke)}),bh("terminal.input.captured",Ke,{terminalSessionId:r,seq:U.current,...bn(Ke)}),Dt(Ke)}),qe=Nse({active:e&&!t,activeCommand:n,apiBase:m,clientMode:s,error:je,paneWorkspace:a,searchOpen:ge.open,scroll:Pe,sessionStatus:c,terminalRef:_,terminalSessionId:r,terminalState:u,token:v});p.useEffect(()=>{Te.current=qe.handleOutputReceived},[qe.handleOutputReceived]),p.useLayoutEffect(()=>{var q,J;k.current=e;const Ke=(J=(q=_.current)==null?void 0:q.element)==null?void 0:J.querySelector(".xterm-rows:not([data-terminal-frame-overlay])");Ke!=null&&Ke.textContent&&(V.current=Ke.cloneNode(!0))},[e]),p.useEffect(()=>{j.current=h},[h]),p.useEffect(()=>{R.current=g},[g]),p.useEffect(()=>{I.current=Ke=>{var se,fe;if(((se=window.electronAPI)==null?void 0:se.isElectron)!==!0){Kc({url:Ke,placement:{kind:"new-group"}}).catch(()=>{});return}const q=Vt.getState().browser,J=q.tabs.find(xe=>xe.id===q.activeTabId);if(J&&((fe=window.electronAPI)!=null&&fe.terminalBrowserCreateTab)&&window.electronAPI.terminalBrowserGetWorkspace){window.electronAPI.terminalBrowserGetWorkspace(w).then(xe=>{const Be=xe.tabs.find($e=>$e.tabId===xe.activeTabId);return Kc({url:Ke,source:x,profileId:w,placement:Be?{kind:"current-group",groupId:Be.browserGroupId,openerTabId:Be.tabId}:{kind:"new-group"}})}).catch(xe=>{Vt.getState().updateBrowserTab(J.id,{error:xe instanceof Error?xe.message:"Failed to open browser link"})}).finally(S);return}else{const xe=zh(Ke);if(!xe.ok)return;C(xe.url)}S()}},[w,C,S,x]),p.useEffect(()=>{O.current=v},[v]),p.useEffect(()=>{L.current=Mt},[Mt]),zne({enqueueResize:et,orderedResizeRef:xt,activeRef:k,clientMode:s,imeCommitRef:te,imeCompositionEndedAtRef:H,lastResizedAtRef:$,lastSentResizeRef:ne,onBufferTypeChange:qe.setBufferType,onViewportResizeRef:j,onUserInputData:qe.handleUserInputData,onTextPaste:qe.textAttachments.capture,onRichPaste:qe.richPaste.capture,openTerminalLinkRef:I,openTerminalFileLinkRef:P,paneWorkspaceRef:A,refreshTerminalViewportRef:E,runtimeKindRef:L,singleRowScrollRef:Ze,resetScrollInputRef:B,searchAddonRef:ge.addonRef,sendResize:Ft,sendTerminalInput:dt,setPasteError:we,setSearchResults:ge.setResults,terminalContainerRef:b,terminalRef:_,terminalSessionId:r,xtermUserInputSequenceRef:K,onBottomStateChange:qe.handleBottomStateChange,onTmuxScrollbackActiveChange:qe.setTmuxScrollbackActive,onTmuxExitCopyModeRequest:qe.onTmuxExitCopyModeRequest});const Ht=qe.insertDraft;p.useEffect(()=>{if(!e||!y||vQ(y,(a==null?void 0:a.activePanelId)??l,Ht,N))return;if(!Bj({activeCommand:n,terminalState:u})){N(y.id);return}const Ke=_.current;if(!Ke)return;const q=()=>{Ke.paste(y.text),N(y.id)};if(L.current==="tmux"&&_e){Le();const J=window.setTimeout(q,320);return()=>window.clearTimeout(J)}q()},[e,n,l,N,Ht,a==null?void 0:a.activePanelId,y,Le,u,_e]),p.useEffect(()=>{if(!(!e||!_.current))return WQ(()=>{var Ke;!k.current||!_.current||(_.current.focus(),(Ke=E.current)==null||Ke.call(E))},{delayMs:ZA})},[e,i]),Fse({active:e,apiBase:m,deferredSnapshotRef:ee,hasDeferredOutputRef:G,hasRenderedSnapshotRef:oe,onAuthExpiredRef:R,renderTerminalSnapshot:Ie,replayDeferredOutput:ye,requiresSnapshotRestoreRef:re,restoreSnapshotRequestRef:ce,terminalRef:_,terminalSessionId:r,tokenRef:O,websocketContentVersionRef:be}),p.useEffect(()=>{e&&s==="mobile"||he(!1)},[e,s]);const Ce=e&&s!=="mobile",lt=e&&s==="mobile",Nt=e&&s!=="mobile"&&!!d;return o.jsx(nZ,{active:e,error:je??Ge,notice:Me,paneWorkspace:Nt?a:null,toolbar:Ce?o.jsx(ZQ,{inputRef:ge.inputRef,open:ge.open,query:ge.query,results:ge.results,options:ge.options,onQueryChange:ge.setQuery,onOptionsChange:ge.setOptions,onRunSearch:ge.run,onOpenChange:ge.setOpen,onCloseFocus:()=>{var Ke;return(Ke=_.current)==null?void 0:Ke.focus()}}):null,mobileControls:lt?o.jsx(QQ,{active:e,open:de,terminalRef:_,onOpenChange:he,onSendInput:dt}):null,controls:o.jsx(YQ,{diagnostics:qe.diagnostics,textAttachments:qe.textAttachments,richPaste:qe.richPaste,draft:qe.draft,sending:qe.sending,sendError:qe.sendError,hasNewOutputBelow:qe.hasNewOutputBelow,instantReplyAvailable:qe.instantReplyAvailable,instantReplyFeedback:qe.instantReplyFeedback,instantReplyOpen:qe.instantReplyOpen,scrollButtonMode:qe.scrollButtonMode,showTrigger:qe.showTrigger,terminalRef:_,visible:qe.visible,onClose:qe.onClose,onDraftChange:qe.onDraftChange,onInstantReplyClose:qe.onInstantReplyClose,onInstantReplyOpen:qe.onInstantReplyOpen,onInstantReplySend:qe.onInstantReplySend,onOpen:qe.onOpen,onScrollToBottom:qe.onScrollToBottom,onSend:qe.onSend,onQueue:qe.onQueue,queueKey:qe.queueKey}),terminalContainerRef:b,terminalRef:_,onResizePane:d})}function gv(e){return e.decisions.filter(t=>t.contextRevision===e.contextRevision&&(!t.threadId||t.threadId===e.target.threadId))}function Zce(e){var r,n;const t={completed:"任务已完成",blocked:"需要你处理",continue:"任务可以继续"}[e.outcome];return((r=e.assessment)==null?void 0:r.disposition)==="hold"&&e.assessment.holdReason==="background_wait"?"等待后台结果 · 本次不续接":((n=e.assessment)==null?void 0:n.disposition)==="hold"?`判断待核对 · 候选:${t}(未采用)`:e.assessment&&e.outcome==="completed"?"据报告完成":t}function Use(e){const r=[...e.split(/\r?\n\s*(?:\{|```)/,1)[0].trim()||e.trim()].slice(0,240).join("");return r.length<e.trim().length?`${r}…`:r}function eue(e,t,r,n,s){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goal-preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:s})}function tue(e,t,r,n){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goal-apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({previewId:n})})}function rue(e,t,r,n,s){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goals/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function Hse(e,t,r,n,s){const i=new URLSearchParams({terminalSessionId:r});return me(e,`/api/task-supervision?${i}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function nue(e,t,r){return me(e,"/api/task-supervision",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)})}function sue(e,t,r,n){return me(e,`/api/task-supervision/${encodeURIComponent(r)}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}function iue(e,t,r){return me(e,`/api/task-supervision/${encodeURIComponent(r)}`,{headers:{Authorization:`Bearer ${t}`}})}function oue(e,t,r,n,s){const i=new URLSearchParams(n?{cursor:n}:{});return me(e,`/api/task-supervision/${encodeURIComponent(r)}/decisions?${i}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function aue(e,t,r,n,s){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/decisions/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function lue(e,t,r,n,s){const i=new URLSearchParams(n?{cursor:n}:{});return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goals?${i}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function Wse(e,t=!1){const{apiBase:r,token:n,scope:s,onAuthExpired:i}=vt(),a=Ct({queryKey:["task-supervision",s,e],queryFn:({signal:l})=>Hse(r,n,e,null,l),enabled:e!==null,staleTime:4e3,refetchInterval:t?5e3:!1,refetchIntervalInBackground:!1,retry:!1});return p.useEffect(()=>{a.error instanceof De&&a.error.status===401&&(i==null||i())},[a.error,i]),a}function qse(e){var r,n,s;if(!e.enabled)return"监控已关闭";if(e.status==="watching"&&e.waitingFor)return e.waitingFor==="permission"?"等待你在原终端批准权限":"等待你在原终端回答问题";if(e.pauseReason==="continuation_limit")return"已达续接上限 · 任务仍未完成";if(e.pauseReason==="delivery_unknown")return"续接待确认";if(e.status==="error")return((r=gv(e).at(-1))==null?void 0:r.deliveryBlock)==="draft_unconfirmed"?"任务可以继续 · 自动续接未发送":"监听异常 / 上下文待补充";if(e.status==="paused")return"监控已暂停";if(e.goalState==="needs_review")return"目标待核对 · 暂不自动续接";if(e.goalState==="checking"&&!e.taskStartMessageId.startsWith("pending:"))return"正在核对任务目标";if(e.status==="classifying")return"正在判断任务状态";if(e.taskStartMessageId.startsWith("pending:"))return"等待新任务 · 终端监听已开启";const t=gv(e).at(-1);return(t==null?void 0:t.goalVersion)===((n=e.goalDefinition)==null?void 0:n.version)&&((s=t==null?void 0:t.assessment)==null?void 0:s.disposition)==="hold"?t.assessment.holdReason==="background_wait"?"等待后台结果 · 继续监听":"判断待核对 · 暂不自动续接":e.status==="watching"&&e.outcome==="completed"?t!=null&&t.assessment?"本轮据报告完成 · 继续监听此终端":"本轮任务已完成 · 继续监听此终端":e.status==="watching"&&e.outcome==="blocked"?"本轮需要你处理 · 继续监听此终端":e.status==="ended"?e.outcome==="completed"?"目标已达成":"需要你处理":"正在监听最终回复"}function Kse(e){return gv(e).some(t=>{var r,n;return t.goalVersion===((r=e.goalDefinition)==null?void 0:r.version)&&((n=t.assessment)==null?void 0:n.disposition)==="hold"&&t.assessment.holdReason!=="background_wait"})||e.goalState==="needs_review"||e.waitingFor!=null||e.status==="error"||e.status==="paused"||e.pauseReason==="continuation_limit"||e.pauseReason==="delivery_unknown"||e.outcome==="blocked"}function Vse({sessionId:e}){var u,d,h;const t=Wse(e,!0),r=W(()=>{Vt.getState().openTaskSupervision()}),n=(u=t.data)==null?void 0:u.watch;if(!(n!=null&&n.enabled))return null;const s=Kse(n)||t.isError,i=qse(n),a=Use(((d=n.goalDefinition)==null?void 0:d.objective)??n.goal)||((h=t.data)==null?void 0:h.threadTitle),l=[a,i].filter(Boolean).join(" · "),c=s?pa:gE;return o.jsxs("button",{type:"button","data-testid":"terminal-task-supervision-status-strip","aria-label":`查看长任务监控:${l}`,title:t.isError?`${l} · 状态暂时无法更新,显示上次结果`:l,onClick:r,className:`flex min-h-10 w-full shrink-0 items-center gap-2 border-b border-slate-800 px-3 py-2 text-left text-xs transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-emerald-400 ${s?"bg-amber-950/20 text-amber-300 hover:bg-amber-950/30":"bg-emerald-950/20 text-emerald-300 hover:bg-emerald-950/30"}`,children:[o.jsx(c,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),a?o.jsx("span",{className:"min-w-0 flex-1 truncate",children:a}):null,o.jsxs("span",{className:a?"shrink-0":"min-w-0 flex-1 truncate",children:[t.isError?"上次状态 · ":"",i]}),o.jsxs("span",{className:"shrink-0 text-[11px] opacity-80",children:[n.continuationCount,"/",n.continuationLimit," 次续接"]}),o.jsx(Jr,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"})]})}const Gse={requesting:"等待 Agent 结束当前轮次,请先不要操作页面",waiting:"Agent 等待协助:请处理页面,完成后交还",resume_pending:"已发送交还,等待 Agent 确认(不会自动重发)",acknowledged:"Agent 已确认交还,将重新观察页面;不代表任务已完成",cancelled:"已取消协助,Agent 不会自动恢复",expired:"协助请求已过期,请让 Agent 重新观察并请求",invalidated:"原 Agent、Panel 已改变或终端收到新输入,请重新请求协助",delivery_unknown:"交还投递结果不确定,请检查原终端;不会自动重发"},Yse=new Set(["acknowledged","cancelled","expired","invalidated"]);function Xse({sessionId:e}){const{apiBase:t,token:r,onAuthExpired:n}=vt(),[s,i]=p.useState([]),[a,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState([]),f=p.useRef(e);f.current=e;const m=W((_,C)=>{_ instanceof De&&_.status===401&&(n==null||n()),l({message:_ instanceof Error?_.message:"无法读取协助请求",requestId:C})});p.useEffect(()=>{var w;if(i([]),l(null),!e||!((w=window.electronAPI)!=null&&w.terminalBrowserResolveAssistanceTarget))return;const _=new AbortController;let C;const S=async()=>{try{const y=await aJ(t,r,e,_.signal);_.signal.aborted||i(y)}catch(y){_.signal.aborted||m(y)}finally{_.signal.aborted||(C=setTimeout(()=>void S(),2e3))}};return S(),()=>{_.abort(),clearTimeout(C)}},[t,r,e,m]);const g=W(async(_,C)=>{if(!(c||_.terminalSessionId!==f.current)){u(_.requestId),l(null);try{if(C!=="cancel"){const w=window.electronAPI;if(!(w!=null&&w.terminalBrowserResolveAssistanceTarget)||!w.terminalBrowserShow)throw new Error("当前桌面版本不支持浏览器协助");const y=await w.terminalBrowserResolveAssistanceTarget(_,C==="open");if(_.terminalSessionId!==f.current)return;if(C==="open"){if(y===null)return;await w.terminalBrowserShow(y),Vt.getState().activateBrowser(_.profileId,null);return}}const S=await lJ(t,r,_,C);_.terminalSessionId===f.current&&i(w=>w.map(y=>y.requestId===S.requestId?S:y))}catch(S){_.terminalSessionId===f.current&&m(S,_.requestId)}finally{u(null)}}}),v=new Map;for(const _ of s)v.set(_.panelId,_);const x=[...v.values()].filter(_=>!d.includes(_.requestId)),b=a&&(!a.requestId||x.some(_=>_.requestId===a.requestId))?a.message:null;return!x.length&&!b?null:o.jsxs("section",{"aria-label":"浏览器人工协助",className:"max-h-64 shrink-0 overflow-auto border-b border-amber-500/30 bg-amber-500/5 p-3 text-xs",children:[x.map(_=>o.jsxs("div",{className:"space-y-2 py-1","data-assistance-id":_.requestId,children:[o.jsx("p",{role:"status",className:"font-medium",children:Gse[_.state]}),o.jsx("p",{className:"whitespace-pre-wrap break-words",children:_.reason}),o.jsxs("p",{className:"text-muted-foreground",children:["Panel ",_.panelId.slice(0,8)," · ",_.profileId," ·"," ",_.requestId.slice(0,8)]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:c!==null||_.state!=="waiting",onClick:()=>void g(_,"open"),children:"打开协助页面"}),o.jsx(Z,{size:"sm",disabled:c!==null||_.state!=="waiting",onClick:()=>void g(_,"resume"),children:"完成并交还 Agent"}),["requesting","waiting"].includes(_.state)?o.jsx(Z,{size:"sm",variant:"ghost",disabled:c!==null,onClick:()=>void g(_,"cancel"),children:"取消协助"}):null,Yse.has(_.state)?o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>h(C=>[...C,_.requestId]),children:"收起"}):null]})]},_.requestId)),b?o.jsx("p",{role:"alert",className:"mt-2 text-rose-400",children:b}):null]})}const Jse=p.lazy(()=>Vr(()=>import("./index-X6z9DRtr.js").then(e=>e.bE),__vite__mapDeps([15,1,6,16])).then(e=>({default:e.TerminalPreviewPanel})));function Qse({clientMode:e,loading:t,panels:r,onEditProject:n,onCreateSession:s}){var be;const{apiBase:i,token:a,scope:l}=vt(),[c,u]=p.useState(null),d=p.useRef(0),h=_s(),f=Zn(),m=h.data??_o,g=f.data??bs,{activeProjectId:v,activeParentProjectId:x}=tt(An(ne=>({activeProjectId:ne.activeProjectId,activeParentProjectId:ne.activeParentProjectId}))),b=Hf(x).data??Uf,{activeSessionId:_,requestError:C,cachedSurfaceSessionIds:S,agentRecoveryRevisionBySessionId:w,terminalStateBySessionId:y,panelWorkspaceBySessionId:N,activePanelIdBySessionId:E}=tt(An(ne=>({activeSessionId:ne.activeSessionId,requestError:ne.requestError,cachedSurfaceSessionIds:ne.cachedSurfaceSessionIds,agentRecoveryRevisionBySessionId:ne.agentRecoveryRevisionBySessionId,terminalStateBySessionId:ne.terminalStateBySessionId,panelWorkspaceBySessionId:ne.panelWorkspaceBySessionId,activePanelIdBySessionId:ne.activePanelIdBySessionId}))),{previewOpen:k,previewWidthPx:D,previewExpanded:j}=Vt(An(ne=>({previewOpen:ne.ui.open,previewWidthPx:ne.ui.widthPx,previewExpanded:ne.ui.expanded}))),R=p.useRef(0);p.useEffect(()=>{var Te,Ve,Ge,we,de;if(((Te=window.electronAPI)==null?void 0:Te.isElectron)!==!0)return;const ne=he=>{const ge=R.current;if(R.current=he,ge===0&&he>0){const Pe=Vt.getState();Pe.ui.open||Pe.openAutomation()}};return(Ge=(Ve=window.electronAPI).terminalBrowserAutomationGetSnapshot)==null||Ge.call(Ve).then(he=>ne(he.connections.length)),(de=(we=window.electronAPI).onTerminalBrowserAutomationStateChanged)==null?void 0:de.call(we,he=>ne(he.connections.length))},[]);const I=e==="mobile",T=p.useMemo(()=>v?g.filter(ne=>ne.projectId===v):[],[v,g]),A=T.find(ne=>ne.terminalSessionId===_)??null,P=p.useMemo(()=>{const ne=new Set(S);return A&&ne.add(A.terminalSessionId),g.filter(Te=>ne.has(Te.terminalSessionId))},[A,S,g]),O=m.find(ne=>ne.projectId===x)??null,L=b.find(ne=>ne.projectId===v)??null,B=O&&L?{...O,projectId:L.projectId,name:L.name,path:L.path}:(O==null?void 0:O.projectId)===v?O:null,M=(c==null?void 0:c.scope)===l&&c.projectId===(B==null?void 0:B.projectId)&&c.terminalSessionId===(A==null?void 0:A.terminalSessionId)?c:null;p.useEffect(()=>{u(null)},[l,v,_]);const $=(A==null?void 0:A.panelSplitEnabled)??!1,U=A?N[A.terminalSessionId]??null:null,F=A?E[A.terminalSessionId]??(U==null?void 0:U.activePanelId)??A.activePanelId??null:null,K=(A==null?void 0:A.terminalSessionId)??null;p.useEffect(()=>{const ne=Vt.getState();ne.ui.activeTool==="conversation"&&ne.setConversationTarget(K?{scope:l,sessionId:K,panelId:F}:null)},[l,K,F]);const Y=Cj(_,F,!I),te=Y.visible&&!I,H=(be=Y.state.snapshot)==null?void 0:be.sourceStatus,G=H==="running"?"执行中":H==="idle"?"等待输入":H==="unavailable"?"原主会话不可用":"状态待确认",z=D?`${D}px`:a8,ee=I?"mobile":`desktop:${k?z:"full"}:${$?"panel-split":"single"}`,V=C??(h.error??f.error?String(h.error??f.error):null),{onPanelWorkspaceChange:re,onRefreshPanelWorkspace:oe,onResizePanel:ce}=r;return o.jsxs("div",{className:"min-h-0 min-w-0 flex-1",children:[V?o.jsx("p",{className:"border-b border-rose-900/60 bg-rose-950/30 px-3 py-1.5 text-xs text-rose-300",children:V}):null,o.jsxs("div",{className:"relative flex h-full min-h-0",children:[o.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[I?null:o.jsx(lQ,{sessionId:(A==null?void 0:A.terminalSessionId)??null}),I?null:o.jsx(Vse,{sessionId:(A==null?void 0:A.terminalSessionId)??null}),I?null:o.jsx(Xse,{sessionId:_}),A!=null&&A.tmuxSessionName&&!I&&$?o.jsx(mQ,{apiBase:i,token:a,activeSession:A,workspace:U,onWorkspaceChange:re}):null,o.jsx("div",{className:"relative min-h-0 flex-1",children:T.length>0?o.jsx(o.Fragment,{children:P.map(ne=>{var Ve;const Te=ne.terminalSessionId===(A==null?void 0:A.terminalSessionId);return o.jsx("div",{"aria-hidden":!Te||te,inert:Te&&te?!0:void 0,className:["absolute top-0 h-full w-full isolate",Te?"left-0":"-left-[9999em] pointer-events-none"].join(" "),children:o.jsx(zse,{onOpenFileLink:(Ge,we)=>{!Te||!B||(u({...Ge,panelId:we,id:++d.current,scope:l,projectId:B.projectId,terminalSessionId:ne.terminalSessionId}),Vt.getState().openPreview(B.projectId))},active:Te,obscured:Te&&te,activeCommand:ne.activeCommand,clientMode:e,layoutVersion:ee,sessionStatus:ne.status,terminalSessionId:ne.terminalSessionId,terminalState:y[ne.terminalSessionId]??ne.terminalState,paneWorkspace:N[ne.terminalSessionId]??null,activePanelId:E[ne.terminalSessionId]??ne.activePanelId??null,onResizePane:!I&&ne.panelSplitEnabled?(Ge,we,de)=>{ce(ne.terminalSessionId,Ge,we,de)}:void 0,onViewportResize:ne.panelSplitEnabled||(((Ve=N[ne.terminalSessionId])==null?void 0:Ve.panels.length)??ne.panelCount??1)>1?()=>{oe(ne.terminalSessionId)}:void 0})},`${i}:${ne.terminalSessionId}:surface:${w[ne.terminalSessionId]??0}`)})}):o.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-sm text-slate-400",children:[o.jsx("p",{children:"No terminal tab yet. Create one to start."}),I?o.jsx(Z,{type:"button",onClick:s,disabled:t,children:"新建终端"}):null]})}),te&&A?o.jsx(fQ,{model:Y.model,title:Ol({alias:A.alias,cwd:A.cwd,activeCommand:A.activeCommand}),mainStatus:G}):null]}),k&&!I?o.jsxs(o.Fragment,{children:[j?o.jsx("div",{"aria-hidden":"true",className:"min-h-0 shrink-0",style:{width:z}}):null,o.jsx("div",{className:j?"absolute inset-0 z-40":"h-full min-h-0 shrink-0",children:o.jsx(p.Suspense,{fallback:o.jsx("aside",{className:"flex h-full items-center justify-center bg-slate-950 text-sm text-slate-400",style:{width:z},children:"Loading preview..."}),children:o.jsx(Jse,{fileLinkIntent:M,onFileLinkDone:()=>u(null),activeProject:B,activeSession:A,activePanelId:F,widthPx:D,onEditProject:n})})})]}):null]})]})}function lc(e){return{...e,details:e.details?{...e.details}:void 0}}class Zse{constructor(){St(this,"bufferedLogs",[]);St(this,"result",null);St(this,"status","ready")}getStatus(){return this.status}isRecording(){return this.status==="recording"}start(){this.bufferedLogs.length=0,this.result=null,this.status="recording"}append(t){this.isRecording()&&this.bufferedLogs.push(lc(t))}getBufferedLogs(){return[...this.bufferedLogs.map(lc),...iE()]}finish(t){this.bufferedLogs.length=0,this.result={...t,logs:t.logs.map(lc),redactionReport:t.redactionReport?{...t.redactionReport}:void 0,files:t.files?{...t.files}:void 0},this.status="ended"}setStatus(t){this.status=t}setResult(t){this.result=t?{...t,logs:t.logs.map(lc),redactionReport:t.redactionReport?{...t.redactionReport}:void 0,files:t.files?{...t.files}:void 0}:null,this.status=t?"ended":"ready"}getResult(){return this.result?{...this.result,logs:this.result.logs.map(lc),redactionReport:this.result.redactionReport?{...this.result.redactionReport}:void 0,files:this.result.files?{...this.result.files}:void 0}:null}clear(){this.bufferedLogs.length=0,this.result=null,this.status="ready"}}function eie({recorder:e,source:t,consoleLog:r=console.log}){return(n,s)=>{r(n,s),e.isRecording()&&e.append({at:new Date().toISOString(),source:t,message:n,details:s})}}function tie(e){return e?e.logs.map(t=>{const r=t.source?` [${t.source}]`:"",n=t.details?` ${JSON.stringify(t.details)}`:"";return`${t.at}${r} ${t.message}${n}`}).join(`
|
|
704
|
+
`)}}}async function bse(e,t,r,n){let s=0,i=[...t.values()].reduce((u,d)=>u+d.bytes,0);const a=new Map,l=new Map,c=async u=>{var v;if(u.path)return;if(!n())throw new Error("粘贴已取消");let d;if(u.source instanceof File)d=u.source;else if(/^data:image\/(png|jpeg|gif|webp);base64,/i.test(u.source)){if(u.source.length>28*1024*1024)throw new Error("图片超过 20 MiB");d=await(await fetch(u.source)).blob()}else if(/^https?:\/\//i.test(u.source)){if(!((v=window.electronAPI)!=null&&v.downloadClipboardImage))throw new Error("当前客户端不支持网络图片,请更新桌面端");const x=await window.electronAPI.downloadClipboardImage(u.source);d=await(await fetch(`data:${x.mimeType};base64,${x.dataBase64}`)).blob()}else throw new Error("无法取得图片内容,请复制图片本身后重试");if(d.size>20*1024*1024)throw new Error("图片超过 20 MiB");if(!["image/png","image/jpeg","image/gif","image/webp"].includes(d.type))throw new Error("不支持的图片格式");const h=await d.arrayBuffer(),f=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",h))).map(x=>x.toString(16).padStart(2,"0")).join(""),m=t.get(f);if(m){u.path=m.path;return}let g=l.get(f);if(!g){if(i+=d.size,i>100*1024*1024)throw new Error("图文图片总计超过 100 MiB");g=(async()=>{if(!n())throw new Error("粘贴已取消");const x=await r(d.type,await lH(new File([d],"clipboard",{type:d.type})));return t.set(f,{path:x,bytes:d.size}),x})(),l.set(f,g)}u.path=await g};if(await Promise.all(Array.from({length:Math.min(3,e.images.length)},async()=>{var u;for(;s<e.images.length;){const d=e.images[s++];d.error=void 0;try{const h=a.get(d.source);if(h)await h,d.path=(u=e.images.find(f=>f.source===d.source&&f.path))==null?void 0:u.path;else{const f=c(d);a.set(d.source,f),await f}}catch(h){d.error=h instanceof Error?h.message:"图片准备失败"}}})),e.images.some(u=>!u.path))throw new Error("部分图片未准备好,内容已保留")}const Ao=new Map,_se=[];function yse(e){const t=JSON.stringify([e.apiBase,e.sessionId,e.panelId]),r=p.useRef(e);r.current=e;const n=p.useRef(0),s=JSON.stringify([t,e.token,e.threadId,e.active]),i=p.useRef(s);i.current!==s&&(i.current=s,n.current++);const[,a]=p.useState(0),l=W(()=>a(m=>m+1)),c=W(()=>{n.current++});p.useEffect(()=>()=>{n.current++},[]),p.useEffect(()=>{const m=g=>{[...Ao.values()].flat().some(v=>v.status!=="inserted")&&(g.preventDefault(),g.returnValue="")};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[]);const u=W(async(m,g,v=!1)=>{var k,D;if(r.current.sending||!r.current.active)return;const x={...r.current},b=i.current,_=++n.current,C=++m.attempt,S=g?{value:g.value,start:g.selectionStart,end:g.selectionEnd}:null,w=()=>(Ao.get(t)??[]).includes(m)&&m.attempt===C,y=()=>w()&&i.current===b&&n.current===_&&r.current.active,N=()=>y()&&(!S||!!(g!=null&&g.isConnected&&g.value===S.value&&g.selectionStart===S.start&&g.selectionEnd===S.end));m.status="pending",m.message="正在准备图文…",m.autoCloseAt=void 0,l();const E=j=>{var I;if(!w())return;const R=j&&!((I=m.document)!=null&&I.images.some(T=>T.error));m.autoCloseAt=R?Date.now()+3e3:m.purpose==="tui"?Date.now()+6e4:void 0,R&&(m.message=m.purpose==="tui"?"图文已插入":"图文已添加"),l()};try{if(m.purpose==="composer"&&!g)throw new Error("请打开 Input 后重新插入");if(!x.panelId)throw new Error("终端目标尚未就绪,内容已保留");const j=m.purpose==="tui"?await Mi(x.apiBase,x.token,x.sessionId,"/prepare","POST",{panelId:x.panelId}):void 0;if(!m.document&&!v&&(m.document=xse(m.snapshot)),!v&&m.document&&await bse(m.document,m.cache,async(I,T)=>(await eL(x.apiBase,x.token,x.sessionId,{mimeType:I,dataBase64:T},AbortSignal.timeout(2e4))).filePath,w),!w())return;const R=v?m.snapshot.plainText||((k=m.document)==null?void 0:k.markdown(!0))||"":m.document.markdown();if(!R)throw new Error("剪贴板没有可插入的文字或图片");if(!N()){m.status="ready",m.message="目标或输入已变化,内容已保留;可重新插入",E(!1),l();return}if(m.purpose==="tui"){if(!r.current.captureText(R,"tui",j.preparationId,E))throw new Error("终端目标不可用,内容已保留");m.message="图文已准备,投递结果见终端附件提示"}else if(r.current.captureText(R,"composer",void 0,E))m.message="已添加为长文本附件";else if(g&&S){const I=S.value.slice(0,S.start)+R+S.value.slice(S.end);r.current.onDraftChange(I);const T=S.start+R.length;requestAnimationFrame(()=>{g.isConnected&&g.value===I&&(g.focus(),g.setSelectionRange(T,T))}),m.message=`已插入图文${(D=m.document)!=null&&D.images.length?`(${m.document.images.length} 张图片)`:""}`,E(!0)}m.status="inserted",l()}catch(j){if(!w())return;m.status="error",m.message=j instanceof Error?j.message:"图文准备失败,内容已保留",E(!1),l()}}),d=W((m,g)=>{if(!m.clipboardData)return!1;const v=vse(m.clipboardData);if(!v)return!1;m.preventDefault(),m.stopPropagation(),"nativeEvent"in m?m.nativeEvent.stopImmediatePropagation():m.stopImmediatePropagation();const x={id:crypto.randomUUID(),purpose:g,snapshot:v,status:"ready",message:"",cache:new Map,attempt:0},b=Ao.get(t)??[];if(Ao.set(t,[...b.filter(C=>C.status!=="inserted"),x]),r.current.sending)return x.status="error",x.message="正在发送,图文已保留",x.autoCloseAt=g==="tui"?Date.now()+6e4:void 0,l(),!0;const _=g==="composer"?m.currentTarget:null;return u(x,_),!0}),h=W(m=>{m.attempt++,Ao.set(t,(Ao.get(t)??[]).filter(g=>g!==m)),l()}),f=Ao.get(t)??_se;return p.useEffect(()=>{const m=f.flatMap(g=>g.autoCloseAt===void 0?[]:[window.setTimeout(()=>h(g),Math.max(0,g.autoCloseAt-Date.now()))]);return()=>m.forEach(g=>window.clearTimeout(g))}),{items:f,capture:d,run:u,remove:h,markInput:c,blocked:f.some(m=>m.purpose==="composer"&&m.status!=="inserted")}}const $d={threshold:5e3,maxBytes:1024*1024,sessionMaxBytes:100*1024*1024,maxDraftAttachments:20},ks=e=>JSON.stringify([e.apiBase,e.sessionId,e.panelId,e.inputContextKey??"legacy"]),wse=new Map,i0=new Set;function Sse(e,t){const r=p.useRef(e),n=p.useRef(0),s=p.useRef(""),i=ks(e),a=JSON.stringify([i,e.token,e.active]);s.current!==a&&(s.current=a,n.current++),p.useEffect(()=>()=>{n.current++},[]);const l=p.useRef(wse),[,c]=p.useState(0),[u,d]=p.useState(null),h=W(()=>c(N=>N+1)),f=l.current.get(ks(e))??[],m=e.threadId;r.current={...e,threadId:m};const g=e.active&&!!e.panelId,v=g&&(u==null?void 0:u.context)===a&&u.value.enabled;p.useEffect(()=>{let N=!1;if(!e.panelId||!e.active)return;const E=()=>{Mi(e.apiBase,e.token,e.sessionId,`/capability?panelId=${encodeURIComponent(e.panelId)}`).then(D=>{N||d({context:a,scopeId:i,value:D})}).catch(()=>{N||d({context:a,scopeId:i,value:{enabled:!1,provider:null,threadId:null,executionHost:null,reason:"附件能力未确认",limits:$d}})})};E();const k=window.setInterval(E,5e3);return()=>{N=!0,window.clearInterval(k)}},[e.apiBase,e.token,e.sessionId,e.panelId,e.active,a,i]);const x=W((N=!1)=>{n.current++,N&&(i0.delete(ks(r.current)),h())}),b=W(N=>{const E=ks(r.current);l.current.set(E,(l.current.get(E)??[]).filter(k=>k!==N)),h(),N.purpose==="composer"&&N.attachment&&N.attachment.state==="draft"&&Wp(r.current.apiBase,r.current.token,r.current.sessionId,N.attachment.id,"release").catch(()=>{})}),_=W(async N=>N.attachment?tL(r.current.apiBase,r.current.token,r.current.sessionId,N.attachment):N.text),C=W((N,E,k,D)=>{if(!g||!k&&N.length<$d.threshold)return!1;const j={...r.current},R=ks(j),I=n.current,T=l.current.get(R)??[],A={key:crypto.randomUUID(),operationId:crypto.randomUUID(),richPaste:!!k,text:N,purpose:E,status:"pending"};if(l.current.set(R,[...T,A]),h(),T.filter(B=>B.status==="pending"||B.status==="saved").length>=$d.maxDraftAttachments)return A.status="error",A.reason="草稿最多保存 20 份附件,原文已保留",h(),D==null||D(!1),!0;const P=()=>(l.current.get(R)??[]).includes(A),O=()=>ks(r.current)===R&&r.current.active&&n.current===I,L=async B=>Mi(j.apiBase,j.token,j.sessionId,`/operations/${encodeURIComponent(B)}`);return(async()=>{try{if(!v){const $=await Mi(j.apiBase,j.token,j.sessionId,`/capability?panelId=${encodeURIComponent(j.panelId)}`);if(!$.enabled)throw new Error($.reason??"附件能力未确认,原文已保留");if(!P()||!O()){A.status="not-inserted",A.reason="目标或输入已变化,原文已保留",h();return}}let B;try{B=await Mi(j.apiBase,j.token,j.sessionId,"","POST",{operationId:A.operationId,panelId:j.panelId,expectedThreadId:j.threadId,purpose:E,text:N,...k?{preparationId:k}:{}})}catch($){const U=await L(A.operationId).catch(()=>null);if((U==null?void 0:U.status)!=="saved")throw $;B=await Mi(j.apiBase,j.token,j.sessionId,`/${U.attachmentIds[0]}`)}if(!P()&&E==="composer"){await Wp(j.apiBase,j.token,j.sessionId,B.id,"release").catch(()=>{});return}if(A.attachment=B,A.status="saved",h(),E==="composer")return;if(!O()){A.status="not-inserted",A.reason="目标或输入已变化,未插入路径",h();return}i0.add(R),t(),h();let M;try{M=await Mi(j.apiBase,j.token,j.sessionId,`/${B.id}/insert`,"POST",{operationId:B.insertOperationId,...k&&N.length<$d.threshold?{inline:!0}:{},panelId:j.panelId,expectedThreadId:j.threadId})}catch($){if($ instanceof De&&[400,409,410,413,507].includes($.status)){A.status="not-inserted",A.reason=$.message,h();return}const U=await L(B.insertOperationId).catch(()=>null);if(!U){A.status="unknown",A.reason="路径交付未确认,请核对终端",h();return}M=U}A.status=M.status==="accepted"?"inserted":M.status==="rejected"?"not-inserted":"unknown",A.reason=M.reason,A.richPaste&&A.status==="inserted"&&!A.reason&&(A.autoCloseAt=Date.now()+3e3),M.status!=="rejected"&&(B.state="referenced"),M.status==="accepted"&&ks(r.current)===R&&n.current++,h()}catch(B){P()&&(A.status="error",A.reason=B instanceof Error?B.message:"保存失败,原文已保留",h())}finally{D==null||D(P()&&(A.status==="inserted"||E==="composer"&&A.status==="saved")&&!A.reason)}})(),!0});p.useEffect(()=>{const N=f.flatMap(E=>E.autoCloseAt===void 0?[]:[window.setTimeout(()=>b(E),Math.max(0,E.autoCloseAt-Date.now()))]);return()=>N.forEach(E=>window.clearTimeout(E))});const S=W((N,E)=>{const k=N.clipboardData;return!k||Array.from(k.items).some(D=>D.kind==="file")||!C(k.getData("text/plain"),E)?!1:(N.preventDefault(),"nativeEvent"in N?N.nativeEvent.stopImmediatePropagation():N.stopImmediatePropagation(),N.stopPropagation(),!0)});p.useEffect(()=>{const N=()=>{var k;for(const D of l.current.get(ks(r.current))??[])((k=D.attachment)==null?void 0:k.state)==="draft"&&Wp(r.current.apiBase,r.current.token,r.current.sessionId,D.attachment.id,"retain").catch(j=>{D.status="error",D.reason=j instanceof Error?j.message:"附件续期失败",h()})};N();const E=window.setInterval(N,1440*60*1e3);return()=>window.clearInterval(E)},[a,h]),p.useEffect(()=>{const N=E=>{[...l.current.values()].flat().some(k=>!k.attachment)&&(E.preventDefault(),E.returnValue="")};return window.addEventListener("beforeunload",N),()=>window.removeEventListener("beforeunload",N)},[]);const w=f.filter(N=>N.purpose==="composer"),y=W(N=>{for(const E of l.current.values())for(const k of N){const D=E.indexOf(k);D!==-1&&E.splice(D,1)}h()});return{items:f,enabled:v,capabilityReason:(u==null?void 0:u.value.reason)??null,mirrorUnreliable:i0.has(ks(e)),composerItems:w,capture:S,captureText:C,markInput:x,remove:b,read:_,consume:y,blocked:w.some(N=>N.status!=="saved"),ids:w.flatMap(N=>N.attachment?[N.attachment.id]:[]),threadId:m,panelId:e.panelId,scopeId:ks(e)}}function Cse(e){const[t,r]=p.useState(null),n=JSON.stringify([e.apiBase,e.sessionId]);return p.useEffect(()=>{if(e.workspace||!e.active)return;let s=!1;const i=async()=>{const{listTerminalPanels:l}=await Vr(async()=>{const{listTerminalPanels:c}=await Promise.resolve().then(()=>L6);return{listTerminalPanels:c}},void 0);try{const c=await l(e.apiBase,e.token,e.sessionId);s||r({key:n,workspace:c})}catch{s||r(null)}};i();const a=window.setInterval(()=>{i()},5e3);return()=>{s=!0,window.clearInterval(a)}},[n,e.apiBase,e.sessionId,e.token,e.active,e.workspace]),e.workspace??((t==null?void 0:t.key)===n?t.workspace:null)}const mv="runweave:handoff-input";function Qce(e){const t={...e};if(window.dispatchEvent(new CustomEvent(mv,{detail:t})),!t.release)throw new Error(t.message??"终端输入尚未就绪,请在终端中继续。");return t.release}function Ese({apiBase:e,available:t,error:r,onSent:n,panelId:s,codexInputContext:i,requestScopeRef:a,sendPendingRef:l,setSending:c,terminalSessionId:u,token:d}){const[h,f]=p.useState(!1),[m,g]=p.useState(null);p.useEffect(()=>{f(!1),g(null)},[e,s,u]),p.useEffect(()=>{t||(f(!1),g(null))},[t]);const v=W(()=>{f(!1),g(null)}),x=W(()=>{f(!0)}),b=W(async _=>{if(l.current||!t)return;if(r){g({message:"终端连接不可用,请重连后再发送。",tone:"error"}),f(!0);return}const C=a.current;l.current=!0,c(!0),g(null);try{if(!C||a.current!==C||(await yf(e,d,u,{data:_,mode:"prompt_replace",submit:!0,recordQuickInput:!1,codexInputContext:i,...s?{panelId:s}:{}},AbortSignal.timeout(2e4)),a.current!==C))return;n(),g({message:`已发送「${_}」`,tone:"success"})}catch(S){if(a.current!==C)return;$t("terminal.instant_reply.send.failed",{terminalSessionId:u,error:String(S)}),g({message:"发送结果未确认,请先核对终端结果;不会自动重发。",tone:"error"}),f(!0)}finally{a.current===C&&(l.current=!1,c(!1))}});return{available:t,feedback:m,onClose:v,onOpen:x,onSend:b,open:h}}const kse=150;function Ise({active:e,activeCommand:t,apiBase:r,bufferType:n,clientMode:s,error:i,paneWorkspace:a,searchOpen:l,scrollToBottom:c,sessionStatus:u,showScrollToBottomControl:d,terminalAtBottom:h,terminalSessionId:f,terminalState:m,token:g}){const v=p.useRef(""),x=p.useRef(""),b=p.useRef(!1),_=p.useRef(!1),C=p.useRef(!1),S=p.useRef(null),[w,y]=p.useState(!1),[N,E]=p.useState(""),[k,D]=p.useState(!0),j=p.useRef(!1),[R,I]=p.useState(!1),[T,A]=p.useState(!1),[P,O]=p.useState(null),L=p.useRef(null),B=Hne(N,T,L),M=p.useRef(P);M.current=P;const $=p.useRef(new Map),U=a==null?void 0:a.panels.find(ye=>ye.panelId===a.activePanelId),F=U==null?void 0:U.codexContext,K=F===void 0?"legacy":`${(F==null?void 0:F.generation)??"unknown"}:${(F==null?void 0:F.displayedThreadId)??"unknown"}`;p.useEffect(()=>{VS(S);const ye=JSON.stringify([r,f,a==null?void 0:a.activePanelId,K]),ae=$.current,le=ae.get(ye);return L.current={},x.current=(le==null?void 0:le.draft)??"",v.current=(le==null?void 0:le.synced)??"",b.current=(le==null?void 0:le.dirty)??!1,_.current=!1,j.current=(le==null?void 0:le.mirrorUnreliable)??!1,D(!j.current),C.current=!1,E(x.current),O((le==null?void 0:le.error)??null),y(!!(le!=null&&le.dirty||le!=null&&le.error)),A(!1),I(!1),()=>{ae.set(ye,{draft:x.current,synced:v.current,dirty:b.current,mirrorUnreliable:j.current,error:_.current?"发送结果未确认,草稿已保留。请先检查终端,再决定是否重新发送。":M.current}),L.current=null}},[r,f,a==null?void 0:a.activePanelId,K]);const Y=a?(U==null?void 0:U.activeCommand)??null:t,te=a?U==null?void 0:U.terminalState:m,H=F&&te?{...te,state:F.displayedRunning?"agent_running":"agent_idle"}:te,G=a?(U==null?void 0:U.status)==="running":u==="running",z=(F===void 0||!!(F!=null&&F.inputReady&&F.displayedThreadId))&&BQ({activeCommand:Y,bufferType:n,clientMode:s,searchOpen:l,sessionRunning:G,terminalState:H}),ee=Cse({apiBase:r,token:g,sessionId:f,active:e,workspace:a}),V=ee==null?void 0:ee.panels.find(ye=>ye.panelId===ee.activePanelId),re=Sse({apiBase:r,token:g,sessionId:f,panelId:(ee==null?void 0:ee.activePanelId)??"",inputContextKey:K,threadId:F!==void 0?(F==null?void 0:F.displayedThreadId)??null:(V==null?void 0:V.threadId)??((V==null?void 0:V.lastThreadStatus)==="idle"?V.lastThreadId:null)??null,active:e},()=>{j.current=!0,ne(),I(!1),D(!1),O("TUI 路径投递后,光标草稿无法可靠镜像;请核对终端并在那里继续编辑、提交。")}),oe=yse({apiBase:r,token:g,sessionId:f,panelId:re.panelId,threadId:re.threadId,active:e,sending:T,captureText:re.captureText,onDraftChange:ye=>Ge(ye)}),ce=k&&!re.mirrorUnreliable,be=PQ({activeCommand:Y,terminalState:H}),ne=W(()=>{VS(S)}),Te=W(()=>{ne()}),Ve=W(ye=>{if(F!==void 0&&ye==="")return;if(oe.markInput(),re.markInput(ye==="\r"||ye===""),j.current||re.mirrorUnreliable)if(ye==="\r"||ye==="")j.current=!1,v.current="",b.current||(x.current="",E("")),D(!0),O(null);else return;if(!z||!ce)return;const ae=v.current,le=FQ(ae,ye);if(!le.supported){ne(),v.current&&D(!1);return}if(v.current=le.draft,!(b.current||_.current)&&(x.current=le.draft,E(le.draft),F===void 0)){if(!le.draft){ne(),I(!1);return}le.draft===ae||C.current||S.current!==null||(S.current=window.setTimeout(()=>{S.current=null,!(!x.current||!z||!ce)&&(I(!0),y(!0))},kse))}}),Ge=W(ye=>{oe.markInput(),re.markInput(),x.current=ye,E(ye),b.current=ye!==v.current}),we=Une({eligible:z,draftMirrorSupported:ce,floatingDraftSyncPendingRef:_,floatingDraftRef:x,setSendError:O,setFloatingComposerOpen:y,handleDraftChange:Ge}),de=W(async(ye={})=>{const ae=B();if(_.current||re.blocked||oe.blocked||j.current||re.mirrorUnreliable)return ae.reject();const le=[...re.composerItems],je=[...re.ids],Me=b.current||je.length>0;if(je.length&&ye.submit!==!0)return ae.reject();const ot=ye.submit===!0;if(!Me&&!ot)return ae.noop();if(i)return O("终端连接不可用,草稿已保留;重连后再发送。"),y(!0),ae.reject();if(F!==void 0&&(!(F!=null&&F.inputReady)||!F.displayedThreadId))return O("Codex 会话身份尚未就绪,草稿已保留,请在原终端继续。"),ae.reject();const ct=x.current,yt=L.current,Dt=je.length?re.panelId:a==null?void 0:a.activePanelId,Ft=ae.id;re.markInput(),_.current=!0,A(!0),O(null);try{return!yt||L.current!==yt||(await yf(r,g,f,{data:ct,mode:"prompt_replace",...F!=null&&F.displayedThreadId?{codexInputContext:{generation:F.generation,revision:F.revision,threadId:F.displayedThreadId}}:{},...je.length?{operationId:Ft,textAttachmentIds:je,expectedThreadId:re.threadId??void 0,recordQuickInput:!1}:{},submit:ot,...ye.submitKey?{submitKey:ye.submitKey}:{},...Dt?{panelId:Dt}:{}},AbortSignal.timeout(2e4),ae),je.length&&re.consume(le),L.current!==yt)||(v.current=ot?"":ct,x.current!==ct)?!1:(b.current=!1,ot&&(x.current="",E("")),ae.stateUpdated(ot),!0)}catch(Mt){if(je.length){const Ze=await Mi(r,g,f,`/operations/${Ft}`).catch(()=>null);if((Ze==null?void 0:Ze.status)==="accepted")return ae.stage("confirmed"),re.consume(le),L.current===yt&&x.current===ct&&(x.current="",v.current="",b.current=!1,E(""),ae.stateUpdated(!0)),!0;if((Ze==null?void 0:Ze.status)==="unknown"||(Ze==null?void 0:Ze.status)==="dispatching"||!Ze)for(const xt of le)xt.status="unknown",xt.reason="提交结果未确认,请核对终端;不会自动重发"}return L.current!==yt||($t("terminal.floating_composer.sync.failed",{terminalSessionId:f,error:String(Mt)}),b.current=!0,O("发送结果未确认,草稿已保留。请先检查终端,再决定是否重新发送。"),y(!0)),!1}finally{L.current===yt&&(_.current=!1,A(!1))}}),he=z&&(ce||!!P||re.composerItems.length>0)&&(d||R||w||T||!!P),ge=he&&w,Pe=he&&!w,Le=W(()=>{v.current="",b.current=x.current.length>0,b.current&&y(!0)}),_e=Ese({codexInputContext:F!=null&&F.displayedThreadId?{generation:F.generation,revision:F.revision,threadId:F.displayedThreadId}:void 0,apiBase:r,available:z&&ce&&!oe.blocked,error:i,onSent:Le,panelId:a==null?void 0:a.activePanelId,requestScopeRef:L,sendPendingRef:_,setSending:A,terminalSessionId:f,token:g}),et=W(async()=>{!N&&!re.ids.length||await de({submit:!0})&&(ne(),I(!1),y(!1),c())}),it=W(async()=>{!x.current&&!re.ids.length||!be||await de({submit:!0,submitKey:be})&&(ne(),I(!1),y(!0))});p.useEffect(()=>{const ye=C.current;if(C.current=ge,!ye&&ge&&!b.current&&!_.current){const ae=v.current;x.current=ae,b.current=!1,E(ae);return}ye&&!ge&&F===void 0&&b.current&&!_.current&&!P&&de()},[de,P,ge,F]),p.useEffect(()=>{h&&!j.current&&D(!0)},[h]),p.useEffect(()=>{j.current||D(!0),ne(),I(!1)},[Y,ne,f,H==null?void 0:H.agent,H==null?void 0:H.state]),p.useEffect(()=>{z||(ne(),I(!1),y(!1))},[ne,z]),p.useEffect(()=>()=>{ne()},[ne]);const ue=W(ye=>{const ae=ye.detail;if(!(ae.apiBase!==r||ae.terminalSessionId!==f||ae.panelId!==((a==null?void 0:a.activePanelId)??null))){if(oe.blocked||!z||!ce||i||_.current){ae.message="终端输入未就绪或正在发送,请稍后再试。";return}if(x.current.trim()||v.current.trim()){ae.message="终端中有未发送的草稿,请先处理草稿,再继续验收。";return}_.current=!0,A(!0),ae.release=()=>{_.current=!1,A(!1)}}});p.useEffect(()=>(window.addEventListener(mv,ue),()=>window.removeEventListener(mv,ue)),[ue]);const Ie=W(()=>{oe.markInput(),ne(),I(!1),y(!1)});return{richPaste:oe,textAttachments:re,draft:N,sending:T,sendError:P,draftMirrorSupported:ce,eligible:z,handleOutputReceived:Te,handleDraftChange:Ge,insertDraft:we,handleSend:et,handleQueue:it,queueKey:be,handleUserInputData:Ve,inputLagFallbackActive:R,instantReplyAvailable:_e.available,instantReplyFeedback:_e.feedback,instantReplyOpen:_e.open,onClose:Ie,onInstantReplyClose:_e.onClose,onInstantReplyOpen:_e.onOpen,onInstantReplySend:_e.onSend,onOpen:()=>y(!0),showTrigger:Pe,visible:ge}}function Nse({active:e,activeCommand:t,apiBase:r,clientMode:n,error:s,paneWorkspace:i,searchOpen:a,sessionStatus:l,scroll:c,terminalRef:u,terminalSessionId:d,terminalState:h,token:f}){const[m,g]=p.useState(void 0),v=Ise({active:e,activeCommand:t,apiBase:r,bufferType:m,clientMode:n,error:s,paneWorkspace:i,searchOpen:a,scrollToBottom:c.scrollToBottom,sessionStatus:l,showScrollToBottomControl:c.showScrollToBottomControl,terminalAtBottom:c.terminalAtBottom,terminalSessionId:d,terminalState:h,token:f}),x=v.eligible,b=v.visible,_=v.showTrigger,S=b&&(!c.terminalAtBottom||c.tmuxScrollbackActive)?"floating":c.showScrollToBottomControl&&!b?"legacy":"none",w={activeCommand:t,bottomOffsetRows:c.bottomOffsetRows,bufferType:m,draftMirrorSupported:v.draftMirrorSupported,eligible:x,inputLagFallbackActive:v.inputLagFallbackActive,sessionStatus:l,terminalAgent:(h==null?void 0:h.agent)??null,terminalAtBottom:c.terminalAtBottom,terminalState:(h==null?void 0:h.state)??null,tmuxScrollbackActive:c.tmuxScrollbackActive},y=W(()=>{v.onClose(),requestAnimationFrame(()=>{var E;return(E=u.current)==null?void 0:E.focus()})}),N=W(()=>{v.onInstantReplyClose(),requestAnimationFrame(()=>{var E;return(E=u.current)==null?void 0:E.focus()})});return{diagnostics:w,textAttachments:v.textAttachments,richPaste:v.richPaste,draft:v.draft,sending:v.sending,sendError:v.sendError,handleBottomStateChange:c.handleBottomStateChange,handleOutputReceived:v.handleOutputReceived,handleUserInputData:v.handleUserInputData,hasNewOutputBelow:c.hasNewOutputBelow,instantReplyAvailable:v.instantReplyAvailable,instantReplyFeedback:v.instantReplyFeedback,instantReplyOpen:v.instantReplyOpen,onClose:y,onDraftChange:v.handleDraftChange,insertDraft:v.insertDraft,onInstantReplyClose:N,onInstantReplyOpen:v.onInstantReplyOpen,onInstantReplySend:v.onInstantReplySend,onOpen:v.onOpen,onScrollToBottom:c.scrollToBottom,onSend:v.handleSend,onQueue:v.handleQueue,queueKey:v.queueKey,onTmuxExitCopyModeRequest:c.requestTmuxExitCopyMode,scrollButtonMode:S,setBufferType:g,setHasNewOutputBelow:c.setHasNewOutputBelow,setTerminalAtBottom:c.setTerminalAtBottom,setTmuxScrollbackActive:c.setTmuxScrollbackActive,showTrigger:_,visible:b}}const Rse=1e3;function jse({active:e,apiBase:t,runtimeKindRef:r,terminalRef:n,terminalSessionId:s,token:i,resetScrollInput:a}){const l=p.useRef(0),[c,u]=p.useState(0),[d,h]=p.useState(!0),[f,m]=p.useState(!1),[g,v]=p.useState(!1),x=W(()=>{a==null||a();const S=Date.now();if(S-l.current<Rse)return;l.current=S;const w=()=>{yf(t,i,s,{data:"",mode:"tmux_exit_copy_mode"})};w(),window.setTimeout(w,250),window.setTimeout(w,800)}),b=W(()=>{const S=n.current;S&&(r.current==="tmux"&&x(),CH(S),h(!0),u(0),m(!1),v(!1),S.focus())}),_=W(S=>{h(S.isAtBottom),u(S.bottomOffsetRows),S.isAtBottom&&m(!1)});return{bottomOffsetRows:c,handleBottomStateChange:_,hasNewOutputBelow:f,requestTmuxExitCopyMode:x,scrollToBottom:b,setHasNewOutputBelow:m,setTerminalAtBottom:h,setTmuxScrollbackActive:v,showScrollToBottomControl:e&&(!d||f||g),terminalAtBottom:d,tmuxScrollbackActive:g}}const mT="\x1B",Ase=new RegExp(`${mT}\\[\\?[\\d;]+\\$p`,"g"),Tse=new Set(["1000","1002","1003","1005","1006","1015"]),Dse=new RegExp(`${mT}\\[\\?([\\d;]+)([hl])`,"g");function XS(e){return e.replace(Ase,"").replace(Dse,(t,r)=>r.split(";").every(s=>Tse.has(s))?"":t)}const Pse="\x1B[?2026h",Lse="\x1B[?2026l",Mse="\x1B[?2004h",Ose="\x1B[?2004l";function o0(e){return`${Pse}${e}${Lse}`}function JS(e,t,r){var l,c,u;const n=(l=e.element)==null?void 0:l.querySelector(".xterm-screen"),s=n==null?void 0:n.querySelector(".xterm-rows:not([data-terminal-frame-overlay])");s!=null&&s.textContent&&(r.current=s.cloneNode(!0));const i=s!=null&&s.textContent?s:r.current;if(!n||!(i!=null&&i.textContent))return $t("terminal.frame.preserve.skipped",{terminalSessionId:t,hasScreen:!!n,rowTextLength:((c=s==null?void 0:s.textContent)==null?void 0:c.length)??0}),()=>{};const a=i.cloneNode(!0);return a.dataset.terminalFrameOverlay="true",a.setAttribute("aria-hidden","true"),Object.assign(a.style,{position:"absolute",inset:"0",zIndex:"4",width:"100%",height:"100%",overflow:"hidden",pointerEvents:"none",backgroundColor:((u=e.options.theme)==null?void 0:u.background)??"#0b1220"}),n.appendChild(a),$t("terminal.frame.preserved",{terminalSessionId:t,rowTextLength:i.textContent.length}),()=>{a.remove()}}function QS(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}function Bse({onLocalReset:e,activeRef:t,deferredOutputRef:r,deferredSnapshotRef:n,hasDeferredOutputRef:s,hasRenderedSnapshotRef:i,lastInputSentAtRef:a,outputSequenceRef:l,onOutputReceived:c,refreshTerminalViewportRef:u,requiresSnapshotRestoreRef:d,setHasNewOutputBelow:h,setTerminalAtBottom:f,setTmuxScrollbackActive:m,terminalRef:g,terminalFrameRef:v,terminalSessionId:x,websocketContentVersionRef:b}){const _=p.useRef(Promise.resolve()),C=W(j=>{_.current=_.current.then(j,j)}),S=W(j=>{C(()=>new Promise(R=>{const I=g.current;if(!I){R();return}I.write("",()=>{try{j()}finally{R()}})}))}),w=W((j,R,I)=>{I||e();const T=XS(j),A=g.current;if(!A){I==null||I.commit(!1);return}f(!0),h(!1),m(!1),$t("terminal.snapshot.received",{terminalSessionId:x,...bn(T)}),i.current=!0,s.current=!1,r.current="",n.current=null,d.current=!1;const P=JS(A,x,v),O=(R==null?void 0:R.bracketedPasteMode)??A.modes.bracketedPasteMode;A.reset();const L={cols:A.cols,rows:A.rows};I!=null&&I.cols&&I.rows&&A.resize(I.cols,I.rows);const B=performance.now();A.write(`${o0(T)}${O?Mse:Ose}`,()=>{var M;I!=null&&I.cols&&I.rows&&I.resizeMode!=="ordered"&&A.resize(L.cols,L.rows),I==null||I.commit(),$t("terminal.snapshot.rendered",{terminalSessionId:x,renderDurationMs:Number((performance.now()-B).toFixed(2)),...bn(T)}),A.scrollToBottom(),f(!0),h(!1),m(!1),(M=u.current)==null||M.call(u),QS(P)})}),y=W(j=>{const R=g.current;if(!R){r.current+=j;return}const I=n.current,T=`${r.current}${j}`;r.current="",n.current=null,s.current=!1,I!==null&&w(I.data,I.modes);const A=performance.now();R.write(o0(T),()=>{$t("terminal.background-output.rendered",{terminalSessionId:x,renderDurationMs:Number((performance.now()-A).toFixed(2)),...bn(T)})})}),N=W(j=>{if(s.current=!0,!d.current){if(r.current.length+j.length>Rne){y(j);return}r.current+=j}}),E=W(()=>{const j=g.current,R=n.current,I=r.current;if(!j||R===null&&I.length===0)return!1;if(r.current="",n.current=null,s.current=!1,R!==null&&w(R.data,R.modes),!I)return!0;const T=JS(j,x,v),A=performance.now();return j.write(o0(I),()=>{var P;$t("terminal.deferred-output.rendered",{terminalSessionId:x,renderDurationMs:Number((performance.now()-A).toFixed(2)),...bn(I)}),(P=u.current)==null||P.call(u),QS(T)}),!0}),k=W((j,R,I)=>{if(b.current+=1,I){C(()=>new Promise(T=>{const A=g.current;if(!A){I.commit(!1),T();return}A.write("",()=>w(j,R,{...I,commit:P=>{I.commit(P),T()}}))}));return}if(!t.current){n.current={data:j,modes:R},r.current="",s.current=!0,d.current=!1;return}w(j,R)}),D=W((j,R)=>{const I=XS(j);if(R){b.current+=1,I&&(c==null||c()),C(()=>new Promise(B=>{const M=g.current;if(!M||d.current){R.commit(!1),B();return}if(R.resizeMode==="ordered"&&R.cols&&R.rows){M.resize(R.cols,R.rows),R.commit(),B();return}k1(M)||h(!0),M.write(I,()=>{R.commit(),B()})}));return}if(!I)return;c==null||c(),b.current+=1;const T=Date.now();l.current+=1;const A=l.current;if($t("terminal.output.received",{terminalSessionId:x,seq:A,sinceLastInputMs:a.current===null?null:T-a.current,...bn(I)}),bh("terminal.output.received",I,{terminalSessionId:x,seq:A,sinceLastInputMs:a.current===null?null:T-a.current,...bn(I)}),!t.current){N(I);return}const P=g.current;if(!P)return;k1(P)||h(!0);const L=performance.now();P.write(I,()=>{const B=performance.now(),M=a.current===null?null:Date.now()-a.current;$t("terminal.output.rendered",{terminalSessionId:x,seq:A,sinceLastInputMs:M,renderDurationMs:Number((B-L).toFixed(2)),...bn(I)}),bh("terminal.output.rendered",I,{terminalSessionId:x,seq:A,sinceLastInputMs:M,renderDurationMs:Number((B-L).toFixed(2)),...bn(I)}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{const $=Number((performance.now()-B).toFixed(2)),U=a.current===null?null:Date.now()-a.current;bh("terminal.output.painted",I,{terminalSessionId:x,seq:A,sinceLastInputMs:U,paintDelayMs:$,...bn(I)})})})})});return{enqueueResize:S,onOutput:D,onSnapshot:k,renderTerminalSnapshot:w,replayDeferredOutput:E}}function Fse({active:e,apiBase:t,deferredSnapshotRef:r,hasDeferredOutputRef:n,hasRenderedSnapshotRef:s,onAuthExpiredRef:i,renderTerminalSnapshot:a,replayDeferredOutput:l,requiresSnapshotRestoreRef:c,restoreSnapshotRequestRef:u,terminalRef:d,terminalSessionId:h,tokenRef:f,websocketContentVersionRef:m}){p.useEffect(()=>{if(!e||!d.current)return;let g=!1;const v=u.current+1;u.current=v;const x=async b=>{var C;const _=m.current;try{const S=await _f(t,f.current,h);if(g||u.current!==v)return;if(m.current!==_){if(c.current&&b<2){await x(b+1);return}if(!c.current)return}a(S.scrollback)}catch(S){if(g)return;n.current=!0,c.current=!0,S instanceof De&&S.status===401&&((C=i.current)==null||C.call(i))}};return s.current&&!n.current&&!c.current?()=>{g=!0}:!c.current&&(s.current||r.current!==null)?l()?()=>{g=!0}:(n.current=!1,()=>{g=!0}):(x(0),()=>{g=!0})},[e,t,r,n,s,i,a,l,c,u,d,h,f,m])}function $se(e){var l,c;const t=tt(u=>u.completionMarkers[e.terminalSessionId]??0),r=Zn(),n=Math.max(t,((c=(l=r.data)==null?void 0:l.find(u=>u.terminalSessionId===e.terminalSessionId))==null?void 0:c.completionRevision)??0),s=p.useRef(""),i=p.useRef(!1),a=W(async()=>{var m;if(!e.active||!e.atBottom||!e.connected||!n||i.current||document.visibilityState!=="visible"||!document.hasFocus())return;const u=(m=e.terminalRef.current)==null?void 0:m.element;if(!u)return;const d=u.getBoundingClientRect();if(d.width<=0||d.height<=0)return;const h=document.elementFromPoint(d.left+d.width/2,d.top+d.height/2);if(!h||!u.contains(h))return;const f=JSON.stringify([e.apiBase,e.terminalSessionId,e.panelId,n]);if(s.current!==f){i.current=!0;try{await V6(e.apiBase,e.token,e.terminalSessionId,{completionRevision:n,panelIds:e.panelId?[e.panelId]:[]}),s.current=f}catch{}finally{i.current=!1}}});p.useEffect(()=>{if(!e.active||!e.atBottom||!e.connected||!n)return;const u=window.setInterval(()=>{a()},1e3);return()=>window.clearInterval(u)},[e.active,e.atBottom,e.connected,n,a])}function zse({active:e,obscured:t=!1,terminalSessionId:r,activeCommand:n=null,clientMode:s="desktop",layoutVersion:i="default",paneWorkspace:a=null,activePanelId:l=null,sessionStatus:c="running",terminalState:u,onResizePane:d,onViewportResize:h,onOpenFileLink:f}){const{apiBase:m,onAuthExpired:g,token:v}=vt(),x=NQ(r),b=p.useRef(null),_=p.useRef(null),C=Vt(Ke=>Ke.createBrowserTab),S=Vt(Ke=>Ke.openBrowser),w=Vt(Ke=>Ke.activeBrowserProfileId),y=xQ(e,r),N=Nj(Ke=>Ke.consumeInsertion),E=p.useRef(null),k=p.useRef(e),D=p.useRef(e&&!t),j=p.useRef(h),R=p.useRef(g),I=p.useRef(()=>{}),T=W((Ke,q,J)=>{var xe,Be,$e;if(!e||!f)return;const se=wg(Ke);if(!se){we("This file link is not supported on the connected backend");return}let fe;if(a&&a.panels.length>1){const He=(Be=(xe=_.current)==null?void 0:xe.element)==null?void 0:Be.querySelector(".xterm-screen"),Fe=He==null?void 0:He.getBoundingClientRect(),Ne=_.current;if(!Fe||!Ne)return;const Je=Math.floor((q.clientX-Fe.left)*Ne.cols/Fe.width),ze=Math.floor((q.clientY-Fe.top)*Ne.rows/Fe.height);if(fe=($e=a.panels.find(({geometry:rt})=>rt&&Je>=rt.paneLeft&&Je<rt.paneLeft+rt.paneWidth&&ze>=rt.paneTop&&ze<rt.paneTop+rt.paneHeight))==null?void 0:$e.panelId,!fe){we("Cannot determine the source terminal panel. Refresh the terminal and try again.");return}}f({...se,context:J},fe)}),A=p.useRef(a);A.current=a;const P=p.useRef(T),O=p.useRef(v),L=p.useRef(null),B=p.useRef(null),M=W(()=>{var Ke;return(Ke=B.current)==null?void 0:Ke.call(B)}),$=p.useRef(null),U=p.useRef(0),F=p.useRef(0),K=p.useRef(0),Y=p.useRef(null),te=p.useRef(null),H=p.useRef(null),G=p.useRef(!1),z=p.useRef(""),ee=p.useRef(null),V=p.useRef(null),re=p.useRef(!1),oe=p.useRef(!1),ce=p.useRef(0),be=p.useRef(0),ne=p.useRef(null),Te=p.useRef(()=>{}),Ve=p.useRef(()=>{}),[Ge,we]=p.useState(null),[de,he]=p.useState(!1),ge=qQ({active:e&&!t,clientMode:s,terminalRef:_}),Pe=jse({resetScrollInput:M,active:e,apiBase:m,runtimeKindRef:L,terminalRef:_,terminalSessionId:r,token:v}),Le=Pe.requestTmuxExitCopyMode,_e=Pe.tmuxScrollbackActive,{enqueueResize:et,onOutput:it,onSnapshot:ue,renderTerminalSnapshot:Ie,replayDeferredOutput:ye}=Bse({onLocalReset:()=>Ve.current(),activeRef:D,deferredOutputRef:z,deferredSnapshotRef:ee,hasDeferredOutputRef:G,hasRenderedSnapshotRef:oe,lastInputSentAtRef:Y,outputSequenceRef:F,onOutputReceived:()=>Te.current(),refreshTerminalViewportRef:E,requiresSnapshotRestoreRef:re,setHasNewOutputBelow:Pe.setHasNewOutputBelow,setTerminalAtBottom:Pe.setTerminalAtBottom,setTmuxScrollbackActive:Pe.setTmuxScrollbackActive,terminalRef:_,terminalFrameRef:V,terminalSessionId:r,websocketContentVersionRef:be});p.useLayoutEffect(()=>{D.current=e&&!t,e&&!t&&ye()},[e,t,ye]);const{invalidateOutputRecovery:ae,connectionStatus:le,error:je,notice:Me,failureSince:ot,lastCloseReason:ct,reconnectAttempt:yt,sendInput:Dt,sendResize:Ft,runtimeKind:Mt,singleRowScrollRef:Ze,orderedResizeRef:xt,terminalStatus:Ut}=UQ({apiBase:m,terminalSessionId:r,token:v,onAuthExpired:g,onSnapshot:ue,onOutput:it});Ve.current=ae,$se({apiBase:m,token:v,terminalSessionId:r,panelId:a==null?void 0:a.activePanelId,active:e&&!t,atBottom:Pe.terminalAtBottom&&!Pe.tmuxScrollbackActive&&!Pe.hasNewOutputBelow,connected:le==="connected",terminalRef:_});const fr=p.useMemo(()=>{const Ke=Date.now(),q=c==="exited"||Ut==="exited",J=q?"disabled":le==="connected"?"healthy":le==="closed"?"unhealthy":"recovering";return{id:`frontend.terminal.websocket:${r}`,capabilityId:"terminal",label:`Terminal ${r.slice(0,8)}`,state:J,summary:q?"Terminal 已正常退出":J==="healthy"?"Terminal WebSocket 已连接":J==="unhealthy"?ct||(yt>=Gc?"Terminal WebSocket 重试已耗尽":"Terminal WebSocket 已关闭"):"Terminal WebSocket 正在重连",observedAt:Ke,dependsOn:["frontend.node.http","frontend.node.auth"],recovery:J==="recovering"||J==="unhealthy"?{startedAt:ot??Ke,attempt:yt,maxAttempts:Gc,nextAttemptAt:null,deadlineAt:null}:null,facts:[],navigation:null}},[le,ot,ct,yt,Ut,c,r]);Kk(fr,fr.id);const dt=W(Ke=>{const q=performance.now(),J=te.current;if(J&&Ke===J.data&&q-J.at<=eT){if(J.forwarded)return;J.forwarded=!0}U.current+=1,Y.current=Date.now(),$t("terminal.input.captured",{terminalSessionId:r,seq:U.current,...bn(Ke)}),bh("terminal.input.captured",Ke,{terminalSessionId:r,seq:U.current,...bn(Ke)}),Dt(Ke)}),qe=Nse({active:e&&!t,activeCommand:n,apiBase:m,clientMode:s,error:je,paneWorkspace:a,searchOpen:ge.open,scroll:Pe,sessionStatus:c,terminalRef:_,terminalSessionId:r,terminalState:u,token:v});p.useEffect(()=>{Te.current=qe.handleOutputReceived},[qe.handleOutputReceived]),p.useLayoutEffect(()=>{var q,J;k.current=e;const Ke=(J=(q=_.current)==null?void 0:q.element)==null?void 0:J.querySelector(".xterm-rows:not([data-terminal-frame-overlay])");Ke!=null&&Ke.textContent&&(V.current=Ke.cloneNode(!0))},[e]),p.useEffect(()=>{j.current=h},[h]),p.useEffect(()=>{R.current=g},[g]),p.useEffect(()=>{I.current=Ke=>{var se,fe;if(((se=window.electronAPI)==null?void 0:se.isElectron)!==!0){Kc({url:Ke,placement:{kind:"new-group"}}).catch(()=>{});return}const q=Vt.getState().browser,J=q.tabs.find(xe=>xe.id===q.activeTabId);if(J&&((fe=window.electronAPI)!=null&&fe.terminalBrowserCreateTab)&&window.electronAPI.terminalBrowserGetWorkspace){window.electronAPI.terminalBrowserGetWorkspace(w).then(xe=>{const Be=xe.tabs.find($e=>$e.tabId===xe.activeTabId);return Kc({url:Ke,source:x,profileId:w,placement:Be?{kind:"current-group",groupId:Be.browserGroupId,openerTabId:Be.tabId}:{kind:"new-group"}})}).catch(xe=>{Vt.getState().updateBrowserTab(J.id,{error:xe instanceof Error?xe.message:"Failed to open browser link"})}).finally(S);return}else{const xe=zh(Ke);if(!xe.ok)return;C(xe.url)}S()}},[w,C,S,x]),p.useEffect(()=>{O.current=v},[v]),p.useEffect(()=>{L.current=Mt},[Mt]),zne({enqueueResize:et,orderedResizeRef:xt,activeRef:k,clientMode:s,imeCommitRef:te,imeCompositionEndedAtRef:H,lastResizedAtRef:$,lastSentResizeRef:ne,onBufferTypeChange:qe.setBufferType,onViewportResizeRef:j,onUserInputData:qe.handleUserInputData,onTextPaste:qe.textAttachments.capture,onRichPaste:qe.richPaste.capture,openTerminalLinkRef:I,openTerminalFileLinkRef:P,paneWorkspaceRef:A,refreshTerminalViewportRef:E,runtimeKindRef:L,singleRowScrollRef:Ze,resetScrollInputRef:B,searchAddonRef:ge.addonRef,sendResize:Ft,sendTerminalInput:dt,setPasteError:we,setSearchResults:ge.setResults,terminalContainerRef:b,terminalRef:_,terminalSessionId:r,xtermUserInputSequenceRef:K,onBottomStateChange:qe.handleBottomStateChange,onTmuxScrollbackActiveChange:qe.setTmuxScrollbackActive,onTmuxExitCopyModeRequest:qe.onTmuxExitCopyModeRequest});const Ht=qe.insertDraft;p.useEffect(()=>{if(!e||!y||vQ(y,(a==null?void 0:a.activePanelId)??l,Ht,N))return;if(!Bj({activeCommand:n,terminalState:u})){N(y.id);return}const Ke=_.current;if(!Ke)return;const q=()=>{Ke.paste(y.text),N(y.id)};if(L.current==="tmux"&&_e){Le();const J=window.setTimeout(q,320);return()=>window.clearTimeout(J)}q()},[e,n,l,N,Ht,a==null?void 0:a.activePanelId,y,Le,u,_e]),p.useEffect(()=>{if(!(!e||!_.current))return WQ(()=>{var Ke;!k.current||!_.current||(_.current.focus(),(Ke=E.current)==null||Ke.call(E))},{delayMs:ZA})},[e,i]),Fse({active:e,apiBase:m,deferredSnapshotRef:ee,hasDeferredOutputRef:G,hasRenderedSnapshotRef:oe,onAuthExpiredRef:R,renderTerminalSnapshot:Ie,replayDeferredOutput:ye,requiresSnapshotRestoreRef:re,restoreSnapshotRequestRef:ce,terminalRef:_,terminalSessionId:r,tokenRef:O,websocketContentVersionRef:be}),p.useEffect(()=>{e&&s==="mobile"||he(!1)},[e,s]);const Ce=e&&s!=="mobile",lt=e&&s==="mobile",Nt=e&&s!=="mobile"&&!!d;return o.jsx(nZ,{active:e,error:je??Ge,notice:Me,paneWorkspace:Nt?a:null,toolbar:Ce?o.jsx(ZQ,{inputRef:ge.inputRef,open:ge.open,query:ge.query,results:ge.results,options:ge.options,onQueryChange:ge.setQuery,onOptionsChange:ge.setOptions,onRunSearch:ge.run,onOpenChange:ge.setOpen,onCloseFocus:()=>{var Ke;return(Ke=_.current)==null?void 0:Ke.focus()}}):null,mobileControls:lt?o.jsx(QQ,{active:e,open:de,terminalRef:_,onOpenChange:he,onSendInput:dt}):null,controls:o.jsx(YQ,{diagnostics:qe.diagnostics,textAttachments:qe.textAttachments,richPaste:qe.richPaste,draft:qe.draft,sending:qe.sending,sendError:qe.sendError,hasNewOutputBelow:qe.hasNewOutputBelow,instantReplyAvailable:qe.instantReplyAvailable,instantReplyFeedback:qe.instantReplyFeedback,instantReplyOpen:qe.instantReplyOpen,scrollButtonMode:qe.scrollButtonMode,showTrigger:qe.showTrigger,terminalRef:_,visible:qe.visible,onClose:qe.onClose,onDraftChange:qe.onDraftChange,onInstantReplyClose:qe.onInstantReplyClose,onInstantReplyOpen:qe.onInstantReplyOpen,onInstantReplySend:qe.onInstantReplySend,onOpen:qe.onOpen,onScrollToBottom:qe.onScrollToBottom,onSend:qe.onSend,onQueue:qe.onQueue,queueKey:qe.queueKey}),terminalContainerRef:b,terminalRef:_,onResizePane:d})}function gv(e){return e.decisions.filter(t=>t.contextRevision===e.contextRevision&&(!t.threadId||t.threadId===e.target.threadId))}function Zce(e){var r,n;const t={completed:"任务已完成",blocked:"需要你处理",continue:"任务可以继续"}[e.outcome];return((r=e.assessment)==null?void 0:r.disposition)==="hold"&&e.assessment.holdReason==="background_wait"?"等待后台结果 · 本次不续接":((n=e.assessment)==null?void 0:n.disposition)==="hold"?`判断待核对 · 候选:${t}(未采用)`:e.assessment&&e.outcome==="completed"?"据报告完成":t}function Use(e){const r=[...e.split(/\r?\n\s*(?:\{|```)/,1)[0].trim()||e.trim()].slice(0,240).join("");return r.length<e.trim().length?`${r}…`:r}function eue(e,t,r,n,s){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goal-preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:s})}function tue(e,t,r,n){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goal-apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({previewId:n})})}function rue(e,t,r,n,s){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goals/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function Hse(e,t,r,n,s){const i=new URLSearchParams({terminalSessionId:r});return me(e,`/api/task-supervision?${i}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function nue(e,t,r){return me(e,"/api/task-supervision",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)})}function sue(e,t,r,n){return me(e,`/api/task-supervision/${encodeURIComponent(r)}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}function iue(e,t,r){return me(e,`/api/task-supervision/${encodeURIComponent(r)}`,{headers:{Authorization:`Bearer ${t}`}})}function oue(e,t,r,n,s){const i=new URLSearchParams(n?{cursor:n}:{});return me(e,`/api/task-supervision/${encodeURIComponent(r)}/decisions?${i}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function aue(e,t,r,n,s){return me(e,`/api/task-supervision/${encodeURIComponent(r)}/decisions/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function lue(e,t,r,n,s){const i=new URLSearchParams(n?{cursor:n}:{});return me(e,`/api/task-supervision/${encodeURIComponent(r)}/goals?${i}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function Wse(e,t=!1){const{apiBase:r,token:n,scope:s,onAuthExpired:i}=vt(),a=Ct({queryKey:["task-supervision",s,e],queryFn:({signal:l})=>Hse(r,n,e,null,l),enabled:e!==null,staleTime:4e3,refetchInterval:t?5e3:!1,refetchIntervalInBackground:!1,retry:!1});return p.useEffect(()=>{a.error instanceof De&&a.error.status===401&&(i==null||i())},[a.error,i]),a}function qse(e){var r,n,s;if(!e.enabled)return"监控已关闭";if(e.status==="watching"&&e.waitingFor)return e.waitingFor==="permission"?"等待你在原终端批准权限":"等待你在原终端回答问题";if(e.pauseReason==="continuation_limit")return"已达续接上限 · 任务仍未完成";if(e.pauseReason==="delivery_unknown")return"续接待确认";if(e.status==="error")return((r=gv(e).at(-1))==null?void 0:r.deliveryBlock)==="draft_unconfirmed"?"任务可以继续 · 自动续接未发送":"监听异常 / 上下文待补充";if(e.status==="paused")return"监控已暂停";if(e.goalState==="needs_review")return"目标待核对 · 暂不自动续接";if(e.goalState==="checking"&&!e.taskStartMessageId.startsWith("pending:"))return"正在核对任务目标";if(e.status==="classifying")return"正在判断任务状态";if(e.taskStartMessageId.startsWith("pending:"))return"等待新任务 · 终端监听已开启";const t=gv(e).at(-1);return(t==null?void 0:t.goalVersion)===((n=e.goalDefinition)==null?void 0:n.version)&&((s=t==null?void 0:t.assessment)==null?void 0:s.disposition)==="hold"?t.assessment.holdReason==="background_wait"?"等待后台结果 · 继续监听":"判断待核对 · 暂不自动续接":e.status==="watching"&&e.outcome==="completed"?t!=null&&t.assessment?"本轮据报告完成 · 继续监听此终端":"本轮任务已完成 · 继续监听此终端":e.status==="watching"&&e.outcome==="blocked"?"本轮需要你处理 · 继续监听此终端":e.status==="ended"?e.outcome==="completed"?"目标已达成":"需要你处理":"正在监听最终回复"}function Kse(e){return gv(e).some(t=>{var r,n;return t.goalVersion===((r=e.goalDefinition)==null?void 0:r.version)&&((n=t.assessment)==null?void 0:n.disposition)==="hold"&&t.assessment.holdReason!=="background_wait"})||e.goalState==="needs_review"||e.waitingFor!=null||e.status==="error"||e.status==="paused"||e.pauseReason==="continuation_limit"||e.pauseReason==="delivery_unknown"||e.outcome==="blocked"}function Vse({sessionId:e}){var u,d,h;const t=Wse(e,!0),r=W(()=>{Vt.getState().openTaskSupervision()}),n=(u=t.data)==null?void 0:u.watch;if(!(n!=null&&n.enabled))return null;const s=Kse(n)||t.isError,i=qse(n),a=Use(((d=n.goalDefinition)==null?void 0:d.objective)??n.goal)||((h=t.data)==null?void 0:h.threadTitle),l=[a,i].filter(Boolean).join(" · "),c=s?pa:gE;return o.jsxs("button",{type:"button","data-testid":"terminal-task-supervision-status-strip","aria-label":`查看长任务监控:${l}`,title:t.isError?`${l} · 状态暂时无法更新,显示上次结果`:l,onClick:r,className:`flex min-h-10 w-full shrink-0 items-center gap-2 border-b border-slate-800 px-3 py-2 text-left text-xs transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-emerald-400 ${s?"bg-amber-950/20 text-amber-300 hover:bg-amber-950/30":"bg-emerald-950/20 text-emerald-300 hover:bg-emerald-950/30"}`,children:[o.jsx(c,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),a?o.jsx("span",{className:"min-w-0 flex-1 truncate",children:a}):null,o.jsxs("span",{className:a?"shrink-0":"min-w-0 flex-1 truncate",children:[t.isError?"上次状态 · ":"",i]}),o.jsxs("span",{className:"shrink-0 text-[11px] opacity-80",children:[n.continuationCount,"/",n.continuationLimit," 次续接"]}),o.jsx(Jr,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"})]})}const Gse={requesting:"等待 Agent 结束当前轮次,请先不要操作页面",waiting:"Agent 等待协助:请处理页面,完成后交还",resume_pending:"已发送交还,等待 Agent 确认(不会自动重发)",acknowledged:"Agent 已确认交还,将重新观察页面;不代表任务已完成",cancelled:"已取消协助,Agent 不会自动恢复",expired:"协助请求已过期,请让 Agent 重新观察并请求",invalidated:"原 Agent、Panel 已改变或终端收到新输入,请重新请求协助",delivery_unknown:"交还投递结果不确定,请检查原终端;不会自动重发"},Yse=new Set(["acknowledged","cancelled","expired","invalidated"]);function Xse({sessionId:e}){const{apiBase:t,token:r,onAuthExpired:n}=vt(),[s,i]=p.useState([]),[a,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState([]),f=p.useRef(e);f.current=e;const m=W((_,C)=>{_ instanceof De&&_.status===401&&(n==null||n()),l({message:_ instanceof Error?_.message:"无法读取协助请求",requestId:C})});p.useEffect(()=>{var w;if(i([]),l(null),!e||!((w=window.electronAPI)!=null&&w.terminalBrowserResolveAssistanceTarget))return;const _=new AbortController;let C;const S=async()=>{try{const y=await aJ(t,r,e,_.signal);_.signal.aborted||i(y)}catch(y){_.signal.aborted||m(y)}finally{_.signal.aborted||(C=setTimeout(()=>void S(),2e3))}};return S(),()=>{_.abort(),clearTimeout(C)}},[t,r,e,m]);const g=W(async(_,C)=>{if(!(c||_.terminalSessionId!==f.current)){u(_.requestId),l(null);try{if(C!=="cancel"){const w=window.electronAPI;if(!(w!=null&&w.terminalBrowserResolveAssistanceTarget)||!w.terminalBrowserShow)throw new Error("当前桌面版本不支持浏览器协助");const y=await w.terminalBrowserResolveAssistanceTarget(_,C==="open");if(_.terminalSessionId!==f.current)return;if(C==="open"){if(y===null)return;await w.terminalBrowserShow(y),Vt.getState().activateBrowser(_.profileId,null);return}}const S=await lJ(t,r,_,C);_.terminalSessionId===f.current&&i(w=>w.map(y=>y.requestId===S.requestId?S:y))}catch(S){_.terminalSessionId===f.current&&m(S,_.requestId)}finally{u(null)}}}),v=new Map;for(const _ of s)v.set(_.panelId,_);const x=[...v.values()].filter(_=>!d.includes(_.requestId)),b=a&&(!a.requestId||x.some(_=>_.requestId===a.requestId))?a.message:null;return!x.length&&!b?null:o.jsxs("section",{"aria-label":"浏览器人工协助",className:"max-h-64 shrink-0 overflow-auto border-b border-amber-500/30 bg-amber-500/5 p-3 text-xs",children:[x.map(_=>o.jsxs("div",{className:"space-y-2 py-1","data-assistance-id":_.requestId,children:[o.jsx("p",{role:"status",className:"font-medium",children:Gse[_.state]}),o.jsx("p",{className:"whitespace-pre-wrap break-words",children:_.reason}),o.jsxs("p",{className:"text-muted-foreground",children:["Panel ",_.panelId.slice(0,8)," · ",_.profileId," ·"," ",_.requestId.slice(0,8)]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(Z,{size:"sm",variant:"outline",disabled:c!==null||_.state!=="waiting",onClick:()=>void g(_,"open"),children:"打开协助页面"}),o.jsx(Z,{size:"sm",disabled:c!==null||_.state!=="waiting",onClick:()=>void g(_,"resume"),children:"完成并交还 Agent"}),["requesting","waiting"].includes(_.state)?o.jsx(Z,{size:"sm",variant:"ghost",disabled:c!==null,onClick:()=>void g(_,"cancel"),children:"取消协助"}):null,Yse.has(_.state)?o.jsx(Z,{size:"sm",variant:"ghost",onClick:()=>h(C=>[...C,_.requestId]),children:"收起"}):null]})]},_.requestId)),b?o.jsx("p",{role:"alert",className:"mt-2 text-rose-400",children:b}):null]})}const Jse=p.lazy(()=>Vr(()=>import("./index-UR7g5PLZ.js").then(e=>e.bE),__vite__mapDeps([15,1,6,16])).then(e=>({default:e.TerminalPreviewPanel})));function Qse({clientMode:e,loading:t,panels:r,onEditProject:n,onCreateSession:s}){var be;const{apiBase:i,token:a,scope:l}=vt(),[c,u]=p.useState(null),d=p.useRef(0),h=_s(),f=Zn(),m=h.data??_o,g=f.data??bs,{activeProjectId:v,activeParentProjectId:x}=tt(An(ne=>({activeProjectId:ne.activeProjectId,activeParentProjectId:ne.activeParentProjectId}))),b=Hf(x).data??Uf,{activeSessionId:_,requestError:C,cachedSurfaceSessionIds:S,agentRecoveryRevisionBySessionId:w,terminalStateBySessionId:y,panelWorkspaceBySessionId:N,activePanelIdBySessionId:E}=tt(An(ne=>({activeSessionId:ne.activeSessionId,requestError:ne.requestError,cachedSurfaceSessionIds:ne.cachedSurfaceSessionIds,agentRecoveryRevisionBySessionId:ne.agentRecoveryRevisionBySessionId,terminalStateBySessionId:ne.terminalStateBySessionId,panelWorkspaceBySessionId:ne.panelWorkspaceBySessionId,activePanelIdBySessionId:ne.activePanelIdBySessionId}))),{previewOpen:k,previewWidthPx:D,previewExpanded:j}=Vt(An(ne=>({previewOpen:ne.ui.open,previewWidthPx:ne.ui.widthPx,previewExpanded:ne.ui.expanded}))),R=p.useRef(0);p.useEffect(()=>{var Te,Ve,Ge,we,de;if(((Te=window.electronAPI)==null?void 0:Te.isElectron)!==!0)return;const ne=he=>{const ge=R.current;if(R.current=he,ge===0&&he>0){const Pe=Vt.getState();Pe.ui.open||Pe.openAutomation()}};return(Ge=(Ve=window.electronAPI).terminalBrowserAutomationGetSnapshot)==null||Ge.call(Ve).then(he=>ne(he.connections.length)),(de=(we=window.electronAPI).onTerminalBrowserAutomationStateChanged)==null?void 0:de.call(we,he=>ne(he.connections.length))},[]);const I=e==="mobile",T=p.useMemo(()=>v?g.filter(ne=>ne.projectId===v):[],[v,g]),A=T.find(ne=>ne.terminalSessionId===_)??null,P=p.useMemo(()=>{const ne=new Set(S);return A&&ne.add(A.terminalSessionId),g.filter(Te=>ne.has(Te.terminalSessionId))},[A,S,g]),O=m.find(ne=>ne.projectId===x)??null,L=b.find(ne=>ne.projectId===v)??null,B=O&&L?{...O,projectId:L.projectId,name:L.name,path:L.path}:(O==null?void 0:O.projectId)===v?O:null,M=(c==null?void 0:c.scope)===l&&c.projectId===(B==null?void 0:B.projectId)&&c.terminalSessionId===(A==null?void 0:A.terminalSessionId)?c:null;p.useEffect(()=>{u(null)},[l,v,_]);const $=(A==null?void 0:A.panelSplitEnabled)??!1,U=A?N[A.terminalSessionId]??null:null,F=A?E[A.terminalSessionId]??(U==null?void 0:U.activePanelId)??A.activePanelId??null:null,K=(A==null?void 0:A.terminalSessionId)??null;p.useEffect(()=>{const ne=Vt.getState();ne.ui.activeTool==="conversation"&&ne.setConversationTarget(K?{scope:l,sessionId:K,panelId:F}:null)},[l,K,F]);const Y=Cj(_,F,!I),te=Y.visible&&!I,H=(be=Y.state.snapshot)==null?void 0:be.sourceStatus,G=H==="running"?"执行中":H==="idle"?"等待输入":H==="unavailable"?"原主会话不可用":"状态待确认",z=D?`${D}px`:a8,ee=I?"mobile":`desktop:${k?z:"full"}:${$?"panel-split":"single"}`,V=C??(h.error??f.error?String(h.error??f.error):null),{onPanelWorkspaceChange:re,onRefreshPanelWorkspace:oe,onResizePanel:ce}=r;return o.jsxs("div",{className:"min-h-0 min-w-0 flex-1",children:[V?o.jsx("p",{className:"border-b border-rose-900/60 bg-rose-950/30 px-3 py-1.5 text-xs text-rose-300",children:V}):null,o.jsxs("div",{className:"relative flex h-full min-h-0",children:[o.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[I?null:o.jsx(lQ,{sessionId:(A==null?void 0:A.terminalSessionId)??null}),I?null:o.jsx(Vse,{sessionId:(A==null?void 0:A.terminalSessionId)??null}),I?null:o.jsx(Xse,{sessionId:_}),A!=null&&A.tmuxSessionName&&!I&&$?o.jsx(mQ,{apiBase:i,token:a,activeSession:A,workspace:U,onWorkspaceChange:re}):null,o.jsx("div",{className:"relative min-h-0 flex-1",children:T.length>0?o.jsx(o.Fragment,{children:P.map(ne=>{var Ve;const Te=ne.terminalSessionId===(A==null?void 0:A.terminalSessionId);return o.jsx("div",{"aria-hidden":!Te||te,inert:Te&&te?!0:void 0,className:["absolute top-0 h-full w-full isolate",Te?"left-0":"-left-[9999em] pointer-events-none"].join(" "),children:o.jsx(zse,{onOpenFileLink:(Ge,we)=>{!Te||!B||(u({...Ge,panelId:we,id:++d.current,scope:l,projectId:B.projectId,terminalSessionId:ne.terminalSessionId}),Vt.getState().openPreview(B.projectId))},active:Te,obscured:Te&&te,activeCommand:ne.activeCommand,clientMode:e,layoutVersion:ee,sessionStatus:ne.status,terminalSessionId:ne.terminalSessionId,terminalState:y[ne.terminalSessionId]??ne.terminalState,paneWorkspace:N[ne.terminalSessionId]??null,activePanelId:E[ne.terminalSessionId]??ne.activePanelId??null,onResizePane:!I&&ne.panelSplitEnabled?(Ge,we,de)=>{ce(ne.terminalSessionId,Ge,we,de)}:void 0,onViewportResize:ne.panelSplitEnabled||(((Ve=N[ne.terminalSessionId])==null?void 0:Ve.panels.length)??ne.panelCount??1)>1?()=>{oe(ne.terminalSessionId)}:void 0})},`${i}:${ne.terminalSessionId}:surface:${w[ne.terminalSessionId]??0}`)})}):o.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-sm text-slate-400",children:[o.jsx("p",{children:"No terminal tab yet. Create one to start."}),I?o.jsx(Z,{type:"button",onClick:s,disabled:t,children:"新建终端"}):null]})}),te&&A?o.jsx(fQ,{model:Y.model,title:Ol({alias:A.alias,cwd:A.cwd,activeCommand:A.activeCommand}),mainStatus:G}):null]}),k&&!I?o.jsxs(o.Fragment,{children:[j?o.jsx("div",{"aria-hidden":"true",className:"min-h-0 shrink-0",style:{width:z}}):null,o.jsx("div",{className:j?"absolute inset-0 z-40":"h-full min-h-0 shrink-0",children:o.jsx(p.Suspense,{fallback:o.jsx("aside",{className:"flex h-full items-center justify-center bg-slate-950 text-sm text-slate-400",style:{width:z},children:"Loading preview..."}),children:o.jsx(Jse,{fileLinkIntent:M,onFileLinkDone:()=>u(null),activeProject:B,activeSession:A,activePanelId:F,widthPx:D,onEditProject:n})})})]}):null]})]})}function lc(e){return{...e,details:e.details?{...e.details}:void 0}}class Zse{constructor(){St(this,"bufferedLogs",[]);St(this,"result",null);St(this,"status","ready")}getStatus(){return this.status}isRecording(){return this.status==="recording"}start(){this.bufferedLogs.length=0,this.result=null,this.status="recording"}append(t){this.isRecording()&&this.bufferedLogs.push(lc(t))}getBufferedLogs(){return[...this.bufferedLogs.map(lc),...iE()]}finish(t){this.bufferedLogs.length=0,this.result={...t,logs:t.logs.map(lc),redactionReport:t.redactionReport?{...t.redactionReport}:void 0,files:t.files?{...t.files}:void 0},this.status="ended"}setStatus(t){this.status=t}setResult(t){this.result=t?{...t,logs:t.logs.map(lc),redactionReport:t.redactionReport?{...t.redactionReport}:void 0,files:t.files?{...t.files}:void 0}:null,this.status=t?"ended":"ready"}getResult(){return this.result?{...this.result,logs:this.result.logs.map(lc),redactionReport:this.result.redactionReport?{...this.result.redactionReport}:void 0,files:this.result.files?{...this.result.files}:void 0}:null}clear(){this.bufferedLogs.length=0,this.result=null,this.status="ready"}}function eie({recorder:e,source:t,consoleLog:r=console.log}){return(n,s)=>{r(n,s),e.isRecording()&&e.append({at:new Date().toISOString(),source:t,message:n,details:s})}}function tie(e){return e?e.logs.map(t=>{const r=t.source?` [${t.source}]`:"",n=t.details?` ${JSON.stringify(t.details)}`:"";return`${t.at}${r} ${t.message}${n}`}).join(`
|
|
705
705
|
`):""}const zn=new Zse,a0=eie({recorder:zn,source:"frontend"});function nd(e){return{Authorization:`Bearer ${e}`}}async function rie(e,t){return me(e,"/api/diagnostic-logs/status",{headers:nd(t)})}async function ZS(e,t){return me(e,"/api/diagnostic-logs/start",{method:"POST",headers:nd(t)})}async function nie(e,t,r){return me(e,"/api/diagnostic-logs/stop",{method:"POST",headers:{"Content-Type":"application/json",...nd(t)},body:JSON.stringify({frontendLogs:r})})}async function sie(e,t){return me(e,"/api/diagnostic-logs/result",{headers:nd(t)})}async function iie(e,t){return zv(e,"/api/diagnostic-logs/download",{method:"POST",headers:nd(t)})}function oie(e){switch(e){case"recording":return"记录中";case"ended":return"已结束";case"ready":return"可记录"}}function aie(e){switch(e){case"recording":return"正在记录本轮复现窗口内的 AI 诊断日志。";case"ended":return"再次开始会清空上一轮结果和临时文件。";case"ready":return"只收集 AI 诊断日志工具函数写入的内容。"}}function e2(e){var t,r;return((t=e==null?void 0:e.files)==null?void 0:t.logsJsonl)??((r=e==null?void 0:e.files)==null?void 0:r.dir)??null}function l0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:new Date(t)}function t2(e){const t=window.URL.createObjectURL(e),r=document.createElement("a");r.href=t,r.download="diagnostic-logs.jsonl",document.body.append(r),r.click(),r.remove(),window.URL.revokeObjectURL(t)}function cc(e,t){const r=t instanceof Error?t.message:"";return r.includes("Failed to fetch")||r.includes("NetworkError")||r.includes("Load failed")?`${e}失败:后端不可用`:r?`${e}失败:${r}`:`${e}失败`}function lie({embedded:e=!1,apiBase:t,token:r,open:n,onOpenChange:s}){const[i,a]=p.useState(zn.getStatus()),[l,c]=p.useState(zn.getResult()),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,g]=p.useState(null),[v,x]=p.useState(!1),b=p.useMemo(()=>tie(l),[l]),_=p.useMemo(()=>e2(l),[l]),C=m!==null;p.useEffect(()=>{if(v){const L=window.setTimeout(()=>x(!1),1600);return()=>window.clearTimeout(L)}},[v]);const S=W(()=>{a(zn.getStatus()),c(zn.getResult())}),w=W(async()=>{g("refresh"),f(null);try{const[L,B]=await Promise.all([rie(t,r),sie(t,r)]);if(L.status==="recording"){zn.isRecording()||zn.start(),a("recording"),c(null),d(l0(L.startedAt));return}d(null),zn.setResult(B),S()}catch(L){f(cc("加载诊断日志",L))}finally{g(null)}});p.useEffect(()=>{n&&w()},[w,n]);const y=W(async()=>{g("start"),f(null),x(!1);try{const L=await ZS(t,r);zn.start(),a0("diagnostic recording started",{trigger:"terminal_more_menu"}),a(L.status),c(null),d(l0(L.startedAt)??new Date)}catch(L){f(cc("开始记录",L))}finally{g(null)}}),N=W(async()=>{g("stop"),f(null),x(!1);try{a0("diagnostic recording stopping",{trigger:"terminal_more_menu"});const L=await nie(t,r,zn.getBufferedLogs());zn.finish(L),d(null),S(),s(!0),f(e2(L)?"已结束记录并上报。":null)}catch(L){f(cc("结束并上报",L))}finally{g(null)}}),E=W(async()=>{g("download"),f(null);try{const L=await iie(t,r);t2(L)}catch(L){f(cc("下载日志",L))}finally{g(null)}}),k=W(async()=>{g("start"),f(null),x(!1);try{const L=await ZS(t,r);zn.start(),a0("diagnostic recording restarted",{trigger:"terminal_more_menu"}),a(L.status),c(null),d(l0(L.startedAt)??new Date)}catch(L){f(cc("重新开始",L))}finally{g(null)}}),D=W(async()=>{var L;await((L=navigator.clipboard)==null?void 0:L.writeText(b)),x(!0)}),j=W(async()=>{_&&(await navigator.clipboard.writeText(_),x(!0))}),R=o.jsx("span",{className:Xe("shrink-0 rounded-md bg-muted px-2 py-0.5 text-xs font-semibold text-muted-foreground",i==="recording"?"bg-primary/15 text-primary":i==="ended"?"bg-muted text-primary":""),children:oie(i)}),I=u?u.toLocaleString():null;va(!1,e&&C&&m!=="refresh");const T=e?"section":dx,A=e?"h2":Ur,P=e?"p":Zr,O=o.jsxs(T,{className:e?"flex flex-col gap-4 rounded-xl border p-5":"fixed top-[50%] left-[50%] z-50 flex max-h-[84vh] w-[min(48rem,calc(100vw-2rem))] translate-x-[-50%] translate-y-[-50%] flex-col gap-4 rounded-md border border-border bg-background p-4 shadow-xl",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(A,{className:"text-lg font-semibold",children:"日志上报"}),R]}),o.jsx(P,{className:"max-w-2xl text-sm leading-6 text-muted-foreground",children:"开始记录后复现问题,结束时会把本轮 Web 与服务端诊断日志保存到服务端目录。"})]}),!e&&o.jsx(nB,{asChild:!0,children:o.jsx(Z,{type:"button",variant:"secondary",size:"sm",children:"关闭"})})]}),o.jsxs("div",{className:"flex flex-col gap-3 rounded-md border border-border/70 bg-muted/20 p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0 text-sm",children:[o.jsx("p",{className:"font-medium text-foreground",children:aie(i)}),I?o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["记录开始时间:",I]}):null]}),i==="recording"?o.jsx(Z,{type:"button",onClick:N,disabled:C,className:"shrink-0",children:m==="stop"?"上报中...":"结束并上报"}):o.jsx(Z,{type:"button",onClick:i==="ended"?k:y,disabled:C,className:"shrink-0",children:m==="start"?"开始中...":"开始记录"})]}),h?o.jsx("p",{className:"text-sm text-muted-foreground",children:h}):null]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(Z,{type:"button",variant:"outline",onClick:()=>{const L=iE();t2(new Blob([JSON.stringify({logs:L,persistenceFailed:W6()},null,2)],{type:"application/json"}))},children:"导出最近操作诊断"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:"保留最近关键操作,不含输入正文。"})]}),l?o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[o.jsxs("div",{className:"text-sm text-muted-foreground",children:["本轮日志 ",l.logs.length," 条"]}),o.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[o.jsx(Z,{type:"button",variant:"secondary",size:"sm",onClick:E,disabled:C,children:"下载日志"}),o.jsx(Z,{type:"button",variant:"secondary",size:"sm",onClick:D,disabled:!b,children:"复制日志正文"})]})]}),o.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border/70 p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsx("span",{className:"text-sm font-medium",children:"服务端日志文件"}),o.jsx(Z,{type:"button",size:"sm",onClick:j,disabled:!_,children:v&&_?"已复制":"复制日志路径"})]}),_?o.jsx("code",{className:"break-all rounded-md bg-muted px-2 py-1.5 text-xs text-foreground",children:_}):o.jsx("p",{className:"text-sm text-muted-foreground",children:"已结束记录,但未返回服务端日志路径。"})]}),o.jsx("textarea",{className:"min-h-[14rem] resize-y rounded-md border border-border bg-muted/40 p-3 font-mono text-xs text-foreground outline-none focus:border-primary",readOnly:!0,value:b,"aria-label":"Diagnostic log text"})]}):null]});return e?O:o.jsx(Qr,{open:n,onOpenChange:s,children:o.jsxs(Pk,{children:[o.jsx(ux,{className:"fixed inset-0 z-50 bg-black/45 backdrop-blur-sm"}),O]})})}function cie(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function uie({open:e,target:t,title:r,onOpenChange:n}){const{apiBase:s,onAuthExpired:i,token:a}=vt(),{lastThreadId:l,lastThreadProvider:c,lastThreadStatus:u,panelId:d,panelLastThreadId:h,panelLastThreadProvider:f,panelLastThreadStatus:m,panelThreadId:g,panelThreadProvider:v,projectId:x,sessionId:b,threadId:_,threadProvider:C}=t,S=p.useRef(null),w=p.useRef(0),[y,N]=p.useState(null),[E,k]=p.useState(!1),[D,j]=p.useState(null),[R,I]=p.useState(null),[T,A]=p.useState(!1),P=W(async $=>{if(!e||!b)return;const U=w.current+1;w.current=U,$&&(N(null),I(null)),k(!0),j(null);try{const F=d?await ZC(s,a,b,d):await G6(s,a,b);if(w.current!==U)return;N(F),I(Date.now())}catch(F){if(w.current!==U)return;if(F instanceof De&&F.status===401){i==null||i();return}j(String(F))}finally{w.current===U&&k(!1)}});p.useEffect(()=>{if(!e||!b){w.current+=1;return}return P(!0),()=>{w.current+=1}},[s,P,e,d,b,a]);const O=W($=>{$||A(!1),n($)}),L=r??(y?Ol({alias:y.alias,cwd:y.cwd,activeCommand:y.activeCommand}):"Current terminal"),B=p.useMemo(()=>y?`${y.status==="exited"?y.exitCode==null?"Exited":`Exited (${y.exitCode})`:"Running"} ${y.cwd}`:b||"No terminal selected",[y,b]),M=p.useMemo(()=>[{label:"Project ID",value:(y==null?void 0:y.projectId)??x??null},{label:"Terminal ID",value:(y==null?void 0:y.terminalSessionId)??b},{label:"Thread ID",value:(y==null?void 0:y.threadId)??_??null},{label:"Thread Provider",value:(y==null?void 0:y.threadProvider)??C??null},{label:"Recent Thread",value:(y==null?void 0:y.lastThreadId)??l??null},{label:"Recent Thread Provider",value:(y==null?void 0:y.lastThreadProvider)??c??null},{label:"Recent Thread State",value:(y==null?void 0:y.lastThreadStatus)??u??null},{label:"Panel ID",value:d??null},{label:"Panel Thread",value:g??null},{label:"Panel Thread Provider",value:v??null},{label:"Panel Recent Thread",value:h??null},{label:"Panel Recent Thread Provider",value:f??null},{label:"Panel Recent State",value:m??null}],[y==null?void 0:y.lastThreadId,y==null?void 0:y.lastThreadProvider,y==null?void 0:y.lastThreadStatus,y==null?void 0:y.projectId,y==null?void 0:y.terminalSessionId,y==null?void 0:y.threadId,y==null?void 0:y.threadProvider,l,c,u,d,h,f,m,g,v,x,b,_,C]);return p.useEffect(()=>{const $=S.current;if(!e||!$)return;const U=QA,F=new $j,K=new oA;let Y=null;const te=new JA({allowProposedApi:!0,disableStdin:!0,cursorBlink:!1,fontFamily:U.fontFamily,fontSize:U.fontSize,lineHeight:1.2,screenReaderMode:U.screenReaderMode,scrollback:Math.max(Fj,uH((y==null?void 0:y.scrollback)??"")+16),theme:{background:"#0b1220",foreground:"#e2e8f0",cursor:"#f8fafc",selectionBackground:"rgba(148, 163, 184, 0.28)"}});te.loadAddon(F),te.loadAddon(K);try{Y=new Tne.CanvasAddon,te.loadAddon(Y)}catch{Y=null}te.open($),te.unicode.activeVersion="11";const H=()=>{hH({terminal:te,fitAddon:F,sourceCols:y==null?void 0:y.scrollbackSourceCols})};fH({terminal:te,output:(y==null?void 0:y.scrollback)??"",syncSize:H});let G=requestAnimationFrame(()=>{G=null,H()}),z=null;typeof ResizeObserver<"u"?(z=new ResizeObserver(()=>{H()}),z.observe($)):window.addEventListener("resize",H);const ee=()=>{document.visibilityState==="visible"&&H()};return document.addEventListener("visibilitychange",ee),window.addEventListener("focus",ee),()=>{G!==null&&cancelAnimationFrame(G),z?z.disconnect():window.removeEventListener("resize",H),document.removeEventListener("visibilitychange",ee),window.removeEventListener("focus",ee),Y==null||Y.dispose(),te.dispose()}},[y==null?void 0:y.scrollback,y==null?void 0:y.scrollbackSourceCols,e,d,b]),o.jsx(Pu,{modal:!1,open:e,onOpenChange:O,children:o.jsxs(Il,{side:"right",showOverlay:!1,className:Xe("flex h-dvh max-w-none flex-col gap-0 rounded-none border-l border-slate-800 bg-slate-950 p-0 text-slate-100",T?"w-screen border-l-0":"w-[min(64rem,100vw)]"),onCloseAutoFocus:$=>{$.preventDefault()},onOpenAutoFocus:$=>{$.preventDefault()},onInteractOutside:$=>{$.preventDefault()},onFocusOutside:$=>{$.preventDefault()},children:[o.jsxs(Ff,{className:"border-b border-slate-800 px-3 py-2",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2 pr-10",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(Nl,{className:"truncate text-sm text-slate-100",children:"Copy terminal output"}),o.jsxs(Rl,{className:"truncate text-[11px] text-slate-400",children:[L," · ",B]})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(Z,{type:"button",size:"sm",variant:"ghost",className:"size-7 rounded-md p-0 text-slate-400 hover:text-slate-100",disabled:E||!b,onClick:()=>{P(!1)},"aria-label":"Refresh terminal output snapshot",title:"Refresh snapshot (clears the current selection)",children:o.jsx(Ws,{className:Xe(E&&"animate-spin")})}),o.jsx(Z,{type:"button",size:"sm",variant:"ghost",className:"size-7 rounded-md p-0 text-slate-400 hover:text-slate-100",onClick:()=>{A($=>!$)},"aria-label":T?"Restore drawer width":"Expand drawer","aria-pressed":T,title:T?"Restore drawer width":"Expand drawer",children:T?o.jsx(AM,{}):o.jsx(wM,{})})]})]}),o.jsxs("details",{className:"text-[11px] text-slate-400",children:[o.jsx("summary",{className:"cursor-pointer select-none hover:text-slate-200",children:"Terminal details"}),o.jsx("div",{className:"grid grid-cols-1 gap-1 pt-1 sm:grid-cols-2",children:M.map($=>o.jsx(die,{label:$.label,value:$.value},$.label))})]})]}),D?o.jsx("p",{className:"border-b border-slate-800 px-3 py-1.5 text-xs text-rose-400",children:D}):null,E?o.jsx("p",{className:"border-b border-slate-800 px-3 py-1.5 text-xs text-slate-400","aria-live":"polite",children:y?"Refreshing snapshot...":"Loading snapshot..."}):null,o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-1 border-b border-slate-800 px-3 py-1.5 text-[11px] text-slate-400",children:[o.jsx("span",{children:"Drag to select. Keep dragging past the top or bottom edge to scroll."}),o.jsx("span",{"aria-live":"polite",children:R?`Snapshot ${cie(R)}`:"Snapshot not loaded"})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden p-2",children:o.jsx("div",{ref:S,"aria-label":"Terminal output snapshot",className:"h-full min-h-full w-full overflow-x-auto overflow-y-hidden border border-slate-800 bg-[#0b1220] px-1 py-1"})})]})})}function die({label:e,value:t}){const r=(t==null?void 0:t.trim())||"-",n=r!=="-",s=async()=>{var i;!n||!((i=navigator.clipboard)!=null&&i.writeText)||await navigator.clipboard.writeText(r)};return o.jsxs("div",{className:"grid min-w-0 grid-cols-[5.75rem_minmax(0,1fr)] items-center gap-2",children:[o.jsx("span",{className:"text-slate-500",children:e}),o.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-slate-200",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:r}),n?o.jsx("button",{type:"button","aria-label":`Copy ${e}`,title:`Copy ${e}`,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-slate-500 transition-colors hover:bg-slate-800 hover:text-slate-100",onClick:i=>{i.preventDefault(),i.stopPropagation(),s()},children:o.jsx(go,{className:"h-3 w-3"})}):null]})]})}function hie({open:e,mode:t,loading:r,error:n,canSelectDirectory:s,initialName:i="",initialPath:a="",initialMainBranch:l="",onClose:c,onSubmit:u}){var R;const[d,h]=p.useState(i),[f,m]=p.useState(a??""),[g,v]=p.useState(l??""),[x,b]=p.useState(t==="edit"),[_,C]=p.useState(!1),[S,w]=p.useState(null),y=p.useRef(0),N=s&&((R=window.electronAPI)!=null&&R.isElectron)?window.electronAPI.selectProjectDirectory:void 0,E=r||_,k=hr(void 0,"window");p.useEffect(()=>{if(e)return h(i),m(a??""),v(l??""),b(t==="edit"),C(!1),w(null),()=>{y.current+=1}},[i,a,l,t,e]);const D=W(async()=>{var T;if(!N||E)return;const I=++y.current;C(!0),w(null);try{const A=await N(f);if(I!==y.current||A===null)return;if(m(A),!x||!d.trim()){const P=((T=window.electronAPI)==null?void 0:T.platform)==="win32"?/[\\/]/:"/";h(A.split(P).filter(Boolean).at(-1)??A),b(!1)}}catch(A){I===y.current&&w(A instanceof Error?A.message:String(A))}finally{I===y.current&&C(!1)}});if(!e)return null;const j=async()=>{E||(w(null),await u(d,f,g))};return o.jsx("div",{ref:k,className:"fixed inset-0 z-50 flex items-center justify-center bg-black/45 px-4",children:o.jsxs("section",{className:"w-full max-w-md rounded-[1.75rem] border border-slate-800/80 bg-slate-950 p-6 shadow-[0_34px_120px_-72px_rgba(15,23,42,0.92)]",children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold text-slate-100",children:t==="create"?"Create Project":"Edit Project"}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:t==="create"?"Create a project bucket above your terminal tabs.":"Update the name, project path or main branch for this terminal project."})]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"rounded-full px-3 text-slate-300",onClick:c,disabled:E,children:"Close"})]}),o.jsxs("div",{className:"mt-6 space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-slate-500",htmlFor:"terminal-project-path",children:"Project Path"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{id:"terminal-project-path",value:f,placeholder:"/path/to/project",disabled:E,onChange:I=>m(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),j())},className:"h-12 min-w-0 flex-1 rounded-[1.25rem] border border-slate-800 bg-slate-900/80 px-4 text-sm text-slate-100 outline-none transition focus:border-slate-500"}),N?o.jsx(Z,{variant:"outline",className:"h-12 shrink-0 rounded-[1.25rem] px-3",disabled:E,onClick:()=>{D()},children:_?"Selecting...":"Select Folder…"}):null]}),o.jsx("p",{className:"text-xs text-slate-500",children:"Optional. Preview uses this path as its file root."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-slate-500",htmlFor:"terminal-project-name",children:"Project Name"}),o.jsx("input",{id:"terminal-project-name",value:d,disabled:E,onChange:I=>{h(I.target.value),b(!0)},onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),j())},className:"h-12 w-full rounded-[1.25rem] border border-slate-800 bg-slate-900/80 px-4 text-sm text-slate-100 outline-none transition focus:border-slate-500"})]}),t==="edit"?o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-xs uppercase tracking-[0.24em] text-slate-500",htmlFor:"terminal-project-main-branch",children:"主分支"}),o.jsx("input",{id:"terminal-project-main-branch",value:g,placeholder:"默认分支(自动识别)",disabled:E,onChange:I=>v(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),j())},"aria-describedby":"terminal-project-main-branch-help",className:"h-12 w-full rounded-[1.25rem] border border-slate-800 bg-slate-900/80 px-4 text-sm text-slate-100 outline-none transition focus:border-slate-500"}),o.jsx("p",{id:"terminal-project-main-branch-help",className:"text-xs text-slate-500",children:"留空使用远端默认分支。填写分支名(如 release/next),用于关注列表和 Worktree 的差异比较。"})]}):null,S||n?o.jsx("p",{className:"text-sm text-rose-400",role:"alert",children:S||n}):null,o.jsx(Z,{className:"h-12 w-full rounded-full text-sm",disabled:E,onClick:()=>{j()},children:r?t==="create"?"Creating...":"Saving...":t==="create"?"Create Project":"Save Project"})]})]})})}function gT(e){return{Authorization:`Bearer ${e}`}}async function fie(e,t,r){const n=new URLSearchParams;return r.projectId&&n.set("projectId",r.projectId),r.terminalSessionId&&n.set("terminalSessionId",r.terminalSessionId),r.terminalPanelId&&n.set("terminalPanelId",r.terminalPanelId),r.agent&&n.set("agent",r.agent),r.status&&n.set("status",r.status),r.after&&n.set("after",r.after),n.set("limit",String(r.limit)),me(e,`/api/app-server/threads?${n.toString()}`,{headers:gT(t)})}async function pie(e,t,r){return me(e,`/api/app-server/threads/${encodeURIComponent(r)}`,{headers:gT(t)})}const r2={running:0,starting:1,failed:2,idle:3,completed:4,unknown:5},mie=[{label:"status",read:e=>e.status},{label:"threadId",read:e=>e.threadId},{label:"agent",read:e=>e.agent},{label:"identityStatus",read:e=>e.identityStatus},{label:"lifecycleStatus",read:e=>e.lifecycleStatus},{label:"lastLifecycleType",read:e=>e.lastLifecycleType},{label:"lastLifecycleCursor",read:e=>e.lastLifecycleCursor},{label:"terminalSessionId",read:e=>e.terminalSessionId},{label:"terminalPanelId",read:e=>e.terminalPanelId},{label:"projectId",read:e=>e.projectId},{label:"runId",read:e=>e.runId},{label:"lastEventId",read:e=>e.lastEventId},{label:"lastHookEvent",read:e=>e.lastHookEvent},{label:"lastCompletionReason",read:e=>e.lastCompletionReason},{label:"updatedAt",read:e=>e.updatedAt},{label:"cwd",read:e=>e.cwd},{label:"sourceInstanceId",read:e=>e.sourceInstanceId}];function gie(e,t){const r=r2[e.status]-r2[t.status];return r!==0?r:n2(t.updatedAt)-n2(e.updatedAt)}function n2(e){if(!e)return 0;const t=Date.parse(e);return Number.isNaN(t)?0:t}function Nn(e){return e??"null"}function vie(e){return`${e.status} ${e.agent} ${e.threadId} panel=${Nn(e.terminalPanelId)} updatedAt=${e.updatedAt}`}function xie(e,t){const r=["请帮我排查这个 Runweave App Server thread 当前状态:",`threadId: ${e.threadId}`,`agent: ${e.agent}`,`status: ${e.status}`,`projectId: ${Nn(e.projectId)}`,`terminalSessionId: ${Nn(e.terminalSessionId)}`,`terminalPanelId: ${Nn(e.terminalPanelId)}`,`runId: ${Nn(e.runId)}`,`cwd: ${Nn(e.cwd)}`,`lastEventId: ${e.lastEventId}`,`lastHookEvent: ${Nn(e.lastHookEvent)}`,`lastCompletionReason: ${Nn(e.lastCompletionReason)}`,`updatedAt: ${e.updatedAt}`,"","请优先读取 App Server projection/latest thread 状态和相关 JSONL 事件,再判断是否需要继续查终端、hook 或日志。"];return t.length>1&&r.push("",`同一个 terminalSessionId 下命中了 ${t.length} 条 ThreadRef:`,...t.map(n=>`- ${vie(n)}`)),r.join(`
|
|
706
706
|
`)}function bie(e,t){if(t instanceof De)return t.status===404?"未找到该 thread":t.status===503?"App Server 不可用":`${e}失败:${t.message}`;const r=t instanceof Error?t.message:"";return r.includes("Failed to fetch")||r.includes("NetworkError")||r.includes("Load failed")?`${e}失败:后端不可用`:r?`${e}失败:${r}`:`${e}失败`}function _ie({apiBase:e,token:t,open:r,onOpenChange:n,activeProjectId:s,activeSessionId:i,activePanelId:a}){const l=p.useRef(null),[c,u]=p.useState("terminal"),[d,h]=p.useState(""),[f,m]=p.useState(""),[g,v]=p.useState([]),[x,b]=p.useState(null),[_,C]=p.useState(!1),[S,w]=p.useState(null),[y,N]=p.useState(!1),[E,k]=p.useState(null),D=p.useMemo(()=>g.find(P=>P.threadId===x)??null,[x,g]),j=p.useMemo(()=>D?xie(D,g):"",[D,g]);p.useEffect(()=>{r&&(u("terminal"),h(""),m(i??""),v([]),b(null),w(null),N(!1),k(null),window.setTimeout(()=>{var P;return(P=l.current)==null?void 0:P.focus()},0))},[i,r]),p.useEffect(()=>{if(!y)return;const P=window.setTimeout(()=>N(!1),1600);return()=>window.clearTimeout(P)},[y]);const R=W(async()=>{var O;const P=c==="thread"?d.trim():f.trim();if(N(!1),k(null),!P){v([]),b(null),w(c==="thread"?"请输入 Thread ID":"请输入 Terminal ID");return}C(!0),w(null);try{if(c==="thread"){const M=await pie(e,t,P);v([M.thread]),b(M.thread.threadId);return}const B=[...(await fie(e,t,{terminalSessionId:P,limit:100})).threads].sort(gie);v(B),b(((O=B[0])==null?void 0:O.threadId)??null),B.length===0&&w("未找到该 terminal 的 ThreadRef")}catch(L){v([]),b(null),w(bie("查询状态",L))}finally{C(!1)}}),I=W(async()=>{if(j)try{await navigator.clipboard.writeText(j),N(!0),k(null)}catch{k(j),w("复制失败,请手动选择下方文本。")}}),T=W(P=>{u(P),v([]),b(null),w(null),N(!1),k(null),window.setTimeout(()=>{var O;return(O=l.current)==null?void 0:O.focus()},0)}),A=W(P=>{P.key==="Enter"&&(P.preventDefault(),R())});return o.jsx(Qr,{open:r,onOpenChange:n,children:o.jsxs(dn,{className:"max-h-[86vh] max-w-3xl overflow-hidden border-slate-800 bg-slate-950 text-slate-100",children:[o.jsxs(Mn,{children:[o.jsx(Ur,{children:"状态查询"}),o.jsx(Zr,{children:"查询 App Server 投影出的轻量 ThreadRef 状态。"})]}),o.jsxs("div",{className:"flex min-h-0 flex-col gap-4 overflow-hidden",children:[o.jsxs("div",{className:"flex rounded-md border border-slate-800 bg-slate-900 p-1",children:[o.jsx("button",{type:"button",className:["h-8 flex-1 rounded px-3 text-sm",c==="thread"?"bg-slate-700 text-slate-50":"text-slate-400 hover:text-slate-100"].join(" "),onClick:()=>T("thread"),children:"Thread ID"}),o.jsx("button",{type:"button",className:["h-8 flex-1 rounded px-3 text-sm",c==="terminal"?"bg-slate-700 text-slate-50":"text-slate-400 hover:text-slate-100"].join(" "),onClick:()=>T("terminal"),children:"Terminal ID"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(sr,{ref:l,value:c==="thread"?d:f,placeholder:c==="thread"?"threadId":"terminalSessionId",onChange:P=>{c==="thread"?h(P.target.value):m(P.target.value)},onKeyDown:A,className:"border-slate-800 bg-slate-950 text-slate-100"}),o.jsxs(Z,{type:"button",disabled:_,onClick:()=>void R(),className:"shrink-0",children:[o.jsx(Gv,{className:"h-4 w-4"}),"查询"]})]}),s||i||a?o.jsxs("div",{className:"grid grid-cols-[8rem_minmax(0,1fr)] gap-x-2 gap-y-1 rounded-md border border-slate-800 bg-slate-950/60 p-3 text-xs",children:[o.jsx("span",{className:"text-slate-500",children:"projectId"}),o.jsx("span",{className:"truncate text-slate-300",children:Nn(s)}),o.jsx("span",{className:"text-slate-500",children:"terminalSessionId"}),o.jsx("span",{className:"truncate text-slate-300",children:Nn(i)}),o.jsx("span",{className:"text-slate-500",children:"terminalPanelId"}),o.jsx("span",{className:"truncate text-slate-300",children:Nn(a)})]}):null,S?o.jsx("p",{className:"rounded-md border border-slate-800 bg-slate-900/70 px-3 py-2 text-sm text-slate-300",children:S}):null,o.jsxs("div",{className:"grid min-h-0 gap-4 overflow-hidden lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[o.jsxs("div",{className:"min-h-0 overflow-auto rounded-md border border-slate-800",children:[o.jsx("div",{className:"border-b border-slate-800 px-3 py-2 text-xs font-medium uppercase tracking-wide text-slate-500",children:"候选 ThreadRef"}),g.length>0?o.jsx("div",{className:"divide-y divide-slate-800",children:g.map(P=>o.jsxs("button",{type:"button",className:["block w-full px-3 py-2 text-left text-sm hover:bg-slate-900",x===P.threadId?"bg-slate-900 text-slate-50":"text-slate-300"].join(" "),onClick:()=>b(P.threadId),children:[o.jsxs("span",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"truncate font-medium",children:P.threadId}),o.jsx("span",{className:"shrink-0 rounded border border-slate-700 px-1.5 py-0.5 text-xs text-slate-300",children:P.status})]}),o.jsxs("span",{className:"mt-1 block truncate text-xs text-slate-500",children:[P.agent," / panel=",Nn(P.terminalPanelId)]})]},P.threadId))}):o.jsx("p",{className:"px-3 py-6 text-sm text-slate-500",children:"输入 ID 后查询状态。"})]}),o.jsxs("div",{className:"min-h-0 overflow-auto rounded-md border border-slate-800",children:[o.jsx("div",{className:"border-b border-slate-800 px-3 py-2 text-xs font-medium uppercase tracking-wide text-slate-500",children:"状态摘要"}),D?o.jsx("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-x-3 gap-y-2 p-3 text-sm",children:mie.map(P=>o.jsxs("div",{className:"contents",children:[o.jsx("span",{className:"text-slate-500",children:P.label}),o.jsx("span",{className:"min-w-0 break-words font-mono text-xs text-slate-200",children:Nn(P.read(D))})]},P.label))}):o.jsx("p",{className:"px-3 py-6 text-sm text-slate-500",children:"选中候选后显示详情。"})]})]}),E?o.jsx("textarea",{readOnly:!0,value:E,className:"h-28 resize-none rounded-md border border-slate-800 bg-slate-950 p-3 font-mono text-xs text-slate-200"}):null]}),o.jsx(ga,{children:o.jsx(Z,{type:"button",variant:"secondary",disabled:!D,onClick:()=>void I(),children:y?"已复制":"复制给 Agent"})})]})})}function yie(e){return e.alias||e.role||e.panelId.slice(0,8)}function wie(e,t){var r,n,s,i;return!e||!Array.isArray(e.panels)?null:((r=e.panels.find(a=>a.panelId===t))==null?void 0:r.panelId)??((n=e.panels.find(a=>a.panelId===e.activePanelId))==null?void 0:n.panelId)??((s=e.panels.find(a=>a.focused))==null?void 0:s.panelId)??((i=e.panels[0])==null?void 0:i.panelId)??null}function Sie({isMobileMonitor:e,onCloseProjectDialog:t,onSubmitProjectDialog:r,onConfirmDeleteProject:n,onSubmitSessionAlias:s}){var G;const{activeConnectionId:i,apiBase:a,scope:l,token:c}=vt(),u=_s(),d=Zn(),h=u.data??_o,f=d.data??bs,{activeProjectId:m,activeParentProjectId:g,activeSessionId:v,mutationLoading:x,projectDialogMode:b,projectDialogError:_,projectPendingDeletion:C,historyDrawerOpen:S,historyTerminalSessionId:w,historyTerminalPanelId:y,aliasTargetSessionId:N,diagnosticLogOpen:E,statusLookupOpen:k,panelWorkspaceBySessionId:D,activePanelIdBySessionId:j,setProjectPendingDeletion:R,setHistoryDrawerOpen:I,setHistoryTerminalSessionId:T,setHistoryTerminalPanelId:A,closeSessionAlias:P,setDiagnosticLogOpen:O,setStatusLookupOpen:L}=tt(An(z=>({activeProjectId:z.activeProjectId,activeParentProjectId:z.activeParentProjectId,activeSessionId:z.activeSessionId,mutationLoading:z.loading,projectDialogMode:z.projectDialogMode,projectDialogError:z.projectDialogError,projectPendingDeletion:z.projectPendingDeletion,historyDrawerOpen:z.historyDrawerOpen,historyTerminalSessionId:z.historyTerminalSessionId,historyTerminalPanelId:z.historyTerminalPanelId,aliasTargetSessionId:z.aliasTargetSessionId,diagnosticLogOpen:z.diagnosticLogOpen,statusLookupOpen:z.statusLookupOpen,panelWorkspaceBySessionId:z.panelWorkspaceBySessionId,activePanelIdBySessionId:z.activePanelIdBySessionId,setProjectPendingDeletion:z.setProjectPendingDeletion,setHistoryDrawerOpen:z.setHistoryDrawerOpen,setHistoryTerminalSessionId:z.setHistoryTerminalSessionId,setHistoryTerminalPanelId:z.setHistoryTerminalPanelId,closeSessionAlias:z.closeSessionAlias,setDiagnosticLogOpen:z.setDiagnosticLogOpen,setStatusLookupOpen:z.setStatusLookupOpen}))),B=x||u.isPending||d.isPending,M=h.find(z=>z.projectId===g)??null,$=f.find(z=>z.terminalSessionId===v)??null,U=$?D[$.terminalSessionId]:null,F=$&&U?wie(U,j[$.terminalSessionId]??null):($==null?void 0:$.activePanelId)??null,K=f.find(z=>z.terminalSessionId===w)??null,Y=w?((G=D[w])==null?void 0:G.panels.find(z=>z.panelId===y))??null:null,te=K?[Ol({alias:K.alias,cwd:K.cwd,activeCommand:K.activeCommand}),Y?yie(Y):null].filter(Boolean).join(" / "):void 0,H=f.find(z=>z.terminalSessionId===N)??null;return o.jsxs(o.Fragment,{children:[o.jsx(hie,{canSelectDirectory:i===Vn,open:b!==null,mode:b??"create",loading:B,error:_,initialName:b==="edit"?(M==null?void 0:M.name)??"":"",initialPath:b==="edit"?(M==null?void 0:M.path)??"":"",initialMainBranch:b==="edit"?M==null?void 0:M.mainBranch:null,onClose:t,onSubmit:r},l),o.jsx(uie,{open:S,target:{lastThreadId:(K==null?void 0:K.lastThreadId)??null,lastThreadProvider:(K==null?void 0:K.lastThreadProvider)??null,lastThreadStatus:(K==null?void 0:K.lastThreadStatus)??null,panelId:y,panelLastThreadId:(Y==null?void 0:Y.lastThreadId)??null,panelLastThreadProvider:(Y==null?void 0:Y.lastThreadProvider)??null,panelLastThreadStatus:(Y==null?void 0:Y.lastThreadStatus)??null,panelThreadId:(Y==null?void 0:Y.threadId)??null,panelThreadProvider:(Y==null?void 0:Y.threadProvider)??null,projectId:(K==null?void 0:K.projectId)??null,sessionId:w,threadId:(K==null?void 0:K.threadId)??null,threadProvider:(K==null?void 0:K.threadProvider)??null},title:te,onOpenChange:z=>{I(z),z||(T(null),A(null))}}),o.jsx(sQ,{open:H!==null,loading:B,session:H,onClose:()=>{B||P()},onSubmit:async z=>{H&&(await s(H.terminalSessionId,z),P())}}),e?null:o.jsx(lie,{apiBase:a,token:c,open:E,onOpenChange:O}),e?null:o.jsx(_ie,{apiBase:a,token:c,open:k,onOpenChange:L,activeProjectId:m,activeSessionId:($==null?void 0:$.terminalSessionId)??null,activePanelId:F}),o.jsx(Tl,{open:C!==null,onOpenChange:z=>{!z&&!B&&R(null)},children:o.jsxs(xa,{children:[o.jsxs(Dl,{children:[o.jsx(ba,{children:"Delete Project"}),o.jsxs(_a,{children:['Delete "',C==null?void 0:C.name,'" and all terminal tabs inside it. This cannot be undone.']})]}),o.jsxs(Pl,{children:[o.jsx(ya,{disabled:B,children:"Cancel"}),o.jsx(Lu,{disabled:B,className:"bg-rose-500 text-white hover:bg-rose-500/90 hover:shadow-[0_22px_50px_-24px_rgba(244,63,94,0.82)]",onClick:z=>{z.preventDefault(),n()},children:B?"Deleting...":"Delete"})]})]})})]})}function Cie({clientMode:e,className:t,connection:r,projects:n,sessions:s}){const{apiBase:i,onAuthExpired:a,token:l}=vt(),{activeConnectionId:c,connectionName:u,connections:d,onOpenManager:h,onSelect:f}=r,{onCloseDialog:m,onConfirmDelete:g,onReorder:v,onSelect:x,onSelectContext:b,onSubmitDialog:_}=n,{onReorder:C,onRequestClose:S,onRequestCreate:w,onSelect:y,onSubmitAlias:N}=s,E=e==="mobile",k=_s(),D=Zn(),j=D.data??bs,{queryClient:R,scope:I}=Al(),{activeProjectId:T,activeParentProjectId:A}=tt(An(de=>({activeProjectId:de.activeProjectId,activeParentProjectId:de.activeParentProjectId}))),{activeSessionId:P,mutationLoading:O,setRequestError:L,setPanelWorkspaceBySessionId:B,setActivePanelIdBySessionId:M,setProjectDialogMode:$,setProjectDialogError:U,setProjectPendingDeletion:F,openSessionAlias:K}=tt(An(de=>({activeSessionId:de.activeSessionId,mutationLoading:de.loading,setRequestError:de.setRequestError,setPanelWorkspaceBySessionId:de.setPanelWorkspaceBySessionId,setActivePanelIdBySessionId:de.setActivePanelIdBySessionId,setProjectDialogMode:de.setProjectDialogMode,setProjectDialogError:de.setProjectDialogError,setProjectPendingDeletion:de.setProjectPendingDeletion,openSessionAlias:de.openSessionAlias}))),Y=O||k.isPending||D.isPending,te=p.useMemo(()=>T?j.filter(de=>de.projectId===T):[],[T,j]),H=P?te.find(de=>de.terminalSessionId===P)??null:null,G=(H==null?void 0:H.panelSplitEnabled)??!1,z=tt(de=>H?de.panelWorkspaceBySessionId[H.terminalSessionId]:void 0),ee=(z==null?void 0:z.panels.length)??(H==null?void 0:H.panelCount)??1,V=ee>1,re=!z||z.panels.some(de=>!de.geometry),oe=W(()=>{U(null),$("create")}),ce=W(de=>{de&&x(de),U(null),$("edit")}),be=W(de=>{F(de)}),ne=W(x),Te=W(v),Ve=W(async(de,he)=>{try{const ge=await Fc(i,l,de,{panelSplitEnabled:he});return L(null),Ga(R,I,Pe=>Pe.map(Le=>Le.terminalSessionId===de?ge:Le)),ge}catch(ge){return ge instanceof De&&ge.status===401?(a==null||a(),null):(L(String(ge)),null)}}),Ge=W(async(de,he,ge,Pe)=>{try{const Le=await QC(i,l,de,he,{direction:ge,cells:Pe});L(null),B(_e=>({..._e,[Le.terminalSessionId]:Le})),M(_e=>({..._e,[Le.terminalSessionId]:Le.activePanelId}))}catch(Le){if(Le instanceof De&&Le.status===401){a==null||a();return}L(String(Le))}}),we=W(async de=>{await new Promise(he=>setTimeout(he,150));try{const he=await w0(i,l,de);B(ge=>({...ge,[he.terminalSessionId]:he}))}catch{}});return p.useEffect(()=>{if(!(H!=null&&H.terminalSessionId)||E||!(G||V)||!re)return;let de=!1;return w0(i,l,H.terminalSessionId).then(he=>{de||(B(ge=>({...ge,[he.terminalSessionId]:he})),M(ge=>({...ge,[he.terminalSessionId]:he.activePanelId})))}).catch(()=>{}),()=>{de=!0}},[H==null?void 0:H.terminalSessionId,ee,re,i,E,V,G,M,B,l]),o.jsxs("section",{className:["flex h-full min-h-0 flex-col overflow-hidden bg-slate-950 text-slate-100","dark",t].filter(Boolean).join(" "),children:[o.jsx(LJ,{loading:Y,isMobileMonitor:E,onCreateSession:w,connection:{activeConnectionId:c,connectionName:u,connections:d,onOpenManager:h,onSelect:f},projects:{onReorderProjects:Te,onSelectProject:ne,requestCreateProject:oe,requestDeleteProject:be,requestEditProject:ce}}),o.jsxs("div",{className:"flex min-h-0 flex-1",children:[E?null:o.jsx(dN,{parentProjectId:A,onSelectContext:b}),o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[o.jsx(oQ,{visibleSessions:te,isMobileMonitor:E,loading:Y,onReorderSessions:C,onSelectSession:y,onRequestCloseSession:S,onRequestEditAlias:de=>K(de.terminalSessionId),onPanelSplitEnabledChange:(de,he)=>{Ve(de,he)},onRequestCreateSession:w,onMoveSession:s.onMove}),o.jsx(Qse,{clientMode:e,loading:Y,onCreateSession:w,onEditProject:()=>ce(),panels:{onPanelWorkspaceChange:de=>{B(he=>({...he,[de.terminalSessionId]:de})),M(he=>({...he,[de.terminalSessionId]:de.activePanelId}))},onRefreshPanelWorkspace:de=>void we(de),onResizePanel:(de,he,ge,Pe)=>{Ge(de,he,ge,Pe)}}})]})]}),o.jsx(Sie,{isMobileMonitor:E,onCloseProjectDialog:m,onSubmitProjectDialog:_,onConfirmDeleteProject:g,onSubmitSessionAlias:N})]})}function Eie({apiBase:e,token:t,scope:r,initialTerminalSessionId:n,activeSession:s,ready:i,onAuthExpired:a}){const{queryClient:l}=Al(),c=p.useRef(!1),u=p.useRef(null),d=W((h,f)=>{if(h!==n&&(u.current=h),!f)return;const{setCompletionMarkers:m}=tt.getState();m(g=>{if(g[h]!==f)return g;const v={...g};return delete v[h],v}),Fc(e,t,h,{acknowledgedCompletionRevision:f}).then(g=>{Ga(l,r,v=>v.map(x=>x.terminalSessionId===h?{...x,completionRevision:Math.max(x.completionRevision,g.completionRevision),acknowledgedCompletionRevision:Math.max(x.acknowledgedCompletionRevision,g.acknowledgedCompletionRevision)}:x))}).catch(g=>{m(v=>({...v,[h]:Math.max(v[h]??0,f)})),g instanceof De&&g.status===401&&(a==null||a())})});return p.useEffect(()=>{c.current=!1},[r,n]),p.useEffect(()=>{if(!(c.current||!i||!n||(s==null?void 0:s.terminalSessionId)!==n||tt.getState().activeSessionId!==n)){if(c.current=!0,u.current===n){u.current=null;return}QW(e,n)||s.completionRevision>s.acknowledgedCompletionRevision&&d(n,s.completionRevision)}},[d,s,e,n,i,r]),d}const kie=2e3;function Iie({apiBase:e,token:t,clientMode:r="desktop",connection:n,initialTerminalSessionId:s,onActiveSessionChange:i,onNoSessionAvailable:a,onAuthExpired:l,className:c}){const{activeConnectionId:u,connectionName:d,connections:h,onOpenConnectionManager:f,onSelectConnection:m}=n??{},{scope:g}=vt(),v=_s(),x=Zn(),b=v.data??_o,_=x.data??bs,C=v.isFetched&&x.isFetched,{activeParentProjectId:S,activeProjectId:w,activeSessionId:y,projectDialogMode:N,projectPendingDeletion:E,historyTerminalSessionId:k,setActiveParentProjectId:D,selectProjectContext:j,setActiveSessionId:R,setTerminalStateBySessionId:I,setCompletionMarkers:T,setBellMarkers:A,setCachedSurfaceSessionIds:P,setHistoryDrawerOpen:O,setHistoryTerminalSessionId:L,setHistoryTerminalPanelId:B,selectActiveSession:M,resetWorkspaceForConnection:$,reconcileProjectNavigationHistory:U,recordProjectNavigationSelection:F}=tt(An(ae=>({activeParentProjectId:ae.activeParentProjectId,activeProjectId:ae.activeProjectId,activeSessionId:ae.activeSessionId,projectDialogMode:ae.projectDialogMode,projectPendingDeletion:ae.projectPendingDeletion,historyTerminalSessionId:ae.historyTerminalSessionId,setActiveParentProjectId:ae.setActiveParentProjectId,selectProjectContext:ae.selectProjectContext,setActiveSessionId:ae.setActiveSessionId,setTerminalStateBySessionId:ae.setTerminalStateBySessionId,setCompletionMarkers:ae.setCompletionMarkers,setBellMarkers:ae.setBellMarkers,setCachedSurfaceSessionIds:ae.setCachedSurfaceSessionIds,setHistoryDrawerOpen:ae.setHistoryDrawerOpen,setHistoryTerminalSessionId:ae.setHistoryTerminalSessionId,setHistoryTerminalPanelId:ae.setHistoryTerminalPanelId,selectActiveSession:ae.selectActiveSession,resetWorkspaceForConnection:ae.resetForConnection,reconcileProjectNavigationHistory:ae.reconcileProjectNavigationHistory,recordProjectNavigationSelection:ae.recordProjectNavigationSelection}))),K=Hf(S),Y=K.data??Uf,te=v.isPending||x.isPending||!!(S&&K.isPending),H=v.error??x.error??K.error,G=H?String(H):null,z=p.useRef(s),ee=Vt(ae=>ae.removeProjectPreview),V=W(ae=>{const le=oa(g),je=le==null?void 0:le.contextProjectIdByParentProjectId[ae],Me=je&&Tn(je)===ae?je:ae,ot=_.filter(Dt=>Dt.projectId===Me),ct=tt.getState().activeSessionId;if(ct&&ot.some(Dt=>Dt.terminalSessionId===ct)){j(ae,Me,ct);return}const yt=sh(g,Me,ot);!yt&&s&&(i==null||i(null)),j(ae,Me,yt)}),re=W(ae=>{s&&!_.some(le=>le.projectId===ae)&&(i==null||i(null)),hN({activeParentProjectId:S,projectId:ae,sessions:_,scope:g,selectProjectContext:j})}),oe=b,ce=p.useMemo(()=>w?_.filter(ae=>ae.projectId===w):[],[w,_]),be=p.useMemo(()=>_.map(ae=>ae.terminalSessionId),[_]),ne=y?ce.find(ae=>ae.terminalSessionId===y)??null:null,Te=W(async()=>{const[ae,le]=await Promise.all([v.refetch(),x.refetch()]),je=ae.error??le.error;if(je)throw je}),{resetTerminalEventCursor:Ve}=jq({apiBase:e,token:t,onAuthExpired:l,loadSessions:Te});p.useEffect(()=>{z.current=s},[s,R]),p.useEffect(()=>{$(z.current),Ve()},[Ve,$,g]),p.useEffect(()=>{GU(g,s)},[s,g]),p.useEffect(()=>{C&&!v.error&&!x.error&&U(b.map(ae=>ae.projectId),_)},[b,_,C,v.error,x.error,U]),p.useEffect(()=>{if(!G||te)return;const ae=window.setTimeout(()=>{Te()},kie);return()=>window.clearTimeout(ae)},[Te,te,G]),p.useEffect(()=>{s&&R(s)},[s,R]),p.useEffect(()=>{if(!Sd(S,w,y)||oe.length===0)return;const ae=XU(oe,_,S,w,y),le=YU(g,oe,_,S,ae?null:s);if(le){D(le);return}j(null,null,null)},[S,w,y,s,g,_,D,j,oe]),p.useEffect(()=>{var Ft,Mt;if(!Sd(S,w,y)||!S||K.isPending)return;const ae=oa(g),le=s?(Ft=_.find(Ze=>Ze.terminalSessionId===s))==null?void 0:Ft.projectId:null,je=y?(Mt=_.find(Ze=>Ze.terminalSessionId===y))==null?void 0:Mt.projectId:null,Me=ae==null?void 0:ae.contextProjectIdByParentProjectId[S],ot=Ze=>!!(Ze&&Tn(Ze)===S&&(Ze===S||Y.some(xt=>xt.projectId===Ze)||_.some(xt=>xt.projectId===Ze))),ct=[je,w,le,Me,S].find(ot);if(!ct)return;const yt=_.filter(Ze=>Ze.projectId===ct),Dt=sh(g,ct,yt,y??s);w===ct&&y===Dt||j(S,ct,Dt)},[S,w,y,Y,K.isPending,s,g,j,_]),p.useEffect(()=>{if(Sd(S,w,y)){if(ce.length===0){if(!C)return;M(null);return}y&&ce.some(ae=>ae.terminalSessionId===y)||M(sh(g,w??ce[0].projectId,ce,s))}},[S,w,y,C,s,M,g,ce]),p.useEffect(()=>{!C||G||ne!=null&&ne.terminalSessionId&&ne.terminalSessionId===tt.getState().activeSessionId&&(i==null||i(ne.terminalSessionId))},[ne==null?void 0:ne.terminalSessionId,C,i,G]),p.useEffect(()=>{P(ae=>wq({activeSessionId:(ne==null?void 0:ne.terminalSessionId)??null,cachedSessionIds:ae,sessionIds:be}))},[ne==null?void 0:ne.terminalSessionId,be,P]);const Ge=!!(S&&w&&b.some(ae=>ae.projectId===S)&&(w===S||Y.some(ae=>ae.projectId===w))),we=C&&K.isFetched&&!G&&Ge&&(ce.length===0||ne!==null);p.useEffect(()=>{we&&Sd(S,w,y)&&F()},[S,w,y,we,F]),p.useEffect(()=>{s&&we&&ce.length===0&&(i==null||i(null))},[we,s,i,ce.length]);const de=Eie({apiBase:e,token:t,scope:g,initialTerminalSessionId:s,activeSession:ne,ready:C&&Ge&&!G,onAuthExpired:l}),he=W(ae=>{const le=tt.getState().completionMarkers[ae];M(ae),de(ae,le??0)});ZU({apiBase:g,activeParentProjectId:S,activeProjectId:w,activeSessionId:(ne==null?void 0:ne.terminalSessionId)??null,canPersist:we,requestError:G}),JU({enabled:!N&&!E,activeProjectId:S,activeSessionId:(ne==null?void 0:ne.terminalSessionId)??null,visibleProjects:oe,visibleSessions:ce,onSelectProject:V,onSelectSession:he}),p.useEffect(()=>{!C||G||_.length>0||a==null||a()},[C,a,G,_.length]),p.useEffect(()=>{T(ae=>{let le=!1;const je={...ae};for(const Me of _){const ot=je[Me.terminalSessionId]??0;ot>0&&ot<=Me.acknowledgedCompletionRevision&&(delete je[Me.terminalSessionId],le=!0),!(Me.completionRevision<=Me.acknowledgedCompletionRevision||ot>=Me.completionRevision)&&(je[Me.terminalSessionId]=Me.completionRevision,le=!0)}return le?je:ae})},[_,T]),p.useEffect(()=>{ne!=null&&ne.terminalSessionId&&A(ae=>{if(!ae[ne.terminalSessionId])return ae;const le={...ae};return delete le[ne.terminalSessionId],le})},[ne==null?void 0:ne.terminalSessionId,A]),QU({sessions:_,historyTerminalSessionId:k,setCompletionMarkers:T,setBellMarkers:A,setHistoryDrawerOpen:O,setHistoryTerminalSessionId:L,setHistoryTerminalPanelId:B}),p.useEffect(()=>{I(ae=>{const le=new Set(be);let je=!1;const Me={};for(const ot of _){const ct=ot.terminalSessionId,yt=ot.terminalState??ae[ct];if(!yt)continue;Me[ct]=yt;const Dt=ae[ct];((Dt==null?void 0:Dt.state)!==yt.state||Dt.agent!==yt.agent)&&(je=!0)}return Object.keys(ae).some(ot=>!le.has(ot))&&(je=!0),je?Me:ae})},[be,_,I]);const{createSession:ge,closeSession:Pe,updateSessionAlias:Le,moveSession:_e,closeProjectDialog:et,submitProjectDialog:it,removeProject:ue,handleProjectReorder:Ie,handleSessionReorder:ye}=Sq({apiBase:e,token:t,clientMode:r,removeProjectPreview:ee,loadSessions:Te,onAuthExpired:l});return o.jsx(Cie,{clientMode:r,className:c,connection:{activeConnectionId:u,connectionName:d,connections:h,onOpenManager:f,onSelect:m},projects:{onCloseDialog:et,onConfirmDelete:()=>void ue(),onReorder:Ie,onSelect:V,onSelectContext:re,onSubmitDialog:it},sessions:{onReorder:ye,onRequestClose:ae=>void Pe(ae),onRequestCreate:()=>void ge(),onSelect:he,onSubmitAlias:Le,onMove:_e}})}function Nie(e){var t,r,n,s;return p.useLayoutEffect(()=>{var i;Vt.getState().setConnectionScope(((i=e.connection)==null?void 0:i.activeConnectionId)??"web")},[(t=e.connection)==null?void 0:t.activeConnectionId]),o.jsx(zf,{activeConnectionId:(r=e.connection)==null?void 0:r.activeConnectionId,connectionName:(n=e.connection)==null?void 0:n.connectionName,apiBase:e.apiBase,onAuthExpired:e.onAuthExpired,token:e.token,remote:(s=e.connection)==null?void 0:s.remote,children:o.jsx(Iie,{...e})})}function s2({apiBase:e,token:t,clientMode:r,connections:n,activeConnectionId:s,connectionName:i,activeConnection:a,onSelectConnection:l,onOpenConnectionManager:c,onAuthExpired:u}){const{terminalSessionId:d}=mf(),h=Cr();return o.jsx("main",{className:"h-dvh overflow-hidden bg-slate-950",children:o.jsx(Nie,{apiBase:e,token:t,clientMode:r,connection:{activeConnectionId:s,connectionName:i,remote:a!=null&&a.tunnelEndpointId?{endpointId:a.tunnelEndpointId,generation:a.generation??0,browserProfileId:a.browserProfileId??null}:null,connections:n,onOpenConnectionManager:c,onSelectConnection:l},initialTerminalSessionId:d,onActiveSessionChange:f=>{f!==d&&h(f?`/terminal/${encodeURIComponent(f)}`:"/terminal",{replace:!0})},onNoSessionAvailable:()=>{d&&h("/terminal",{replace:!0})},onAuthExpired:u})})}const Rie="runweave.prototype-gallery.selection.v1",jie="runweave.prototype-gallery.sidebar-collapsed.v1";function vT(e){return`${Rie}:${e||"local"}`}function xT(e){return`${jie}:${e||"local"}`}function i2(e){try{const t=ht.getItem(vT(e));if(!t)return null;const r=JSON.parse(t),n=r.source==="architecture-flows"?r.source:"prototypes";return typeof r.projectId=="string"&&typeof r.slug=="string"?{projectId:r.projectId,source:n,slug:r.slug}:null}catch{return null}}function o2(e){try{return ht.getItem(xT(e))==="true"}catch{return!1}}function Aie(e,t){try{ht.setItem(xT(e),String(t))}catch{}}function Tie(e,t){try{ht.setItem(vT(e),JSON.stringify(t))}catch{}}function c0(e,t){return(e==null?void 0:e.projectId)===t.projectId&&e.source===t.source&&e.slug===t.slug}function vv(e,t){if(!t)return null;const r=e.projects.find(s=>s.projectId===t.projectId),n=r==null?void 0:r.prototypes.find(s=>s.source===t.source&&s.slug===t.slug);return r&&n?{project:r,prototype:n}:null}function Die(e){if(vv(e.gallery,e.current))return e.current;const t=e.gallery.projects.find(n=>n.projectId===e.activeProjectId),r=t==null?void 0:t.prototypes[0];if(t&&r)return{projectId:t.projectId,source:r.source,slug:r.slug};if(vv(e.gallery,e.stored))return e.stored;for(const n of e.gallery.projects){const s=n.prototypes[0];if(s)return{projectId:n.projectId,source:s.source,slug:s.slug}}return null}function Pie(e){return e.status==="project-path-missing"?"Project path is not set":e.status==="prototype-root-missing"?"No docs/prototypes or docs/architecture-flows directory":e.status==="prototype-root-unavailable"?"Prototype directory is unavailable":"No prototypes"}function a2(e){return e==="prototypes"?"docs/prototypes":"docs/architecture-flows"}function Lie(e,t){return`${e.replace(/\/$/,"")}${t}`}function Mie({apiBase:e,token:t,activeProjectId:r,selectedProjectId:n,selectedPrototypeSource:s,selectedPrototypeSlug:i,onSelectionChange:a,onAuthExpired:l}){const[c,u]=p.useState(null),[d,h]=p.useState(()=>n&&s&&i?{projectId:n,source:s,slug:i}:r?null:i2(e)),[f,m]=p.useState(!0),[g,v]=p.useState(null),[x,b]=p.useState(null),[_,C]=p.useState(!1),[S,w]=p.useState(null),[y,N]=p.useState(()=>o2(e)),E=p.useRef(0),k=p.useRef(0),D=p.useMemo(()=>c?vv(c,d):null,[c,d]),j=W(P=>(P instanceof De&&P.status===401&&(l==null||l()),P instanceof Error?P.message:String(P))),R=W(P=>{Tie(e,P),h(O=>c0(O,P)?O:P),a==null||a(P)}),I=W(()=>{N(P=>{const O=!P;return Aie(e,O),O})}),T=W(async()=>{const P=E.current+1;E.current=P,m(!0),v(null);try{const O=await D6(e,t);if(E.current!==P)return;const L=Die({gallery:O,current:d,stored:i2(e),activeProjectId:r});u(O),L&&R(L)}catch(O){E.current===P&&v(j(O))}finally{E.current===P&&m(!1)}}),A=W(async()=>{const P=k.current+1;if(k.current=P,!(D!=null&&D.prototype.entry)){b(null),w(null),C(!1);return}b(null),w(null),C(!0);try{const O=await P6(e,t,D.project.projectId,D.prototype.source,D.prototype.slug);if(k.current!==P)return;b(Lie(e,O.path))}catch(O){k.current===P&&(w(j(O)),C(!1))}});return p.useEffect(()=>{!n||!s||!i||h(P=>{const O={projectId:n,source:s,slug:i};return c0(P,O)?P:O})},[n,i,s]),p.useEffect(()=>{T()},[e,T,t]),p.useEffect(()=>{N(o2(e))},[e]),p.useEffect(()=>{A()},[A,D==null?void 0:D.project.projectId,D==null?void 0:D.prototype.entry,D==null?void 0:D.prototype.source,D==null?void 0:D.prototype.slug]),o.jsxs("div",{className:["grid h-full min-h-0 bg-slate-950",y?"grid-cols-[32px_minmax(0,1fr)]":"grid-cols-[minmax(260px,320px)_minmax(0,1fr)]"].join(" "),children:[o.jsx("aside",{className:"flex min-h-0 flex-col border-r border-slate-800",children:y?o.jsxs("button",{type:"button","aria-label":"Show prototype library",title:"Show prototype library",className:"flex h-full w-full flex-col items-center gap-2 pt-3 text-slate-600 transition hover:bg-slate-900 hover:text-slate-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-slate-500",onClick:I,children:[o.jsx(UM,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] [writing-mode:vertical-rl]",children:"Library"})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between border-b border-slate-800 px-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(oM,{className:"h-3.5 w-3.5 shrink-0 text-slate-400"}),o.jsx("span",{className:"truncate text-xs font-medium text-slate-200",children:"Project prototypes"})]}),o.jsxs("div",{className:"flex shrink-0 items-center",children:[o.jsx("button",{type:"button","aria-label":"Hide prototype library",title:"Hide prototype library",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-400 transition hover:bg-slate-800 hover:text-slate-100 focus:outline-none focus:ring-2 focus:ring-slate-500",onClick:I,children:o.jsx(uE,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button","aria-label":"Refresh prototype library",title:"Refresh prototype library",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-400 transition hover:bg-slate-800 hover:text-slate-100 focus:outline-none focus:ring-2 focus:ring-slate-500",onClick:()=>void T(),children:o.jsx(Ws,{className:["h-3.5 w-3.5",f?"animate-spin":""].join(" ")})})]})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:f&&!c?o.jsx("p",{className:"px-2 py-4 text-xs text-slate-500",children:"Loading prototypes..."}):g?o.jsxs("div",{className:"flex gap-2 rounded-md border border-rose-900/70 bg-rose-950/40 p-2 text-xs text-rose-200",children:[o.jsx(PL,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.jsx("span",{children:g})]}):c?o.jsxs("div",{className:"space-y-3",children:[c.projects.map(P=>o.jsxs("section",{"aria-label":P.name,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 text-[10px] font-medium uppercase tracking-wide text-slate-500",children:[o.jsx("span",{className:"truncate normal-case",title:P.path??void 0,children:P.name}),o.jsx("span",{children:P.prototypes.length})]}),P.prototypes.length>0?o.jsx("div",{className:"space-y-0.5",children:P.prototypes.map(O=>{const L=c0(d,{projectId:P.projectId,source:O.source,slug:O.slug});return o.jsxs("button",{type:"button","aria-current":L?"page":void 0,className:["flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs transition focus:outline-none focus:ring-2 focus:ring-slate-500",L?"bg-slate-800 text-slate-50":"text-slate-400 hover:bg-slate-900 hover:text-slate-100"].join(" "),onClick:()=>R({projectId:P.projectId,source:O.source,slug:O.slug}),children:[o.jsx(ry,{className:"h-3.5 w-3.5 shrink-0"}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate",title:O.title,children:O.title}),o.jsxs("span",{className:"block truncate text-[10px] text-slate-600",children:[a2(O.source)," /"," ",O.slug]})]}),O.entry?null:o.jsx("span",{className:"shrink-0 rounded border border-amber-900/80 px-1 py-0.5 text-[8px] uppercase text-amber-400",children:"No entry"})]},`${O.source}:${O.slug}`)})}):o.jsx("p",{className:"px-2 py-1 text-[10px] text-slate-600",children:Pie(P)})]},P.projectId)),c.projects.length===0?o.jsx("p",{className:"px-2 py-4 text-xs text-slate-500",children:"No Runweave projects"}):null]}):null})]})}),o.jsxs("section",{className:"flex min-h-0 min-w-0 flex-col",children:[o.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-slate-800 px-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"truncate text-xs font-medium text-slate-200",children:(D==null?void 0:D.prototype.title)??"Prototype preview"}),D?o.jsxs("p",{className:"truncate text-[10px] text-slate-600",children:[D.project.name," /"," ",a2(D.prototype.source)," /"," ",D.prototype.slug]}):null]}),D!=null&&D.prototype.entry?o.jsx("button",{type:"button","aria-label":"Reload prototype",title:"Reload prototype",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-slate-400 transition hover:bg-slate-800 hover:text-slate-100 focus:outline-none focus:ring-2 focus:ring-slate-500",onClick:()=>void A(),children:o.jsx(Ws,{className:["h-3.5 w-3.5",_?"animate-spin":""].join(" ")})}):null]}),o.jsx("div",{className:"relative min-h-0 flex-1 bg-slate-950",children:S?o.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center text-xs text-rose-300",children:S}):D&&!D.prototype.entry?o.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[o.jsx(ry,{className:"h-8 w-8 text-slate-700"}),o.jsxs("div",{children:[o.jsx("p",{className:"text-sm text-slate-300",children:"No index.html entry"}),o.jsx("p",{className:"mt-1 text-xs text-slate-600",children:"Add index.html to this prototype directory to run it here."})]}),o.jsx("div",{className:"max-w-md text-[10px] text-slate-600",children:D.prototype.files.join(" · ")||"No files"})]}):x?o.jsx("iframe",{title:(D==null?void 0:D.prototype.title)??"Prototype preview",sandbox:"allow-scripts",referrerPolicy:"no-referrer",src:x,className:"h-full w-full border-0 bg-white",onLoad:()=>C(!1)},x):D&&_?o.jsx("div",{className:"flex h-full items-center justify-center text-xs text-slate-500",children:"Loading prototype..."}):o.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center text-xs text-slate-500",children:"Select a prototype"})})]})]})}function l2({embedded:e=!1,apiBase:t,token:r,onAuthExpired:n}){const s=Cr(),{projectId:i,prototypeSource:a,prototypeSlug:l}=mf(),[c]=fa(),u=i??c.get("project"),d=a==="prototypes"||a==="architecture-flows"?a:void 0,h=W(f=>{const m=`/prototypes/${encodeURIComponent(f.projectId)}/${encodeURIComponent(f.source)}/${encodeURIComponent(f.slug)}`;f.projectId===i&&f.source===d&&f.slug===l||s(m,{replace:!0})});return o.jsxs("main",{className:e?"flex h-full min-h-0 flex-col overflow-hidden":"flex h-dvh min-h-0 flex-col overflow-hidden bg-slate-950 text-slate-100 dark",children:[o.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-3 border-b border-slate-800 px-4",children:[o.jsx(Vv,{className:"h-4 w-4 text-slate-400"}),!e&&o.jsxs("div",{className:"min-w-0",children:[o.jsx("h1",{className:"truncate text-sm font-medium text-slate-100",children:"Prototypes"}),o.jsx("p",{className:"truncate text-[10px] text-slate-500",children:"Project prototype library"})]}),o.jsx(Sa,{className:"ml-auto h-7 max-w-[18rem] border-slate-700 bg-slate-900 text-slate-300"})]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(Mie,{apiBase:t,token:r,activeProjectId:u,selectedProjectId:i,selectedPrototypeSource:d,selectedPrototypeSlug:l,onSelectionChange:h,onAuthExpired:n})})]})}function Oie(){const e=Nc(a=>a.result),t=Nc(a=>a.error),r=Nc(a=>a.dismiss),[n,s]=p.useState(null),i=W(async()=>{var a;if(e)try{(a=window.electronAPI)!=null&&a.openExternal?await window.electronAPI.openExternal(e.url):window.open(e.url,"_blank","noopener,noreferrer")}catch{s(e.url)}});return!e&&!t?null:o.jsxs(eo,{kind:"snapshot-share",noticeKey:e??t,onDismiss:r,duration:e?0:8e3,className:"flex flex-col gap-2 rounded-lg border border-slate-700 bg-slate-900 p-3 text-sm text-slate-100 shadow-lg",children:[o.jsx("div",{className:"flex items-start justify-between gap-2",children:o.jsx("span",{children:t??(e!=null&&e.copied?"快照链接已复制,24 小时后失效。":"快照已创建,24 小时后失效。复制失败,请手动复制链接。")})}),e?o.jsxs(o.Fragment,{children:[o.jsx("input",{"aria-label":"终端快照链接",readOnly:!0,value:e.url,onFocus:a=>a.currentTarget.select(),className:"w-full rounded border border-slate-700 bg-slate-950 p-1 text-xs"}),o.jsx("button",{type:"button",className:"self-start text-sky-400 underline",onClick:()=>{i()},children:"打开快照"}),n===e.url?o.jsx("span",{children:"无法打开快照,请手动复制链接。"}):null]}):null]})}function Ea(e){return{Authorization:`Bearer ${e}`}}function bT(e){const t=new URLSearchParams;for(const[n,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(n,String(s));const r=t.toString();return r?`?${r}`:""}function Bie(e,t,r){return me(e,`/api/activity/facts${bT({runtimeChannel:r.runtimeChannel,runtimeSurface:r.runtimeSurface,projectId:r.projectId,terminalSessionId:r.terminalSessionId,threadId:r.threadId,runId:r.runId,eventName:r.eventName,actorType:r.actorType,resultStatus:r.resultStatus,search:r.search,cursor:r.cursor,asOfActivityOffset:r.asOfActivityOffset,limit:r.limit})}`,{headers:Ea(t)})}function Fie(e,t,r,n={}){return me(e,`/api/activity/timelines${bT({selector:r.type,id:r.id,cursor:n.cursor,asOfActivityOffset:n.asOfActivityOffset,limit:n.limit})}`,{headers:Ea(t)})}async function $ie(e,t){return(await me(e,"/api/activity/sources",{headers:Ea(t)})).sources}function zie(e,t){return me(e,"/api/activity/policy",{headers:Ea(t)})}function Uie(e,t,r){return me(e,`/api/activity/contents/${encodeURIComponent(r)}`,{headers:Ea(t)})}function Hie(e,t,r,n){return me(e,"/api/activity/operations",{method:"POST",headers:{...Ea(t),"Content-Type":"application/json"},body:JSON.stringify({action:r,scope:n})})}function Wie(e,t,r){return me(e,`/api/activity/delete-jobs/${encodeURIComponent(r)}`,{headers:Ea(t)})}function _T({apiBase:e,token:t,fact:r,onClose:n}){var u,d;const[s,i]=p.useState(null),a=Ct({queryKey:["activity","content",e,s],queryFn:()=>Uie(e,t,s),enabled:!!s}),l=W(h=>{i(h)}),c=(u=a.data)!=null&&u.bytesBase64?new TextDecoder().decode(Uint8Array.from(atob(a.data.bytesBase64),h=>h.charCodeAt(0))):null;return o.jsxs("aside",{className:"mt-4 rounded-xl border border-border/70 bg-card/70 p-5","aria-label":"Fact detail",children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx("span",{className:"rounded-full border border-border px-2 py-1 text-[0.68rem] text-muted-foreground",children:"Recorded"}),o.jsx("h2",{className:"mt-3 font-semibold",children:r.eventName}),o.jsx("p",{className:"mt-1 break-all text-xs text-muted-foreground",children:r.eventId})]}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:n,"aria-label":"Close fact detail",children:o.jsx(vo,{className:"h-4 w-4"})})]}),o.jsxs("dl",{className:"mt-5 grid gap-3 text-sm md:grid-cols-2",children:[o.jsxs("div",{children:[o.jsx("dt",{className:"text-xs text-muted-foreground",children:"Recorded at"}),o.jsx("dd",{children:r.occurredAt})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"text-xs text-muted-foreground",children:"Ingest offset"}),o.jsx("dd",{children:r.activityOffset})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"text-xs text-muted-foreground",children:"Runtime"}),o.jsxs("dd",{children:[r.runtime.channel," · ",r.runtime.surface]})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"text-xs text-muted-foreground",children:"Result"}),o.jsx("dd",{children:((d=r.result)==null?void 0:d.status)??"not reported"})]})]}),o.jsxs("div",{className:"mt-5",children:[o.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Recorded payload"}),o.jsx("pre",{className:"mt-2 overflow-auto rounded-lg bg-muted/50 p-3 text-xs",children:JSON.stringify(r.payload,null,2)})]}),o.jsxs("div",{className:"mt-5",children:[o.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Short-lived content"}),r.contentDescriptors.length===0?o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No Content descriptor was recorded."}):o.jsx("div",{className:"mt-2 grid gap-2",children:r.contentDescriptors.map(h=>o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/70 p-3 text-sm",children:[o.jsxs("div",{children:[o.jsxs("p",{children:[h.role," · ",h.mediaType]}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.availability," · ",h.byteLength," bytes"]})]}),o.jsx(Z,{variant:"outline",size:"sm",disabled:h.availability!=="available",onClick:()=>l(h.contentId),children:"Read content"})]},h.contentId))}),s?o.jsxs("div",{className:"mt-3 rounded-lg border border-border/70 p-3",children:[a.isPending?o.jsx("p",{className:"text-sm text-muted-foreground",children:"Reading audited content…"}):null,a.isError?o.jsx("p",{className:"text-sm text-destructive",children:"Content is unavailable or expired."}):null,c!==null?o.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap text-xs",children:c}):null]}):null]}),o.jsxs("div",{className:"mt-5",children:[o.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"External references"}),r.externalRefDescriptors.length===0?o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No ExternalRef descriptor was recorded."}):o.jsx("div",{className:"mt-2 grid gap-2",children:r.externalRefDescriptors.map(h=>o.jsxs("div",{className:"rounded-lg border border-border/70 p-3 text-sm",children:[o.jsxs("p",{children:[h.role," · ",h.authority]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[h.availability," · ",h.versionOrDigest]})]},h.refId))})]})]})}function c2(e,[t,r]){return Math.min(r,Math.max(t,e))}function zb(e,t=[]){let r=[];function n(i,a){const l=p.createContext(a);l.displayName=i+"Context";const c=r.length;r=[...r,a];const u=h=>{var b;const{scope:f,children:m,...g}=h,v=((b=f==null?void 0:f[e])==null?void 0:b[c])||l,x=p.useMemo(()=>g,Object.values(g));return o.jsx(v.Provider,{value:x,children:m})};u.displayName=i+"Provider";function d(h,f,m={}){var b;const{optional:g=!1}=m,v=((b=f==null?void 0:f[e])==null?void 0:b[c])||l,x=p.useContext(v);if(x)return x;if(a!==void 0)return a;if(!g)throw new Error(`\`${h}\` must be used within \`${i}\``)}return[u,d]}const s=()=>{const i=r.map(a=>p.createContext(a));return function(l){const c=(l==null?void 0:l[e])||i;return p.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return s.scopeName=e,[n,qie(s,...t)]}function qie(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const n=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const a=n.reduce((l,{useScope:c,scopeName:u})=>{const h=c(i)[`__scope${u}`];return{...l,...h}},{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}function Kie(e){const t=e+"CollectionProvider",[r,n]=zb(t),[s,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),a=v=>{const{scope:x,children:b}=v,_=p.useRef(null),C=p.useRef(new Map).current;return o.jsx(s,{scope:x,itemMap:C,collectionRef:_,children:b})};a.displayName=t;const l=e+"CollectionSlot",c=Rh(l),u=p.forwardRef((v,x)=>{const{scope:b,children:_}=v,C=i(l,b),S=yr(x,C.collectionRef);return o.jsx(c,{ref:S,children:_})});u.displayName=l;const d=e+"CollectionItemSlot",h="data-radix-collection-item",f=Rh(d),m=p.forwardRef((v,x)=>{const{scope:b,children:_,...C}=v,S=p.useRef(null),w=yr(x,S),y=i(d,b);return p.useEffect(()=>(y.itemMap.set(S,{ref:S,...C}),()=>void y.itemMap.delete(S))),o.jsx(f,{[h]:"",ref:w,children:_})});m.displayName=d;function g(v){const x=i(e+"CollectionConsumer",v);return p.useCallback(()=>{const _=x.collectionRef.current;if(!_)return[];const C=Array.from(_.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((y,N)=>C.indexOf(y.ref.current)-C.indexOf(N.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:a,Slot:u,ItemSlot:m},g,n]}var Vie=p.createContext(void 0);function Gie(e){const t=p.useContext(Vie);return e||t||"ltr"}var zd=0,Is=null;function Yie(){p.useEffect(()=>{Is||(Is={start:u2(),end:u2()});const{start:e,end:t}=Is;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zd++,()=>{zd===1&&(Is==null||Is.start.remove(),Is==null||Is.end.remove(),Is=null),zd=Math.max(0,zd-1)}},[])}function u2(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var u0="focusScope.autoFocusOnMount",d0="focusScope.autoFocusOnUnmount",d2={bubbles:!1,cancelable:!0},Xie="FocusScope",yT=p.forwardRef((e,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...a}=e,[l,c]=p.useState(null),u=mi(s),d=mi(i),h=p.useRef(null),f=yr(t,c),m=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(n){let v=function(C){if(m.paused||!l)return;const S=C.target;l.contains(S)?h.current=S:Pi(h.current,{select:!0})},x=function(C){if(m.paused||!l)return;const S=C.relatedTarget;S!==null&&(l.contains(S)||Pi(h.current,{select:!0}))},b=function(C){if(document.activeElement===document.body)for(const w of C)w.removedNodes.length>0&&Pi(l)};document.addEventListener("focusin",v),document.addEventListener("focusout",x);const _=new MutationObserver(b);return l&&_.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",v),document.removeEventListener("focusout",x),_.disconnect()}}},[n,l,m.paused]),p.useEffect(()=>{if(l){f2.add(m);const v=document.activeElement;if(!l.contains(v)){const b=new CustomEvent(u0,d2);l.addEventListener(u0,u),l.dispatchEvent(b),b.defaultPrevented||(Jie(roe(wT(l)),{select:!0}),document.activeElement===v&&Pi(l))}return()=>{l.removeEventListener(u0,u),setTimeout(()=>{const b=new CustomEvent(d0,d2);l.addEventListener(d0,d),l.dispatchEvent(b),b.defaultPrevented||Pi(v??document.body,{select:!0}),l.removeEventListener(d0,d),f2.remove(m)},0)}}},[l,u,d,m]);const g=p.useCallback(v=>{if(!r&&!n||m.paused)return;const x=v.key==="Tab"&&!v.altKey&&!v.ctrlKey&&!v.metaKey,b=document.activeElement;if(x&&b){const _=v.currentTarget,[C,S]=Qie(_);C&&S?!v.shiftKey&&b===S?(v.preventDefault(),r&&Pi(C,{select:!0})):v.shiftKey&&b===C&&(v.preventDefault(),r&&Pi(S,{select:!0})):b===_&&v.preventDefault()}},[r,n,m.paused]);return o.jsx(ir.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});yT.displayName=Xie;function Jie(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(Pi(n,{select:t}),document.activeElement!==r)return}function Qie(e){const t=wT(e),r=h2(t,e),n=h2(t.reverse(),e);return[r,n]}function wT(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const s=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||s?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function h2(e,t){const r=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(r?!n.checkVisibility({checkVisibilityCSS:!0}):Zie(n,{upTo:t})))return n}function Zie(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function eoe(e){return e instanceof HTMLInputElement&&"select"in e}function Pi(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&eoe(e)&&t&&e.select()}}var f2=toe();function toe(){let e=[];return{add(t){const r=e[0];t!==r&&(r==null||r.pause()),e=p2(e,t),e.unshift(t)},remove(t){var r;e=p2(e,t),(r=e[0])==null||r.resume()}}}function p2(e,t){const r=[...e],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function roe(e){return e.filter(t=>t.tagName!=="A")}var zr=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},noe=da[" useId ".trim().toString()]||(()=>{}),soe=0;function Ub(e){const[t,r]=p.useState(noe());return zr(()=>{r(n=>n??String(soe++))},[e]),t?`radix-${t}`:""}var ioe="Arrow",ST=p.forwardRef((e,t)=>{const{children:r,width:n=10,height:s=5,...i}=e;return o.jsx(ir.svg,{...i,ref:t,width:n,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});ST.displayName=ioe;var ooe=ST;function aoe(e){const[t,r]=p.useState(void 0);return zr(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const n=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const i=s[0];let a,l;if("borderBoxSize"in i){const c=i.borderBoxSize,u=Array.isArray(c)?c[0]:c;a=u.inlineSize,l=u.blockSize}else a=e.offsetWidth,l=e.offsetHeight;r({width:a,height:l})});return n.observe(e,{box:"border-box"}),()=>n.unobserve(e)}else r(void 0)},[e]),t}var Hb="Popper",[CT,ET]=zb(Hb),[loe,kT]=CT(Hb),IT=e=>{const{__scopePopper:t,children:r}=e,[n,s]=p.useState(null),[i,a]=p.useState(void 0);return o.jsx(loe,{scope:t,anchor:n,onAnchorChange:s,placementState:i,setPlacementState:a,children:r})};IT.displayName=Hb;var NT="PopperAnchor",RT=p.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:n,...s}=e,i=kT(NT,r),a=p.useRef(null),l=i.onAnchorChange,c=p.useCallback(g=>{a.current=g,g&&l(g)},[l]),u=yr(t,c),d=p.useRef(null);p.useEffect(()=>{if(!n)return;const g=d.current;d.current=n.current,g!==d.current&&l(d.current)});const h=i.placementState&&qb(i.placementState),f=h==null?void 0:h[0],m=h==null?void 0:h[1];return n?null:o.jsx(ir.div,{"data-radix-popper-side":f,"data-radix-popper-align":m,...s,ref:u})});RT.displayName=NT;var Wb="PopperContent",[coe,uoe]=CT(Wb),jT=p.forwardRef((e,t)=>{var G,z,ee,V,re,oe;const{__scopePopper:r,side:n="bottom",sideOffset:s=0,align:i="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:d=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,x=kT(Wb,r),[b,_]=p.useState(null),C=yr(t,_),[S,w]=p.useState(null),y=aoe(S),N=(y==null?void 0:y.width)??0,E=(y==null?void 0:y.height)??0,k=n+(i!=="center"?"-"+i:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},j=Array.isArray(u)?u:[u],R=j.length>0,I={padding:D,boundary:j.filter(hoe),altBoundary:R},{refs:T,floatingStyles:A,placement:P,isPositioned:O,middlewareData:L}=l5({strategy:"fixed",placement:k,whileElementsMounted:(...ce)=>o5(...ce,{animationFrame:m==="always"}),elements:{reference:x.anchor},middleware:[c5({mainAxis:s+E,alignmentAxis:a}),c&&u5({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?d5():void 0,...I}),c&&h5({...I}),f5({...I,apply:({elements:ce,rects:be,availableWidth:ne,availableHeight:Te})=>{const{width:Ve,height:Ge}=be.reference,we=ce.floating.style;we.setProperty("--radix-popper-available-width",`${ne}px`),we.setProperty("--radix-popper-available-height",`${Te}px`),we.setProperty("--radix-popper-anchor-width",`${Ve}px`),we.setProperty("--radix-popper-anchor-height",`${Ge}px`)}}),S&&m5({element:S,padding:l}),foe({arrowWidth:N,arrowHeight:E}),f&&p5({strategy:"referenceHidden",...I,boundary:R?I.boundary:void 0})]}),B=x.setPlacementState;zr(()=>(B(P),()=>{B(void 0)}),[P,B]);const[M,$]=qb(P),U=mi(g);zr(()=>{O&&(U==null||U())},[O,U]);const F=(G=L.arrow)==null?void 0:G.x,K=(z=L.arrow)==null?void 0:z.y,Y=((ee=L.arrow)==null?void 0:ee.centerOffset)!==0,[te,H]=p.useState();return zr(()=>{b&&H(window.getComputedStyle(b).zIndex)},[b]),o.jsx("div",{ref:T.setFloating,"data-radix-popper-content-wrapper":"",style:{...A,transform:O?A.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:te,"--radix-popper-transform-origin":[(V=L.transformOrigin)==null?void 0:V.x,(re=L.transformOrigin)==null?void 0:re.y].join(" "),...((oe=L.hide)==null?void 0:oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(coe,{scope:r,placedSide:M,placedAlign:$,onArrowChange:w,arrowX:F,arrowY:K,shouldHideArrow:Y,children:o.jsx(ir.div,{"data-side":M,"data-align":$,...v,ref:C,style:{...v.style,animation:O?void 0:"none"}})})})});jT.displayName=Wb;var AT="PopperArrow",doe={top:"bottom",right:"left",bottom:"top",left:"right"},TT=p.forwardRef(function(t,r){const{__scopePopper:n,...s}=t,i=uoe(AT,n),a=doe[i.placedSide];return o.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:o.jsx(ooe,{...s,ref:r,style:{...s.style,display:"block"}})})});TT.displayName=AT;function hoe(e){return e!==null}var foe=e=>({name:"transformOrigin",options:e,fn(t){var x,b,_;const{placement:r,rects:n,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[u,d]=qb(r),h={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+l/2,m=(((_=s.arrow)==null?void 0:_.y)??0)+c/2;let g="",v="";return u==="bottom"?(g=a?h:`${f}px`,v=`${-c}px`):u==="top"?(g=a?h:`${f}px`,v=`${n.floating.height+c}px`):u==="right"?(g=`${-c}px`,v=a?h:`${m}px`):u==="left"&&(g=`${n.floating.width+c}px`,v=a?h:`${m}px`),{data:{x:g,y:v}}}});function qb(e){const[t,r="center"]=e.split("-");return[t,r]}var poe=IT,moe=RT,goe=jT,voe=TT,xoe="Portal",DT=p.forwardRef((e,t)=>{var l;const{container:r,...n}=e,[s,i]=p.useState(!1);zr(()=>i(!0),[]);const a=r||s&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?Yr.createPortal(o.jsx(ir.div,{...n,ref:t}),a):null});DT.displayName=xoe;function boe(e,t){return p.useReducer((r,n)=>t[r][n]??r,e)}var PT=e=>{const{present:t,children:r}=e,n=_oe(t),s=typeof r=="function"?r({present:n.isPresent}):p.Children.only(r),i=yoe(n.ref,woe(s));return typeof r=="function"||n.isPresent?p.cloneElement(s,{ref:i}):null};PT.displayName="Presence";function _oe(e){const[t,r]=p.useState(),n=p.useRef(null),s=p.useRef(e),i=p.useRef("none"),a=p.useRef(void 0),l=e?"mounted":"unmounted",[c,u]=boe(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{c==="mounted"?(i.current=a.current??uc(n.current),a.current=void 0):i.current="none"},[c]),zr(()=>{const d=n.current,h=s.current;if(h!==e){const m=i.current,g=uc(d);e?(a.current=g,u("MOUNT")):g==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&m!==g?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,u]),zr(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,f=g=>{const x=uc(n.current).includes(CSS.escape(g.animationName));if(g.target===t&&x&&(u("ANIMATION_END"),!s.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},m=g=>{g.target===t&&(i.current=uc(n.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:p.useCallback(d=>{if(d){const h=getComputedStyle(d);n.current=h,a.current=uc(h)}else n.current=null;r(d)},[])}}function m2(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function yoe(...e){const t=p.useRef(e);return t.current=e,p.useCallback(r=>{const n=t.current;let s=!1;const i=n.map(a=>{const l=m2(a,r);return!s&&typeof l=="function"&&(s=!0),l});if(s)return()=>{for(let a=0;a<i.length;a++){const l=i[a];typeof l=="function"?l():m2(n[a],null)}}},[])}function uc(e){return(e==null?void 0:e.animationName)||"none"}function woe(e){var n,s;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Soe=da[" useInsertionEffect ".trim().toString()]||zr;function g2({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[s,i,a]=Coe({defaultProp:t,onChange:r}),l=e!==void 0,c=l?e:s;{const d=p.useRef(e!==void 0);p.useEffect(()=>{const h=d.current;h!==l&&console.warn(`${n} is changing from ${h?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=l},[l,n])}const u=p.useCallback(d=>{var h;if(l){const f=Eoe(d)?d(e):d;f!==e&&((h=a.current)==null||h.call(a,f))}else i(d)},[l,e,i,a]);return[c,u]}function Coe({defaultProp:e,onChange:t}){const[r,n]=p.useState(e),s=p.useRef(r),i=p.useRef(t);return Soe(()=>{i.current=t},[t]),p.useEffect(()=>{var a;s.current!==r&&((a=i.current)==null||a.call(i,r),s.current=r)},[r,s]),[r,n,i]}function Eoe(e){return typeof e=="function"}function koe(e){const t=p.useRef({value:e,previous:e});return p.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var LT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Ioe="VisuallyHidden",Noe=p.forwardRef((e,t)=>o.jsx(ir.span,{...e,ref:t,style:{...LT,...e.style}}));Noe.displayName=Ioe;var Roe=[" ","Enter","ArrowUp","ArrowDown"],joe=[" ","Enter"],ua="Select",[pp,mp,Aoe]=Kie(ua),[ka]=zb(ua,[Aoe,ET]),gp=ET(),[Toe,wo]=ka(ua),[Doe,Poe]=ka(ua),Loe="SelectProvider";function MT(e){const{__scopeSelect:t,children:r,open:n,defaultOpen:s,onOpenChange:i,value:a,defaultValue:l,onValueChange:c,dir:u,name:d,autoComplete:h,disabled:f,required:m,form:g,internal_do_not_use_render:v}=e,x=gp(t),[b,_]=p.useState(null),[C,S]=p.useState(null),[w,y]=p.useState(!1),N=Gie(u),[E,k]=g2({prop:n,defaultProp:s??!1,onChange:i,caller:ua}),[D,j]=g2({prop:a,defaultProp:l,onChange:c,caller:ua}),R=p.useRef(null),I=p.useRef(D);p.useEffect(()=>{const U=g?b==null?void 0:b.ownerDocument.getElementById(g):b==null?void 0:b.form;if(U instanceof HTMLFormElement){const F=()=>j(I.current);return U.addEventListener("reset",F),()=>U.removeEventListener("reset",F)}},[g,b,j]);const T=b?!!g||!!b.closest("form"):!0,[A,P]=p.useState(new Set),O=Ub(),L=Array.from(A).map(U=>U.props.value).join(";"),B=p.useCallback(U=>{P(F=>new Set(F).add(U))},[]),M=p.useCallback(U=>{P(F=>{const K=new Set(F);return K.delete(U),K})},[]),$={required:m,trigger:b,onTriggerChange:_,valueNode:C,onValueNodeChange:S,valueNodeHasChildren:w,onValueNodeHasChildrenChange:y,contentId:O,value:D,onValueChange:j,open:E,onOpenChange:k,dir:N,triggerPointerDownPosRef:R,disabled:f,name:d,autoComplete:h,form:g,nativeOptions:A,nativeSelectKey:L,isFormControl:T};return o.jsx(poe,{...x,children:o.jsx(Toe,{scope:t,...$,children:o.jsx(pp.Provider,{scope:t,children:o.jsx(Doe,{scope:t,onNativeOptionAdd:B,onNativeOptionRemove:M,children:Yoe(v)?v($):r})})})})}MT.displayName=Loe;var OT=e=>{const{__scopeSelect:t,children:r,...n}=e;return o.jsx(MT,{__scopeSelect:t,...n,internal_do_not_use_render:({isFormControl:s})=>o.jsxs(o.Fragment,{children:[r,s?o.jsx(i4,{__scopeSelect:t}):null]})})};OT.displayName=ua;var BT="SelectTrigger",Kb=p.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:n=!1,...s}=e,i=gp(r),a=wo(BT,r),l=a.disabled||n,c=yr(t,a.onTriggerChange),u=mp(r),d=p.useRef("touch"),[h,f,m]=o4(v=>{const x=u().filter(C=>!C.disabled),b=x.find(C=>C.value===a.value),_=a4(x,v,b);_!==void 0&&a.onValueChange(_.value)}),g=v=>{l||(a.onOpenChange(!0),m()),v&&(a.triggerPointerDownPosRef.current={x:Math.round(v.pageX),y:Math.round(v.pageY)})};return o.jsx(moe,{asChild:!0,...i,children:o.jsx(ir.button,{type:"button",role:"combobox","aria-controls":a.open?a.contentId:void 0,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":vp(a.value)?"":void 0,...s,ref:c,onClick:ur(s.onClick,v=>{v.currentTarget.focus(),d.current!=="mouse"&&g(v)}),onPointerDown:ur(s.onPointerDown,v=>{d.current=v.pointerType;const x=v.target;x.hasPointerCapture(v.pointerId)&&x.releasePointerCapture(v.pointerId),v.button===0&&v.ctrlKey===!1&&v.pointerType==="mouse"&&(g(v),v.preventDefault())}),onKeyDown:ur(s.onKeyDown,v=>{const x=h.current!=="";!(v.ctrlKey||v.altKey||v.metaKey)&&v.key.length===1&&f(v.key),!(x&&v.key===" ")&&Roe.includes(v.key)&&(g(),v.preventDefault())})})})});Kb.displayName=BT;var FT="SelectValue",$T=p.forwardRef((e,t)=>{const{__scopeSelect:r,className:n,style:s,children:i,placeholder:a="",...l}=e,c=wo(FT,r),{onValueNodeHasChildrenChange:u}=c,d=i!==void 0,h=yr(t,c.onValueNodeChange);zr(()=>{u(d)},[u,d]);const f=vp(c.value);return o.jsx(ir.span,{...l,asChild:f?!1:l.asChild,ref:h,style:{pointerEvents:"none"},children:o.jsx(p.Fragment,{children:f?a:i},f?"placeholder":"value")})});$T.displayName=FT;var Moe="SelectIcon",zT=p.forwardRef((e,t)=>{const{__scopeSelect:r,children:n,...s}=e;return o.jsx(ir.span,{"aria-hidden":!0,...s,ref:t,children:n||"▼"})});zT.displayName=Moe;var UT="SelectPortal",[Ooe,Boe]=ka(UT,{forceMount:void 0}),HT=e=>{const{__scopeSelect:t,forceMount:r,...n}=e;return o.jsx(Ooe,{scope:e.__scopeSelect,forceMount:r,children:o.jsx(DT,{asChild:!0,...n})})};HT.displayName=UT;var mo="SelectContent",Vb=p.forwardRef((e,t)=>{const r=Boe(mo,e.__scopeSelect),{forceMount:n=r.forceMount,...s}=e,i=wo(mo,e.__scopeSelect),[a,l]=p.useState();return zr(()=>{l(new DocumentFragment)},[]),o.jsx(PT,{present:n||i.open,children:({present:c})=>c?o.jsx(KT,{...s,ref:t}):o.jsx(WT,{...s,fragment:a})})});Vb.displayName=mo;var WT=p.forwardRef((e,t)=>{const{__scopeSelect:r,children:n,fragment:s}=e;return s?Yr.createPortal(o.jsx(qT,{scope:r,children:o.jsx(pp.Slot,{scope:r,children:o.jsx("div",{ref:t,children:n})})}),s):null});WT.displayName="SelectContentFragment";var is=10,[qT,So]=ka(mo),Foe="SelectContentImpl",$oe=Rh("SelectContent.RemoveScroll"),KT=p.forwardRef((e,t)=>{const{__scopeSelect:r}=e,{position:n="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:i,onPointerDownOutside:a,side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:h,collisionBoundary:f,collisionPadding:m,sticky:g,hideWhenDetached:v,avoidCollisions:x,...b}=e,_=wo(mo,r),[C,S]=p.useState(null),[w,y]=p.useState(null),N=yr(t,S),[E,k]=p.useState(null),[D,j]=p.useState(null),R=mp(r),[I,T]=p.useState(!1),A=p.useRef(!1);p.useEffect(()=>{if(C)return jf(C)},[C]),Yie();const P=p.useCallback(H=>{const[G,...z]=R().map(re=>re.ref.current),[ee]=z.slice(-1),V=document.activeElement;for(const re of H)if(re===V||(re==null||re.scrollIntoView({block:"nearest"}),re===G&&w&&(w.scrollTop=0),re===ee&&w&&(w.scrollTop=w.scrollHeight),re==null||re.focus(),document.activeElement!==V))return},[R,w]),O=p.useCallback(()=>P([E,C]),[P,E,C]);p.useEffect(()=>{I&&O()},[I,O]);const{onOpenChange:L,triggerPointerDownPosRef:B}=_;p.useEffect(()=>{if(C){let H={x:0,y:0};const G=ee=>{var V,re;H={x:Math.abs(Math.round(ee.pageX)-(((V=B.current)==null?void 0:V.x)??0)),y:Math.abs(Math.round(ee.pageY)-(((re=B.current)==null?void 0:re.y)??0))}},z=ee=>{H.x<=10&&H.y<=10?ee.preventDefault():ee.composedPath().includes(C)||L(!1),document.removeEventListener("pointermove",G),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",G),document.addEventListener("pointerup",z,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",G),document.removeEventListener("pointerup",z,{capture:!0})}}},[C,L,B]),p.useEffect(()=>{const H=()=>L(!1);return window.addEventListener("blur",H),window.addEventListener("resize",H),()=>{window.removeEventListener("blur",H),window.removeEventListener("resize",H)}},[L]);const[M,$]=o4(H=>{const G=R().filter(V=>!V.disabled),z=G.find(V=>V.ref.current===document.activeElement),ee=a4(G,H,z);ee&&setTimeout(()=>{var V;return(V=ee.ref.current)==null?void 0:V.focus()})}),U=p.useCallback((H,G,z)=>{const ee=!A.current&&!z;(_.value!==void 0&&_.value===G||ee)&&(k(H),ee&&(A.current=!0))},[_.value]),F=p.useCallback(()=>C==null?void 0:C.focus(),[C]),K=p.useCallback((H,G,z)=>{const ee=!A.current&&!z;(_.value!==void 0&&_.value===G||ee)&&j(H)},[_.value]),Y=n==="popper"?xv:VT,te=Y===xv?{side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:h,collisionBoundary:f,collisionPadding:m,sticky:g,hideWhenDetached:v,avoidCollisions:x}:{};return o.jsx(qT,{scope:r,content:C,viewport:w,onViewportChange:y,itemRefCallback:U,selectedItem:E,onItemLeave:F,itemTextRefCallback:K,focusSelectedItem:O,selectedItemText:D,position:n,isPositioned:I,searchRef:M,children:o.jsx(Eu,{as:$oe,allowPinchZoom:!0,children:o.jsx(yT,{asChild:!0,trapped:_.open,onMountAutoFocus:H=>{H.preventDefault()},onUnmountAutoFocus:ur(s,H=>{var G;(G=_.trigger)==null||G.focus({preventScroll:!0}),H.preventDefault()}),children:o.jsx(Cu,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:H=>H.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:o.jsx(Y,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:H=>H.preventDefault(),...b,...te,onPlaced:()=>T(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:ur(b.onKeyDown,H=>{const G=H.ctrlKey||H.altKey||H.metaKey;if(H.key==="Tab"&&H.preventDefault(),!G&&H.key.length===1&&$(H.key),["ArrowUp","ArrowDown","Home","End"].includes(H.key)){let ee=R().filter(V=>!V.disabled).map(V=>V.ref.current);if(["ArrowUp","End"].includes(H.key)&&(ee=ee.slice().reverse()),["ArrowUp","ArrowDown"].includes(H.key)){const V=H.target,re=ee.indexOf(V);ee=ee.slice(re+1)}setTimeout(()=>P(ee)),H.preventDefault()}})})})})})})});KT.displayName=Foe;var zoe="SelectItemAlignedPosition",VT=p.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:n,...s}=e,i=wo(mo,r),a=So(mo,r),[l,c]=p.useState(null),[u,d]=p.useState(null),h=yr(t,d),f=mp(r),m=p.useRef(!1),g=p.useRef(!0),{viewport:v,selectedItem:x,selectedItemText:b,focusSelectedItem:_}=a,C=p.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&u&&v&&x&&b){const N=i.trigger.getBoundingClientRect(),E=u.getBoundingClientRect(),k=i.valueNode.getBoundingClientRect(),D=b.getBoundingClientRect();if(i.dir!=="rtl"){const V=D.left-E.left,re=k.left-V,oe=N.left-re,ce=N.width+oe,be=Math.max(ce,E.width),ne=window.innerWidth-is,Te=c2(re,[is,Math.max(is,ne-be)]);l.style.minWidth=ce+"px",l.style.left=Te+"px"}else{const V=E.right-D.right,re=window.innerWidth-k.right-V,oe=window.innerWidth-N.right-re,ce=N.width+oe,be=Math.max(ce,E.width),ne=window.innerWidth-is,Te=c2(re,[is,Math.max(is,ne-be)]);l.style.minWidth=ce+"px",l.style.right=Te+"px"}const j=f(),R=window.innerHeight-is*2,I=v.scrollHeight,T=window.getComputedStyle(u),A=parseInt(T.borderTopWidth,10),P=parseInt(T.paddingTop,10),O=parseInt(T.borderBottomWidth,10),L=parseInt(T.paddingBottom,10),B=A+P+I+L+O,M=Math.min(x.offsetHeight*5,B),$=window.getComputedStyle(v),U=parseInt($.paddingTop,10),F=parseInt($.paddingBottom,10),K=N.top+N.height/2-is,Y=R-K,te=x.offsetHeight/2,H=x.offsetTop+te,G=A+P+H,z=B-G;if(G<=K){const V=j.length>0&&x===j[j.length-1].ref.current;l.style.bottom="0px";const re=u.clientHeight-v.offsetTop-v.offsetHeight,oe=Math.max(Y,te+(V?F:0)+re+O),ce=G+oe;l.style.height=ce+"px"}else{const V=j.length>0&&x===j[0].ref.current;l.style.top="0px";const oe=Math.max(K,A+v.offsetTop+(V?U:0)+te)+z;l.style.height=oe+"px",v.scrollTop=G-K+v.offsetTop}l.style.margin=`${is}px 0`,l.style.minHeight=M+"px",l.style.maxHeight=R+"px",n==null||n(),requestAnimationFrame(()=>m.current=!0)}},[f,i.trigger,i.valueNode,l,u,v,x,b,i.dir,n]);zr(()=>C(),[C]);const[S,w]=p.useState();zr(()=>{u&&w(window.getComputedStyle(u).zIndex)},[u]);const y=p.useCallback(N=>{N&&g.current===!0&&(C(),_==null||_(),g.current=!1)},[C,_]);return o.jsx(Hoe,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:m,onScrollButtonChange:y,children:o.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:o.jsx(ir.div,{...s,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});VT.displayName=zoe;var Uoe="SelectPopperPosition",xv=p.forwardRef((e,t)=>{const{__scopeSelect:r,align:n="start",collisionPadding:s=is,...i}=e,a=gp(r);return o.jsx(goe,{...a,...i,ref:t,align:n,collisionPadding:s,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});xv.displayName=Uoe;var[Hoe,Gb]=ka(mo,{}),bv="SelectViewport",GT=p.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:n,...s}=e,i=So(bv,r),a=Gb(bv,r),l=yr(t,i.onViewportChange),c=p.useRef(0);return o.jsxs(o.Fragment,{children:[o.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),o.jsx(pp.Slot,{scope:r,children:o.jsx(ir.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:ur(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:f}=a;if(f!=null&&f.current&&h){const m=Math.abs(c.current-d.scrollTop);if(m>0){const g=window.innerHeight-is*2,v=parseFloat(h.style.minHeight),x=parseFloat(h.style.height),b=Math.max(v,x);if(b<g){const _=b+m,C=Math.min(g,_),S=_-C;h.style.height=C+"px",h.style.bottom==="0px"&&(d.scrollTop=S>0?S:0,h.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});GT.displayName=bv;var YT="SelectGroup",[Woe,qoe]=ka(YT),XT=p.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e,s=Ub();return o.jsx(Woe,{scope:r,id:s,children:o.jsx(ir.div,{role:"group","aria-labelledby":s,...n,ref:t})})});XT.displayName=YT;var JT="SelectLabel",Yb=p.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e,s=qoe(JT,r);return o.jsx(ir.div,{id:s.id,...n,ref:t})});Yb.displayName=JT;var ff="SelectItem",[Koe,QT]=ka(ff),Xb=p.forwardRef((e,t)=>{const{__scopeSelect:r,value:n,disabled:s=!1,textValue:i,...a}=e,l=wo(ff,r),c=So(ff,r),u=l.value===n,[d,h]=p.useState(i??""),[f,m]=p.useState(!1),g=mi(C=>{var S;return(S=c.itemRefCallback)==null?void 0:S.call(c,C,n,s)}),v=yr(t,g),x=Ub(),b=p.useRef("touch"),_=()=>{s||(l.onValueChange(n),l.onOpenChange(!1))};return o.jsx(Koe,{scope:r,value:n,disabled:s,textId:x,isSelected:u,onItemTextChange:p.useCallback(C=>{h(S=>S||((C==null?void 0:C.textContent)??"").trim())},[]),children:o.jsx(pp.ItemSlot,{scope:r,value:n,disabled:s,textValue:d,children:o.jsx(ir.div,{role:"option","aria-labelledby":x,"data-highlighted":f?"":void 0,"aria-selected":u&&f,"data-state":u?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:v,onFocus:ur(a.onFocus,()=>m(!0)),onBlur:ur(a.onBlur,()=>m(!1)),onClick:ur(a.onClick,()=>{b.current!=="mouse"&&_()}),onPointerUp:ur(a.onPointerUp,()=>{b.current==="mouse"&&_()}),onPointerDown:ur(a.onPointerDown,C=>{b.current=C.pointerType}),onPointerMove:ur(a.onPointerMove,C=>{var S;b.current=C.pointerType,s?(S=c.onItemLeave)==null||S.call(c):b.current==="mouse"&&C.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ur(a.onPointerLeave,C=>{var S;C.currentTarget===document.activeElement&&((S=c.onItemLeave)==null||S.call(c))}),onKeyDown:ur(a.onKeyDown,C=>{var w;s||C.target!==C.currentTarget||((w=c.searchRef)==null?void 0:w.current)!==""&&C.key===" "||(joe.includes(C.key)&&_(),C.key===" "&&C.preventDefault())})})})})});Xb.displayName=ff;var Sc="SelectItemText",ZT=p.forwardRef((e,t)=>{const{__scopeSelect:r,className:n,style:s,...i}=e,a=wo(Sc,r),l=So(Sc,r),c=QT(Sc,r),u=Poe(Sc,r),[d,h]=p.useState(null),f=mi(_=>{var C;return(C=l.itemTextRefCallback)==null?void 0:C.call(l,_,c.value,c.disabled)}),m=yr(t,h,c.onItemTextChange,f),g=d==null?void 0:d.textContent,v=p.useMemo(()=>o.jsx("option",{value:c.value,disabled:c.disabled,children:g},c.value),[c.disabled,c.value,g]),{onNativeOptionAdd:x,onNativeOptionRemove:b}=u;return zr(()=>(x(v),()=>b(v)),[x,b,v]),o.jsxs(o.Fragment,{children:[o.jsx(ir.span,{id:c.textId,...i,ref:m}),c.isSelected&&a.valueNode&&!a.valueNodeHasChildren&&!vp(a.value)?Yr.createPortal(i.children,a.valueNode):null]})});ZT.displayName=Sc;var e4="SelectItemIndicator",t4=p.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e;return QT(e4,r).isSelected?o.jsx(ir.span,{"aria-hidden":!0,...n,ref:t}):null});t4.displayName=e4;var _v="SelectScrollUpButton",Jb=p.forwardRef((e,t)=>{const r=So(_v,e.__scopeSelect),n=Gb(_v,e.__scopeSelect),[s,i]=p.useState(!1),a=yr(t,n.onScrollButtonChange);return zr(()=>{if(r.viewport&&r.isPositioned){let l=function(){const u=c.scrollTop>0;i(u)};const c=r.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[r.viewport,r.isPositioned]),s?o.jsx(r4,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=r;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});Jb.displayName=_v;var yv="SelectScrollDownButton",Qb=p.forwardRef((e,t)=>{const r=So(yv,e.__scopeSelect),n=Gb(yv,e.__scopeSelect),[s,i]=p.useState(!1),a=yr(t,n.onScrollButtonChange);return zr(()=>{if(r.viewport&&r.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<u;i(d)};const c=r.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[r.viewport,r.isPositioned]),s?o.jsx(r4,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=r;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});Qb.displayName=yv;var r4=p.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:n,...s}=e,i=So("SelectScrollButton",r),a=p.useRef(null),l=mp(r),c=p.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return p.useEffect(()=>()=>c(),[c]),zr(()=>{var d;const u=l().find(h=>h.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[l]),o.jsx(ir.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:ur(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(n,50))}),onPointerMove:ur(s.onPointerMove,()=>{var u;(u=i.onItemLeave)==null||u.call(i),a.current===null&&(a.current=window.setInterval(n,50))}),onPointerLeave:ur(s.onPointerLeave,()=>{c()})})}),Voe="SelectSeparator",Zb=p.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e;return o.jsx(ir.div,{"aria-hidden":!0,...n,ref:t})});Zb.displayName=Voe;var n4="SelectArrow",Goe=p.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e,s=gp(r);return So(n4,r).position==="popper"?o.jsx(voe,{...s,...n,ref:t}):null});Goe.displayName=n4;var s4="SelectBubbleInput",i4=p.forwardRef(({__scopeSelect:e,...t},r)=>{const n=wo(s4,e),{value:s,onValueChange:i,required:a,disabled:l,name:c,autoComplete:u,form:d}=n,{nativeOptions:h,nativeSelectKey:f}=n,m=p.useRef(null),g=yr(r,m),v=s??"",x=koe(v),b=Array.from(h).some(_=>(_.props.value??"")==="");return p.useEffect(()=>{const _=m.current;if(!_)return;const C=window.HTMLSelectElement.prototype,w=Object.getOwnPropertyDescriptor(C,"value").set;if(x!==v&&w){const y=new Event("change",{bubbles:!0});w.call(_,v),_.dispatchEvent(y)}},[x,v]),o.jsxs(ir.select,{"aria-hidden":!0,required:a,tabIndex:-1,name:c,autoComplete:u,disabled:l,form:d,onChange:_=>i(_.target.value),...t,style:{...LT,...t.style},ref:g,defaultValue:v,children:[vp(s)&&!b?o.jsx("option",{value:""}):null,Array.from(h)]},f)});i4.displayName=s4;function Yoe(e){return typeof e=="function"}function vp(e){return e===""||e===void 0}function o4(e){const t=mi(e),r=p.useRef(""),n=p.useRef(0),s=p.useCallback(a=>{const l=r.current+a;t(l),(function c(u){r.current=u,window.clearTimeout(n.current),u!==""&&(n.current=window.setTimeout(()=>c(""),1e3))})(l)},[t]),i=p.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return p.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,s,i]}function a4(e,t,r){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=r?e.indexOf(r):-1;let a=Xoe(e,Math.max(i,0));s.length===1&&(a=a.filter(u=>u!==r));const c=a.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==r?c:void 0}function Xoe(e,t){return e.map((r,n)=>e[(t+n)%e.length])}const e_=OT,t_=XT,r_=$T,xp=p.forwardRef(({className:e,children:t,...r},n)=>o.jsxs(Kb,{ref:n,className:Xe("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",e),...r,children:[t,o.jsx(zT,{asChild:!0,children:o.jsx(Kv,{className:"h-4 w-4 opacity-50"})})]}));xp.displayName=Kb.displayName;const l4=p.forwardRef(({className:e,...t},r)=>o.jsx(Jb,{ref:r,className:Xe("flex cursor-default items-center justify-center py-1",e),...t,children:o.jsx(AL,{className:"h-4 w-4"})}));l4.displayName=Jb.displayName;const c4=p.forwardRef(({className:e,...t},r)=>o.jsx(Qb,{ref:r,className:Xe("flex cursor-default items-center justify-center py-1",e),...t,children:o.jsx(Kv,{className:"h-4 w-4"})}));c4.displayName=Qb.displayName;const bp=p.forwardRef(({className:e,children:t,position:r="popper",...n},s)=>{const i=hr(s,"intersection");return o.jsx(HT,{children:o.jsxs(Vb,{ref:i,className:Xe("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]",r==="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",e),position:r,...n,children:[o.jsx(l4,{}),o.jsx(GT,{className:Xe("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),o.jsx(c4,{})]})})});bp.displayName=Vb.displayName;const Joe=p.forwardRef(({className:e,...t},r)=>o.jsx(Yb,{ref:r,className:Xe("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Joe.displayName=Yb.displayName;const Gn=p.forwardRef(({className:e,children:t,...r},n)=>o.jsxs(Xb,{ref:n,className:Xe("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",e),...r,children:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(t4,{children:o.jsx(di,{className:"h-4 w-4"})})}),o.jsx(ZT,{children:t})]}));Gn.displayName=Xb.displayName;const Qoe=p.forwardRef(({className:e,...t},r)=>o.jsx(Zb,{ref:r,className:Xe("-mx-1 my-1 h-px bg-muted",e),...t}));Qoe.displayName=Zb.displayName;function Zoe({apiBase:e,token:t}){const[r,n]=p.useState("project"),[s,i]=p.useState(""),[a,l]=p.useState(null),[c,u]=p.useState(null),d=Ct({queryKey:["activity","delete-job",e,c],queryFn:()=>Wie(e,t,c),enabled:!!c,refetchInterval:f=>{var m;return((m=f.state.data)==null?void 0:m.status)==="completed"?!1:1e3}}),h=nr({mutationFn:async f=>{const m=s.trim();if(!m)throw new Error("Enter a scope ID");return Hie(e,t,f,r==="project"?{projectId:m}:{threadId:m})},onSuccess:f=>{l(f);const m=f;typeof m.deleteJobId=="string"&&u(m.deleteJobId)}});return o.jsxs("section",{className:"mt-5 rounded-xl border border-border/70 bg-card/70 p-5",children:[o.jsx("h2",{className:"font-semibold",children:"Export or delete a scope"}),o.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.jsxs(e_,{value:r,onValueChange:f=>n(f),children:[o.jsx(xp,{className:"h-9 w-44","aria-label":"Scope type",children:o.jsx(r_,{})}),o.jsx(bp,{children:o.jsxs(t_,{children:[o.jsx(Gn,{value:"project",children:"Project"}),o.jsx(Gn,{value:"thread",children:"Thread"})]})})]}),o.jsx("input",{className:"h-9 min-w-0 flex-1 basis-72 rounded-lg border border-border bg-background px-3 text-sm",value:s,onChange:f=>i(f.target.value),placeholder:`${r} ID`}),o.jsx(Z,{variant:"outline",onClick:()=>h.mutate("export"),disabled:h.isPending,children:"Export"}),o.jsxs(Tl,{children:[o.jsx(Nz,{asChild:!0,children:o.jsx(Z,{variant:"destructive",disabled:h.isPending,children:"Delete"})}),o.jsxs(xa,{children:[o.jsxs(Dl,{children:[o.jsx(ba,{children:"Delete Activity data?"}),o.jsxs(_a,{children:["This permanently deletes Activity facts and short-lived content for ",r," ",s.trim()||"Not recorded",". This action cannot be undone."]})]}),o.jsxs(Pl,{children:[o.jsx(ya,{disabled:h.isPending,children:"Cancel"}),o.jsx(Lu,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:h.isPending,onClick:()=>h.mutate("delete"),children:"Delete Activity data"})]})]})]})]}),h.isError?o.jsx("p",{className:"mt-3 text-sm text-destructive",children:h.error.message}):null,d.data?o.jsxs("div",{className:"mt-4 rounded-lg border border-border bg-background p-4 text-sm",children:[o.jsxs("p",{className:"font-medium",children:["Delete job ",d.data.status]}),o.jsxs("p",{className:"mt-2 text-muted-foreground",children:[d.data.deletedFactCount," /"," ",d.data.previewFactCount," facts physically deleted"]}),d.data.lastErrorCode?o.jsx("p",{className:"mt-2 text-destructive",children:d.data.lastErrorCode}):null]}):null,a?o.jsx("pre",{className:"mt-4 max-h-64 overflow-auto rounded-lg bg-muted/50 p-3 text-xs",children:JSON.stringify(a,null,2)}):null]})}const v2=[{id:"terminals",label:"Terminal History",icon:vE,group:"Work history"},{id:"facts",label:"Events",icon:XL,group:"Raw data"},{id:"timeline",label:"Timeline",icon:fE,group:"Raw data"},{id:"sources",label:"Sources",icon:wO,group:"Raw data"},{id:"policy",label:"Data Policy",icon:Yv,group:"Data"}];function u4(e){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(e))}function d4({fact:e,onSelect:t}){const r=e.scope.threadId??e.scope.runId??e.scope.projectId??e.scope.terminalSessionId??"unlinked";return o.jsxs("article",{className:"flex select-text items-start justify-between gap-4 border-b border-border/70 px-5 py-4 last:border-b-0",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("span",{className:"rounded-full border border-border bg-muted/70 px-2 py-0.5 text-[0.68rem] font-medium text-muted-foreground",children:"Recorded"}),o.jsx("h3",{className:"truncate text-sm font-semibold text-foreground",children:e.eventName})]}),o.jsx("p",{className:"mt-2 truncate text-xs text-muted-foreground",children:r}),o.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[0.68rem] text-muted-foreground",children:[o.jsx("span",{className:"rounded-full border border-border/70 px-2 py-1",children:e.runtime.channel}),o.jsx("span",{className:"rounded-full border border-border/70 px-2 py-1",children:e.runtime.surface}),o.jsxs("span",{className:"rounded-full border border-border/70 px-2 py-1",children:["offset ",e.activityOffset]})]})]}),o.jsxs("div",{className:"flex shrink-0 items-start gap-2",children:[o.jsx("time",{className:"pt-2 text-xs text-muted-foreground",children:u4(e.occurredAt)}),t?o.jsx(Z,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":`Open ${e.eventName} event details`,onClick:()=>t(e),children:o.jsx(Jr,{className:"h-4 w-4"})}):null]})]})}function su({message:e}){return o.jsx("div",{className:"flex min-h-56 items-center justify-center px-6 text-center text-sm text-muted-foreground",children:e})}function eae({embedded:e=!1,view:t,onSelectView:r,currentSourceCount:n,sourceCount:s}){return e?o.jsxs("nav",{"aria-label":"Activity views",className:"settings-tabs shrink-0 border-b pb-2",children:[v2.map(i=>o.jsx("button",{"aria-current":t===i.id?"page":void 0,onClick:()=>r(i.id),children:i.label},i.id)),o.jsxs("span",{className:"ml-auto self-center text-xs text-muted-foreground",children:[n,"/",s," sources current"]})]}):o.jsxs("aside",{className:"min-h-0 overflow-y-auto border-r border-border/70 bg-card/55 p-4 max-md:overflow-hidden max-md:border-b max-md:border-r-0 max-md:px-3 max-md:py-2",children:[o.jsxs("div",{className:"flex items-center gap-3 px-2 py-3 max-md:hidden",children:[o.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[hsl(var(--primary))] text-sm font-bold text-primary-foreground",children:"R"}),o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-semibold tracking-[0.18em]",children:"RUNWEAVE"}),o.jsx("p",{className:"text-[0.68rem] text-muted-foreground",children:"Activity"})]})]}),o.jsx("nav",{className:"mt-6 grid gap-1 max-md:mt-0 max-md:flex max-md:gap-2 max-md:overflow-x-auto max-md:[scrollbar-width:none] max-md:[&::-webkit-scrollbar]:hidden","aria-label":"Activity views",children:["Work history","Raw data","Data"].map(i=>o.jsxs("div",{className:"mb-3 grid gap-1 max-md:contents",children:[o.jsx("p",{className:"px-3 pb-1 text-[0.65rem] font-semibold uppercase tracking-[0.16em] text-muted-foreground max-md:hidden",children:i}),v2.filter(a=>a.group===i).map(a=>{const l=a.icon;return o.jsxs("button",{type:"button","aria-current":t===a.id?"page":void 0,className:`flex h-10 items-center gap-3 whitespace-nowrap rounded-lg px-3 text-left text-sm max-md:shrink-0 ${t===a.id?"bg-[hsl(var(--primary))]/12 text-foreground":"text-muted-foreground hover:bg-muted/60"}`,onClick:()=>r(a.id),children:[o.jsx(l,{className:"h-4 w-4"}),a.label]},a.id)})]},i))}),o.jsxs("div",{className:"mt-8 border-t border-border/70 px-2 pt-4 text-xs text-muted-foreground max-md:hidden",children:[n," of ",s," sources current"]})]})}function tae({search:e,runtimeChannel:t,onSearchChange:r,onRuntimeChannelChange:n}){return o.jsx("header",{className:"flex shrink-0 items-center gap-2 border-b border-border/70 pb-2",children:o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Sa,{className:"max-md:max-w-40"}),o.jsxs("label",{className:"flex h-9 min-w-72 items-center gap-2 rounded-lg border border-border bg-card px-3 text-sm max-lg:min-w-0 max-lg:flex-1",children:[o.jsx(Gv,{className:"h-4 w-4 text-muted-foreground"}),o.jsx("input",{className:"min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground",value:e,onChange:s=>r(s.target.value),placeholder:"Search event, Thread, project"})]}),o.jsxs(e_,{value:t||"all",onValueChange:s=>n(s==="all"?"":s),children:[o.jsx(xp,{className:"h-9 w-36 bg-card max-md:w-28","aria-label":"Runtime",children:o.jsx(r_,{})}),o.jsx(bp,{children:o.jsxs(t_,{children:[o.jsx(Gn,{value:"all",children:"All runtimes"}),o.jsx(Gn,{value:"stable",children:"Stable"}),o.jsx(Gn,{value:"beta",children:"Beta"}),o.jsx(Gn,{value:"dev",children:"Dev"}),o.jsx(Gn,{value:"external",children:"External"})]})})]})]})})}function rae({facts:e,frozenOffset:t,isError:r,hasNextPage:n,isFetchingNextPage:s,onLoadMore:i,onSelectFact:a}){return o.jsxs("section",{className:"overflow-hidden rounded-xl border border-border/70 bg-card/70",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-border/70 px-5 py-4",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold",children:"Recorded events"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Frozen at offset ",t]})]}),o.jsxs("span",{className:"text-sm tabular-nums text-muted-foreground",children:[e.length," recorded"]})]}),r?o.jsx(su,{message:"Activity facts are unavailable."}):e.length===0?o.jsx(su,{message:"No recorded facts match these filters."}):e.map(l=>o.jsx(d4,{fact:l,onSelect:a},l.eventId)),n?o.jsx("div",{className:"border-t border-border/70 p-4 text-center",children:o.jsx(Z,{variant:"outline",onClick:i,disabled:s,children:s?"Loading…":"Load more"})}):null]})}function nae({timelineType:e,timelineId:t,computed:r,onTimelineTypeChange:n,onTimelineIdChange:s,children:i}){return o.jsxs("section",{className:"rounded-xl border border-border/70 bg-card/70 p-5",children:[o.jsx("h2",{className:"font-semibold",children:"Interaction Timeline"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Timelines use explicit IDs only; time proximity never creates a link."}),r?o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[o.jsx("span",{className:"font-medium text-foreground",children:"Computed"}),` · ${r.eventCount} events`,r.durationMs!==void 0?` · ${r.durationMs} ms duration`:""]}):null,o.jsxs("div",{className:"mt-5 flex gap-2 max-sm:flex-col",children:[o.jsxs(e_,{value:e,onValueChange:a=>n(a),children:[o.jsx(xp,{className:"h-9 w-40 max-sm:w-full","aria-label":"Timeline type",children:o.jsx(r_,{})}),o.jsx(bp,{children:o.jsxs(t_,{children:[o.jsx(Gn,{value:"interaction",children:"Interaction"}),o.jsx(Gn,{value:"correlation",children:"Correlation"}),o.jsx(Gn,{value:"thread",children:"Thread"}),o.jsx(Gn,{value:"run",children:"Run"})]})})]}),o.jsx("input",{className:"h-9 flex-1 rounded-lg border border-border bg-background px-3 text-sm outline-none",value:t,onChange:a=>s(a.target.value),placeholder:`Enter ${e} ID`})]}),i]})}function sae({deferredTimelineId:e,facts:t,hasNextPage:r,isFetchingNextPage:n,onLoadMore:s}){return o.jsxs("div",{className:"mt-5 overflow-hidden rounded-lg border border-border/70",children:[e?t.length===0?o.jsx(su,{message:"No facts are linked to this ID."}):t.map(i=>o.jsx(d4,{fact:i},i.eventId)):o.jsx(su,{message:"Enter an explicit ID to open a timeline."}),r?o.jsx("div",{className:"border-t border-border/70 p-4 text-center",children:o.jsx(Z,{variant:"outline",onClick:s,disabled:n,children:n?"Loading…":"Load more"})}):null]})}function iae({currentSourceCount:e,sources:t,policy:r}){return o.jsxs("section",{className:"overflow-hidden rounded-xl border border-border/70 bg-card/70",children:[o.jsxs("div",{className:"border-b border-border/70 px-5 py-4",children:[o.jsx("h2",{className:"font-semibold",children:"Sources"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[e," current of ",t.length," observed sources"]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["WAL ",(r==null?void 0:r.journalMode)??"unavailable",r!=null&&r.lastCheckpointAt?` · checkpoint ${r.lastCheckpointAt}`:" · checkpoint not observed"]})]}),t.length===0?o.jsx(su,{message:"No producer source has been observed."}):t.map(n=>o.jsxs("article",{className:"grid grid-cols-[minmax(0,1fr)_repeat(3,auto)] items-center gap-6 border-b border-border/70 px-5 py-4 text-sm last:border-b-0 max-md:grid-cols-1",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"truncate font-medium",children:n.producerName}),o.jsxs("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:[n.runtimeChannel," · ",n.runtimeSurface," ·"," ",n.producerVersion]}),o.jsxs("p",{className:"mt-1 break-all text-xs text-muted-foreground",children:["instance ",n.producerInstanceId," · boot"," ",n.producerBootId]}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:n.gapRanges.length===0?"no observed gap ranges":n.gapRanges.map(s=>`${s.firstSequence}-${s.lastSequence} ${s.status}${s.reasonCode?` (${s.reasonCode})`:""}`).join(" · ")}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[n.rejectionCount," rejections",n.lastCommitLatencyMs!==void 0?` · ${n.lastCommitLatencyMs} ms last commit`:" · latency unavailable",n.lastErrorCode?` · error ${n.lastErrorCode}`:" · no error"]})]}),o.jsxs("span",{className:"tabular-nums",children:[n.highestContiguousSequence,"/",n.highestSeenSequence]}),o.jsxs("span",{children:[n.openGapCount," gaps"]}),o.jsx("span",{className:"text-xs text-muted-foreground",children:u4(n.lastSeenAt)})]},`${n.producerInstanceId}:${n.producerBootId}`))]})}function oae({apiBase:e,token:t,policy:r}){return o.jsxs(o.Fragment,{children:[o.jsx("section",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:[["Fact retention",`${(r==null?void 0:r.factRetentionDays)??30} days`,"Recorded metadata"],["Content retention",`${(r==null?void 0:r.contentRetentionDays)??7} days`,"Query, response, command and excerpt"],["SQLite",(r==null?void 0:r.journalMode)??"unavailable",(r==null?void 0:r.databasePathLabel)??"Local database"],["Database size",SQ((r==null?void 0:r.databaseBytes)??0),"Computed from the shared database file"],["Delete jobs",String((r==null?void 0:r.pendingDeleteJobs)??0),"Pending, running or blocked"],["Schema",String((r==null?void 0:r.schemaVersion)??0),"Compatibility major and additive minor"]].map(([n,s,i])=>o.jsxs("article",{className:"rounded-xl border border-border/70 bg-card/70 p-5",children:[o.jsx(tM,{className:"h-5 w-5 text-muted-foreground"}),o.jsx("p",{className:"mt-4 text-xs text-muted-foreground",children:n}),o.jsx("p",{className:"mt-1 text-2xl font-semibold tabular-nums",children:s}),o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:i})]},n))}),o.jsx(Zoe,{apiBase:e,token:t})]})}function h4(e){return{Authorization:`Bearer ${e}`}}function f4(e){const t=new URLSearchParams;for(const[n,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(n,String(s));const r=t.toString();return r?`?${r}`:""}function aae(e,t,r,n){return me(e,`/api/work-history/terminals${f4(r)}`,{headers:h4(t),signal:n})}function lae(e,t,r,n={},s){return me(e,`/api/work-history/terminals/${encodeURIComponent(r)}${f4(n)}`,{headers:h4(t),signal:s})}function cae(e){var n,s,i,a;const t=[{id:`terminal:${e.terminal.terminalSessionId}:created`,occurredAt:e.terminal.createdAt,sourceType:"terminal",sourceId:e.terminal.terminalSessionId,title:"Terminal created",summary:e.terminal.command||e.terminal.cwd,selection:{type:"terminal",terminal:e.terminal}}],r=new Map(e.threadDetails.map(l=>[l.thread.threadId,l]));for(const l of e.threadRefs){const c=r.get(l.threadId);if(c){t.push({id:`thread:${l.threadId}`,occurredAt:l.lastActivityAt,sourceType:"thread",sourceId:l.threadId,title:`${l.agent} Thread`,summary:c.availability==="available"?((n=c.detail)==null?void 0:n.preview)||l.status:c.availability.replaceAll("_"," "),selection:{type:"thread",thread:c}});for(const u of((s=c.detail)==null?void 0:s.turns)??[]){const d="id"in u?u.id:u.turnId;t.push({id:`turn:${l.threadId}:${d}`,occurredAt:u.startedAt??u.completedAt??l.updatedAt,sourceType:"turn",sourceId:`${l.threadId}:${d}`,title:`Turn ${u.status}`,summary:"messages"in u?((i=u.messages.find(h=>h.role==="user"))==null?void 0:i.text)||`${u.itemCount} recorded items`:u.preview||`${u.status} turn`,selection:{type:"thread",thread:c}})}}}for(const l of e.facts.facts)t.push({id:`fact:${l.eventId}`,occurredAt:l.occurredAt,sourceType:"activity",sourceId:l.eventId,title:l.eventName,summary:((a=l.result)==null?void 0:a.status)??l.runtime.surface,selection:{type:"fact",fact:l}});return e.terminal.status==="exited"&&t.push({id:`terminal:${e.terminal.terminalSessionId}:exited`,occurredAt:e.terminal.lastActivityAt,sourceType:"terminal",sourceId:`${e.terminal.terminalSessionId}:exited`,title:"Terminal exited",summary:e.terminal.exitCode===void 0?"Exit code not recorded":`Exit code ${e.terminal.exitCode}`,selection:{type:"terminal",terminal:e.terminal}}),t.sort(uae)}function uae(e,t){return e.occurredAt.localeCompare(t.occurredAt)||x2(e.sourceType)-x2(t.sourceType)||e.sourceId.localeCompare(t.sourceId)}function x2(e){return{terminal:0,thread:1,turn:2,activity:3}[e]}function dae({apiBase:e,token:t,selection:r,onClose:n}){return r?r.type==="fact"?o.jsx("div",{className:"p-4",children:o.jsx(_T,{apiBase:e,token:t,fact:r.fact,onClose:n})}):o.jsxs("div",{className:"p-5",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:r.type}),o.jsx("h2",{className:"mt-2 font-semibold",children:hae(r)})]}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:n,"aria-label":"Close inspector",children:o.jsx(vo,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"mt-5",children:fae(r)})]}):o.jsx("div",{className:"flex min-h-64 items-center justify-center p-6 text-center text-sm text-muted-foreground",children:"Select an event to inspect its recorded details."})}function hae(e){switch(e.type){case"terminal":return e.terminal.alias||e.terminal.terminalSessionId;case"thread":return e.thread.thread.threadId}}function fae(e){var t,r;switch(e.type){case"terminal":return o.jsx(b2,{values:{ID:e.terminal.terminalSessionId,Project:e.terminal.projectId,Status:e.terminal.status,Command:e.terminal.command,Directory:e.terminal.cwd,Created:e.terminal.createdAt,"Last activity":e.terminal.lastActivityAt}});case"thread":{const{thread:n}=e,s=n.detail&&"updatedAt"in n.detail?n.detail.updatedAt:n.thread.updatedAt;return o.jsxs("div",{children:[o.jsx(b2,{values:{Provider:n.thread.agent,Availability:n.availability,Status:((t=n.detail)==null?void 0:t.status)??n.thread.status,Updated:s}}),(r=n.detail)!=null&&r.turns.length?o.jsx("div",{className:"mt-6 grid gap-4",children:n.detail.turns.map(i=>{const a="id"in i?i.id:i.turnId;return"messages"in i?o.jsxs("section",{className:"rounded-lg border border-border/70 p-3",children:[o.jsx("p",{className:"text-sm font-medium",children:a}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[i.status," · ",i.itemsView," · ",i.itemCount," items"]}),o.jsx("div",{className:"mt-3 grid gap-2",children:i.messages.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No text messages recorded."}):i.messages.map(l=>o.jsxs("div",{className:"rounded-md bg-muted/55 p-3 text-sm",children:[o.jsx("p",{className:"text-[0.68rem] font-medium uppercase text-muted-foreground",children:l.role}),o.jsx("p",{className:"mt-1 whitespace-pre-wrap",children:l.text})]},l.id))})]},a):o.jsxs("section",{className:"rounded-lg border border-border/70 p-3",children:[o.jsx("p",{className:"text-sm font-medium",children:a}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[i.status," · ",i.preview||"No preview"]})]},a)})}):o.jsxs("p",{className:"mt-5 text-sm text-muted-foreground",children:["Thread content is ",n.availability.replaceAll("_"," "),"."]})]})}}}function b2({values:e}){return o.jsx("dl",{className:"grid gap-4 text-sm",children:Object.entries(e).map(([t,r])=>o.jsxs("div",{children:[o.jsx("dt",{className:"text-xs text-muted-foreground",children:t}),o.jsx("dd",{className:"mt-1 break-words",children:r??"Not recorded"})]},t))})}function pae({list:e,journal:t,inspector:r,inspectorOpen:n,onCloseInspector:s,mobileDetailOpen:i,mobileDetailLabel:a,onCloseMobileDetail:l}){const c=p.useRef(null),u=p.useRef(null),[d,h]=p.useState(()=>window.matchMedia("(max-width: 1379px)").matches);return p.useEffect(()=>{const f=window.matchMedia("(max-width: 1379px)"),m=()=>h(f.matches);return f.addEventListener("change",m),window.addEventListener("resize",m),m(),()=>{f.removeEventListener("change",m),window.removeEventListener("resize",m)}},[]),p.useEffect(()=>{if(!n)return;c.current=document.activeElement;const f=g=>{var v;if(g.key==="Escape"&&s(),g.key==="Tab"&&window.matchMedia("(max-width: 1379px)").matches){const x=[...((v=u.current)==null?void 0:v.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))??[]].filter(C=>!C.hasAttribute("disabled")),b=x[0],_=x.at(-1);if(!b||!_)return;g.shiftKey&&document.activeElement===b?(g.preventDefault(),_.focus()):!g.shiftKey&&document.activeElement===_&&(g.preventDefault(),b.focus())}};window.addEventListener("keydown",f);const m=window.requestAnimationFrame(()=>{var g,v;window.matchMedia("(max-width: 1379px)").matches&&((v=(g=u.current)==null?void 0:g.querySelector("button"))==null||v.focus())});return()=>{var g;window.removeEventListener("keydown",f),window.cancelAnimationFrame(m),(g=c.current)==null||g.focus()}},[n,s]),o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[300px_minmax(0,1fr)] overflow-hidden rounded-xl border border-border/70 bg-card/50 min-[1380px]:grid-cols-[300px_minmax(0,1fr)_380px] max-md:grid-cols-1",children:[o.jsx("section",{className:`${i?"max-md:hidden":""} min-h-0 min-w-0 overflow-auto border-r border-border/70 max-md:border-r-0`,children:e}),o.jsxs("section",{className:`${i?"":"max-md:hidden"} min-h-0 min-w-0 overflow-auto`,children:[o.jsx("div",{className:"sticky top-0 z-10 hidden border-b border-border/70 bg-background/95 px-3 py-2 backdrop-blur max-md:block",children:o.jsxs("button",{type:"button",className:"flex min-h-10 items-center gap-2 rounded-md px-2 text-sm font-medium text-foreground hover:bg-muted",onClick:l,children:[o.jsx(xi,{className:"h-4 w-4"}),a]})}),t]}),o.jsx("aside",{ref:u,className:`${n?"block":"hidden"} min-h-0 overflow-auto border-l border-border/70 bg-background min-[1380px]:block max-[1379px]:fixed max-[1379px]:inset-y-0 max-[1379px]:right-0 max-[1379px]:z-50 max-[1379px]:w-[min(92vw,420px)] max-[1379px]:shadow-2xl`,"aria-label":"Work history inspector","aria-modal":n&&d?!0:void 0,role:n&&d?"dialog":"complementary",children:r}),n?o.jsx("button",{type:"button","aria-label":"Close inspector",className:"fixed inset-0 z-40 bg-black/35 min-[1380px]:hidden",onClick:s}):null]})}function _2(e){switch(e.type){case"terminal":return`terminal:${e.terminal.terminalSessionId}`;case"thread":return`thread:${e.thread.thread.threadId}`;case"fact":return`fact:${e.fact.eventId}`}}function mae({apiBase:e,token:t,search:r,selectedTerminalId:n,selectedEventKey:s,onSelectTerminal:i,onSelectEvent:a,onSelectEntry:l}){var R,I,T,A,P,O,L,B;const[c,u]=p.useState(null),[d,h]=p.useState(null),f=ia({queryKey:["work-history","terminals",e,r],initialPageParam:void 0,queryFn:({pageParam:M,signal:$})=>aae(e,t,{search:r||void 0,cursor:M,limit:50},$),getNextPageParam:M=>M.nextCursor}),m=((R=f.data)==null?void 0:R.pages.flatMap(M=>M.terminals))??[],g=n??((I=m[0])==null?void 0:I.terminalSessionId)??null,v=ia({queryKey:["work-history","terminal",e,g],initialPageParam:{},queryFn:({pageParam:M,signal:$})=>lae(e,t,g,{activityCursor:M.activityCursor,asOfActivityOffset:M.asOfActivityOffset,threadCursor:M.threadCursor,includeActivity:M.includeActivity,includeThreadDetails:M.includeThreadDetails},$),getNextPageParam:(M,$,U)=>{const F=U.pendingActivityCursor??M.facts.nextCursor;if(M.nextThreadCursor)return{threadCursor:M.nextThreadCursor,includeActivity:!1,pendingActivityCursor:F,asOfActivityOffset:U.asOfActivityOffset??M.asOfActivityOffset};if(F)return{activityCursor:F,asOfActivityOffset:U.asOfActivityOffset??M.asOfActivityOffset,includeThreadDetails:!1}},enabled:!!g,retry:!1}),x=((T=v.data)==null?void 0:T.pages)??[],b=x[0],_=b?{...b,threadDetails:y2(x.flatMap(M=>M.threadDetails),M=>M.thread.threadId),facts:{...b.facts,facts:y2(x.flatMap(M=>M.facts.facts),M=>M.eventId),nextCursor:(A=x.at(-1))==null?void 0:A.facts.nextCursor},nextThreadCursor:(P=x.at(-1))==null?void 0:P.nextThreadCursor,sourceStatus:{...b.sourceStatus,appServer:((O=x.at(-1))==null?void 0:O.sourceStatus.appServer)??b.sourceStatus.appServer,activity:((L=x.findLast(M=>M.facts.facts.length>0))==null?void 0:L.sourceStatus.activity)??b.sourceStatus.activity}}:null,C=_?cae(_):[],S=(B=C.find(M=>_2(M.selection)===s))==null?void 0:B.selection,w=c??S??(_?{type:"terminal",terminal:_.terminal}:null);p.useEffect(()=>{u(null)},[g]),p.useEffect(()=>{n&&v.error instanceof De&&v.error.status===404&&(h(n),i(null))},[v.error,i,n]);const y=W(M=>{h(null),u(null),a(null),i(M)}),N=W(M=>{u(M),g&&l(g,_2(M))}),E=W(()=>{u(null),a(null)}),k=W(()=>{u(null),a(null),i(null)}),D=W(()=>{v.fetchNextPage()}),j=W(()=>{f.fetchNextPage()});return o.jsx(pae,{inspectorOpen:!!(w&&s),onCloseInspector:E,mobileDetailOpen:!!n,mobileDetailLabel:"Terminal History",onCloseMobileDetail:k,list:o.jsxs("div",{children:[o.jsxs("div",{className:"border-b border-border/70 p-4",children:[o.jsx("h2",{className:"font-semibold",children:"Terminal History"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"One archive per terminal session"})]}),f.isError?o.jsx(Ud,{text:"Terminal archives are unavailable."}):m.length===0?o.jsx(Ud,{text:"No Terminal history recorded."}):o.jsxs("div",{children:[m.map(M=>o.jsx("article",{className:`w-full select-text border-b border-border/70 p-4 ${g===M.terminalSessionId?n?"bg-primary/10":"md:bg-primary/10":""}`,children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"truncate text-sm font-medium",children:M.title}),o.jsx("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:M.projectId}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[M.knownThreadCount," known Threads · ",w2(M.lastActivityAt)]})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx("span",{className:"text-[0.68rem] text-muted-foreground",children:M.status}),o.jsx("button",{type:"button","aria-label":`Open ${M.title} Terminal archive`,className:"flex h-10 w-10 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground md:h-8 md:w-8",onClick:()=>y(M.terminalSessionId),children:o.jsx(Jr,{className:"h-4 w-4"})})]})]})},M.terminalSessionId)),f.hasNextPage?o.jsx("div",{className:"p-3 text-center",children:o.jsx(Z,{variant:"outline",size:"sm",onClick:j,children:"Load more terminals"})}):null]})]}),journal:o.jsxs("div",{className:"p-5",children:[d?o.jsxs("p",{className:"mb-4 rounded-lg border border-amber-500/35 bg-amber-500/10 p-3 text-sm",children:["Terminal ",d," no longer exists. Select another archive."]}):null,v.isError?o.jsx(Ud,{text:"The selected Terminal no longer exists or is unavailable."}):_?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold",children:_.terminal.alias||_.terminal.terminalSessionId}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:_.terminal.cwd})]}),o.jsx("span",{className:"rounded-full border border-border px-2 py-1 text-xs",children:_.terminal.status})]}),o.jsx(gae,{values:_.sourceStatus}),o.jsx("div",{className:"mt-5 grid gap-3",children:C.map(M=>o.jsxs("article",{className:"flex select-text items-start justify-between gap-3 rounded-lg border border-border/70 p-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-sm font-medium",children:M.title}),o.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:M.summary}),o.jsxs("p",{className:"mt-2 text-[0.68rem] text-muted-foreground",children:[M.sourceType," · ",M.sourceId]})]}),o.jsxs("div",{className:"flex shrink-0 items-start gap-2",children:[o.jsx("time",{className:"pt-2 text-xs text-muted-foreground",children:w2(M.occurredAt)}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":`Open ${M.title} details`,onClick:()=>N(M.selection),children:o.jsx(Jr,{className:"h-4 w-4"})})]})]},M.id))}),v.hasNextPage?o.jsx("div",{className:"mt-4 text-center",children:o.jsx(Z,{variant:"outline",onClick:D,disabled:v.isFetchingNextPage,children:_.nextThreadCursor?"Load more Threads":"Load more Activity Facts"})}):null]}):o.jsx(Ud,{text:g?"Loading Terminal journal…":"Select a Terminal."})]}),inspector:o.jsx(dae,{apiBase:e,token:t,selection:w,onClose:E})})}function gae({values:e}){const t=Object.entries(e).filter(([,r])=>r.status!=="available");return t.length===0?null:o.jsx("div",{className:"mt-4 rounded-lg border border-amber-500/35 bg-amber-500/10 p-3 text-xs",children:t.map(([r,n])=>o.jsxs("p",{children:[o.jsx("span",{className:"font-medium",children:r}),": ",n.status,"reason"in n?` · ${n.reason}`:""]},r))})}function Ud({text:e}){return o.jsx("div",{className:"flex min-h-48 items-center justify-center p-6 text-center text-sm text-muted-foreground",children:e})}function y2(e,t){return[...new Map(e.map(r=>[t(r),r])).values()]}function w2(e){return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(e))}const vae=new Set(["terminals","facts","timeline","sources","policy"]);function xae({apiBase:e,token:t,embedded:r=!1}){var Y,te,H,G,z,ee;const[n,s]=fa(),[i,a]=p.useState(n.get("search")??""),[l,c]=p.useState(""),[u,d]=p.useState("thread"),[h,f]=p.useState(""),[m,g]=p.useState(null),v=p.useDeferredValue(i),x=p.useDeferredValue(h.trim()),b=n.get("view"),_=b&&vae.has(b)?b:"terminals",C=ia({queryKey:["activity","facts",e,v,l],initialPageParam:{},queryFn:({pageParam:V})=>Bie(e,t,{limit:100,search:v||void 0,runtimeChannel:l||void 0,cursor:V.cursor,asOfActivityOffset:V.asOfActivityOffset}),getNextPageParam:V=>V.nextCursor?{cursor:V.nextCursor,asOfActivityOffset:V.asOfActivityOffset}:void 0,enabled:_==="facts"}),S=Ct({queryKey:["activity","sources",e],queryFn:()=>$ie(e,t)}),w=Ct({queryKey:["activity","policy",e],queryFn:()=>zie(e,t),enabled:_==="sources"||_==="policy"}),y=ia({queryKey:["activity","timeline",e,u,x],initialPageParam:{},queryFn:({pageParam:V})=>Fie(e,t,{type:u,id:x},{limit:100,cursor:V.cursor,asOfActivityOffset:V.asOfActivityOffset}),getNextPageParam:V=>V.nextCursor?{cursor:V.nextCursor,asOfActivityOffset:V.asOfActivityOffset}:void 0,enabled:_==="timeline"&&x.length>0}),N=W(V=>{const re=new URLSearchParams(n);for(const[oe,ce]of Object.entries(V))ce?re.set(oe,ce):re.delete(oe);s(re,{replace:!0})}),E=W(V=>{N({view:V==="terminals"?null:V,terminal:null,run:null,event:null}),g(null)}),k=W(V=>g(V)),D=W(()=>g(null)),j=W(V=>a(V)),R=W(V=>c(V)),I=W(V=>d(V)),T=W(V=>f(V)),A=W(()=>void C.fetchNextPage()),P=W(()=>void y.fetchNextPage()),O=W(V=>N({terminal:V,run:null,event:null})),L=W(V=>N({event:V})),B=W((V,re)=>N({terminal:V,run:null,event:re})),M=S.data??[],$=M.filter(V=>!V.lastErrorCode&&V.openGapCount===0&&V.rejectionCount===0).length,U=((Y=C.data)==null?void 0:Y.pages.flatMap(V=>V.facts))??[],F=((te=y.data)==null?void 0:te.pages.flatMap(V=>V.facts))??[],K=(G=(H=y.data)==null?void 0:H.pages[0])==null?void 0:G.computed;return o.jsx("main",{className:r?"h-full min-h-0 overflow-hidden text-foreground":"h-dvh overflow-hidden bg-background text-foreground",children:o.jsxs("div",{className:r?"flex h-full min-h-0 flex-col":"grid h-full min-h-0 grid-cols-[220px_minmax(0,1fr)] max-md:grid-cols-1 max-md:grid-rows-[auto_minmax(0,1fr)]",children:[o.jsx(eae,{embedded:r,view:_,onSelectView:E,currentSourceCount:$,sourceCount:M.length}),o.jsxs("section",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:[o.jsx(tae,{search:i,runtimeChannel:l,onSearchChange:j,onRuntimeChannelChange:R}),o.jsxs("div",{className:_==="terminals"?"min-h-0 flex-1 overflow-hidden pt-2":"min-h-0 flex-1 overflow-auto pt-2",children:[_==="terminals"?o.jsx(mae,{apiBase:e,token:t,search:v,selectedTerminalId:n.get("terminal"),selectedEventKey:n.get("event"),onSelectTerminal:O,onSelectEvent:L,onSelectEntry:B}):null,_==="facts"?o.jsx(rae,{facts:U,frozenOffset:((ee=(z=C.data)==null?void 0:z.pages[0])==null?void 0:ee.asOfActivityOffset)??0,isError:C.isError,hasNextPage:C.hasNextPage,isFetchingNextPage:C.isFetchingNextPage,onLoadMore:A,onSelectFact:k}):null,_==="facts"&&m?o.jsx(_T,{apiBase:e,token:t,fact:m,onClose:D}):null,_==="timeline"?o.jsx(nae,{timelineType:u,timelineId:h,computed:K,onTimelineTypeChange:I,onTimelineIdChange:T,children:o.jsx(sae,{deferredTimelineId:x,facts:F,hasNextPage:y.hasNextPage,isFetchingNextPage:y.isFetchingNextPage,onLoadMore:P})}):null,_==="sources"?o.jsx(iae,{currentSourceCount:$,sources:M,policy:w.data}):null,_==="policy"?o.jsx(oae,{apiBase:e,token:t,policy:w.data}):null]})]})]})})}function bae(e,t,r){return me(e,`/api/knowledge-inbox/items/${encodeURIComponent(r.itemId)}/share`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({contentVersion:r.contentVersion,sourceRevision:r.sourceRevision})})}function _ae(e,t,r,n){const s=new URLSearchParams;return Object.entries(r).forEach(([i,a])=>{a!==void 0&&a!==""&&s.set(i,String(a))}),me(e,`/api/knowledge-inbox/items?${s}`,{headers:{Authorization:`Bearer ${t}`},signal:n})}function yae(e,t,r,n,s){return me(e,`/api/knowledge-inbox/items/${encodeURIComponent(r)}${n?`?contentVersion=${encodeURIComponent(n)}`:""}`,{headers:{Authorization:`Bearer ${t}`},signal:s})}function wae(e,t,r,n){return me(e,`/api/knowledge-inbox/items/${encodeURIComponent(r)}/state`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)})}function wv(e){try{return JSON.parse(atob(e.split(".")[1].replace(/-/gu,"+").replace(/_/gu,"/"))).sub??"unknown"}catch{return"unknown"}}function Sae({item:e,busy:t,disabled:r,onChange:n,apiBase:s,token:i}){const[a,l]=p.useState(!1),[c,u]=p.useState(""),[d,h]=p.useState(""),f=`${s}:${e.itemId}:${e.contentVersion}:${e.sourceRevision}`,m=p.useRef(f);p.useEffect(()=>(m.current=f,()=>{m.current=""}),[f]);const g=W(async()=>{if(a)return;const v=f;l(!0),u(""),h("");try{const x=await bae(s,i,e);if(m.current!==v)return;h(x.text);try{await navigator.clipboard.writeText(x.text),m.current===v&&u("已复制,粘贴给 Agent 即可")}catch{m.current===v&&u("自动复制不可用,请复制下方内容")}}catch(x){m.current===v&&u(x instanceof De&&x.status===409?"成果已变化,请刷新后重新复制":"生成引用失败,请检查连接与服务版本后重试")}finally{m.current===v&&l(!1)}});return o.jsxs("article",{className:"space-y-5 rounded-2xl border border-border bg-card p-6",children:[o.jsxs("div",{children:[o.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.projectName," · ",e.source==="experience"?"经验":"洞察"]}),o.jsx("h2",{className:"mt-2 text-xl font-semibold",children:e.title}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.validationLabel," ·"," ",new Date(e.contentUpdatedAt).toLocaleString()]})]}),e.availability!=="available"?o.jsx("p",{role:"status",className:"text-amber-600",children:e.availability==="unknown"?"来源暂不可用":"已失效 / 不可用"}):null,e.currentContentVersion?o.jsxs("p",{className:"text-amber-600",children:["这是处理时的正文,当前已有新版本",e.hasUpdate?"待处理":"","。"]}):null,e.statement?o.jsx("p",{className:"whitespace-pre-wrap text-sm leading-7",children:e.statement}):null,e.applicability?o.jsxs("section",{children:[o.jsx("h3",{className:"font-medium",children:"适用条件"}),o.jsx("p",{className:"mt-2 whitespace-pre-wrap text-sm leading-7",children:e.applicability})]}):null,[["guidance","建议"],["actions","步骤"],["avoid","避坑"],["verification","验证说明"]].map(([v,x])=>{var b;return(b=e[v])!=null&&b.length?o.jsxs("section",{children:[o.jsx("h3",{className:"font-medium",children:x}),o.jsx("ol",{className:"mt-2 list-inside list-decimal space-y-2 text-sm leading-7",children:e[v].map((_,C)=>o.jsx("li",{className:"whitespace-pre-wrap",children:_},C))})]},v):null}),o.jsxs(Z,{variant:"outline",onClick:()=>void g(),disabled:a||r||e.availability!=="available",children:[o.jsx(go,{className:"mr-2 h-4 w-4"}),a?"正在生成引用…":"复制给 Agent"]}),c?o.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:c}):null,d&&c.startsWith("自动复制")?o.jsx("textarea",{"aria-label":"成果交接内容",readOnly:!0,value:d,className:"w-full rounded border p-3 text-sm",rows:6,onFocus:v=>v.target.select()}):null,o.jsx(Z,{onClick:n,disabled:t||r||e.availability!=="available",children:t?"正在保存…":e.processedAt?e.currentContentVersion?"查看当前版本":"恢复待处理":"已处理"})]})}const S2=(e,t)=>!(t instanceof De&&[401,403,404].includes(t.status))&&e<1;function Cae(e){return e instanceof De?e.status===404?"当前服务版本不支持,或内容已不可用":e.status===409?"内容或处理状态已变化,请刷新后重试":e.message:"离线,显示最近缓存;连接恢复后请刷新"}function Eae({apiBase:e,token:t}){var C,S;const[r,n]=p.useState("pending"),[s,i]=p.useState(""),[a,l]=p.useState(null),c=xs(),u=["knowledge-inbox",e,wv(t)],d=ia({queryKey:[...u,"list",r,s],initialPageParam:void 0,queryFn:({pageParam:w,signal:y})=>_ae(e,t,{state:r,repositoryId:s,cursor:w,limit:20},y),getNextPageParam:w=>w.nextCursor??void 0,refetchInterval:w=>w.state.error instanceof De&&w.state.error.status===404?!1:15e3,refetchIntervalInBackground:!1,refetchOnWindowFocus:"always",refetchOnMount:"always",retry:S2}),h=Ct({queryKey:[...u,"detail",a==null?void 0:a.itemId,a==null?void 0:a.version],queryFn:({signal:w})=>yae(e,t,a.itemId,a==null?void 0:a.version,w),enabled:!!a,refetchInterval:w=>w.state.error instanceof De&&w.state.error.status===404?!1:15e3,refetchIntervalInBackground:!1,refetchOnWindowFocus:"always",refetchOnMount:"always",retry:S2}),f=W(async()=>{await c.invalidateQueries({queryKey:u})}),m=nr({mutationFn:w=>wae(e,t,w.itemId,{state:w.processedAt?"pending":"processed",expectedContentVersion:w.contentVersion,expectedStateVersion:w.stateVersion}),onSuccess:async w=>{l(w.processedAt?null:{itemId:w.itemId}),await f()},onError:async()=>{await f()}}),g=((C=d.data)==null?void 0:C.pages)??[],v=[...new Map(g.flatMap(w=>w.items).map(w=>[w.itemId,w])).values()],x=g.some(w=>w.sourceStatus.status==="partial"),b=m.error??h.error??d.error,_=W(w=>{m.reset(),l({itemId:w.itemId,version:w.processedAt?w.contentVersion:void 0})});return o.jsxs("div",{className:"w-full space-y-3 py-3",children:[o.jsxs("header",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"flex items-center gap-2 text-base font-semibold",children:[o.jsx(Ef,{className:"h-4 w-4"}),"自进化"]}),o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"阅读项目中的发现与经验,按自己的节奏处理。"})]}),o.jsx(Z,{variant:"ghost",onClick:()=>void f(),"aria-label":"刷新成果",children:o.jsx(Ws,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"flex flex-wrap gap-3",children:[[["pending","待处理"],["processed","已处理"]].map(([w,y])=>o.jsx(Z,{variant:r===w?"default":"outline","aria-pressed":r===w,onClick:()=>{n(w),l(null),m.reset()},children:y},w)),o.jsxs("select",{"aria-label":"筛选项目",className:"rounded-md border border-input bg-background px-3 text-sm",value:s,onChange:w=>{i(w.target.value),l(null)},children:[o.jsx("option",{value:"",children:"全部项目"}),(S=g[0])==null?void 0:S.repositories.map(w=>o.jsx("option",{value:w.repositoryId,children:w.displayName},w.repositoryId))]})]}),x?o.jsx("p",{role:"status",className:"rounded-lg bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-300",children:"部分来源暂不可用,当前列表不完整。"}):null,b?o.jsx("p",{role:"alert",className:"rounded-lg bg-destructive/10 p-3 text-sm",children:Cae(b)}):null,o.jsxs("div",{className:`grid gap-3 ${a?"lg:grid-cols-2":""}`,children:[o.jsxs("div",{className:"space-y-3",children:[d.isPending?o.jsx("p",{className:"py-12 text-center text-muted-foreground",children:"正在读取成果…"}):null,!d.isPending&&!b&&!x&&!v.length?o.jsx("p",{className:"py-16 text-center text-muted-foreground",children:r==="pending"?"当前没有待处理成果":"暂无处理历史"}):null,v.map(w=>{var y;return o.jsxs("button",{type:"button",onClick:()=>_(w),className:"w-full space-y-2 rounded-md border border-border bg-card p-3 text-left transition-colors hover:bg-muted/50",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[o.jsxs("span",{children:[w.projectName," ·"," ",w.source==="experience"?"经验":"洞察"]}),w.hasUpdate?o.jsx("span",{className:"text-amber-600",children:"有更新"}):w.processedAt?o.jsx(di,{className:"h-4 w-4"}):o.jsx(Jr,{className:"h-4 w-4"})]}),o.jsx("h2",{className:"font-medium",children:w.title}),o.jsx("p",{className:"line-clamp-3 whitespace-pre-wrap text-sm leading-5 text-muted-foreground",children:w.statement||((y=w.actions)==null?void 0:y[0])||w.applicability}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[new Date(w.contentUpdatedAt).toLocaleString(),w.availability!=="available"?" · 不可用":""]})]},w.itemId)}),d.hasNextPage?o.jsx(Z,{variant:"outline",disabled:d.isFetchingNextPage,onClick:()=>void d.fetchNextPage(),children:"加载更多"}):null]}),a?o.jsxs("div",{className:"space-y-3",children:[o.jsx(Z,{variant:"ghost",onClick:()=>l(null),children:"关闭详情"}),h.isPending?o.jsx("p",{children:"正在读取详情…"}):h.data?o.jsx(Sae,{apiBase:e,token:t,item:h.data,busy:m.isPending,disabled:!!d.error||!!h.error||!navigator.onLine,onChange:()=>{h.data.currentContentVersion?l({itemId:h.data.itemId}):m.mutate(h.data)}},`${e}:${wv(t)}:${h.data.itemId}:${h.data.contentVersion}:${h.data.sourceRevision}`):null]}):null]})]})}const p4=new Set(["overview","runs","insights","candidates","schedules"]),kae=[],Iae=[],Nae=[],Rae=[],jae=[],Aae=[];function Tae(e){return[{id:"global:runweave",kind:"global",label:"全部仓库",description:`分别复盘 ${e.filter(t=>t.available).length} 个可用仓库,最多 ${e.filter(t=>t.available).length*20} 分钟,顺序执行`},...e.map(t=>({id:t.repositoryId,kind:"repository",cwd:t.paths[0],available:t.available,label:t.name,description:t.paths[0]??"仓库历史"}))]}function h0(e){return e instanceof Error?e.message:"Evolution 请求失败"}function dc(e,t){return t==="global:runweave"?e:e.filter(r=>{var n;return r.learningScopeId===t||((n=r.attribution)==null?void 0:n.repositoryIds.includes(t))})}const Sv="global:runweave",On=e=>({Authorization:`Bearer ${e}`}),Ci=e=>({...On(e),"Content-Type":"application/json"});function ql(e){const t=new URLSearchParams;for(const[n,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(n,String(s));const r=t.toString();return r?`?${r}`:""}function Dae(e,t,r={}){return me(e,`/api/evolution/runs${ql(r)}`,{headers:On(t)})}function Pae(e,t,r){return me(e,`/api/evolution/runs/${encodeURIComponent(r)}/artifacts/summary`,{headers:On(t)})}function Lae(e,t,r,n){return me(e,`/api/evolution/runs/${encodeURIComponent(r)}/artifacts/page${ql({...n})}`,{headers:On(t)})}function Mae(e,t,r){return me(e,"/api/evolution/runs",{method:"POST",headers:Ci(t),body:JSON.stringify(r)})}function Oae(e,t,r){return me(e,`/api/evolution/runs/${encodeURIComponent(r)}/cancel`,{method:"POST",headers:Ci(t),body:"{}"})}function Bae(e,t,r){return me(e,`/api/evolution/runs/${encodeURIComponent(r)}/retry`,{method:"POST",headers:Ci(t),body:"{}"})}function Fae(e,t){return me(e,"/api/evolution/providers",{headers:On(t)})}function $ae(e,t,r){return me(e,`/api/evolution/insights${ql({learningScopeId:r})}`,{headers:On(t)})}function zae(e,t,r){return me(e,`/api/evolution/schedules${ql({learningScopeId:r})}`,{headers:On(t)})}function Uae(e,t,r){return me(e,"/api/evolution/schedules",{method:"POST",headers:Ci(t),body:JSON.stringify(r)})}function Hae(e,t,r,n){return me(e,`/api/evolution/schedules/${encodeURIComponent(r)}`,{method:"PATCH",headers:Ci(t),body:JSON.stringify(n)})}function Wae(e,t,r){return Vs(e,`/api/evolution/schedules/${encodeURIComponent(r)}`,{method:"DELETE",headers:On(t)})}function qae(e,t,r){return me(e,`/api/evolution/candidates${ql({learningScopeId:r})}`,{headers:On(t)})}function Kae(e,t,r){return me(e,`/api/evolution/candidates/${encodeURIComponent(r)}/canary`,{method:"POST",headers:Ci(t),body:"{}"})}function Vae(e,t,r,n){return me(e,`/api/evolution/candidates/${encodeURIComponent(r)}/retire`,{method:"POST",headers:Ci(t),body:JSON.stringify({reason:n})})}function Gae(e,t,r){return me(e,`/api/evolution/scopes/${encodeURIComponent(r)}/policy`,{headers:On(t)})}function Yae(e,t,r,n){return me(e,`/api/evolution/scopes/${encodeURIComponent(r)}/policy`,{method:"PUT",headers:Ci(t),body:JSON.stringify(n)})}function Xae(e,t,r){return me(e,`/api/evolution/runtime-traces${ql(r)}`,{headers:On(t)})}function Jae(e,t){return me(e,"/api/evolution/scopes",{headers:On(t)})}function Qae(e,t,r){return me(e,`/api/evolution/scopes/resolve?${new URLSearchParams({learningScopeId:r})}`,{headers:On(t)})}function Zae(e,t,r){return me(e,"/api/evolution/reflection-batches",{method:"POST",headers:Ci(t),body:JSON.stringify({idempotencyKey:r})})}function ele(e,t,r){var d,h;const n=Ct({queryKey:["evolution","project-metadata",e],queryFn:()=>Jae(e,t)}),s=((d=n.data)==null?void 0:d.repositories)??Aae,i=p.useMemo(()=>Tae(s),[s]),a=r,l=Ct({queryKey:["evolution","legacy-scope",e,a],queryFn:()=>Qae(e,t,a),enabled:!!a&&a!==Sv&&!i.some(f=>f.id===a)&&!n.isLoading,retry:!1}),c=((h=l.data)==null?void 0:h.repositoryId)??(a||Sv),u=i.find(f=>f.id===c)??{id:c,kind:"legacy",label:"历史范围",description:"历史归属未确认;可查看原始记录"};return{scopeOptions:i,selectedScopeId:c,selectedScope:u,scopeError:n.error??(l.error?new Error("旧范围无法唯一对应仓库:历史可能涉及多个仓库,或缺少可靠归属依据。原始记录仍可查看,请从左侧选择仓库。"):null)}}const tle=[{value:"quick",label:"Quick"},{value:"standard",label:"Standard"},{value:"deep",label:"Deep"}],rle=[{value:"auto",label:"Auto"},{value:"codex",label:"Codex"},{value:"trae",label:"Trae"},{value:"mixed",label:"Mixed"}];function Li({label:e,hint:t,children:r}){return o.jsxs("div",{className:"space-y-2",children:[o.jsx(cp,{children:e}),r,t?o.jsx("p",{className:"text-xs text-muted-foreground",children:t}):null]})}function C2({value:e,onChange:t,children:r}){return o.jsx("select",{className:"h-10 w-full rounded-md border border-input bg-background px-3 text-sm",value:e,onChange:n=>t(n.target.value),children:r})}function nle({open:e,pending:t,error:r,schedule:n,initialProjectId:s,onOpenChange:i,onSubmit:a}){var E;const[l,c]=p.useState(((E=n==null?void 0:n.repository)==null?void 0:E.cwd)??s),[u,d]=p.useState((n==null?void 0:n.name)??""),[h,f]=p.useState((n==null?void 0:n.cronExpression)??"0 10 * * 1"),[m,g]=p.useState((n==null?void 0:n.timezone)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC"),[v,x]=p.useState((n==null?void 0:n.enabled)??!0),[b,_]=p.useState((n==null?void 0:n.profile)??"standard"),[C,S]=p.useState((n==null?void 0:n.providerPolicy)??"auto"),[w,y]=p.useState((n==null?void 0:n.dataWindow)??"since_last_success"),N=W(k=>{k.preventDefault();const D={name:u.trim(),cronExpression:h.trim(),timezone:m.trim(),enabled:v,profile:b,providerPolicy:C,dataWindow:w.trim()};a(n?D:{...D,scope:{type:"repository",cwd:l.trim()}})});return o.jsx(Qr,{open:e,onOpenChange:i,children:o.jsx(dn,{className:"max-h-[90dvh] max-w-xl overflow-auto",children:o.jsxs("form",{onSubmit:N,children:[o.jsxs(Mn,{children:[o.jsx(Ur,{children:n?"编辑运行计划":"新建运行计划"}),o.jsx(Zr,{children:"Schedule 持久化在 Evolution 数据库;cron、时区与数据窗口按原值提交给 Backend。"})]}),o.jsxs("div",{className:"mt-6 grid gap-5 sm:grid-cols-2",children:[n?null:o.jsx(Li,{label:"仓库工作目录",children:o.jsx(sr,{required:!0,value:l,onChange:k=>c(k.target.value)})}),o.jsx(Li,{label:"名称",children:o.jsx(sr,{required:!0,value:u,onChange:k=>d(k.target.value),placeholder:"每周增量反思"})}),o.jsx(Li,{label:"Cron",children:o.jsx(sr,{required:!0,value:h,onChange:k=>f(k.target.value),placeholder:"0 10 * * 1"})}),o.jsx(Li,{label:"时区",children:o.jsx(sr,{required:!0,value:m,onChange:k=>g(k.target.value),placeholder:"Asia/Shanghai"})}),o.jsx(Li,{label:"数据窗口",children:o.jsx(sr,{required:!0,value:w,onChange:k=>y(k.target.value),placeholder:"since_last_success"})}),o.jsx(Li,{label:"Profile",children:o.jsx(C2,{value:b,onChange:k=>_(k),children:tle.map(k=>o.jsx("option",{value:k.value,children:k.label},k.value))})}),o.jsx(Li,{label:"Provider policy",children:o.jsx(C2,{value:C,onChange:k=>S(k),children:rle.map(k=>o.jsx("option",{value:k.value,children:k.label},k.value))})}),o.jsxs("label",{className:"flex items-center gap-3 text-sm sm:col-span-2",children:[o.jsx("input",{type:"checkbox",checked:v,onChange:k=>x(k.target.checked)}),"创建后启用 Schedule"]})]}),r?o.jsx("p",{className:"mt-4 text-sm text-red-600",role:"alert",children:r}):null,o.jsxs(ga,{className:"mt-6",children:[o.jsx(Z,{type:"button",variant:"outline",onClick:()=>i(!1),children:"取消"}),o.jsx(Z,{type:"submit",disabled:t||!u.trim()||!h.trim()||!m.trim()||!n&&!l.trim(),children:t?"保存中…":n?"保存":"创建 Schedule"})]})]})})})}function sle({candidate:e,pending:t,error:r,onOpenChange:n,onSubmit:s}){const[i,a]=p.useState("scope owner rollback"),l=W(c=>{c.preventDefault(),s(i.trim())});return o.jsx(Qr,{open:!0,onOpenChange:n,children:o.jsx(dn,{children:o.jsxs("form",{onSubmit:l,children:[o.jsxs(Mn,{children:[o.jsx(Ur,{children:"退休 / 回滚 Memory"}),o.jsxs(Zr,{children:["退休 ",e.assetId," 后,后续任务不会再检索或注入该 revision。 历史 RuntimeTrace 会保留用于审计。"]})]}),o.jsx("div",{className:"mt-6",children:o.jsx(Li,{label:"回滚原因",children:o.jsx(sr,{required:!0,autoFocus:!0,maxLength:500,value:i,onChange:c=>a(c.target.value)})})}),r?o.jsx("p",{className:"mt-4 text-sm text-red-600",role:"alert",children:r}):null,o.jsxs(ga,{className:"mt-6",children:[o.jsx(Z,{type:"button",variant:"outline",disabled:t,onClick:()=>n(!1),children:"取消"}),o.jsx(Z,{type:"submit",variant:"destructive",disabled:t||!i.trim(),children:t?"回滚中…":"确认退休"})]})]})})})}function Cv(e){var t;return e.repository?e.repository.cwd.split("/").filter(Boolean).at(-1)??e.learningScopeId:e.learningScopeId==="global:runweave"?"历史全局复盘":((t=e.attribution)==null?void 0:t.resolution)==="mixed"?"历史混合仓库复盘":`历史复盘 · ${e.learningScopeId.slice(0,8)}`}const ile=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),E2=[{id:"overview",label:"概览",icon:Ef},{id:"runs",label:"运行记录",icon:vE},{id:"insights",label:"洞察",icon:Sf},{id:"candidates",label:"资产候选",icon:Yv},{id:"schedules",label:"运行计划",icon:wl}],Ev={queued:"排队中",snapshotting:"冻结证据",segmenting:"构建片段",independent_analysis:"独立分析",cross_questioning:"交叉质疑",adjudicating:"裁决",novelty_check:"新颖性检查",validating:"验证",completed:"已完成",no_material_novelty:"无实质新知识",partial:"部分完成",failed:"失败",cancelled:"已取消",blocked:"已阻塞"},Pc=new Set(["completed","no_material_novelty","partial","failed","cancelled","blocked"]);function iu(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.valueOf())?e:ile.format(t)}function ole(e){return e==="completed"||e==="promoted"||e==="available"?"border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-300":e==="failed"||e==="blocked"||e==="rejected"||e==="unavailable"?"border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-300":e==="partial"||e==="no_material_novelty"||e==="canary"||e==="needs_revalidation"?"border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-300":"border-border bg-muted/60 text-muted-foreground"}function Zo({status:e,label:t}){return o.jsx("span",{className:`inline-flex rounded-full border px-2.5 py-1 text-[0.68rem] font-medium ${ole(e)}`,children:t})}function fi({children:e,className:t=""}){return o.jsx("section",{className:`rounded-md border border-border/70 bg-card/80 shadow-[0_20px_80px_-64px_rgba(17,24,39,0.8)] ${t}`,children:e})}function ale({view:e,scopes:t,selectedScopeId:r,counts:n,providers:s,onSelectView:i,onSelectScope:a,embedded:l=!1}){const c=t.find(h=>h.id===r),u=t.find(h=>h.kind==="global"),d=t.filter(h=>h.kind==="repository");return l?o.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-b py-2",children:[o.jsx("nav",{"aria-label":"Evolution 导航",className:"settings-tabs !mb-0",children:E2.map(h=>o.jsxs("button",{"aria-current":e===h.id?"page":void 0,onClick:()=>i(h.id),children:[h.label,n[h.id]!==void 0&&o.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:n[h.id]})]},h.id))}),o.jsxs("label",{className:"ml-auto flex items-center gap-2 text-xs text-muted-foreground",children:["复盘范围",o.jsx("select",{"aria-label":"复盘范围",className:"h-7 max-w-48 rounded border bg-background px-2",value:r,onChange:h=>a(h.target.value),children:t.map(h=>o.jsx("option",{value:h.id,children:h.label},h.id))})]})]}):o.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-border/70 bg-card/55 p-3 max-md:border-b max-md:border-r-0",children:[o.jsx("div",{className:"flex items-center justify-between gap-3 px-2 py-3",children:o.jsxs("div",{children:[o.jsx("p",{className:"text-[0.68rem] font-semibold uppercase tracking-[0.3em] text-foreground",children:"Runweave"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Evolution"})]})}),o.jsxs("div",{className:"mt-2 rounded-lg border border-border/70 bg-background/55 p-3",children:[o.jsx("p",{className:"text-[0.65rem] font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"复盘范围"}),t.length>0?o.jsxs("select",{"aria-label":"复盘范围",className:"mt-2 h-9 w-full rounded-md border border-input bg-background px-2 text-sm",value:r,onChange:h=>a(h.target.value),children:[u?o.jsx("option",{value:u.id,children:u.label}):null,d.length>0?o.jsx("optgroup",{label:"按项目",children:d.map(h=>o.jsx("option",{value:h.id,children:h.label},h.id))}):null]}):o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"正在读取可用范围"}),c?o.jsxs("div",{className:"mt-2 min-w-0 space-y-1",children:[o.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:c.label}),o.jsx("p",{className:"text-[0.68rem] leading-5 text-muted-foreground",title:c.description,children:c.description})]}):null]}),o.jsx("nav",{className:"mt-4 grid gap-1 max-md:grid-cols-5 max-sm:grid-cols-2","aria-label":"Evolution 导航",children:E2.map(h=>{const f=h.icon;return o.jsxs("button",{type:"button",className:`flex items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors ${e===h.id?"bg-primary/12 font-medium text-foreground":"text-muted-foreground hover:bg-muted/70 hover:text-foreground"}`,onClick:()=>i(h.id),children:[o.jsx(f,{className:"h-4 w-4 shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.label}),n[h.id]!==void 0?o.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[0.65rem] tabular-nums",children:n[h.id]}):null]},h.id)})}),o.jsx("div",{className:"mt-auto space-y-2 px-2 pt-5 text-xs text-muted-foreground max-md:hidden",children:s.map(h=>o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:`h-2 w-2 rounded-full ${h.available?"bg-emerald-500":"bg-amber-500"}`}),o.jsx("span",{className:"capitalize",children:h.provider}),o.jsx("span",{children:h.available?"可用":"未接入"})]},h.provider))})]})}function lle({embedded:e=!1,view:t,scopeLabel:r,reflectionPending:n,reflectionDisabled:s,onStartReflection:i,onOpenSchedule:a}){const l={overview:["进化概览","运行、候选资产与激活状态"],runs:["运行记录","查看真实队列、阶段、预算与 RuntimeTrace"],insights:["洞察","分析链路产出的长期结论与 revision"],candidates:["资产候选","查看候选生命周期与真实注入策略"],schedules:["运行计划","管理持久化的 cron、时区和数据窗口"]};return o.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border/70 py-2",children:[o.jsxs("div",{children:[!e&&o.jsx("h1",{className:"text-lg font-semibold",children:l[t][0]}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l[t][1]})]}),o.jsxs("div",{className:"flex shrink-0 gap-2",children:[o.jsx(Sa,{className:"max-sm:max-w-36"}),o.jsxs(Z,{variant:"secondary",size:"sm",onClick:a,children:[o.jsx(wl,{className:"h-4 w-4"}),o.jsx("span",{className:"max-sm:hidden",children:"运行计划"})]}),o.jsxs(Z,{size:"sm",disabled:n||s,onClick:i,children:[o.jsx(Ef,{className:"h-4 w-4"}),o.jsx("span",{className:"max-sm:hidden",children:n?"正在发起…":`复盘 ${r}`}),o.jsx("span",{className:"sm:hidden",children:n?"发起中…":"开始复盘"})]})]})]})}function cle({message:e,onRetry:t}){return o.jsxs("div",{role:"alert",className:"flex items-center justify-between gap-3 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-700 dark:text-red-200",children:[o.jsx("span",{children:e}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:t,children:[o.jsx(Ws,{className:"h-4 w-4"}),"重试"]})]})}function ule({runs:e,insights:t,candidates:r,schedules:n,providers:s,runtimeAvailable:i,runtimeUnavailableReason:a,onSelectRun:l,onSelectView:c}){var f;const u=e.filter(m=>!Pc.has(m.stage)),d=e[0],h=s.filter(m=>!m.available);return o.jsxs("div",{className:"space-y-4",children:[!i||h.length>0?o.jsx("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200",children:i?`${h.map(m=>`${m.provider}${m.reason?` (${m.reason})`:""}`).join("、")} Provider 尚不可用;不会将单 Provider 结果标记为交叉验证。`:fle(a)}):null,o.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[["运行总数",e.length,"真实持久化 Run"],["进行中",u.length,"queued 或执行阶段"],["长期洞察",t.length,`${r.length} 条候选资产`],["运行计划",n.filter(m=>m.enabled).length,`${n.length} 条已配置`]].map(([m,g,v])=>o.jsxs(fi,{className:"px-3 py-2",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:m}),o.jsx("p",{className:"mt-1 text-xl font-semibold tabular-nums",children:g}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:v})]},m))}),o.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.5fr)_minmax(280px,0.7fr)]",children:[o.jsxs(fi,{children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-border/70 px-3 py-2",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold",children:"最近一次反思"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"当前 Backend 返回的真实 Run 状态"})]}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:()=>c("runs"),children:"全部运行"})]}),d?o.jsxs("button",{type:"button",className:"w-full p-3 text-left hover:bg-muted/30",onClick:()=>l(d.runId),children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:Cv(d)}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[d.profile," · ",d.providerPolicy," · attempt"," ",d.attempt]})]}),o.jsx(Zo,{status:d.stage,label:Ev[d.stage]})]}),o.jsxs("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"创建时间"}),o.jsx("p",{className:"mt-1 text-sm",children:iu(d.createdAt)})]}),o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"模型轮次预算"}),o.jsx("p",{className:"mt-1 text-sm",children:d.budget.maxModelTurns})]}),o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"工具调用预算"}),o.jsx("p",{className:"mt-1 text-sm",children:d.budget.maxToolCalls})]})]})]}):o.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"尚无运行。发起第一次反思后,真实状态会显示在这里。"})]}),o.jsxs(fi,{className:"p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Sf,{className:"h-4 w-4 text-amber-500"}),o.jsx("h2",{className:"font-semibold",children:"洞察链路"})]}),t[0]?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"mt-4 text-sm font-medium leading-6",children:(f=hle(t[0]))==null?void 0:f.statement}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[t[0].topicKey," · ",t[0].revisions.length," 个 revision"]})]}):o.jsx("p",{className:"mt-4 text-sm leading-6 text-muted-foreground",children:"尚无真实 Insight。没有实质新知识时,Run 会合法零产出。"}),o.jsx(Z,{className:"mt-5",variant:"outline",size:"sm",onClick:()=>c("insights"),children:"查看接入状态"})]})]})]})}function dle(){return o.jsxs("div",{className:"flex min-h-[420px] items-center justify-center text-sm text-muted-foreground",children:[o.jsx(Sl,{className:"mr-2 h-4 w-4 animate-pulse"}),"正在读取 Evolution 控制面…"]})}function hle(e){return e.revisions.find(t=>t.revisionId===e.currentRevisionId)}function fle(e){switch(e){case"migration_required":return"Evolution 数据需要迁移,当前不可用。请管理员按仓库身份迁移指南完成备份、迁移和校验后重启后端。";case"migration_incomplete":return"Evolution 数据迁移尚未完成,当前不可用。请管理员检查迁移状态,完成校验后重启后端。";case"schema_incompatible":return"当前后端版本无法读取 Evolution 数据。请升级到兼容版本后重试。";case"storage_unavailable":return"Evolution 存储初始化失败,当前不可用。请管理员检查后端日志与数据目录,修复后重启后端。";default:return"Evolution runtime 当前不可用;页面保持只读并展示后端返回的降级状态。"}}function ple({insights:e}){return o.jsxs(fi,{className:"overflow-hidden",children:[o.jsxs("div",{className:"border-b border-border/70 px-5 py-4",children:[o.jsx("h2",{className:"font-semibold",children:"长期洞察"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[e.length," 条稳定语义身份,revision 保留历史"]})]}),e.length>0?o.jsx("div",{className:"divide-y divide-border/60",children:e.map(t=>{var n;const r=mle(t);return o.jsxs("article",{className:"[content-visibility:auto] p-3 [contain-intrinsic-size:auto_180px]",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:t.topicKey}),((n=t.lineage)==null?void 0:n.status)==="contested"?o.jsx("p",{className:"mt-2 text-sm text-amber-600",children:"历史观点存在冲突,等待重新验证"}):null,t.attribution&&t.attribution.resolution!=="resolved"?o.jsxs("p",{className:"mt-2 text-sm text-amber-600",children:["历史归属",t.attribution.resolution==="mixed"?"涉及多个仓库":"尚未确认",",仅供审计"]}):null,o.jsx("h3",{className:"mt-2 font-medium",children:(r==null?void 0:r.statement)??"当前 revision 不可用"}),o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:r==null?void 0:r.scope})]}),r?o.jsx("span",{className:"rounded-full border border-border bg-muted/60 px-2.5 py-1 text-xs",children:r.novelty}):null]}),o.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-xs text-muted-foreground",children:[o.jsxs("span",{children:[t.revisions.length," revisions"]}),o.jsx("span",{children:"·"}),o.jsx("span",{children:iu(t.updatedAt)}),r?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:"·"}),o.jsxs("span",{children:["confidence ",Math.round(r.confidence*100),"%"]})]}):null]}),r!=null&&r.evidenceIds.length?o.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:r.evidenceIds.slice(0,6).map(s=>o.jsx(Z,{variant:"outline",size:"sm",asChild:!0,children:o.jsx(bu,{to:`/activity?view=facts&search=${encodeURIComponent(s)}`,children:s})},s))}):null]},t.insightId)})}):o.jsx("div",{className:"flex min-h-[420px] items-center justify-center p-8 text-center",children:o.jsxs("div",{className:"max-w-lg",children:[o.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:o.jsx(Sf,{className:"h-5 w-5 text-muted-foreground"})}),o.jsx("h2",{className:"mt-3 text-base font-semibold",children:"尚无实质新知识"}),o.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"只有通过证据和 Novelty Gate 的结论才会出现在这里;页面不使用 Candidate 或 mock 数据补空状态。"})]})})]})}function mle(e){return e.revisions.find(t=>t.revisionId===e.currentRevisionId)}const gle=[{value:"evidence",label:"冻结证据"},{value:"data-quality",label:"质量记录"},{value:"segments",label:"轨迹片段"},{value:"episodes",label:"任务片段"}];function vle({apiBase:e,token:t,runId:r}){const[n,s]=p.useState(!1),[i,a]=p.useState("evidence"),[l,c]=p.useState([void 0]),u=l[l.length-1],d=Ct({queryKey:["evolution","artifact-page",e,t,r,i,u],queryFn:()=>Lae(e,t,r,{collection:i,cursor:u}),enabled:n,refetchOnWindowFocus:!1,gcTime:0,retry:!1});return o.jsxs("section",{className:"rounded-lg border border-border/70 p-3",children:[o.jsx(Z,{variant:"outline",size:"sm","aria-expanded":n,onClick:()=>s(!n),children:n?"收起详细记录":"查看详细记录"}),n?o.jsxs("div",{className:"mt-3 space-y-3",children:[o.jsx("div",{className:"flex flex-wrap gap-2","aria-label":"详细记录类型",children:gle.map(({value:h,label:f})=>o.jsx(Z,{size:"sm",variant:i===h?"secondary":"outline","aria-pressed":i===h,onClick:()=>{a(h),c([void 0])},children:f},h))}),d.isFetching?o.jsx("p",{className:"text-xs text-muted-foreground",children:"正在读取详细记录…"}):null,d.error?o.jsxs("div",{role:"alert",className:"text-xs text-destructive",children:["读取失败:",d.error.message,o.jsx(Z,{variant:"outline",size:"sm",onClick:()=>void d.refetch(),children:"重试读取"}),o.jsx(Z,{variant:"outline",size:"sm",onClick:()=>c([void 0]),children:"返回首页"})]}):null,d.data?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-xs text-muted-foreground",children:["共 ",d.data.total," 条 · 第 ",l.length," 页 · 本页"," ",d.data.items.length," 条"]}),o.jsxs("div",{className:"space-y-2",children:[d.data.items.map((h,f)=>o.jsx(xle,{item:h,index:f},`${i}:${u??"first"}:${f}`)),d.data.items.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"暂无记录"}):null]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{variant:"outline",size:"sm",disabled:l.length===1||d.isFetching,onClick:()=>c(l.slice(0,-1)),children:"上一页"}),o.jsx(Z,{variant:"outline",size:"sm",disabled:!d.data.nextCursor||d.isFetching,onClick:()=>c([...l,d.data.nextCursor]),children:"下一页"})]})]}):null]}):null]})}function xle({item:e,index:t}){const[r,n]=p.useState(!1),s="evidenceId"in e?e.evidenceId:"segmentId"in e?e.segmentId:"episodeId"in e?e.episodeId:"code"in e?e.code:t+1;return o.jsxs("details",{className:"rounded-md bg-muted/45 p-2",onToggle:i=>n(i.currentTarget.open),children:[o.jsx("summary",{className:"cursor-pointer break-all text-xs",children:String(s)}),r?o.jsx("pre",{className:"mt-2 max-h-80 overflow-auto whitespace-pre-wrap break-all text-xs",children:JSON.stringify(e,null,2)}):null]})}function ble({apiBase:e,token:t,runs:r,selectedRunId:n,traces:s,artifacts:i,actionPending:a,onSelectRun:l,onCancelRun:c,onRetryRun:u}){var h;const d=r.find(f=>f.runId===n)??r[0]??null;return o.jsxs("div",{className:"grid min-h-full gap-4 xl:grid-cols-[minmax(280px,0.7fr)_minmax(0,1.3fr)]",children:[o.jsxs(fi,{className:"min-h-0 overflow-hidden",children:[o.jsxs("div",{className:"border-b border-border/70 px-4 py-3",children:[o.jsx("h2",{className:"font-semibold",children:"运行队列"}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[r.length," 条真实记录"]})]}),o.jsx("div",{className:"max-h-[calc(100dvh-190px)] overflow-auto",children:r.length>0?r.map(f=>o.jsxs("button",{type:"button",className:`block w-full border-b border-border/60 p-3 text-left last:border-b-0 ${(d==null?void 0:d.runId)===f.runId?"bg-primary/8":"hover:bg-muted/35"}`,onClick:()=>l(f.runId),children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"min-w-0 truncate text-sm font-medium",children:Cv(f)}),o.jsx(Zo,{status:f.stage,label:Ev[f.stage]})]}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[iu(f.createdAt)," · ",f.profile," ·"," ",f.providerPolicy]})]},f.runId)):o.jsx("p",{className:"p-6 text-sm text-muted-foreground",children:"暂无 Evolution Run。"})})]}),o.jsxs(fi,{className:"min-w-0 p-3",children:[d?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-xs uppercase tracking-[0.18em] text-muted-foreground",children:"Run detail"}),o.jsx("h2",{className:"mt-2 truncate text-base font-semibold",children:d.runId}),o.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:[Cv(d)," · ",d.trigger.type,d.repository?o.jsx("span",{className:"block break-all",children:d.repository.cwd}):null]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Zo,{status:d.stage,label:Ev[d.stage]}),Pc.has(d.stage)?o.jsxs(Z,{variant:"outline",size:"sm",disabled:a,onClick:()=>u(d.runId),children:[o.jsx(Ws,{className:"h-4 w-4"}),"重试"]}):o.jsx(Z,{variant:"outline",size:"sm",disabled:a,onClick:()=>c(d.runId),children:"取消"})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"Profile"}),o.jsx("p",{className:"mt-1 text-sm capitalize",children:d.profile})]}),o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"Provider policy"}),o.jsx("p",{className:"mt-1 text-sm capitalize",children:d.providerPolicy})]}),o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"数据上界"}),o.jsx("p",{className:"mt-1 truncate text-sm",children:iu(d.dataRange.atOrBefore)})]}),o.jsxs("div",{className:"rounded-lg bg-muted/45 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"最长时间"}),o.jsxs("p",{className:"mt-1 text-sm",children:[Math.round(d.budget.maxWallTimeMs/6e4)," 分钟"]})]})]}),i!=null&&i.contextPack?o.jsx(_le,{artifacts:i}):null,o.jsxs("div",{className:"mt-6 border-t border-border/70 pt-6",children:[o.jsx("h3",{className:"font-semibold",children:"审计详情"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"冻结证据、独立报告、Claim 与 Novelty 的真实持久化结果"})]}),i?o.jsxs("div",{className:"mt-3 space-y-3",children:[(h=i.contextPack)!=null&&h.dataQualityIssueCount?o.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 p-3",children:[o.jsxs("p",{className:"text-xs font-medium text-amber-700 dark:text-amber-200",children:["DataQuality ·"," ",i.contextPack.dataQualityIssueCount," 项"]}),i.contextPack.dataQualitySummary.map(f=>o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[f.code," · ",f.count," 项:",f.detail]},f.code))]}):null,o.jsx(vle,{apiBase:e,token:t,runId:d.runId},d.runId),o.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[o.jsxs("div",{className:"rounded-lg border border-border/70 p-3",children:[o.jsxs("p",{className:"text-xs font-medium",children:["Attempts · ",i.attempts.length]}),o.jsxs("div",{className:"mt-2 space-y-2",children:[i.attempts.map(f=>o.jsxs("div",{className:"rounded-md bg-muted/45 p-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[o.jsx("span",{className:"font-medium",children:f.role}),o.jsx("span",{children:f.provider}),o.jsx("span",{children:f.status})]}),o.jsxs("p",{className:"mt-1 text-[0.68rem] text-muted-foreground",children:[f.selectionReason,f.errorCode?` · ${f.errorCode}`:""]})]},f.attemptId)),i.attempts.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"尚无 Provider attempt。"}):null]})]}),o.jsxs("div",{className:"rounded-lg border border-border/70 p-3",children:[o.jsxs("p",{className:"text-xs font-medium",children:["Reports · ",i.reports.length]}),o.jsxs("div",{className:"mt-2 space-y-2",children:[i.reports.map(f=>o.jsxs("div",{className:"[content-visibility:auto] rounded-md bg-muted/45 p-2",children:[o.jsxs("p",{className:"text-xs font-medium",children:[f.role," · ",f.provider]}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:f.summary}),o.jsxs("p",{className:"mt-1 text-[0.68rem] text-muted-foreground",children:["visible reports: ",f.visibleReportIds.length]})]},f.reportId)),i.reports.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"尚无完整报告。"}):null]})]}),o.jsxs("div",{className:"rounded-lg border border-border/70 p-3",children:[o.jsxs("p",{className:"text-xs font-medium",children:["Claims · ",i.claims.length]}),o.jsxs("div",{className:"mt-2 space-y-2",children:[i.claims.map(f=>{const m=i.novelty.find(g=>g.claimId===f.claimId);return o.jsxs("div",{className:"[content-visibility:auto] rounded-md bg-muted/45 p-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[o.jsx("span",{className:"font-medium",children:f.topicKey}),o.jsx("span",{children:f.status}),m?o.jsx("span",{children:m.novelty}):null]}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:f.statement})]},f.claimId)}),i.claims.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"尚无 Claim;空证据或未完成 Run 不会生成模拟结论。"}):null]})]})]})]}):o.jsx("div",{className:"mt-3 rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground",children:"正在读取该 Run 的分析产物。"})]}):o.jsx("div",{className:"rounded-lg border border-dashed border-border p-3 text-sm text-muted-foreground",children:"该学习范围暂无分析 Run;下方展示已记录的激活轨迹。"}),o.jsxs("div",{className:d?"mt-6":"mt-3",children:[o.jsx("h3",{className:"font-semibold",children:"RuntimeTrace"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"按当前学习范围展示已记录的运行轨迹"})]}),o.jsx("div",{className:"mt-3 space-y-2",children:s.length>0?s.map(f=>o.jsxs("div",{className:"rounded-lg border border-border/70 bg-background/45 p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsx("p",{className:"font-mono text-xs",children:f.traceId}),o.jsx(Zo,{status:f.assignmentBucket==="canary"?"canary":"draft",label:f.assignmentBucket})]}),o.jsxs("p",{className:"mt-2 break-all text-xs text-muted-foreground",children:["run ",f.runId," · dispatch ",f.dispatchId," ·"," ",f.exposedRevisionIds.length," exposed"]}),o.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:f.events.map(m=>o.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 text-[0.68rem] text-muted-foreground",children:m.kind},m.eventId))}),o.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[f.failOpenReason?o.jsxs("p",{className:"text-xs text-amber-600",children:["fail-open: ",f.failOpenReason]}):o.jsx("span",{}),o.jsx(Z,{variant:"ghost",size:"sm",asChild:!0,children:o.jsxs(bu,{to:`/activity?view=facts&search=${encodeURIComponent(f.runId)}`,children:[o.jsx(cs,{className:"h-4 w-4"}),"Activity 证据"]})})]})]},f.traceId)):o.jsx("div",{className:"rounded-lg border border-dashed border-border p-3 text-sm text-muted-foreground",children:"该学习范围暂无 RuntimeTrace。纯分析不会自动生成模拟激活轨迹。"})})]})]})}function _le({artifacts:e}){var i,a;const t=(i=e.contextPack)==null?void 0:i.sources.find(l=>l.source==="activity"),r=((a=e.contextPack)==null?void 0:a.workspaceCount)??0,n=e.claims.filter(l=>l.status==="corroborated"&&l.guidance),s=e.claims.filter(l=>l.status==="contested");return o.jsxs("section",{className:"mt-6 rounded-xl border border-primary/20 bg-primary/[0.04] p-4",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Sf,{className:"h-4 w-4 text-amber-500"}),o.jsx("h3",{className:"font-semibold",children:"本次复盘结论"})]}),o.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[o.jsxs("div",{className:"rounded-lg bg-background/80 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"覆盖数据"}),o.jsxs("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:[(t==null?void 0:t.recordCount)??0," 条"]})]}),o.jsxs("div",{className:"rounded-lg bg-background/80 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"涉及工作区"}),o.jsxs("p",{className:"mt-1 text-lg font-semibold tabular-nums",children:[r," 个"]})]}),o.jsxs("div",{className:"rounded-lg bg-background/80 p-3",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"数据范围"}),o.jsx("p",{className:"mt-1 text-sm font-medium",children:(t==null?void 0:t.afterWatermark)==="0"?"首次复盘至当前":"上次成功复盘至当前"}),o.jsx("p",{className:"mt-1 text-[0.68rem] text-muted-foreground",children:t!=null&&t.truncated?"仍有未处理数据":"已覆盖本次冻结且归属明确的范围"})]})]}),o.jsxs("div",{className:"mt-4",children:[o.jsx("p",{className:"text-sm font-medium",children:"关键决策与优化建议"}),n.length>0?o.jsx("div",{className:"mt-2 space-y-2",children:n.map(l=>o.jsxs("article",{className:"rounded-lg bg-background/80 p-3",children:[o.jsx("p",{className:"text-sm font-medium",children:l.statement}),o.jsx("p",{className:"mt-1 text-sm leading-6 text-muted-foreground",children:l.guidance})]},l.claimId))}):o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"当前没有经过交叉验证的新优化建议。"})]}),s.length>0?o.jsxs("p",{className:"mt-3 text-xs text-amber-700 dark:text-amber-200",children:["另有 ",s.length," 项判断仍存在分歧,已保留证据等待后续验证。"]}):null]})}function yle({candidates:e,policy:t,selectedScopeId:r,policyPending:n,candidateActionPending:s,onUpdateCanary:i,onAuthorizeCandidate:a,onRetireCandidate:l}){const[c,u]=p.useState(10);p.useEffect(()=>{t&&u(t.canaryRate>0?Math.round(t.canaryRate*100):10)},[t]);const d=W(m=>{const g=Number(m.target.value);Number.isFinite(g)&&u(Math.max(1,Math.min(100,Math.round(g))))}),h=W(()=>{i(!0,c/100)}),f=W(()=>{i(!1,0)});return o.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(280px,0.6fr)]",children:[o.jsxs(fi,{className:"overflow-hidden",children:[o.jsxs("div",{className:"border-b border-border/70 px-5 py-4",children:[o.jsx("h2",{className:"font-semibold",children:"候选资产"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r?`${r} · ${e.length} 条`:"尚无学习范围"})]}),e.length>0?o.jsx("div",{className:"divide-y divide-border/60",children:e.map(m=>o.jsxs("article",{className:"[content-visibility:auto] p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"font-medium",children:m.statement}),o.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:m.guidance})]}),o.jsx(Zo,{status:m.lifecycle,label:m.lifecycle})]}),o.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{children:m.type}),o.jsx("span",{children:"·"}),o.jsx("span",{children:m.evidenceGrade}),o.jsx("span",{children:"·"}),o.jsxs("span",{children:[m.risk," risk"]}),o.jsx("span",{children:"·"}),o.jsxs("span",{children:["revision ",m.revisionId]})]}),m.evidenceRefs.length>0?o.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:m.evidenceRefs.slice(0,4).map(g=>o.jsx(Z,{variant:"outline",size:"sm",asChild:!0,children:o.jsx(bu,{to:`/activity?view=facts&search=${encodeURIComponent(g)}`,children:g})},g))}):null,m.type==="memory"?o.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[m.lifecycle==="shadow"?o.jsx(Z,{size:"sm",disabled:s||!/^[a-f0-9]{64}$/u.test(m.learningScopeId)||!(t!=null&&t.memoryCanaryEnabled)||(t.canaryRate??0)<=0,onClick:()=>a(m),children:"授权进入 Canary"}):null,m.lifecycle!=="retired"&&m.lifecycle!=="rejected"?o.jsx(Z,{size:"sm",variant:"outline",disabled:s,onClick:()=>l(m),children:"退休 / 回滚"}):null,m.lifecycle==="shadow"&&!(t!=null&&t.memoryCanaryEnabled)?o.jsx("span",{className:"self-center text-xs text-muted-foreground",children:"先在右侧显式启用 scope policy"}):null]}):null]},m.revisionId))}):o.jsx("p",{className:"p-8 text-center text-sm text-muted-foreground",children:"当前范围没有 Candidate;页面不会为填充状态生成示例资产。"})]}),o.jsxs(fi,{className:"h-fit p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Yv,{className:"h-4 w-4"}),o.jsx("h2",{className:"font-semibold",children:"Memory Canary Policy"})]}),t?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"mt-3 space-y-3 text-sm",children:[o.jsxs("div",{className:"flex justify-between gap-3",children:[o.jsx("span",{className:"text-muted-foreground",children:"真实注入"}),o.jsx(Zo,{status:t.memoryCanaryEnabled?"canary":"draft",label:t.memoryCanaryEnabled?"已启用":"默认关闭"})]}),o.jsxs("div",{className:"flex justify-between gap-3",children:[o.jsx("span",{className:"text-muted-foreground",children:"Canary 比例"}),o.jsxs("span",{children:[Math.round(t.canaryRate*100),"%"]})]}),o.jsxs("label",{className:"block",children:[o.jsx("span",{className:"text-muted-foreground",children:"设置实验流量(1–100%)"}),o.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[o.jsx("input",{className:"h-9 min-w-0 flex-1 rounded-md border border-input bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",type:"number",min:1,max:100,step:1,value:c,disabled:n,onChange:d}),o.jsx("span",{className:"text-muted-foreground",children:"%"})]})]}),o.jsxs("div",{className:"flex justify-between gap-3",children:[o.jsx("span",{className:"text-muted-foreground",children:"单次资产上限"}),o.jsx("span",{children:t.maxInjectedAssets})]}),o.jsxs("div",{className:"flex justify-between gap-3",children:[o.jsx("span",{className:"text-muted-foreground",children:"单次字节上限"}),o.jsx("span",{children:t.maxInjectionBytes})]}),o.jsxs("div",{className:"flex justify-between gap-3",children:[o.jsx("span",{className:"text-muted-foreground",children:"Policy revision"}),o.jsx("span",{children:t.revision})]})]}),o.jsx(Z,{className:"mt-3 w-full",variant:"default",disabled:n,onClick:h,children:t.memoryCanaryEnabled?`更新为 ${c}%`:`启用 ${c}% Canary`}),t.memoryCanaryEnabled?o.jsx(Z,{className:"mt-2 w-full",variant:"outline",disabled:n,onClick:f,children:"关闭真实注入"}):null]}):o.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:"选择已有学习范围后读取真实策略。"})]})]})}function wle({schedules:e,actionPending:t,onEdit:r,onToggle:n,onDelete:s}){return o.jsxs(fi,{className:"overflow-hidden",children:[o.jsxs("div",{className:"border-b border-border/70 px-5 py-4",children:[o.jsx("h2",{className:"font-semibold",children:"持久化运行计划"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Schedule 与手动触发共享同一个 Evolution Run 服务"})]}),e.length>0?o.jsx("div",{className:"divide-y divide-border/60",children:e.map(i=>o.jsxs("article",{className:"flex flex-wrap items-center justify-between gap-4 p-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("h3",{className:"font-medium",children:i.name}),i.pausedReason?o.jsxs("p",{className:"mt-2 text-xs text-amber-600",children:["已暂停:",i.pausedReason==="repository_attribution_unresolved"?"历史仓库或工作目录尚未确认":i.pausedReason==="repository_unavailable"?"仓库工作目录不可用":"迁移完成后等待恢复"]}):null,o.jsx(Zo,{status:i.enabled?"available":"draft",label:i.enabled?"已启用":"已停用"})]}),o.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:[o.jsx(fE,{className:"mr-1 inline h-3.5 w-3.5"}),i.cronExpression," · ",i.timezone," ·"," ",i.dataWindow]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[i.learningScopeId," · ",i.profile," ·"," ",i.providerPolicy," · 下次"," ",iu(i.nextDueAt)]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"outline",size:"sm",disabled:t,onClick:()=>n(i),children:i.enabled?"停用":"启用"}),o.jsx(Z,{variant:"outline",size:"sm",disabled:t,onClick:()=>r(i),children:"编辑"}),o.jsx(Z,{variant:"ghost",size:"sm",disabled:t,onClick:()=>s(i),children:"删除"})]})]},i.scheduleId))}):o.jsx("div",{className:"flex min-h-72 items-center justify-center p-8 text-center",children:o.jsxs("div",{children:[o.jsx(ML,{className:"mx-auto h-6 w-6 text-muted-foreground"}),o.jsx("h2",{className:"mt-4 font-semibold",children:"尚未配置 Schedule"}),o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"使用页面右上角“运行计划”创建真实持久化计划。"})]})})]})}function Sle(e){const[t,r]=fa(),n=p4.has(t.get("view"));return o.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-auto bg-background",children:[o.jsxs("nav",{className:"flex shrink-0 gap-1 border-b border-border pb-2","aria-label":"自进化视图",children:[o.jsx(Z,{size:"sm",variant:n?"ghost":"secondary",onClick:()=>r({}),children:"成果"}),o.jsx(Z,{size:"sm",variant:n?"secondary":"ghost",onClick:()=>r({view:"overview"}),children:"分析管理"})]}),n?o.jsx(Cle,{...e}):o.jsx(Eae,{apiBase:e.apiBase,token:e.token},`${e.apiBase}:${wv(e.token)}`)]})}function Cle({apiBase:e,token:t,embedded:r=!1}){var Dt,Ft,Mt,Ze,xt,Ut,fr,dt,qe,Ht;const[n,s]=fa(),i=xs(),[a,l]=p.useState(!1),[c,u]=p.useState(null),[d,h]=p.useState(null),f=n.get("view"),m=f&&p4.has(f)?f:"overview",g=Ct({queryKey:["evolution","runs",e],queryFn:()=>Dae(e,t,{limit:200}),refetchInterval:Ce=>{var lt;return(lt=Ce.state.data)!=null&<.runs.some(Nt=>!Pc.has(Nt.stage))?5e3:!1}}),v=Ct({queryKey:["evolution","providers",e],queryFn:()=>Fae(e,t),refetchInterval:3e4}),x=Ct({queryKey:["evolution","schedules",e],queryFn:()=>zae(e,t)}),b=Ct({queryKey:["evolution","candidates",e],queryFn:()=>qae(e,t)}),_=Ct({queryKey:["evolution","insights",e],queryFn:()=>$ae(e,t)}),C=Ct({queryKey:["evolution","runtime-traces",e],queryFn:()=>Xae(e,t,{limit:200})}),S=((Dt=g.data)==null?void 0:Dt.runs)??kae,w=((Ft=x.data)==null?void 0:Ft.schedules)??Iae,y=((Mt=b.data)==null?void 0:Mt.candidates)??Nae,N=((Ze=_.data)==null?void 0:Ze.insights)??Rae,E=((xt=C.data)==null?void 0:xt.traces)??jae,k=((Ut=v.data)==null?void 0:Ut.providers)??[],{scopeOptions:D,selectedScopeId:j,selectedScope:R,scopeError:I}=ele(e,t,n.get("scope")??""),T=dc(S,j),A=dc(w,j),P=dc(y,j),O=dc(N,j),L=dc(E,j),B=n.get("run"),M=B&&T.some(Ce=>Ce.runId===B)&&B||((fr=T[0])==null?void 0:fr.runId)||null,$=Ct({queryKey:["evolution","artifacts-summary",e,M],queryFn:()=>Pae(e,t,M??""),enabled:m==="runs"&&M!==null,refetchInterval:T.some(Ce=>Ce.runId===M&&!Pc.has(Ce.stage))?5e3:!1}),U=(dt=T.find(Ce=>Ce.runId===M))==null?void 0:dt.stage;p.useEffect(()=>{m!=="runs"||M===null||!U||!Pc.has(U)||i.invalidateQueries({queryKey:["evolution","artifacts-summary",e,M]})},[e,i,M,U,m]);const F=Ct({queryKey:["evolution","policy",e,j],queryFn:()=>Gae(e,t,j),enabled:m==="candidates"&&R.kind==="repository"}),K=W(async()=>{await i.invalidateQueries({queryKey:["evolution"]})}),Y=W(Ce=>{const lt=new URLSearchParams(n);for(const[Nt,Ke]of Object.entries(Ce))Ke?lt.set(Nt,Ke):lt.delete(Nt);s(lt,{replace:!0})}),te=W(Ce=>{Y({view:Ce,run:Ce==="runs"?M:null})}),H=W(Ce=>{Y({scope:Ce,run:null})}),G=W(Ce=>{Y({view:"runs",run:Ce})}),z=W(()=>{u(null),l(!0)}),ee=W(()=>{l(!1),u(null)}),V=W(Ce=>{u(Ce),l(!0)}),re=W(()=>{h(null)}),oe=nr({mutationFn:Ce=>Mae(e,t,Ce),onSuccess:async Ce=>{Y({view:"runs",scope:Ce.learningScopeId,run:Ce.runId}),await K()}}),[ce,be]=p.useState(()=>crypto.randomUUID()),ne=nr({mutationFn:()=>Zae(e,t,ce),onSuccess:async()=>{be(crypto.randomUUID()),Y({view:"runs",scope:Sv}),await K()}}),Te=W(()=>{if(R.kind==="global"){ne.mutate();return}R.kind!=="repository"||!R.available||(oe.reset(),oe.mutate({scope:{type:"repository",repositoryId:R.id,cwd:R.cwd}}))}),Ve=nr({mutationFn:Ce=>Oae(e,t,Ce),onSuccess:K}),Ge=nr({mutationFn:Ce=>Bae(e,t,Ce),onSuccess:async Ce=>{Y({scope:Ce.learningScopeId,run:Ce.runId}),await K()}}),we=nr({mutationFn:Ce=>Uae(e,t,Ce),onSuccess:async Ce=>{ee(),Y({view:"schedules",scope:Ce.learningScopeId}),await K()}}),de=nr({mutationFn:({scheduleId:Ce,input:lt})=>Hae(e,t,Ce,lt),onSuccess:async()=>{ee(),await K()}}),he=nr({mutationFn:Ce=>Wae(e,t,Ce),onSuccess:K}),ge=nr({mutationFn:({learningScopeId:Ce,policy:lt})=>Yae(e,t,Ce,lt),onSuccess:K}),Pe=nr({mutationFn:Ce=>Kae(e,t,Ce),onSuccess:K}),Le=nr({mutationFn:({candidateId:Ce,reason:lt})=>Vae(e,t,Ce,lt),onSuccess:async()=>{h(null),await K()}}),_e=W(Ce=>{c?de.mutate({scheduleId:c.scheduleId,input:Ce}):we.mutate(Ce)}),et=W(Ce=>{de.mutate({scheduleId:Ce.scheduleId,input:{enabled:!Ce.enabled}})}),it=W(Ce=>{window.confirm(`删除运行计划“${Ce.name}”?该操作不会删除已有 Run。`)&&he.mutate(Ce.scheduleId)}),ue=W((Ce,lt)=>{const Nt=F.data;Nt&&(Ce&&!window.confirm(`为 ${Nt.learningScopeId} 启用 ${Math.round(lt*100)}% Memory Canary?`)||ge.mutate({learningScopeId:Nt.learningScopeId,policy:{memoryCanaryEnabled:Ce,canaryRate:lt,maxInjectedAssets:Nt.maxInjectedAssets,maxInjectionBytes:Nt.maxInjectionBytes,autoPromotion:Nt.autoPromotion,minimumPromotionGrade:Nt.minimumPromotionGrade,minimumPromotionSamples:Nt.minimumPromotionSamples}}))}),Ie=W(Ce=>{window.confirm(`将 Memory ${Ce.assetId} 授权进入 Canary?它只会按当前 scope policy 注入匹配的 code worker。`)&&Pe.mutate(Ce.assetId)}),ye=W(Ce=>{Le.reset(),h(Ce)}),ae=W(()=>{Ve.reset(),Ge.reset(),de.reset(),he.reset(),ge.reset(),Pe.reset(),Le.reset(),Promise.all([g.refetch(),v.refetch(),x.refetch(),b.refetch(),_.refetch(),$.refetch()])}),le=I??ne.error??g.error??v.error??x.error??b.error??_.error??C.error??$.error??F.error??oe.error??Pe.error??Le.error??Ve.error??Ge.error??de.error??he.error??ge.error,je=g.isLoading||v.isLoading||x.isLoading||b.isLoading||_.isLoading,Me=c!==null?de:we,ot=Ve.isPending||Ge.isPending,ct=we.isPending||de.isPending||he.isPending,yt=Pe.isPending||Le.isPending;return o.jsxs("main",{className:r?"min-h-0 flex-1 overflow-hidden text-foreground":"h-dvh overflow-hidden bg-background text-foreground",children:[o.jsxs("div",{className:r?"flex h-full min-h-0 flex-col":"grid h-full min-h-0 grid-cols-[220px_minmax(0,1fr)] max-md:grid-cols-1 max-md:grid-rows-[auto_minmax(0,1fr)]",children:[o.jsx(ale,{view:m,scopes:D,selectedScopeId:j,counts:{runs:T.length,insights:O.length,candidates:P.length,schedules:A.length},providers:k,onSelectView:te,onSelectScope:H,embedded:r}),o.jsxs("section",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:[o.jsx(lle,{embedded:r,view:m,scopeLabel:R.label,reflectionPending:oe.isPending||ne.isPending,reflectionDisabled:R.kind==="legacy"||R.kind==="repository"&&!R.available,onStartReflection:Te,onOpenSchedule:z}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto pt-2",children:[o.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:R.description}),le?o.jsx(cle,{message:h0(le),onRetry:ae}):null,o.jsxs("div",{className:le?"mt-4":"",children:[je?o.jsx(dle,{}):null,!je&&m==="overview"?o.jsx(ule,{runs:T,insights:O,candidates:P,schedules:A,providers:k,runtimeUnavailableReason:(qe=v.data)==null?void 0:qe.runtimeUnavailableReason,runtimeAvailable:((Ht=v.data)==null?void 0:Ht.runtimeAvailable)??!1,onSelectRun:G,onSelectView:te}):null,!je&&m==="runs"?o.jsx(ble,{apiBase:e,token:t,runs:T,selectedRunId:M,traces:L,artifacts:$.data,actionPending:ot,onSelectRun:G,onCancelRun:Ve.mutate,onRetryRun:Ge.mutate}):null,!je&&m==="insights"?o.jsx(ple,{insights:O}):null,!je&&m==="candidates"?o.jsx(yle,{candidates:P,policy:F.data,selectedScopeId:j,policyPending:ge.isPending,candidateActionPending:yt,onUpdateCanary:ue,onAuthorizeCandidate:Ie,onRetireCandidate:ye}):null,!je&&m==="schedules"?o.jsx(wle,{schedules:A,actionPending:ct,onEdit:V,onToggle:et,onDelete:it}):null]})]})]})]}),a?o.jsx(nle,{open:!0,pending:Me.isPending,error:Me.error?h0(Me.error):null,schedule:c,initialProjectId:R.cwd??"",onOpenChange:Ce=>{Ce||ee()},onSubmit:_e},(c==null?void 0:c.scheduleId)??"new"):null,d?o.jsx(sle,{candidate:d,pending:Le.isPending,error:Le.error?h0(Le.error):null,onOpenChange:Ce=>{Ce||re()},onSubmit:Ce=>{Le.mutate({candidateId:d.assetId,reason:Ce})}}):null]})}function m4({task:e,onEdit:t,readOnly:r=!1}){const{api:n}=es(),s=Jf(),{go:i}=cR(),a=Gt(),l=p.useRef(a.key);l.current=a.key;const c=p.useRef(null),u=p.useRef(!0);p.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const d=p.useRef(null),h=nr({mutationFn:async f=>{if(f==="toggle")return n.update(e.id,{expectedRevision:e.revision,enabled:!e.enabled});if(f==="delete")return n.remove(e.id,e.revision);d.current??(d.current=crypto.randomUUID()),c.current=l.current;const m=await n.start(e.id,d.current);return d.current=null,m},onSuccess:(f,m)=>{m==="run"&&u.current&&c.current===l.current&&"taskId"in f&&i(`/scheduled-tasks/${encodeURIComponent(f.taskId)}?run=${encodeURIComponent(f.id)}`)},onSettled:()=>{s()}});return r&&!e.deletedAt?o.jsx("span",{className:"text-xs text-muted-foreground",children:"调度已关闭 · 只读"}):e.deletedAt?o.jsx("span",{className:"text-xs text-muted-foreground",children:"已删除 · 只读"}):o.jsxs("div",{className:"flex flex-col items-end gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button",role:"switch","aria-checked":e.enabled,"aria-label":`${e.enabled?"暂停":"启用"} ${e.name}`,disabled:h.isPending,onClick:()=>h.mutate("toggle"),className:`relative h-5 w-9 shrink-0 rounded-full transition-colors disabled:opacity-50 ${e.enabled?"bg-primary":"bg-muted"}`,children:o.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-background transition-transform ${e.enabled?"left-0.5 translate-x-4":"left-0.5"}`})}),o.jsxs($u,{children:[o.jsx(zu,{asChild:!0,children:o.jsx(Z,{size:"icon",variant:"ghost",className:"h-7 w-7","aria-label":`${e.name} 更多操作`,disabled:h.isPending,children:o.jsx(wf,{className:"h-4 w-4"})})}),o.jsxs(Ll,{align:"end",children:[o.jsx(Bt,{onSelect:()=>h.mutate("run"),children:"立即运行"}),o.jsx(Bt,{onSelect:()=>t(e),children:"编辑任务"}),o.jsx(Bt,{className:"text-destructive",onSelect:()=>{window.confirm("删除任务并关闭后续安排?历史和已打开的终端将保留,正在执行的运行不会停止。")&&h.mutate("delete")},children:"删除任务"})]})]})]}),o.jsx(Mr,{error:h.error})]})}function Ele({tasks:e,onOpen:t,onEdit:r,readOnly:n=!1}){return o.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:e.map(s=>o.jsxs("article",{className:"min-w-0 rounded-xl border bg-card p-5 shadow-sm",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("button",{type:"button",className:"min-w-0 text-left text-base font-semibold hover:text-primary",onClick:()=>t(s.id),children:o.jsx("span",{className:"break-words",children:s.name})}),o.jsx(m4,{task:s,onEdit:r,readOnly:n})]}),o.jsxs("button",{type:"button",onClick:()=>t(s.id),className:"mt-3 block w-full text-left",children:[o.jsx("p",{className:"line-clamp-3 break-words text-sm text-muted-foreground",children:s.prompt}),o.jsx("p",{className:"mt-4 break-words text-xs text-muted-foreground",children:s.provider}),o.jsxs("p",{className:"mt-3 flex items-start gap-2 text-xs",children:[o.jsx(wl,{className:"h-4 w-4 shrink-0"}),o.jsx("span",{children:ib(s.schedule)})]}),o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:s.enabled?`下次运行:${as(s.nextRunAt,s.schedule.timezone)}`:"已暂停后续安排"})]})]},s.id))})}function kle({run:e,highlighted:t}){var u,d,h,f,m,g;const[r,n]=p.useState(t),s=p.useRef(null),i=gj(),a=["queued","running","stopping"].includes(e.status),l=!a&&e.recoverable&&!!e.threadRef,c=W(()=>{l&&!i.fullscreen?i.mutate(e.id):n(v=>!v)});return p.useEffect(()=>{var v;t&&((v=s.current)==null||v.scrollIntoView({block:"center",behavior:"smooth"}))},[t]),o.jsxs("article",{ref:s,id:`run-${e.id}`,className:`min-w-0 scroll-m-6 rounded-xl border p-4 ${t?"border-primary ring-1 ring-primary":"bg-card"}`,children:[o.jsxs("button",{type:"button",className:"w-full text-left",disabled:i.isPending,onClick:c,children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsx("span",{className:"text-sm font-medium",children:as(e.startedAt??e.scheduledFor)}),o.jsx("span",{className:"rounded-md bg-muted px-2 py-1 text-xs",children:bb(e)})]}),o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:((u=e.snapshot.origin)==null?void 0:u.kind)==="quick-input"?`${e.snapshot.origin.projectName}${e.snapshot.origin.worktreeName?` / ${e.snapshot.origin.worktreeName}`:""} · 后台运行`:`${e.trigger==="manual"?"手动运行":"定时触发"} · 配置版本 ${e.taskRevision}`})]}),e.trigger==="scheduled"?o.jsxs("div",{className:"mt-2 space-y-1 text-xs text-muted-foreground",children:[o.jsxs("p",{children:["计划时间:",as(e.scheduledFor,e.snapshot.schedule.timezone)]}),o.jsxs("p",{children:["实际开始:",e.startedAt?as(e.startedAt,e.snapshot.schedule.timezone):"尚未开始"]}),e.dispatch?o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:[e.dispatch.catchUp?"延迟执行 · ":"","调度延迟:",pg(e.dispatch.latenessMs)]}),e.startedAt?o.jsxs("p",{children:["排队等待:",pg(Date.parse(e.startedAt)-Date.parse(e.dispatch.evaluatedAt))]}):null,e.dispatch.coalescedFrom?o.jsxs("p",{children:["更早的安排已合并忽略(从"," ",as(e.dispatch.coalescedFrom,e.snapshot.schedule.timezone)," ","起)"]}):null]}):null]}):null,e.summary?o.jsx(vb,{text:e.summary}):null,e.status==="completed"&&!e.outcome?o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"此历史运行未记录任务结果,请根据摘要确认是否完成。"}):null,e.error?o.jsxs("p",{className:"mt-2 break-words text-sm text-destructive",children:[e.error.code==="missed"?"超过允许的延迟,已跳过":e.error.message," ","(",e.error.code,")"]}):null,o.jsx(mj,{run:e}),o.jsx("button",{type:"button",className:"mt-3 text-left text-xs text-primary",disabled:i.isPending||i.fullscreen&&i.prepared,onClick:()=>l?i.mutate(e.id):c(),children:i.isPending?i.attachmentState==="starting"||i.attachmentState==="creating"?"正在恢复对话…":"正在打开…":i.prepared?"会话已准备,请从左上角返回终端":l?i.fullscreen?"准备运行会话":(d=e.continuation)!=null&&d.nextAt?"停止自动继续并接管到终端 →":"打开对话并继续追问 →":a?"查看运行进度":"查看记录"}),((h=e.terminalBinding)==null?void 0:h.attachmentState)==="starting"||((f=e.terminalBinding)==null?void 0:f.attachmentState)==="creating"?o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"正在恢复对话…"}):null,((m=e.terminalBinding)==null?void 0:m.attachmentState)==="failed"?o.jsx("p",{className:"mt-2 text-xs text-destructive",children:e.terminalBinding.error??"恢复失败"}):null,o.jsx(Mr,{error:i.error}),o.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:e.artifacts.map((v,x)=>{const b=ob(v.url);return b?o.jsx("a",{className:"break-all text-sm text-primary underline",href:b,target:"_blank",rel:"noopener noreferrer",children:v.label},x):o.jsxs("span",{className:"whitespace-pre-wrap break-words text-sm",children:[v.label,v.text?`:${v.text}`:""]},x)})}),o.jsxs("div",{className:"mt-3 flex flex-wrap items-start gap-3",children:[o.jsxs("details",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer",children:"本次配置快照"}),o.jsxs("p",{className:"mt-2 break-words",children:[e.snapshot.name," · ",e.snapshot.provider," ·"," ",e.executionContext.kind==="project"?e.executionContext.projectId:"独立任务工作区"]}),((g=e.snapshot.origin)==null?void 0:g.kind)==="quick-input"?null:o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"mt-1",children:ib(e.snapshot.schedule)}),o.jsx("p",{className:"mt-1",children:eG(e.snapshot.misfirePolicy)})]}),o.jsxs("p",{className:"mt-1",children:["模型:",e.snapshot.model||"默认"," · 推理:",e.snapshot.effort||"默认"," · 权限:",sp(e.snapshot.executionPolicy)]}),o.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words",children:e.snapshot.prompt})]}),o.jsx("button",{type:"button",className:"text-xs text-muted-foreground underline",onClick:()=>n(v=>!v),children:r?"收起输出":"查看输出"})]}),r?o.jsx(bj,{run:e},e.id):null]})}function Ile({taskId:e,onEdit:t,readOnly:r=!1}){var d,h,f,m,g;const n=zq(e),s=Uq(e),[i]=fa(),a=i.get("run"),l=Ml(a),c=((d=s.data)==null?void 0:d.pages.flatMap(v=>v.items))??[],u=((h=l.data)==null?void 0:h.taskId)===e&&!c.some(v=>v.id===a)?[l.data,...c]:c;return o.jsxs("div",{className:"space-y-5",children:[o.jsx(Mr,{error:n.error}),n.isPending?o.jsx("p",{children:"正在加载任务…"}):n.data?o.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsx("h2",{className:"min-w-0 break-words text-xl font-semibold",children:n.data.name}),((f=n.data.origin)==null?void 0:f.kind)==="quick-input"?null:o.jsx(m4,{task:n.data,onEdit:t,readOnly:r})]}),n.data.deletedAt?o.jsx("p",{className:"mt-3 text-sm text-muted-foreground",children:"此任务已删除。历史仍可查看和打开,调度不会恢复。"}):null,o.jsx("p",{className:"mt-3 break-words text-sm text-muted-foreground",children:n.data.provider}),((m=n.data.origin)==null?void 0:m.kind)==="quick-input"?null:o.jsx("p",{className:"mt-2 text-sm",children:ib(n.data.schedule)}),o.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["执行权限:",sp(n.data.executionPolicy)]}),((g=n.data.origin)==null?void 0:g.kind)==="quick-input"?null:o.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:n.data.enabled?`下次运行:${as(n.data.nextRunAt,n.data.schedule.timezone)}`:"已暂停后续安排"}),o.jsxs("details",{className:"mt-4 text-sm",children:[o.jsx("summary",{className:"cursor-pointer",children:"任务提示词"}),o.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words",children:n.data.prompt})]})]}):null,o.jsx("h3",{className:"font-semibold",children:"运行历史"}),o.jsx(Mr,{error:s.error??l.error}),l.data&&l.data.taskId!==e?o.jsx("p",{role:"alert",children:"此运行不属于当前任务。"}):null,s.isPending?o.jsx("p",{className:"text-sm text-muted-foreground",children:"正在加载历史…"}):!s.error&&!u.length?o.jsx("p",{className:"text-sm text-muted-foreground",children:"还没有运行记录。"}):null,u.map(v=>{var x;return o.jsx(kle,{run:((x=l.data)==null?void 0:x.id)===v.id&&l.data.taskId===e?l.data:v,highlighted:v.id===a},v.id)}),s.hasNextPage?o.jsx(Z,{variant:"outline",disabled:s.isFetchingNextPage,onClick:()=>{s.fetchNextPage()},children:"加载更多记录"}):null]})}function Nle({provider:e,model:t,effort:r,onChange:n}){var u;const s=Bq(),i=e==="pi"||(u=s.data)==null?void 0:u.catalogs[e==="trae"?"traex":e],a=(i==null?void 0:i.availability)==="available",l=a?i.models:[],c=l.find(d=>d.id===t);return o.jsxs("section",{className:"grid gap-3 rounded-lg border p-3","aria-label":"模型配置",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{children:"模型"}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:["当前:",(c==null?void 0:c.label)??(t||"Agent 默认配置")]})]}),o.jsx(Z,{type:"button",variant:t?"outline":"secondary","aria-pressed":!t&&!r,onClick:()=>n("",""),children:"Agent 默认配置"}),s.isPending?o.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"正在加载模型…"}):s.isError||!a?o.jsxs("div",{role:"status",className:"text-sm text-muted-foreground",children:["模型目录暂不可用,已有配置仍会保留。",o.jsx(Z,{type:"button",variant:"ghost",disabled:s.isFetching,onClick:()=>void s.refetch(),children:"重试"})]}):o.jsx("div",{className:"overflow-hidden rounded-md border",children:o.jsxs("div",{className:"max-h-48 overflow-y-auto p-1.5","aria-label":"可用模型",children:[l.map(d=>o.jsxs("button",{type:"button","aria-pressed":t===d.id,className:"flex w-full items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent aria-pressed:bg-accent",onClick:()=>n(d.id,d.defaultReasoningEffort??""),children:[o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-sm font-medium",children:d.label}),o.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:d.id})]}),t===d.id?o.jsx(di,{className:"h-4 w-4 shrink-0"}):null]},d.id)),l.length?null:o.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"暂无可用模型"})]})}),o.jsxs("div",{className:"grid gap-2",role:"group","aria-label":"推理强度",children:[o.jsx("span",{className:"text-sm",children:"推理强度"}),c!=null&&c.reasoningEfforts.length?o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(Z,{type:"button",size:"sm",variant:r?"outline":"secondary","aria-pressed":!r,onClick:()=>n(t,""),children:"Agent 默认配置"}),c.reasoningEfforts.map(d=>o.jsx(Z,{type:"button",size:"sm",variant:r===d?"secondary":"outline","aria-pressed":r===d,onClick:()=>n(t,d),children:d},d))]}):o.jsx("p",{className:"text-sm text-muted-foreground",children:c?"此模型不提供可配置档位":"选择模型后可设置其支持的推理强度"}),r&&!(c!=null&&c.reasoningEfforts.includes(r))?o.jsxs("p",{role:"status",className:"text-xs text-muted-foreground",children:["已保存推理强度:",r,"(当前无法验证)。",o.jsx(Z,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(t,""),children:"重置推理强度"})]}):null]}),a&&t&&!c?o.jsxs("p",{role:"status",className:"text-xs text-muted-foreground",children:["已保存模型 ",t," 不在当前目录中,可重新选择。"]}):null,o.jsx("p",{className:"text-xs text-muted-foreground",children:"模型列表来自当前连接的 CLI;配置仅对本任务生效。"})]})}function Rle({task:e,capabilities:t,onClose:r,onSaved:n}){var y,N,E;const{api:s,scope:i}=es(),a=Jf(),l=p.useRef(!0);p.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const[c,u]=p.useState(()=>{var k;return{name:(e==null?void 0:e.name)??"",provider:(e==null?void 0:e.provider)??"codex",prompt:(e==null?void 0:e.prompt)??"",model:(e==null?void 0:e.model)??"",effort:(e==null?void 0:e.effort)??"",executionPolicy:e==null?void 0:e.executionPolicy,continuationPolicy:(e==null?void 0:e.continuationPolicy)??{mode:!e&&((k=t.providers.find(D=>D.provider==="codex"))!=null&&k.continuation)?"bounded":"off"},misfirePolicy:e?e.misfirePolicy:{mode:"catch-up-latest",maxDelaySeconds:86400},enabled:(e==null?void 0:e.enabled)??!0,schedule:(e==null?void 0:e.schedule)??{kind:"daily",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",localTime:"09:00"}}}),[d,h]=p.useState(null),f=p.useRef(null),m=t.providers.find(k=>k.provider===c.provider),g=c.executionPolicy??"sandbox",v=mm(g)&&((m==null?void 0:m.executionPolicies)??["sandbox"]).includes(g),x=hC(c.schedule,{wait:350}),b=Ct({queryKey:[...hs.all(i),"preview",x],queryFn:({signal:k})=>s.preview(x,k),enabled:x.kind!=="once"||!!x.runAt,staleTime:0}),_=nr({mutationFn:async()=>{var j,R,I;const k={...c,name:c.name.trim(),prompt:c.prompt.trim(),model:((j=c.model)==null?void 0:j.trim())||void 0,effort:((R=c.effort)==null?void 0:R.trim())||void 0};if(e)return s.update(e.id,{...k,expectedRevision:e.revision,model:k.model??null,effort:k.effort??null});const D=JSON.stringify(k);return((I=f.current)==null?void 0:I.body)!==D&&(f.current={body:D,key:crypto.randomUUID()}),s.create(k,f.current.key)},onSuccess:k=>{a(),l.current&&n(k)},onError:()=>{a()}}),C=(k,D)=>u(j=>({...j,[k]:D})),S=k=>{const D=c.schedule.timezone,j="localTime"in c.schedule?c.schedule.localTime:"09:00";C("schedule",k==="once"?{kind:k,timezone:D,runAt:""}:k==="weekly"?{kind:k,timezone:D,localTime:j,weekdays:[1]}:{kind:k,timezone:D,localTime:j})},w=W(k=>{if(k.preventDefault(),!c.name.trim()||!c.prompt.trim()){h("请填写名称和提示词。");return}if(c.schedule.kind==="weekly"&&!c.schedule.weekdays.length){h("请至少选择一个运行日期。");return}if(!v){h(mm(g)?"当前 Agent 不支持所选执行权限。":"任务包含未知执行权限,请先选择受支持的权限。");return}if(!t.enabled||!(m!=null&&m.available)||!b.data||!b.data.occurrences.length||b.isError||b.isFetching||x!==c.schedule){h("请先选择可用 Agent 并等待时间预览通过。");return}h(null),_.mutate()});return o.jsx(Qr,{open:!0,onOpenChange:k=>{!k&&!_.isPending&&r()},children:o.jsxs(dn,{className:"max-h-[90dvh] overflow-y-auto sm:max-w-xl",children:[o.jsx(Ur,{children:e?"编辑任务":"新建定时任务"}),o.jsx(Zr,{children:"每次运行建立独立对话,时间预览由当前 Backend 计算。"}),o.jsxs("form",{className:"grid gap-4",onSubmit:w,children:[o.jsxs("label",{className:"grid gap-1 text-sm",children:["任务名称",o.jsx(sr,{required:!0,maxLength:80,value:c.name,onChange:k=>C("name",k.target.value)})]}),m!=null&&m.continuation?o.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[o.jsx("input",{type:"checkbox",checked:((y=c.continuationPolicy)==null?void 0:y.mode)==="bounded",onChange:k=>C("continuationPolicy",{mode:k.target.checked?"bounded":"off"})}),"自动继续(最多 3 次,保留原对话和进度)"]}):null,o.jsxs("label",{className:"grid gap-1 text-sm",children:["Agent",o.jsx("select",{className:Xl,value:c.provider,onChange:k=>u(D=>({...D,provider:k.target.value,model:"",effort:"",executionPolicy:"sandbox",continuationPolicy:{mode:"off"}})),children:t.providers.map(k=>o.jsxs("option",{value:k.provider,disabled:!k.available,children:[k.provider==="trae"?"TraeX":k.provider==="codex"?"Codex":"Pi",k.available?"":` · ${k.reason??"暂不可用"}`]},k.provider))})]}),m!=null&&m.available?null:o.jsx("p",{className:"text-sm text-destructive",children:(m==null?void 0:m.reason)??"当前 Agent 不可用"}),o.jsx(Nle,{provider:c.provider,model:c.model??"",effort:c.effort??"",onChange:(k,D)=>u(j=>({...j,model:k,effort:D}))},c.provider),o.jsxs("label",{className:"grid gap-1 text-sm",children:["任务提示词",o.jsx("textarea",{className:`${Xl} min-h-32`,required:!0,maxLength:12e3,value:c.prompt,onChange:k=>C("prompt",k.target.value),placeholder:"描述任务、执行要求和期望产出;可以引用 Skill。"})]}),o.jsxs("section",{className:"grid gap-3 rounded-lg border p-3",children:[o.jsxs("label",{className:"grid gap-1 text-sm",children:["执行权限",o.jsxs("select",{className:Xl,value:g,onChange:k=>C("executionPolicy",k.target.value),children:[mm(g)?null:o.jsx("option",{value:String(g),disabled:!0,children:"未知权限"}),o.jsx("option",{value:"sandbox",children:"仅沙箱"}),o.jsx("option",{value:"auto-review",disabled:!((N=m==null?void 0:m.executionPolicies)!=null&&N.includes("auto-review")),children:"自动审批"}),o.jsx("option",{value:"full-access",disabled:!((E=m==null?void 0:m.executionPolicies)!=null&&E.includes("full-access")),children:"完全访问"})]})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:g==="full-access"?"无沙箱且不等待交互审批,可联网、操作 Browser、模拟器及本机文件;仅用于可信任务与提示词。":g==="auto-review"?"保留沙箱,Git 写入、联网等越界操作由 Codex 自动审查;拒绝或无法审批时记录为受阻。":g==="sandbox"?"可修改工作区普通文件;Git 元数据写入和命令联网受限。需要创建 Worktree、提交或拉取时,可选择自动审批。":`${sp(g)}:请选择受支持的权限后再保存。`})]}),o.jsxs("section",{className:"grid gap-3 rounded-lg border p-3",children:[o.jsxs("label",{className:"grid gap-1 text-sm",children:["时间规则",o.jsxs("select",{className:Xl,value:c.schedule.kind,onChange:k=>S(k.target.value),children:[o.jsx("option",{value:"daily",children:"每天"}),o.jsx("option",{value:"weekdays",children:"工作日"}),o.jsx("option",{value:"weekly",children:"每周"}),o.jsx("option",{value:"once",children:"仅一次"})]})]}),c.schedule.kind==="once"?o.jsxs("label",{className:"grid gap-1 text-sm",children:["执行时间(UTC)",o.jsx(sr,{type:"datetime-local",required:!0,value:c.schedule.runAt.slice(0,16),onChange:k=>C("schedule",{kind:"once",timezone:c.schedule.timezone,runAt:k.target.value?`${k.target.value}:00.000Z`:""})}),o.jsx("span",{className:"text-xs text-muted-foreground",children:"下方预览按所选时区显示。"})]}):o.jsxs("label",{className:"grid gap-1 text-sm",children:["当地时间",o.jsx(sr,{type:"time",required:!0,value:c.schedule.localTime,onChange:k=>C("schedule",{...c.schedule,localTime:k.target.value})})]}),c.schedule.kind==="weekly"?o.jsx("div",{className:"flex flex-wrap gap-3",children:[1,2,3,4,5,6,0].map(k=>o.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[o.jsx("input",{type:"checkbox",checked:c.schedule.kind==="weekly"&&c.schedule.weekdays.includes(k),onChange:D=>{c.schedule.kind==="weekly"&&C("schedule",{...c.schedule,weekdays:D.target.checked?[...c.schedule.weekdays,k]:c.schedule.weekdays.filter(j=>j!==k)})}}),"周","日一二三四五六"[k]]},k))}):null,o.jsxs("label",{className:"grid gap-1 text-sm",children:["时区",o.jsx(sr,{required:!0,value:c.schedule.timezone,onChange:k=>C("schedule",{...c.schedule,timezone:k.target.value}),placeholder:"Asia/Shanghai"})]}),o.jsx("div",{"aria-live":"polite",className:"text-xs text-muted-foreground",children:b.isFetching||x!==c.schedule?"正在计算…":b.data?o.jsxs(o.Fragment,{children:["接下来运行:",b.data.occurrences.map(k=>o.jsx("div",{children:as(k,c.schedule.timezone)},k)),b.data.occurrences.length?null:"没有未来执行时间"]}):null}),o.jsx(Mr,{error:b.error})]}),o.jsxs("section",{className:"grid gap-3 rounded-lg border p-3",children:[o.jsxs("label",{className:"grid gap-1 text-sm",children:["错过执行时间",o.jsxs("select",{className:Xl,value:c.misfirePolicy.mode,onChange:k=>C("misfirePolicy",k.target.value==="skip"?{mode:"skip"}:{mode:"catch-up-latest",maxDelaySeconds:86400}),children:[o.jsx("option",{value:"catch-up-latest",children:"恢复后补最近一次"}),o.jsx("option",{value:"skip",children:"错过就跳过"})]})]}),c.misfirePolicy.mode==="catch-up-latest"?o.jsxs("label",{className:"grid gap-1 text-sm",children:["允许延迟(小时)",o.jsx(sr,{type:"number",required:!0,min:1,max:168,step:1,value:c.misfirePolicy.maxDelaySeconds/3600||"",onChange:k=>C("misfirePolicy",{mode:"catch-up-latest",maxDelaySeconds:Number(k.target.value)*3600})})]}):null,o.jsx("p",{className:"text-xs text-muted-foreground",children:c.misfirePolicy.mode==="catch-up-latest"?"在允许延迟内只补最近一次,更早的安排合并忽略;已有运行时不重复启动。":"超过计划时间 60 秒仍未调度则跳过,等待下一次安排。"})]}),d?o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:d}):null,o.jsx(Mr,{error:_.error}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(Z,{type:"button",variant:"outline",disabled:_.isPending,onClick:r,children:"取消"}),o.jsx(Z,{type:"submit",disabled:_.isPending||!t.enabled||!(m!=null&&m.available)||!v,children:_.isPending?"正在保存…":"保存任务"})]})]})]})})}function jle(e){const t=ml({apiBase:e.apiBase,connectionId:e.activeConnectionId,generation:e.activeConnectionGeneration});return o.jsx(zf,{apiBase:e.apiBase,token:e.token,activeConnectionId:e.activeConnectionId,connectionGeneration:e.activeConnectionGeneration,children:o.jsx(Ale,{...e},t)})}function Ale(e){var _,C,S,w,y,N,E;const t=p.useSyncExternalStore(k=>sa.subscribe(k),()=>sa.isOnline()),{taskId:r}=mf(),[n]=fa(),s=Gt(),i=Ml(r?n.get("run"):null,!1),{go:a}=cR(),[l,c]=p.useState(!1),[u,d]=p.useState(""),h=hC(u,{wait:250}),[f,m]=p.useState(null),g=Fq(),v=!!g.data&&!g.isError,x=$q({archived:l,q:h},v&&!r),b=((_=x.data)==null?void 0:_.pages.flatMap(k=>k.items))??[];return((C=i.data)==null?void 0:C.taskId)===r&&((w=(S=i.data)==null?void 0:S.snapshot.origin)==null?void 0:w.kind)==="quick-input"?o.jsx(Rt,{to:Qf(i.data),replace:!0,state:s.state}):o.jsxs("main",{className:"min-h-0 bg-background text-foreground",children:[o.jsxs("header",{className:"sticky top-0 z-10 flex flex-wrap items-center gap-2 border-b bg-background/95 px-2 py-2 backdrop-blur",children:[o.jsx(wl,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:"任务与运行"}),o.jsx("div",{className:"ml-auto",children:e.activeConnectionId&&e.onSelectConnection&&e.onOpenConnectionManager?o.jsx(Xf,{connections:e.connections,activeConnectionId:e.activeConnectionId,activeConnectionName:e.connectionName,onSelectConnection:k=>{var D;a("/scheduled-tasks"),(D=e.onSelectConnection)==null||D.call(e,k)},onOpenConnectionManager:e.onOpenConnectionManager}):o.jsx("span",{className:"text-xs text-muted-foreground",children:e.connectionName??"当前 Backend"})})]}),o.jsxs("div",{className:"mx-auto w-full space-y-3 py-3",children:[t?null:o.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"网络已断开,等待连接恢复。未提交的草稿会保留。"}),o.jsx(Mr,{error:g.error}),g.isPending?o.jsx("p",{children:"正在检查定时任务能力…"}):null,g.data&&!g.data.enabled?o.jsx("p",{role:"status",children:g.data.reason??"当前 Backend 未启用定时任务,请检查服务配置。"}):null,g.isError?o.jsx(Z,{variant:"outline",onClick:()=>{g.refetch()},children:"重试连接"}):null,v?o.jsx(o.Fragment,{children:r?o.jsxs(o.Fragment,{children:[o.jsxs(Z,{variant:"ghost",onClick:()=>a("/scheduled-tasks"),children:[o.jsx(xi,{className:"mr-2 h-4 w-4"}),"任务列表"]}),o.jsx(Ile,{taskId:r,onEdit:m,readOnly:!((y=g.data)!=null&&y.enabled)},r)]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsx("h2",{className:"mr-auto text-xl font-semibold",children:l?"已删除任务":"我的任务"}),o.jsxs(Z,{disabled:!((N=g.data)!=null&&N.enabled),onClick:()=>m("new"),children:[o.jsx(yu,{className:"mr-1 h-4 w-4"}),"新建任务"]}),o.jsxs($u,{children:[o.jsx(zu,{asChild:!0,children:o.jsx(Z,{variant:"outline",size:"icon","aria-label":"列表更多操作",children:o.jsx(wf,{className:"h-4 w-4"})})}),o.jsx(Ll,{children:o.jsx(Bt,{onSelect:()=>c(k=>!k),children:l?"当前任务":"已删除任务"})})]})]}),o.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.jsx(sr,{"aria-label":"搜索任务",value:u,onChange:k=>d(k.target.value),placeholder:"搜索任务"})}),o.jsx(Mr,{error:x.error}),x.isPending?o.jsx("p",{children:"正在加载任务…"}):null,!x.isPending&&!x.error&&!b.length?o.jsx("div",{className:"rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground",children:l?"没有已删除的任务":"还没有符合条件的任务"}):null,o.jsx(Ele,{tasks:b,onOpen:k=>a(`/scheduled-tasks/${encodeURIComponent(k)}`),onEdit:m,readOnly:!((E=g.data)!=null&&E.enabled)}),x.hasNextPage?o.jsx(Z,{variant:"outline",disabled:x.isFetchingNextPage,onClick:()=>{x.fetchNextPage()},children:"加载更多任务"}):null]})}):null]}),f&&g.data?o.jsx(Rle,{task:f==="new"?void 0:f,capabilities:g.data,onClose:()=>m(null),onSaved:k=>{m(null),a(`/scheduled-tasks/${encodeURIComponent(k.id)}`)}}):null]})}function Tle(e){const t=ml({apiBase:e.apiBase,connectionId:e.activeConnectionId,generation:e.activeConnectionGeneration});return o.jsx(zf,{apiBase:e.apiBase,token:e.token,activeConnectionId:e.activeConnectionId,connectionGeneration:e.activeConnectionGeneration,children:o.jsx(Dle,{connectionName:e.connectionName},t)})}function Dle({connectionName:e}){var i;const{runId:t}=mf(),r=Gt(),n=Ml(t??null),{upsertBackgroundRun:s}=xj(!1);return n.data&&((i=n.data.snapshot.origin)==null?void 0:i.kind)!=="quick-input"?o.jsx(Rt,{to:Qf(n.data),replace:!0,state:r.state}):o.jsxs("main",{className:"min-h-0 bg-background text-foreground",children:[o.jsxs("header",{className:"sticky top-0 z-10 flex items-center gap-2 border-b bg-background/95 px-2 py-2 backdrop-blur",children:[o.jsx(Sl,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:"运行详情"}),o.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:e??"当前 Backend"})]}),o.jsxs("div",{className:"mx-auto w-full space-y-3 py-3",children:[o.jsx(Mr,{error:n.error}),n.isPending?o.jsx("p",{children:"正在加载运行记录…"}):null,n.isError?o.jsx(Z,{variant:"outline",onClick:()=>void n.refetch(),children:"重试"}):null,n.data?o.jsx(_j,{initial:n.data,onUpdate:s,onOpened:()=>{}},n.data.id):null]})]})}function Ple(e){const t=e.snapshot.origin,r=`${t.projectName}${t.worktreeName?` / ${t.worktreeName}`:""}`,n=e.status==="completed"&&e.outcome==="succeeded";return{runId:e.id,taskId:e.taskId,title:`${r} · ${n?"已完成":"需要处理"}`.slice(-120),body:`${e.snapshot.name} · ${n?"打开查看结果":"失败或受阻,打开查看原因"}`.slice(0,240)}}function Lle(e,t,r,n){const[s,i]=p.useState(null),a=W(()=>i(null));return p.useEffect(()=>{if(!n||!t||!r)return;const l=`runweave:quick-input-notices:${r}`,c=Date.now()-3e5;let u={since:new Date(c).toISOString(),seen:[]};try{const g=localStorage.getItem(l);if(g){const v=JSON.parse(g);Number.isFinite(Date.parse(v.since))&&Array.isArray(v.seen)&&(u=v)}}catch{}let d=!1,h=!1;const f=async()=>{var g,v;if(!(h||d)){h=!0;try{const x=new Set(u.seen);let b=u.since,_;const C=[];do{const S=await Uu(e,t).quickInputRuns({source:"quick-input",finishedSince:u.since,cursor:_,limit:100});if(d)return;for(const w of S.items){w.finishedAt&&w.finishedAt>b&&(b=w.finishedAt);const y=w.resultRevision?`${w.id}:${w.resultRevision}`:w.id;!x.has(y)&&["completed","failed"].includes(w.status)&&(x.add(y),C.push(w))}_=S.nextCursor??void 0}while(_);if(d)return;u={since:new Date(Math.max(c,Date.parse(b)-1e4)).toISOString(),seen:[...x].slice(-500)};try{localStorage.setItem(l,JSON.stringify(u))}catch{}for(const S of C){const w=Ple(S);!await((v=(g=window.electronAPI)==null?void 0:g.showScheduledRunNotification)==null?void 0:v.call(g,{connectionId:r,runId:S.id,title:w.title,body:w.body}).catch(()=>!1))&&!d&&i({connectionId:r,value:w})}}catch{}finally{h=!1}}};f();const m=window.setInterval(()=>void f(),5e3);return()=>{d=!0,window.clearInterval(m)}},[e,t,r,n]),{notice:(s==null?void 0:s.connectionId)===r?s.value:null,dismissNotice:a}}const k2=["_clck","_clsk"],f0="runweave:clarity:cookie:";function Mle(){const e=Object.getOwnPropertyDescriptor(Document.prototype,"cookie");if(!(e!=null&&e.get)||!e.set||Object.hasOwn(document,"cookie"))return;const t=()=>{var n;return(n=e.get)==null?void 0:n.call(document)},r=n=>{var s;return(s=e.set)==null?void 0:s.call(document,n)};try{Object.defineProperty(document,"cookie",{configurable:!0,get(){const n=t(),s=n?[n]:[];for(const i of k2)if(!n.split(";").some(a=>a.trim().startsWith(`${i}=`)))try{const a=JSON.parse(localStorage.getItem(`${f0}${i}`)??"null");if(!a||typeof a!="object"||!("value"in a)||!("expires"in a))continue;typeof a.expires!="number"||a.expires<=Date.now()?localStorage.removeItem(`${f0}${i}`):typeof a.value=="string"&&!/[;\r\n]/u.test(a.value)&&s.push(`${i}=${a.value}`)}catch{}return s.join("; ")},set(n){var g;const s=String(n);r(s);const[i="",...a]=s.split(";"),l=i.indexOf("=");if(l<0)return;const c=i.slice(0,l).trim();if(!k2.some(v=>v===c))return;const u=i.slice(l+1),d=new Map(a.flatMap(v=>{const x=v.indexOf("=");return x<0?[]:[[v.slice(0,x).trim().toLowerCase(),v.slice(x+1).trim()]]})),h=(g=d.get("domain"))==null?void 0:g.replace(/^\./u,"");if(h&&h!==location.hostname||(d.get("path")??"/")!=="/")return;const f=d.get("max-age"),m=f!==void 0&&/^-?\d+$/u.test(f)?Date.now()+Number(f)*1e3:Date.parse(d.get("expires")??"");if(Number.isFinite(m))try{const v=`${f0}${c}`;m<=Date.now()||t().split(";").some(x=>x.trim()===`${c}=${u}`)?localStorage.removeItem(v):localStorage.setItem(v,JSON.stringify({value:u,expires:m}))}catch{}}})}catch{}}const I2="runweave-clarity-script",N2="yo8dc0des6";let ou=!1,R2=null,Cc=null,kv=null,Hd=!1,yh=0,g4=!1,p0=null,j2=-1/0;function Ec(){const e=window.clarity;!ou||!g4||e!=null&&e.v||!e||p0!==null||document.visibilityState!=="visible"||!navigator.onLine||Date.now()-j2<3e4||(p0=setTimeout(()=>{p0=null;const t=window.clarity;if(!(!t||t.v||document.visibilityState!=="visible"||!navigator.onLine)){j2=Date.now();try{t("start")}catch{}}},1e3))}function A2(e){const t=window.clarity;if(!(!ou||!(t!=null&&t.v)))try{t("event",`surface_open_${e}`)}catch{}}function T2(e){Cc=e,Ec(),n_()}function n_(){const e=window.clarity;if(!ou||!(e!=null&&e.v)||!Cc||Hd||Cc===kv)return;const t=Cc,r=yh;Hd=!0;try{R2??(R2=crypto.randomUUID()),Promise.resolve(e("identify",R2,void 0,t)).then(()=>{yh===r&&(kv=t)}).catch(()=>{}).finally(()=>{Hd=!1,(Cc!==t||yh!==r)&&n_()})}catch{Hd=!1}}function Ole(){var i;const e=Oo("analytics"),t=N2.trim(),r=((i=window.electronAPI)==null?void 0:i.isElectron)===!0,n=r?window.location.protocol==="runweave:":["http:","https:"].includes(window.location.protocol);if(!t||!/^[a-zA-Z0-9]+$/.test(t)||!n||window.companionAPI!==void 0||document.getElementById(I2)){e.stage("rejected");return}const s=window;if(!s.clarity){const a=(...l)=>{(a.q??(a.q=[])).push(l)};s.clarity=a}try{r&&Mle();const a=document.createElement("script");a.id=I2,a.async=!0,a.src=`https://www.clarity.ms/tag/${t}`,document.head.append(a),ou=!0,H6(l=>{const c=window.clarity;ou&&(c!=null&&c.v)&&c("event",l)}),a.addEventListener("error",()=>Oo("analytics").stage("failed"),{once:!0}),window.addEventListener("online",Ec),window.addEventListener("focus",Ec),window.addEventListener("pointerdown",Ec,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",Ec),s.clarity("metadata",()=>{var u;g4=!0;const l=hu(),c={diagnostic_launch_id:nE,client:r?"desktop":"web",environment:t===N2?"production":"qa",app_version:l.version,build_id:l.buildId??"unknown",source_revision:l.sourceRevision??"unknown"};try{for(const[d,h]of Object.entries(c))(u=s.clarity)==null||u.call(s,"set",d,h);Oo("analytics").stage("confirmed")}catch{Oo("analytics").stage("failed")}yh+=1,kv=null,n_()},!1,!0)}catch{}}function Ble(e,t,r){var l,c,u;const n=ci(Ch(e),t),s=(l=n==null?void 0:n.at(-1))==null?void 0:l.route;if(!s||(c=s.path)!=null&&c.includes("*"))return null;const i=s.element;if(i===r||p.isValidElement(i)&&i.type===Rt)return null;const a=(u=s.handle)==null?void 0:u.analyticsScreen;return typeof a=="string"?a:i==null?null:(n==null?void 0:n.flatMap(({route:d})=>(d.path??"").split("/")).filter(d=>d&&!d.startsWith(":")).map(d=>d.replace(/\?$/u,"").replace(/-/gu,"_")).join("_"))||null}function Fle({routes:e,pendingElement:t}){const{pathname:r}=Gt(),n=Ble(e,r,t);return p.useEffect(()=>(T2(n),()=>T2(null)),[n]),null}function $le(){return p.useEffect(()=>{const e=$o.subscribe((r,n)=>{r.open&&!n.open&&A2("suiji")}),t=Xr.subscribe((r,n)=>{var s;r.open&&!n.open&&((s=window.electronAPI)==null?void 0:s.isElectron)===!0&&A2("tunnels")});return()=>{e(),t()}},[]),null}const D2=window.location.origin,zle="viewer.auth.token",Ule="viewer.connections",m0="/terminal";var rC;const Pt=((rC=window.electronAPI)==null?void 0:rC.isElectron)===!0;function Hle(){const e=Gt();return Pt&&e.pathname==="/agent-observer"?o.jsx(LO,{}):o.jsx(RH,{children:o.jsx(yB,{children:o.jsxs(oW,{children:[o.jsx(iB,{children:o.jsx(Wle,{})}),o.jsx($le,{}),o.jsx(uW,{}),o.jsx(tW,{}),o.jsx(Oie,{})]})})})}function Wle(){var H,G;const e=Gt(),t=Cr(),r=rx(),n=Bo(e.pathname),s=ju(),i=p.useRef(Ih(e));p.useEffect(()=>{/^\/terminal(?:\/|$)/u.test(e.pathname)&&(i.current=e)},[e]);const a=n?i.current??Ih(e):null,l=iq(Pt),{connections:c,activeConnection:u,addConnection:d,removeConnection:h,updateConnection:f,setActive:m,reconnectSystemConnection:g}=GC(Ule),v=oL(c,m,t,z=>{s!=null&&s.active?s.prepare(z,"返回观察画面的来源终端"):z()});oH(c);const x=Pt?(u==null?void 0:u.url)??"":D2,b=Pt?(u==null?void 0:u.id)??null:null,{token:_,sessionId:C,status:S,setSession:w,clearToken:y}=hx({apiBase:x,isElectron:Pt,connectionId:b,webStorageKey:zle}),N=p.useRef(null);p.useEffect(()=>{var ee;if(b!==Vn||!x||_||S!=="unauthenticated"||!((ee=window.electronAPI)!=null&&ee.getDevSessionAuth)||N.current===x)return;N.current=x;let z=!1;return window.electronAPI.getDevSessionAuth(x).then(V=>{z||w(V)}).catch(()=>{}),()=>{z=!0}},[b,x,S,w,_]),p.useEffect(()=>{var z,ee;return(ee=(z=window.electronAPI)==null?void 0:z.onResourceNotificationOpen)==null?void 0:ee.call(z,V=>{const re=c.find(oe=>oe.id===V.connectionId);re&&(m(re.id),t(`/system-monitor?app=${encodeURIComponent(V.appKey)}`))})},[c,t,m]);const E=_6(Pt,u),k=!E&&S==="checking",D=ml({apiBase:x,connectionId:b,generation:u!=null&&u.tunnelEndpointId?u.generation:void 0}),j=g8({scope:D,apiBase:x,token:_},t),[R,I]=p.useState(null),[T,A]=p.useState(null),{notice:P,dismissNotice:O}=Lle(x,_,b,Pt&&S!=="unauthenticated"),L=((H=e.state)==null?void 0:H.scope)===D?(G=e.state)==null?void 0:G.returnTo:null,B=typeof L=="string"&&/^\/(?:scheduled-tasks|background-runs|system-monitor|dev-resources)(?:\/|\?|$)/u.test(L)?L:n?"/settings/appearance":m0,M=z=>{m(z)};p.useEffect(()=>{var z,ee;if(Pt)return(ee=(z=window.electronAPI)==null?void 0:z.onAttentionNotificationOpen)==null?void 0:ee.call(z,V=>{const re=c.find(ce=>ce.id===V.connectionId);if(!re||re.available===!1)return;const oe=()=>{wu(ml({apiBase:re.url,connectionId:re.id,generation:re.tunnelEndpointId?re.generation:void 0}),{parentProjectId:V.parentProjectId,projectId:V.projectId,terminalSessionId:V.terminalSessionId,...V.panelId?{panelId:V.panelId}:{}}),m(re.id),t(`/terminal/${encodeURIComponent(V.terminalSessionId)}`)};s!=null&&s.active?s.prepare(oe,"进入通知对应的会话"):oe()})},[c,s,t,m]),p.useEffect(()=>{var z,ee;if(Pt)return(ee=(z=window.electronAPI)==null?void 0:z.onScheduledRunNotificationOpen)==null?void 0:ee.call(z,V=>{const re=c.find(oe=>oe.id===V.connectionId);if(!re){A("通知对应的连接已不存在,无法打开运行记录");return}if(re.available===!1){A("通知对应的连接当前不可用,请恢复连接后重试");return}A(null),I(V),m(re.id)})},[c,m]),p.useEffect(()=>{if(!R||R.connectionId!==b)return;if(!_){t("/login",{state:{scope:D,returnTo:"/scheduled-tasks"}});return}let z=!1;return Uu(x,_).run(R.runId).then(ee=>{z||(I(null),t(Qf(ee)))}).catch(ee=>{z||(I(null),A(ee instanceof De&&ee.status===404?"这条运行记录已不存在,无法打开通知目标":"无法读取通知对应的运行记录,请检查连接和登录状态后重试"))}),()=>{z=!0}},[b,x,t,R,D,_]);const $=(z,ee,V)=>{d(z,ee,V)},U=()=>{r("connections")},F=o.jsx("main",{className:"min-h-screen bg-background"});eq({activeConnectionId:b,apiBase:x,enabled:Pt,token:_}),tq({apiBase:x,token:_,connectionId:b,enabled:Pt});const K=o.jsxs(o.Fragment,{children:[o.jsx(Wr,{path:"/background-runs/:runId",handle:{analyticsScreen:"background_run"},element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(Tle,{embedded:!0,apiBase:x,token:_,activeConnectionId:b,activeConnectionGeneration:u!=null&&u.tunnelEndpointId?u.generation:void 0,connectionName:u==null?void 0:u.name}):o.jsx(Rt,{to:"/login",replace:!0,state:{returnTo:e.pathname+e.search,scope:D}})}),o.jsx(Wr,{path:"/scheduled-tasks/:taskId?",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(jle,{embedded:!0,apiBase:x,token:_,activeConnectionId:b,activeConnectionGeneration:u!=null&&u.tunnelEndpointId?u.generation:void 0,connectionName:u==null?void 0:u.name,connections:c,onSelectConnection:Pt?M:void 0,onOpenConnectionManager:Pt?U:void 0}):o.jsx(Rt,{to:"/login",replace:!0,state:{returnTo:e.pathname+e.search,scope:D}})}),o.jsx(Wr,{path:"/dev-resources",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(iH,{embedded:!0,apiBase:x,token:_,activeConnectionId:b,connectionGeneration:u!=null&&u.tunnelEndpointId?u.generation:void 0,connectionName:u==null?void 0:u.name,onAuthExpired:y}):o.jsx(Rt,{to:"/login",replace:!0,state:{returnTo:"/dev-resources",scope:D}})}),o.jsx(Wr,{path:"/system-monitor",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(_q,{embedded:!0}):o.jsx(Rt,{to:"/login",replace:!0,state:{returnTo:"/system-monitor",scope:D}})}),Pt&&o.jsx(Wr,{path:"/connections",element:o.jsx(uq,{embedded:!0,connections:c,activeId:(u==null?void 0:u.id)??null,onAdd:$,onRemove:h,onSelect:M,onEdit:f,onReconnect:g})}),o.jsx(Wr,{path:"/login",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(Rt,{to:B,replace:!0}):o.jsx(aq,{returnTo:B,apiBase:x,connectionId:b??void 0,isElectron:Pt,connections:c,connectionName:u==null?void 0:u.name,onSwitchConnection:Pt?M:void 0,onOpenConnectionManager:Pt?U:void 0,onSuccess:w})}),o.jsx(Wr,{path:"/",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(Rt,{to:m0,replace:!0}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/activity",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(xae,{apiBase:x,token:_,embedded:!0}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/evolution",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(Sle,{apiBase:x,token:_,embedded:!0}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/terminal",handle:{analyticsScreen:"terminal_list"},element:E?u!=null&&u.tunnelEndpointId?o.jsx(L1,{connection:u,connections:c,onSelectConnection:M,onOpenConnectionManager:U,onReconnect:()=>Xr.getState().setOpen(!0)}):o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(s2,{apiBase:x,token:_,clientMode:l,connections:c,activeConnectionId:b,connectionName:Pt?u==null?void 0:u.name:void 0,activeConnection:u,onSelectConnection:Pt?M:void 0,onOpenConnectionManager:Pt?U:void 0,onAuthExpired:y}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/terminal/:terminalSessionId",handle:{analyticsScreen:"terminal_workspace"},element:E?u!=null&&u.tunnelEndpointId?o.jsx(L1,{connection:u,connections:c,onSelectConnection:M,onOpenConnectionManager:U,onReconnect:()=>Xr.getState().setOpen(!0)}):o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(s2,{apiBase:x,token:_,clientMode:l,connections:c,activeConnectionId:b,connectionName:Pt?u==null?void 0:u.name:void 0,activeConnection:u,onSelectConnection:Pt?M:void 0,onOpenConnectionManager:Pt?U:void 0,onAuthExpired:y}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/prototypes",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(l2,{embedded:!0,apiBase:x,token:_,onAuthExpired:y}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/prototypes/:projectId/:prototypeSource/:prototypeSlug",element:E?o.jsx(Rt,{to:"/connections",replace:!0}):k?F:_?o.jsx(l2,{embedded:!0,apiBase:x,token:_,onAuthExpired:y}):o.jsx(Rt,{to:"/login",replace:!0})}),o.jsx(Wr,{path:"/settings/:pageId?",handle:{analyticsScreen:"settings"},element:null}),o.jsx(Wr,{path:"*",element:o.jsx(Rt,{to:E?"/connections":_?n?"/settings/appearance":m0:"/login",replace:!0})})]}),Y=(z=e)=>o.jsx(IP,{location:z,children:K}),te=o.jsx(rq,{children:o.jsx(K5,{apiBase:x,token:_,connections:c,isElectron:Pt,children:o.jsx(PH,{apiBase:x,token:_,connectionName:(u==null?void 0:u.name)??"当前连接",onUnauthorized:y,children:o.jsx(f3,{scope:D,onUnauthorized:y,children:o.jsxs(Y5,{apiBase:x,token:_,connectionId:b??D,children:[o.jsx(aH,{onOpen:z=>t(`/system-monitor?app=${encodeURIComponent(z)}`)}),o.jsx("div",{inert:n&&a?!0:void 0,"aria-hidden":n&&a?!0:void 0,children:(!n||a&&_&&!E)&&Y(a??e)}),n&&o.jsx(lz,{background:a,pageContent:e.pathname.startsWith("/settings")?void 0:Y(),connections:c,activeConnection:u??void 0,workspaceAuth:{token:_,sessionId:C,status:S,setSession:w,clearToken:y},webApiBase:D2,onAdd:(z,ee,V)=>{d(z,ee,V,!1)},onRemove:h,onEdit:f,onReconnect:g})]},`${D}:${C??""}`)})},`${D}:${C??""}:${_?"authenticated":"anonymous"}`)})});return o.jsxs(o.Fragment,{children:[v.error&&o.jsx(eo,{className:"rounded bg-rose-950 p-3 text-white",kind:"observer-navigation",noticeKey:v.error,onDismiss:v.dismiss,children:v.error}),o.jsx(Fle,{routes:K,pendingElement:F}),j.notice?o.jsx(eo,{kind:"screen-conversation",noticeKey:j.notice,onDismiss:j.dismiss,className:"rounded bg-slate-900 p-4 text-white",children:j.notice}):null,T?o.jsx(eo,{kind:"scheduled-run-error",role:"alert",noticeKey:T,className:"rounded-lg border border-rose-700 bg-card p-3 text-sm shadow-lg",onDismiss:()=>A(null),children:T}):null,P?o.jsx(eo,{kind:"quick-input",noticeKey:P,onDismiss:O,className:"rounded-lg border bg-card p-3 shadow-lg",children:o.jsxs("button",{type:"button",className:"block w-full text-left",onClick:()=>{O(),t(uR(P.runId))},children:[o.jsx("strong",{className:"block text-sm",children:P.title}),o.jsx("span",{className:"text-xs",children:P.body})]})}):null,Pt&&o.jsx(kW,{connections:c,activeConnectionId:b,activeToken:_,activeAuthStatus:S,onActiveAuthExpired:y,observeActive:e.pathname==="/connections"}),Pt&&u&&_&&C&&S!=="unauthenticated"?o.jsx(KH,{connection:u,token:_,children:te},`${u.id}:${x}:${C}`):te]})}function qle(e){return o.jsx(CJ,{...e,storageKey:"theme"})}function Kle(e={}){const{immediate:t=!1,onNeedRefresh:r,onOfflineReady:n,onRegistered:s,onRegisteredSW:i,onRegisterError:a}=e;let l,c,u;const d=async(f=!0)=>{await c,u==null||u()};async function h(){if("serviceWorker"in navigator){if(l=await Vr(async()=>{const{Workbox:f}=await import("./workbox-window.prod.es5-BIl4cyR9.js");return{Workbox:f}},[]).then(({Workbox:f})=>new f("/sw.js",{scope:"/",type:"classic"})).catch(f=>{a==null||a(f)}),!l)return;u=()=>{l==null||l.messageSkipWaiting()};{let f=!1;const m=()=>{f=!0,l==null||l.addEventListener("controlling",g=>{g.isUpdate&&window.location.reload()}),r==null||r()};l.addEventListener("installed",g=>{typeof g.isUpdate>"u"?typeof g.isExternal<"u"&&g.isExternal?m():!f&&(n==null||n()):g.isUpdate||n==null||n()}),l.addEventListener("waiting",m)}l.register({immediate:t}).then(f=>{i?i("/sw.js",f):s==null||s(f)}).catch(f=>{a==null||a(f)})}}return c=h(),d}const Vle="Runweave has an update ready. Refresh now?";function Gle(e){return e==="http:"||e==="https:"}function Yle(e){return!e.isElectron&&e.serviceWorkerSupported&&Gle(e.protocol)}function Xle(e=window){var t;return{isElectron:((t=e.electronAPI)==null?void 0:t.isElectron)===!0,protocol:e.location.protocol,serviceWorkerSupported:"serviceWorker"in e.navigator}}function P2(e){Object.assign(e.style,{border:"1px solid rgba(255, 255, 255, 0.32)",borderRadius:"6px",background:"rgba(255, 255, 255, 0.12)",color:"#ffffff",cursor:"pointer",font:"inherit",padding:"6px 10px"})}function Jle({message:e,onRefresh:t},r=document){var c;const{body:n}=r;if(!n)return;(c=r.getElementById("runweave-pwa-refresh-banner"))==null||c.remove();const s=r.createElement("div");s.id="runweave-pwa-refresh-banner",s.setAttribute("role","status"),Object.assign(s.style,{alignItems:"center",background:"#123743",border:"1px solid rgba(255, 255, 255, 0.18)",borderRadius:"8px",bottom:"16px",boxShadow:"0 12px 36px rgba(0, 0, 0, 0.28)",color:"#ffffff",display:"flex",gap:"12px",left:"16px",maxWidth:"min(520px, calc(100vw - 32px))",padding:"12px",position:"fixed",right:"16px",zIndex:"2147483647"});const i=r.createElement("span");i.textContent=e,Object.assign(i.style,{flex:"1",fontSize:"14px",lineHeight:"20px"});const a=r.createElement("button");a.type="button",a.textContent="Refresh",P2(a),a.addEventListener("click",()=>{s.remove(),t()});const l=r.createElement("button");l.type="button",l.textContent="Later",P2(l),l.addEventListener("click",()=>{s.remove()}),s.append(i,a,l),n.append(s)}function Qle({runtime:e=Xle(),registerSW:t,promptRefresh:r=Jle}){if(!Yle(e))return null;let n=()=>{};const s=t({immediate:!1,onNeedRefresh(){r({message:Vle,onRefresh(){n(!0)}})}});return n=s,s}function Zle({currentDocument:e=document,...t}){const r=()=>{Qle(t)};if(e.readyState==="loading"){e.addEventListener("DOMContentLoaded",r,{once:!0});return}r()}Zle({registerSW:Kle});hu().sourceRevision;hu().version;Ole(),y4.createRoot(document.getElementById("root")).render(o.jsx(qle,{attribute:"class",defaultTheme:"system",enableSystem:!0,children:o.jsx(d6,{router:QP([{path:"*",element:o.jsx(Hle,{})}])})}));export{tt as $,cE as A,Z as B,TJ as C,iH as D,Ws as E,kB as F,Gv as G,De as H,sr as I,EE as J,Ef as K,Dn as L,BH as M,BM as N,aW as O,yu as P,lO as Q,fq as R,qO as S,tW as T,gce as U,me as V,Vs as W,vo as X,zv as Y,mce as Z,vt as _,lE as a,hi as a$,aR as a0,xce as a1,vce as a2,iR as a3,aQ as a4,OO as a5,Vr as a6,Vx as a7,Gx as a8,di as a9,Qce as aA,yf as aB,hE as aC,mL as aD,eue as aE,rue as aF,tue as aG,xM as aH,yE as aI,lue as aJ,aue as aK,oue as aL,Zce as aM,Wse as aN,gv as aO,nue as aP,sue as aQ,iue as aR,qse as aS,_s as aT,Tn as aU,ig as aV,WU as aW,UM as aX,uE as aY,Jr as aZ,Kv as a_,Kf as aa,Ps as ab,HU as ac,wg as ad,wce as ae,Pn as af,Sce as ag,Qr as ah,dn as ai,Mn as aj,Ur as ak,Zr as al,p8 as am,NQ as an,Kc as ao,CL as ap,ga as aq,m8 as ar,xs as as,jt as at,OJ as au,rx as av,Nw as aw,Rw as ax,pM as ay,Ct as az,Tx as b,SE as b$,or as b0,lx as b1,cx as b2,ku as b3,Cl as b4,kf as b5,_ce as b6,bce as b7,yce as b8,yQ as b9,Nx as bA,Bf as bB,cp as bC,e_ as bD,xp as bE,r_ as bF,bp as bG,t_ as bH,Gn as bI,uce as bJ,cce as bK,hce as bL,fce as bM,a0 as bN,rce as bO,eL as bP,QO as bQ,ice as bR,zh as bS,HO as bT,nce as bU,ace as bV,oce as bW,vO as bX,MM as bY,iO as bZ,cy as b_,wQ as ba,dce as bb,Qn as bc,UO as bd,DE as be,An as bf,lce as bg,a8 as bh,hr as bi,Tl as bj,xa as bk,Dl as bl,ba as bm,_a as bn,Pl as bo,ya as bp,Lu as bq,$u as br,zu as bs,wf as bt,Ll as bu,VW as bv,Bt as bw,Xe as bx,FU as by,Ix as bz,z0 as c,Cf as c0,BR as c1,PM as c2,WO as c3,GO as c4,sce as c5,Jv as c6,fO as c7,AM as c8,wM as c9,Al as ca,Hf as cb,Zn as cc,bs as cd,Sl as ce,Nj as cf,Bj as cg,cs as ch,mE as ci,Fk as d,Gt as e,qH as f,ay as g,va as h,ZF as i,_q as j,PH as k,lie as l,h$ as m,t$ as n,Cr as o,cq as p,ab as q,xi as r,ke as s,ih as t,Vt as u,Oo as v,go as w,hC as x,Yr as y,SJ as z};
|