@jamiexiongr/panda-hub 0.1.26 → 0.1.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-R7HNONWG.mjs → chunk-C6HLB7NI.mjs} +2 -2
- package/dist/{chunk-EUY5V2XS.mjs → chunk-KW522MKT.mjs} +15 -27
- package/dist/cli.mjs +2 -2
- package/dist/index.mjs +2 -2
- package/dist/{src-SMFYPE6P.mjs → src-OBU4SE67.mjs} +1 -1
- package/dist/web/assets/{diagnostics-page-cP5VtBfz.js → diagnostics-page-CoIdkIQI.js} +1 -1
- package/dist/web/assets/{index-C1sZm04V.js → index-OTfJjsxL.js} +6 -6
- package/dist/web/assets/{session-diff-preview-DwKy91Si.js → session-diff-preview-CCCZmf4G.js} +1 -1
- package/dist/web/assets/{session-file-markdown-preview-BCKRbAnB.js → session-file-markdown-preview-Dv-eVJZC.js} +1 -1
- package/dist/web/assets/{session-file-preview-page-tFsJlNPN.js → session-file-preview-page-DK4GwzJS.js} +3 -3
- package/dist/web/assets/{web-eR1IoQga.js → web-CwfmVur7.js} +1 -1
- package/dist/web/assets/{web-BhBxIFnA.js → web-D1pcnorX.js} +1 -1
- package/dist/web/assets/{web-D1qcSAMu.js → web-DeqRViq6.js} +1 -1
- package/dist/web/assets/{web-DuZa6nLj.js → web-Dy_S-Kpy.js} +1 -1
- package/dist/web/assets/{web-Cx7LKGTD.js → web-vTFNt5EQ.js} +1 -1
- package/dist/web/assets/{xml-M87tW4nh.js → xml-CQYUv0yT.js} +1 -1
- package/dist/web/index.html +1 -1
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/session-diff-preview-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/session-diff-preview-CCCZmf4G.js","assets/xml-CQYUv0yT.js","assets/session-file-preview-page-DK4GwzJS.js","assets/diagnostics-page-CoIdkIQI.js","assets/diagnostics-page-BmzeM8p1.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var _v=e=>{throw TypeError(e)};var X1=(e,t,a)=>t.has(e)||_v("Cannot "+a);var $=(e,t,a)=>(X1(e,t,"read from private field"),a?a.call(e):t.get(e)),dt=(e,t,a)=>t.has(e)?_v("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,a),Qe=(e,t,a,l)=>(X1(e,t,"write to private field"),l?l.call(e,a):t.set(e,a),a),Lt=(e,t,a)=>(X1(e,t,"access private method"),a);var _m=(e,t,a,l)=>({set _(o){Qe(e,t,o,a)},get _(){return $(e,t,l)}});(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))l(o);new MutationObserver(o=>{for(const u of o)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function a(o){const u={};return o.integrity&&(u.integrity=o.integrity),o.referrerPolicy&&(u.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?u.credentials="include":o.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function l(o){if(o.ep)return;o.ep=!0;const u=a(o);fetch(o.href,u)}})();const X5="modulepreload",J5=function(e){return"/"+e},yv={},Zr=function(t,a,l){let o=Promise.resolve();if(a&&a.length>0){let f=function(g){return Promise.all(g.map(S=>Promise.resolve(S).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const m=document.querySelector("meta[property=csp-nonce]"),y=(m==null?void 0:m.nonce)||(m==null?void 0:m.getAttribute("nonce"));o=f(a.map(g=>{if(g=J5(g),g in yv)return;yv[g]=!0;const S=g.endsWith(".css"),p=S?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${g}"]${p}`))return;const b=document.createElement("link");if(b.rel=S?"stylesheet":X5,S||(b.as="script"),b.crossOrigin="",b.href=g,y&&b.setAttribute("nonce",y),document.head.appendChild(b),S)return new Promise((w,N)=>{b.addEventListener("load",w),b.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${g}`)))})}))}function u(f){const m=new Event("vite:preloadError",{cancelable:!0});if(m.payload=f,window.dispatchEvent(m),!m.defaultPrevented)throw f}return o.then(f=>{for(const m of f||[])m.status==="rejected"&&u(m.reason);return t().catch(u)})};function e9(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var J1={exports:{}},pf={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react-jsx-runtime.production.js
|
|
@@ -63,9 +63,9 @@ Error generating stack: `+c.message+`
|
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the MIT license found in the
|
|
65
65
|
* LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/var r4;function k7(){if(r4)return fg;r4=1;var e=rh(),t=N7();function a(g,S){return g===S&&(g!==0||1/g===1/S)||g!==g&&S!==S}var l=typeof Object.is=="function"?Object.is:a,o=t.useSyncExternalStore,u=e.useRef,f=e.useEffect,m=e.useMemo,y=e.useDebugValue;return fg.useSyncExternalStoreWithSelector=function(g,S,p,b,w){var N=u(null);if(N.current===null){var j={hasValue:!1,value:null};N.current=j}else j=N.current;N=m(function(){function D(Q){if(!z){if(z=!0,I=Q,Q=b(Q),w!==void 0&&j.hasValue){var se=j.value;if(w(se,Q))return k=se}return k=Q}if(se=k,l(I,Q))return se;var W=b(Q);return w!==void 0&&w(se,W)?(I=Q,se):(I=Q,k=W)}var z=!1,I,k,P=p===void 0?null:p;return[function(){return D(S())},P===null?void 0:function(){return D(P())}]},[S,p,b,w]);var T=o(g,N[0],N[1]);return f(function(){j.hasValue=!0,j.value=T},[T]),y(T),T},fg}var l4;function E7(){return l4||(l4=1,dg.exports=k7()),dg.exports}var C7=E7();function T7(e,t){return e===t}function R7(e,t,a=T7){const l=_.useCallback(f=>{if(!e)return()=>{};const{unsubscribe:m}=e.subscribe(f);return m},[e]),o=_.useCallback(()=>e==null?void 0:e.get(),[e]);return C7.useSyncExternalStoreWithSelector(l,o,o,t,a)}function Ia(e){const t=Za({warn:(e==null?void 0:e.router)===void 0}),a=(e==null?void 0:e.router)||t,l=_.useRef(void 0);return R7(a.__store,o=>{if(e!=null&&e.select){if(e.structuralSharing??a.options.defaultStructuralSharing){const u=Wo(l.current,e.select(o));return l.current=u,u}return e.select(o)}return o})}var Cp=_.createContext(void 0),M7=_.createContext(void 0);function lo(e){const t=_.useContext(e.from?M7:Cp);return Ia({select:a=>{const l=a.matches.find(o=>e.from?e.from===o.routeId:o.id===t);if(io(!((e.shouldThrow??!0)&&!l),`Could not find ${e.from?`an active match from "${e.from}"`:"a nearest match!"}`),l!==void 0)return e.select?e.select(l):l},structuralSharing:e.structuralSharing})}function a_(e){return lo({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function i_(e){const{select:t,...a}=e;return lo({...a,select:l=>t?t(l.loaderDeps):l.loaderDeps})}function ad(e){return lo({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const a=e.strict===!1?t.params:t._strictParams;return e.select?e.select(a):a}})}function r_(e){return lo({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ki(e){const t=Za();return _.useCallback(a=>t.navigate({...a,from:a.from??(e==null?void 0:e.from)}),[e==null?void 0:e.from,t])}function l_(e){return lo({...e,select:t=>e.select?e.select(t.context):t.context})}var Ya=T2();function A7(e,t){const a=Za(),l=nS(t),{activeProps:o,inactiveProps:u,activeOptions:f,to:m,preload:y,preloadDelay:g,hashScrollIntoView:S,replace:p,startTransition:b,resetScroll:w,viewTransition:N,children:j,target:T,disabled:D,style:z,className:I,onClick:k,onBlur:P,onFocus:Q,onMouseEnter:se,onMouseLeave:W,onTouchStart:V,ignoreBlocker:Y,params:ee,search:me,hash:ge,state:te,mask:xe,reloadDocument:C,unsafeRelative:q,from:ie,_fromLocation:he,...re}=e,L=s6(),ae=Ia({select:Ve=>{const Ke=Ve.matches[Ve.matches.length-1];return{search:Ke==null?void 0:Ke.search,hash:Ve.location.hash,path:Ke==null?void 0:Ke.pathname}},structuralSharing:!0}),ke=e.from,U=_.useMemo(()=>({...e,from:ke}),[a,ae,ke,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),ve=_.useMemo(()=>a.buildLocation({...U}),[a,U]),Z=ve.maskedLocation?ve.maskedLocation.publicHref:ve.publicHref,Se=ve.maskedLocation?ve.maskedLocation.external:ve.external,je=_.useMemo(()=>U7(Z,Se,a.history,D),[D,Se,Z,a.history]),Oe=_.useMemo(()=>{if(je!=null&&je.external)return Vm(je.href,a.protocolAllowlist)?void 0:je.href;if(!z7(m)&&!(typeof m!="string"||m.indexOf(":")===-1))try{return new URL(m),Vm(m,a.protocolAllowlist)?void 0:m}catch{}},[m,je,a.protocolAllowlist]),Ie=Ia({select:Ve=>{if(Oe)return!1;if(f!=null&&f.exact){if(!xS(Ve.location.pathname,ve.pathname,a.basepath))return!1}else{const Ke=Xm(Ve.location.pathname,a.basepath),Nt=Xm(ve.pathname,a.basepath);if(!(Ke.startsWith(Nt)&&(Ke.length===Nt.length||Ke[Nt.length]==="/")))return!1}return((f==null?void 0:f.includeSearch)??!0)&&!sc(Ve.location.search,ve.search,{partial:!(f!=null&&f.exact),ignoreUndefined:!(f!=null&&f.explicitUndefined)})?!1:f!=null&&f.includeHash?L&&Ve.location.hash===ve.hash:!0}}),wt=Ie?Jl(o,{})??D7:pg,qe=Ie?pg:Jl(u,{})??pg,bt=[I,wt.className,qe.className].filter(Boolean).join(" "),Ut=(z||wt.style||qe.style)&&{...z,...wt.style,...qe.style},[$t,zt]=_.useState(!1),xt=_.useRef(!1),it=e.reloadDocument||Oe?!1:y??a.options.defaultPreload,ot=g??a.options.defaultPreloadDelay??0,ln=_.useCallback(()=>{a.preloadRoute({...U,_builtLocation:ve}).catch(Ve=>{console.warn(Ve),console.warn(v7)})},[a,U,ve]);tS(l,_.useCallback(Ve=>{Ve!=null&&Ve.isIntersecting&&ln()},[ln]),P7,{disabled:!!D||it!=="viewport"}),_.useEffect(()=>{xt.current||!D&&it==="render"&&(ln(),xt.current=!0)},[D,ln,it]);const on=Ve=>{const Ke=Ve.currentTarget.getAttribute("target"),Nt=T!==void 0?T:Ke;if(!D&&!B7(Ve)&&!Ve.defaultPrevented&&(!Nt||Nt==="_self")&&Ve.button===0){Ve.preventDefault(),Ya.flushSync(()=>{zt(!0)});const Bt=a.subscribe("onResolved",()=>{Bt(),zt(!1)});a.navigate({...U,replace:p,resetScroll:w,hashScrollIntoView:S,startTransition:b,viewTransition:N,ignoreBlocker:Y})}};if(Oe)return{...re,ref:l,href:Oe,...j&&{children:j},...T&&{target:T},...D&&{disabled:D},...z&&{style:z},...I&&{className:I},...k&&{onClick:k},...P&&{onBlur:P},...Q&&{onFocus:Q},...se&&{onMouseEnter:se},...W&&{onMouseLeave:W},...V&&{onTouchStart:V}};const kn=Ve=>{if(D||it!=="intent")return;if(!ot){ln();return}const Ke=Ve.currentTarget;if(bf.has(Ke))return;const Nt=setTimeout(()=>{bf.delete(Ke),ln()},ot);bf.set(Ke,Nt)},En=Ve=>{D||it!=="intent"||ln()},ht=Ve=>{if(D||!it||!ot)return;const Ke=Ve.currentTarget,Nt=bf.get(Ke);Nt&&(clearTimeout(Nt),bf.delete(Ke))};return{...re,...wt,...qe,href:je==null?void 0:je.href,ref:l,onClick:du([k,on]),onBlur:du([P,ht]),onFocus:du([Q,kn]),onMouseEnter:du([se,kn]),onMouseLeave:du([W,ht]),onTouchStart:du([V,En]),disabled:!!D,target:T,...Ut&&{style:Ut},...bt&&{className:bt},...D&&O7,...Ie&&I7,...L&&$t&&L7}}var pg={},D7={className:"active"},O7={role:"link","aria-disabled":!0},I7={"data-status":"active","aria-current":"page"},L7={"data-transitioning":"transitioning"},bf=new WeakMap,P7={rootMargin:"100px"},du=e=>t=>{for(const a of e)if(a){if(t.defaultPrevented)return;a(t)}};function U7(e,t,a,l){if(!l)return t?{href:e,external:!0}:{href:a.createHref(e)||"/",external:!1}}function z7(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var sp=_.forwardRef((e,t)=>{const{_asChild:a,...l}=e,{type:o,...u}=A7(l,t),f=typeof l.children=="function"?l.children({isActive:u["data-status"]==="active"}):l.children;if(!a){const{disabled:m,...y}=u;return _.createElement("a",y,f)}return _.createElement(a,u,f)});function B7(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var H7=class extends n6{constructor(e){super(e),this.useMatch=t=>lo({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>l_({...t,from:this.id}),this.useSearch=t=>r_({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>ad({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>i_({...t,from:this.id}),this.useLoaderData=t=>a_({...t,from:this.id}),this.useNavigate=()=>ki({from:this.fullPath}),this.Link=qr.forwardRef((t,a)=>i.jsx(sp,{ref:a,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function hc(e){return new H7(e)}var $7=class extends b7{constructor(e){super(e),this.useMatch=t=>lo({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>l_({...t,from:this.id}),this.useSearch=t=>r_({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>ad({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>i_({...t,from:this.id}),this.useLoaderData=t=>a_({...t,from:this.id}),this.useNavigate=()=>ki({from:this.fullPath}),this.Link=qr.forwardRef((t,a)=>i.jsx(sp,{ref:a,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function F7(e){return new $7(e)}function o4(e){return typeof e=="object"?new c4(e,{silent:!0}).createRoute(e):new c4(e,{silent:!0}).createRoute}var c4=class{constructor(e,t){this.path=e,this.createRoute=a=>{const l=hc(a);return l.isRoot=!1,l},this.silent=t==null?void 0:t.silent}},u4=class{constructor(e){this.useMatch=t=>lo({select:t==null?void 0:t.select,from:this.options.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>l_({...t,from:this.options.id}),this.useSearch=t=>r_({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useParams=t=>ad({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useLoaderDeps=t=>i_({...t,from:this.options.id}),this.useLoaderData=t=>a_({...t,from:this.options.id}),this.useNavigate=()=>ki({from:Za().routesById[this.options.id].fullPath}),this.options=e,this.$$typeof=Symbol.for("react.memo")}};function d4(e){return typeof e=="object"?new u4(e):t=>new u4({id:e,...t})}function q7(e){const t=Ia({select:a=>`not-found-${a.location.pathname}-${a.status}`});return i.jsx(n_,{getResetKey:()=>t,onCatch:(a,l)=>{var o;if(ea(a))(o=e.onCatch)==null||o.call(e,a,l);else throw a},errorComponent:({error:a})=>{var l;if(ea(a))return(l=e.fallback)==null?void 0:l.call(e,a);throw a},children:e.children})}function W7(){return i.jsx("p",{children:"Not Found"})}function vu(e){return i.jsx(i.Fragment,{children:e.children})}function i6(e,t,a){return t.options.notFoundComponent?i.jsx(t.options.notFoundComponent,{...a}):e.options.defaultNotFoundComponent?i.jsx(e.options.defaultNotFoundComponent,{...a}):i.jsx(W7,{})}function K7(){return Za().isScrollRestoring,null}var r6=_.memo(function({matchId:t}){var N,j;const a=Za(),l=Ia({select:T=>{var I;const D=T.matches.findIndex(k=>k.id===t),z=T.matches[D];return io(z),{routeId:z.routeId,ssr:z.ssr,_displayPending:z._displayPending,resetKey:T.loadedAt,parentRouteId:(I=T.matches[D-1])==null?void 0:I.routeId}},structuralSharing:!0}),o=a.routesById[l.routeId],u=o.options.pendingComponent??a.options.defaultPendingComponent,f=u?i.jsx(u,{}):null,m=o.options.errorComponent??a.options.defaultErrorComponent,y=o.options.onCatch??a.options.defaultOnCatch,g=o.isRoot?o.options.notFoundComponent??((N=a.options.notFoundRoute)==null?void 0:N.options.component):o.options.notFoundComponent,S=l.ssr===!1||l.ssr==="data-only",p=(!o.isRoot||o.options.wrapInSuspense||S)&&(o.options.wrapInSuspense??u??(((j=o.options.errorComponent)==null?void 0:j.preload)||S))?_.Suspense:vu,b=m?n_:vu,w=g?q7:vu;return i.jsxs(o.isRoot?o.options.shellComponent??vu:vu,{children:[i.jsx(Cp.Provider,{value:t,children:i.jsx(p,{fallback:f,children:i.jsx(b,{getResetKey:()=>l.resetKey,errorComponent:m||s_,onCatch:(T,D)=>{if(ea(T))throw T;y==null||y(T,D)},children:i.jsx(w,{fallback:T=>{if(!g||T.routeId&&T.routeId!==l.routeId||!T.routeId&&!o.isRoot)throw T;return _.createElement(g,T)},children:S||l._displayPending?i.jsx(S7,{fallback:f,children:i.jsx(f4,{matchId:t})}):i.jsx(f4,{matchId:t})})})})}),l.parentRouteId===ac&&a.options.scrollRestoration?i.jsxs(i.Fragment,{children:[i.jsx(Q7,{}),i.jsx(K7,{})]}):null]})});function Q7(){const e=Za(),t=_.useRef(void 0);return i.jsx("script",{suppressHydrationWarning:!0,ref:a=>{a&&(t.current===void 0||t.current.href!==e.latestLocation.href)&&(e.emit({type:"onRendered",...rc(e.state)}),t.current=e.latestLocation)}},e.latestLocation.state.__TSR_key)}var f4=_.memo(function({matchId:t}){var y,g,S,p;const a=Za(),{match:l,key:o,routeId:u}=Ia({select:b=>{var T;const w=b.matches.find(D=>D.id===t),N=w.routeId,j=(T=a.routesById[N].options.remountDeps??a.options.defaultRemountDeps)==null?void 0:T({routeId:N,loaderDeps:w.loaderDeps,params:w._strictParams,search:w._strictSearch});return{key:j?JSON.stringify(j):void 0,routeId:N,match:{id:w.id,status:w.status,error:w.error,_forcePending:w._forcePending,_displayPending:w._displayPending}}},structuralSharing:!0}),f=a.routesById[u],m=_.useMemo(()=>{const b=f.options.component??a.options.defaultComponent;return b?i.jsx(b,{},o):i.jsx(l6,{})},[o,f.options.component,a.options.defaultComponent]);if(l._displayPending)throw(y=a.getMatch(l.id))==null?void 0:y._nonReactive.displayPendingPromise;if(l._forcePending)throw(g=a.getMatch(l.id))==null?void 0:g._nonReactive.minPendingPromise;if(l.status==="pending"){const b=f.options.pendingMinMs??a.options.defaultPendingMinMs;if(b){const w=a.getMatch(l.id);if(w&&!w._nonReactive.minPendingPromise){const N=$u();w._nonReactive.minPendingPromise=N,setTimeout(()=>{N.resolve(),w._nonReactive.minPendingPromise=void 0},b)}}throw(S=a.getMatch(l.id))==null?void 0:S._nonReactive.loadPromise}if(l.status==="notFound")return io(ea(l.error)),i6(a,f,l.error);if(l.status==="redirected")throw io(wa(l.error)),(p=a.getMatch(l.id))==null?void 0:p._nonReactive.loadPromise;if(l.status==="error")throw l.error;return m}),l6=_.memo(function(){const t=Za(),a=_.useContext(Cp),l=Ia({select:g=>{var S;return(S=g.matches.find(p=>p.id===a))==null?void 0:S.routeId}}),o=t.routesById[l],u=Ia({select:g=>{const S=g.matches.find(p=>p.id===a);return io(S),S.globalNotFound}}),f=Ia({select:g=>{var p;const S=g.matches;return(p=S[S.findIndex(b=>b.id===a)+1])==null?void 0:p.id}}),m=t.options.defaultPendingComponent?i.jsx(t.options.defaultPendingComponent,{}):null;if(u)return i6(t,o,void 0);if(!f)return null;const y=i.jsx(r6,{matchId:f});return l===ac?i.jsx(_.Suspense,{fallback:m,children:y}):y});function G7(){const e=Za(),t=_.useRef({router:e,mounted:!1}),[a,l]=_.useState(!1),{hasPendingMatches:o,isLoading:u}=Ia({select:p=>({isLoading:p.isLoading,hasPendingMatches:p.matches.some(b=>b.status==="pending")}),structuralSharing:!0}),f=ig(u),m=u||a||o,y=ig(m),g=u||o,S=ig(g);return e.startTransition=p=>{l(!0),_.startTransition(()=>{p(),l(!1)})},_.useEffect(()=>{const p=e.history.subscribe(e.load),b=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return no(e.latestLocation.publicHref)!==no(b.publicHref)&&e.commitLocation({...b,replace:!0}),()=>{p()}},[e,e.history]),vm(()=>{if(typeof window<"u"&&e.ssr||t.current.router===e&&t.current.mounted)return;t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(b){console.error(b)}})()},[e]),vm(()=>{f&&!u&&e.emit({type:"onLoad",...rc(e.state)})},[f,e,u]),vm(()=>{S&&!g&&e.emit({type:"onBeforeRouteMount",...rc(e.state)})},[g,S,e]),vm(()=>{if(y&&!m){const p=rc(e.state);e.emit({type:"onResolved",...p}),e.__store.setState(b=>({...b,status:"idle",resolvedLocation:b.location})),p.hrefChanged&&MS(e)}},[m,y,e]),null}function Y7(){const e=Za(),t=e.routesById[ac].options.pendingComponent??e.options.defaultPendingComponent,a=t?i.jsx(t,{}):null,l=i.jsxs(typeof document<"u"&&e.ssr?vu:_.Suspense,{fallback:a,children:[i.jsx(G7,{}),i.jsx(V7,{})]});return e.options.InnerWrap?i.jsx(e.options.InnerWrap,{children:l}):l}function V7(){const e=Za(),t=Ia({select:o=>{var u;return(u=o.matches[0])==null?void 0:u.id}}),a=Ia({select:o=>o.loadedAt}),l=t?i.jsx(r6,{matchId:t}):null;return i.jsx(Cp.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?l:i.jsx(n_,{getResetKey:()=>a,errorComponent:s_,onCatch:void 0,children:l})})}var Z7=e=>new X7(e),X7=class extends f7{constructor(e){super(e)}};typeof globalThis<"u"?(globalThis.createFileRoute=o4,globalThis.createLazyFileRoute=d4):typeof window<"u"&&(window.createFileRoute=o4,window.createLazyFileRoute=d4);function J7({router:e,children:t,...a}){Object.keys(a).length>0&&e.update({...e.options,...a,context:{...e.options.context,...a.context}});const l=i.jsx(a6.Provider,{value:e,children:t});return e.options.Wrap?i.jsx(e.options.Wrap,{children:l}):l}function ej({router:e,...t}){return i.jsx(J7,{router:e,...t,children:i.jsx(Y7,{})})}/*! Capacitor: https://capacitorjs.com/ - MIT License */var Fu;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(Fu||(Fu={}));class gg extends Error{constructor(t,a,l){super(t),this.message=t,this.code=a,this.data=l}}const tj=e=>{var t,a;return e!=null&&e.androidBridge?"android":!((a=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||a===void 0)&&a.bridge?"ios":"web"},nj=e=>{const t=e.CapacitorCustomPlatform||null,a=e.Capacitor||{},l=a.Plugins=a.Plugins||{},o=()=>t!==null?t.name:tj(e),u=()=>o()!=="web",f=p=>{const b=g.get(p);return!!(b!=null&&b.platforms.has(o())||m(p))},m=p=>{var b;return(b=a.PluginHeaders)===null||b===void 0?void 0:b.find(w=>w.name===p)},y=p=>e.console.error(p),g=new Map,S=(p,b={})=>{const w=g.get(p);if(w)return console.warn(`Capacitor plugin "${p}" already registered. Cannot register plugins twice.`),w.proxy;const N=o(),j=m(p);let T;const D=async()=>(!T&&N in b?T=typeof b[N]=="function"?T=await b[N]():T=b[N]:t!==null&&!T&&"web"in b&&(T=typeof b.web=="function"?T=await b.web():T=b.web),T),z=(W,V)=>{var Y,ee;if(j){const me=j==null?void 0:j.methods.find(ge=>V===ge.name);if(me)return me.rtype==="promise"?ge=>a.nativePromise(p,V.toString(),ge):(ge,te)=>a.nativeCallback(p,V.toString(),ge,te);if(W)return(Y=W[V])===null||Y===void 0?void 0:Y.bind(W)}else{if(W)return(ee=W[V])===null||ee===void 0?void 0:ee.bind(W);throw new gg(`"${p}" plugin is not implemented on ${N}`,Fu.Unimplemented)}},I=W=>{let V;const Y=(...ee)=>{const me=D().then(ge=>{const te=z(ge,W);if(te){const xe=te(...ee);return V=xe==null?void 0:xe.remove,xe}else throw new gg(`"${p}.${W}()" is not implemented on ${N}`,Fu.Unimplemented)});return W==="addListener"&&(me.remove=async()=>V()),me};return Y.toString=()=>`${W.toString()}() { [capacitor code] }`,Object.defineProperty(Y,"name",{value:W,writable:!1,configurable:!1}),Y},k=I("addListener"),P=I("removeListener"),Q=(W,V)=>{const Y=k({eventName:W},V),ee=async()=>{const ge=await Y;P({eventName:W,callbackId:ge},V)},me=new Promise(ge=>Y.then(()=>ge({remove:ee})));return me.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await ee()},me},se=new Proxy({},{get(W,V){switch(V){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?Q:k;case"removeListener":return P;default:return I(V)}}});return l[p]=se,g.set(p,{name:p,proxy:se,platforms:new Set([...Object.keys(b),...j?[N]:[]])}),se};return a.convertFileSrc||(a.convertFileSrc=p=>p),a.getPlatform=o,a.handleError=y,a.isNativePlatform=u,a.isPluginAvailable=f,a.registerPlugin=S,a.Exception=gg,a.DEBUG=!!a.DEBUG,a.isLoggingEnabled=!!a.isLoggingEnabled,a},sj=e=>e.Capacitor=nj(e),Qr=sj(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),mc=Qr.registerPlugin;class o6{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,a){let l=!1;this.listeners[t]||(this.listeners[t]=[],l=!0),this.listeners[t].push(a);const u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),l&&this.sendRetainedArgumentsForEvent(t);const f=async()=>this.removeListener(t,a);return Promise.resolve({remove:f})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,a,l){const o=this.listeners[t];if(!o){if(l){let u=this.retainedEventArguments[t];u||(u=[]),u.push(a),this.retainedEventArguments[t]=u}return}o.forEach(u=>u(a))}hasListeners(t){var a;return!!(!((a=this.listeners[t])===null||a===void 0)&&a.length)}registerWindowListener(t,a){this.windowListeners[a]={registered:!1,windowEventName:t,pluginEventName:a,handler:l=>{this.notifyListeners(a,l)}}}unimplemented(t="not implemented"){return new Qr.Exception(t,Fu.Unimplemented)}unavailable(t="not available"){return new Qr.Exception(t,Fu.Unavailable)}async removeListener(t,a){const l=this.listeners[t];if(!l)return;const o=l.indexOf(a);this.listeners[t].splice(o,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const a=this.retainedEventArguments[t];a&&(delete this.retainedEventArguments[t],a.forEach(l=>{this.notifyListeners(t,l)}))}}const h4=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),m4=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class aj extends o6{async getCookies(){const t=document.cookie,a={};return t.split(";").forEach(l=>{if(l.length<=0)return;let[o,u]=l.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");o=m4(o).trim(),u=m4(u).trim(),a[o]=u}),a}async setCookie(t){try{const a=h4(t.key),l=h4(t.value),o=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),f=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${a}=${l||""}${o}; path=${u}; ${f};`}catch(a){return Promise.reject(a)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(a){return Promise.reject(a)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const a of t)document.cookie=a.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}mc("CapacitorCookies",{web:()=>new aj});const ij=async e=>new Promise((t,a)=>{const l=new FileReader;l.onload=()=>{const o=l.result;t(o.indexOf(",")>=0?o.split(",")[1]:o)},l.onerror=o=>a(o),l.readAsDataURL(e)}),rj=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(o=>o.toLocaleLowerCase()).reduce((o,u,f)=>(o[u]=e[t[f]],o),{})},lj=(e,t=!0)=>e?Object.entries(e).reduce((l,o)=>{const[u,f]=o;let m,y;return Array.isArray(f)?(y="",f.forEach(g=>{m=t?encodeURIComponent(g):g,y+=`${u}=${m}&`}),y.slice(0,-1)):(m=t?encodeURIComponent(f):f,y=`${u}=${m}`),`${l}&${y}`},"").substr(1):null,oj=(e,t={})=>{const a=Object.assign({method:e.method||"GET",headers:e.headers},t),o=rj(e.headers)["content-type"]||"";if(typeof e.data=="string")a.body=e.data;else if(o.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[f,m]of Object.entries(e.data||{}))u.set(f,m);a.body=u.toString()}else if(o.includes("multipart/form-data")||e.data instanceof FormData){const u=new FormData;if(e.data instanceof FormData)e.data.forEach((m,y)=>{u.append(y,m)});else for(const m of Object.keys(e.data))u.append(m,e.data[m]);a.body=u;const f=new Headers(a.headers);f.delete("content-type"),a.headers=f}else(o.includes("application/json")||typeof e.data=="object")&&(a.body=JSON.stringify(e.data));return a};class cj extends o6{async request(t){const a=oj(t,t.webFetchExtra),l=lj(t.params,t.shouldEncodeUrlParams),o=l?`${t.url}?${l}`:t.url,u=await fetch(o,a),f=u.headers.get("content-type")||"";let{responseType:m="text"}=u.ok?t:{};f.includes("application/json")&&(m="json");let y,g;switch(m){case"arraybuffer":case"blob":g=await u.blob(),y=await ij(g);break;case"json":y=await u.json();break;case"document":case"text":default:y=await u.text()}const S={};return u.headers.forEach((p,b)=>{S[b]=p}),{data:y,headers:S,status:u.status,url:u.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}mc("CapacitorHttp",{web:()=>new cj});var l0;(function(e){e.Aztec="AZTEC",e.Codabar="CODABAR",e.Code39="CODE_39",e.Code93="CODE_93",e.Code128="CODE_128",e.DataMatrix="DATA_MATRIX",e.Ean8="EAN_8",e.Ean13="EAN_13",e.Itf="ITF",e.Pdf417="PDF_417",e.QrCode="QR_CODE",e.UpcA="UPC_A",e.UpcE="UPC_E"})(l0||(l0={}));var p4;(function(e){e.CalendarEvent="CALENDAR_EVENT",e.ContactInfo="CONTACT_INFO",e.DriversLicense="DRIVERS_LICENSE",e.Email="EMAIL",e.Geo="GEO",e.Isbn="ISBN",e.Phone="PHONE",e.Product="PRODUCT",e.Sms="SMS",e.Text="TEXT",e.Url="URL",e.Wifi="WIFI",e.Unknown="UNKNOWN"})(p4||(p4={}));var o0;(function(e){e[e["640x480"]=0]="640x480",e[e["1280x720"]=1]="1280x720",e[e["1920x1080"]=2]="1920x1080",e[e["3840x2160"]=3]="3840x2160"})(o0||(o0={}));var c0;(function(e){e.Front="FRONT",e.Back="BACK"})(c0||(c0={}));var g4;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.PENDING=1]="PENDING",e[e.DOWNLOADING=2]="DOWNLOADING",e[e.CANCELED=3]="CANCELED",e[e.COMPLETED=4]="COMPLETED",e[e.FAILED=5]="FAILED",e[e.INSTALLING=6]="INSTALLING",e[e.DOWNLOAD_PAUSED=7]="DOWNLOAD_PAUSED"})(g4||(g4={}));var _4;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})(_4||(_4={}));var y4;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})(y4||(y4={}));var v4;(function(e){e[e.FAX=0]="FAX",e[e.HOME=1]="HOME",e[e.MOBILE=2]="MOBILE",e[e.UNKNOWN=3]="UNKNOWN",e[e.WORK=4]="WORK"})(v4||(v4={}));var b4;(function(e){e[e.OPEN=1]="OPEN",e[e.WEP=2]="WEP",e[e.WPA=3]="WPA"})(b4||(b4={}));const Po=mc("BarcodeScanner",{web:()=>Zr(()=>import("./web-D1qcSAMu.js"),[]).then(e=>new e.BarcodeScannerWeb)}),uj=8e3,ap=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";const a=t.replace(/\/+$/,"");try{const l=new URL(a);return l.pathname==="/health"&&(l.pathname="",l.search="",l.hash=""),l.toString().replace(/\/+$/,"")}catch{return a.replace(/\/health$/i,"")}},c6=e=>new Error(`连接探测超时(${e} ms),请确认手机能直接访问该 Hub 地址。`),dj=(e,t)=>{if(!(e instanceof Error))return"连接失败";const a=e.message.trim();return e.name==="AbortError"||e.name==="TimeoutError"||/aborted/i.test(a)?c6(t).message:a||"连接失败"},u0=async(e,t)=>{const a=ap(e),l=new Date().toISOString();if(!a)return{url:"",healthOk:!1,latencyMs:null,checkedAt:l,error:"地址为空"};const o=uj,u=`${a}/health`,f=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),m=new AbortController,y=window.setTimeout(()=>m.abort(c6(o)),o);try{const g=await fetch(u,{cache:"no-store",signal:m.signal}),S=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return{url:a,healthOk:g.ok,latencyMs:S-f,checkedAt:l,error:g.ok?null:`HTTP ${g.status}`}}catch(g){return{url:a,healthOk:!1,latencyMs:null,checkedAt:l,error:dj(g,o)}}finally{clearTimeout(y)}},fj=()=>{var e;try{const t=(e=Qr.getPlatform)==null?void 0:e.call(Qr);if(t==="android"||t==="ios")return t}catch{}return"web"},qu=()=>fj(),u6=()=>{var e;try{return((e=Qr.isNativePlatform)==null?void 0:e.call(Qr))===!0}catch{return!1}},Tp=()=>qu()==="android"&&u6(),hj=()=>qu()==="ios"&&u6(),qs=()=>Tp()||hj(),x4=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,mj=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},_g=e=>{var l;const t=e.trim();if(!t)return"";try{const o=new URL(t);if(o.protocol==="http:"||o.protocol==="https:")return ap(o.toString())}catch{}const a=(l=t.match(/https?:\/\/[^\s]+/i))==null?void 0:l[0];return a?ap(a):""},pj=e=>{var a;const t=[e.rawValue,e.displayValue,(a=e.urlBookmark)==null?void 0:a.url];for(const l of t){const o=(l==null?void 0:l.trim())??"";if(o)try{const u=new URL(o);return u.protocol==="panda:"&&u.searchParams.get("url")?_g(u.searchParams.get("url")??""):_g(u.toString())}catch{return _g(o)}}return""},gj=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 4.75H5.9A1.9 1.9 0 0 0 4 6.65v1.1M17 4.75h1.1A1.9 1.9 0 0 1 20 6.65v1.1M20 16.25v1.1a1.9 1.9 0 0 1-1.9 1.9H17M7 19.25H5.9A1.9 1.9 0 0 1 4 17.35v-1.1"}),i.jsx("path",{d:"M8 9.25h8M8 12h8M8 14.75h5"})]}),_j=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M6 6 18 18M18 6 6 18"})}),d6=({title:e,description:t,currentHubUrl:a,initialHubUrl:l,hint:o,saveLabel:u,savingLabel:f,saveDescription:m,saveSuccessMessage:y,onSaveSuccess:g})=>{const[S,p]=_.useState(l),[b,w]=_.useState({loading:!1,result:null}),[N,j]=_.useState({saving:!1}),[T,D]=_.useState(null),[z,I]=_.useState({active:!1,starting:!1}),k=_.useRef([]),P=ap(S),Q=qs();_.useEffect(()=>{p(l)},[l]),_.useEffect(()=>{if(!(typeof document>"u"))return document.documentElement.classList.toggle("hub-scanner-active",z.active),document.body.classList.toggle("hub-scanner-active",z.active),()=>{document.documentElement.classList.remove("hub-scanner-active"),document.body.classList.remove("hub-scanner-active")}},[z.active]),_.useEffect(()=>()=>{(async()=>(await Promise.all(k.current.map(ge=>ge.remove().catch(()=>{}))),k.current=[],await Po.stopScan().catch(()=>{})))()},[]);const se=async()=>{const ge=[...k.current];k.current=[],await Promise.all(ge.map(te=>te.remove().catch(()=>{})))},W=async()=>{I(ge=>({...ge,active:!1})),await se(),await Po.stopScan().catch(()=>{})},V=async()=>{if(!P){D({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}D(null),w({loading:!0,result:null});const ge=await u0(P);w({loading:!1,result:ge}),D({tone:ge.healthOk?"success":"danger",text:ge.healthOk?`连接成功,延迟 ${x4(ge.latencyMs)}。`:ge.error??"连接测试失败。"})},Y=async()=>{var ge;if(!P){D({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}D(null),j({saving:!0});try{const te=((ge=b.result)==null?void 0:ge.url)===P?b.result:await u0(P);if(w({loading:!1,result:te}),!te.healthOk){D({tone:"danger",text:te.error??"请先确认 Hub 地址可访问,再继续保存。"});return}await g(te),D({tone:"success",text:y})}catch(te){D({tone:"danger",text:te instanceof Error?te.message:"保存 Hub 地址失败。"})}finally{j({saving:!1})}},ee=async()=>{if(Q){D(null),I({active:!1,starting:!0});try{if(!(await Po.isSupported()).supported){D({tone:"danger",text:"当前设备不支持扫码填入,请手动输入地址。"});return}const te=await Po.requestPermissions();if(te.camera!=="granted"&&te.camera!=="limited"){D({tone:"danger",text:"需要相机权限才能扫码,请在系统设置中允许 Panda 使用相机。"});return}const xe=await Promise.all([Po.addListener("barcodesScanned",C=>{const q=C.barcodes.map(pj).find(Boolean);if(!q){D({tone:"danger",text:"二维码已识别,但没有拿到可用的 Hub 地址。"}),W();return}p(q),w({loading:!1,result:null}),D({tone:"success",text:"已通过扫码填入地址,可以直接测试或保存。"}),W()}),Po.addListener("scanError",C=>{D({tone:"danger",text:C.message||"扫码失败,请稍后重试。"}),W()})]);k.current=xe,I({active:!0,starting:!1}),await Po.startScan({formats:[l0.QrCode],lensFacing:c0.Back,resolution:o0["1280x720"]})}catch(ge){await W(),D({tone:"danger",text:ge instanceof Error?ge.message:"无法启动扫码,请稍后重试。"})}finally{I(ge=>({...ge,starting:!1}))}}},me=z.active&&typeof document<"u"?Ya.createPortal(i.jsx("div",{className:"hub-scanner-sheet",role:"dialog","aria-modal":"true","aria-label":"扫描 Hub 地址二维码",children:i.jsxs("div",{className:"hub-scanner-sheet__content",children:[i.jsxs("div",{className:"hub-scanner-sheet__topbar",children:[i.jsx("span",{className:"hub-scanner-sheet__badge",children:"扫码填入"}),i.jsx("button",{type:"button",className:"hub-scanner-sheet__close",onClick:()=>{W()},"aria-label":"关闭扫码",children:i.jsx(_j,{})})]}),i.jsxs("div",{className:"hub-scanner-sheet__frame","aria-hidden":"true",children:[i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tl"}),i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tr"}),i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--bl"}),i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--br"})]}),i.jsxs("div",{className:"hub-scanner-sheet__footer",children:[i.jsx("p",{children:"把电脑端显示的 Hub 二维码放进取景框,识别后会自动填入地址。"}),i.jsx("button",{type:"button",className:"settings-ghost-button hub-scanner-sheet__cancel",onClick:()=>{W()},children:"取消扫码"})]})]})}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"hub-connection-form",children:[i.jsxs("div",{className:"hub-connection-form__header",children:[i.jsxs("div",{className:"hub-connection-form__copy",children:[i.jsx("h3",{className:"hub-connection-form__title",children:e}),i.jsx("p",{className:"hub-connection-form__description",children:t})]}),a?i.jsxs("div",{className:"hub-connection-form__current",children:[i.jsx("span",{children:"当前"}),i.jsx("strong",{children:a})]}):null]}),i.jsxs("label",{className:"hub-connection-form__field",children:[i.jsx("span",{className:"hub-connection-form__label",children:"Hub 地址"}),i.jsxs("span",{className:"hub-connection-form__input-shell",children:[i.jsx("input",{className:"hub-connection-form__input",type:"url",inputMode:"url",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,placeholder:"例如 http://192.168.31.20:4343",value:S,onChange:ge=>{p(ge.target.value),w({loading:!1,result:null}),D(null)}}),Q?i.jsxs("button",{type:"button",className:"hub-connection-form__scan",onClick:()=>{ee()},disabled:z.starting||N.saving||b.loading,"aria-label":"扫码填入 Hub 地址",children:[i.jsx(gj,{}),i.jsx("span",{children:z.starting?"启动中":"扫码"})]}):null]})]}),i.jsx("p",{className:"hub-connection-form__hint",children:o}),i.jsxs("div",{className:"hub-connection-form__actions",children:[i.jsxs("button",{type:"button",className:"settings-action hub-connection-form__save",onClick:()=>{Y()},disabled:!P||N.saving||z.starting,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:N.saving?f:u}),i.jsx("span",{children:m})]}),i.jsx("span",{className:"settings-action__state",children:N.saving?"处理中…":"→"})]}),i.jsx("button",{type:"button",className:"settings-ghost-button hub-connection-form__test",onClick:()=>{V()},disabled:!P||b.loading||N.saving||z.starting,children:b.loading?"测试中…":"测试连接"})]}),b.result?i.jsxs("div",{className:"hub-connection-form__probe",children:[i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"探测地址"}),i.jsx("strong",{children:b.result.url})]}),i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"连通结果"}),i.jsx("strong",{className:b.result.healthOk?"is-ok":"is-danger",children:b.result.healthOk?"Hub 在线":b.result.error??"无法连接"})]}),i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"延迟"}),i.jsx("strong",{children:x4(b.result.latencyMs)})]}),i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"最近探测"}),i.jsx("strong",{children:mj(b.result.checkedAt)})]})]}):null,T?i.jsx("p",{className:`hub-connection-form__notice is-${T.tone}`,children:T.text}):null]}),me]})};var S4;(function(e){e[e.Sunday=1]="Sunday",e[e.Monday=2]="Monday",e[e.Tuesday=3]="Tuesday",e[e.Wednesday=4]="Wednesday",e[e.Thursday=5]="Thursday",e[e.Friday=6]="Friday",e[e.Saturday=7]="Saturday"})(S4||(S4={}));const lh=mc("LocalNotifications",{web:()=>Zr(()=>import("./web-BhBxIFnA.js"),[]).then(e=>new e.LocalNotificationsWeb)});var mn;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function a(o){throw new Error}e.assertNever=a,e.arrayToEnum=o=>{const u={};for(const f of o)u[f]=f;return u},e.getValidEnumValues=o=>{const u=e.objectKeys(o).filter(m=>typeof o[o[m]]!="number"),f={};for(const m of u)f[m]=o[m];return e.objectValues(f)},e.objectValues=o=>e.objectKeys(o).map(function(u){return o[u]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const u=[];for(const f in o)Object.prototype.hasOwnProperty.call(o,f)&&u.push(f);return u},e.find=(o,u)=>{for(const f of o)if(u(f))return f},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function l(o,u=" | "){return o.map(f=>typeof f=="string"?`'${f}'`:f).join(u)}e.joinValues=l,e.jsonStringifyReplacer=(o,u)=>typeof u=="bigint"?u.toString():u})(mn||(mn={}));var j4;(function(e){e.mergeShapes=(t,a)=>({...t,...a})})(j4||(j4={}));const nt=mn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$l=e=>{switch(typeof e){case"undefined":return nt.undefined;case"string":return nt.string;case"number":return Number.isNaN(e)?nt.nan:nt.number;case"boolean":return nt.boolean;case"function":return nt.function;case"bigint":return nt.bigint;case"symbol":return nt.symbol;case"object":return Array.isArray(e)?nt.array:e===null?nt.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?nt.promise:typeof Map<"u"&&e instanceof Map?nt.map:typeof Set<"u"&&e instanceof Set?nt.set:typeof Date<"u"&&e instanceof Date?nt.date:nt.object;default:return nt.unknown}},Be=mn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Vr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=l=>{this.issues=[...this.issues,l]},this.addIssues=(l=[])=>{this.issues=[...this.issues,...l]};const a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=t}format(t){const a=t||function(u){return u.message},l={_errors:[]},o=u=>{for(const f of u.issues)if(f.code==="invalid_union")f.unionErrors.map(o);else if(f.code==="invalid_return_type")o(f.returnTypeError);else if(f.code==="invalid_arguments")o(f.argumentsError);else if(f.path.length===0)l._errors.push(a(f));else{let m=l,y=0;for(;y<f.path.length;){const g=f.path[y];y===f.path.length-1?(m[g]=m[g]||{_errors:[]},m[g]._errors.push(a(f))):m[g]=m[g]||{_errors:[]},m=m[g],y++}}};return o(this),l}static assert(t){if(!(t instanceof Vr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,mn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=a=>a.message){const a={},l=[];for(const o of this.issues)if(o.path.length>0){const u=o.path[0];a[u]=a[u]||[],a[u].push(t(o))}else l.push(t(o));return{formErrors:l,fieldErrors:a}}get formErrors(){return this.flatten()}}Vr.create=e=>new Vr(e);const d0=(e,t)=>{let a;switch(e.code){case Be.invalid_type:e.received===nt.undefined?a="Required":a=`Expected ${e.expected}, received ${e.received}`;break;case Be.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,mn.jsonStringifyReplacer)}`;break;case Be.unrecognized_keys:a=`Unrecognized key(s) in object: ${mn.joinValues(e.keys,", ")}`;break;case Be.invalid_union:a="Invalid input";break;case Be.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${mn.joinValues(e.options)}`;break;case Be.invalid_enum_value:a=`Invalid enum value. Expected ${mn.joinValues(e.options)}, received '${e.received}'`;break;case Be.invalid_arguments:a="Invalid function arguments";break;case Be.invalid_return_type:a="Invalid function return type";break;case Be.invalid_date:a="Invalid date";break;case Be.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:mn.assertNever(e.validation):e.validation!=="regex"?a=`Invalid ${e.validation}`:a="Invalid";break;case Be.too_small:e.type==="array"?a=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?a=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?a=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?a=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?a=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:a="Invalid input";break;case Be.too_big:e.type==="array"?a=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?a=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?a=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?a=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?a=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:a="Invalid input";break;case Be.custom:a="Invalid input";break;case Be.invalid_intersection_types:a="Intersection results could not be merged";break;case Be.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case Be.not_finite:a="Number must be finite";break;default:a=t.defaultError,mn.assertNever(e)}return{message:a}};let yj=d0;function vj(){return yj}const bj=e=>{const{data:t,path:a,errorMaps:l,issueData:o}=e,u=[...a,...o.path||[]],f={...o,path:u};if(o.message!==void 0)return{...o,path:u,message:o.message};let m="";const y=l.filter(g=>!!g).slice().reverse();for(const g of y)m=g(f,{data:t,defaultError:m}).message;return{...o,path:u,message:m}};function Ge(e,t){const a=vj(),l=bj({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===d0?void 0:d0].filter(o=>!!o)});e.common.issues.push(l)}class ta{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,a){const l=[];for(const o of a){if(o.status==="aborted")return Tt;o.status==="dirty"&&t.dirty(),l.push(o.value)}return{status:t.value,value:l}}static async mergeObjectAsync(t,a){const l=[];for(const o of a){const u=await o.key,f=await o.value;l.push({key:u,value:f})}return ta.mergeObjectSync(t,l)}static mergeObjectSync(t,a){const l={};for(const o of a){const{key:u,value:f}=o;if(u.status==="aborted"||f.status==="aborted")return Tt;u.status==="dirty"&&t.dirty(),f.status==="dirty"&&t.dirty(),u.value!=="__proto__"&&(typeof f.value<"u"||o.alwaysSet)&&(l[u.value]=f.value)}return{status:t.value,value:l}}}const Tt=Object.freeze({status:"aborted"}),kf=e=>({status:"dirty",value:e}),Xa=e=>({status:"valid",value:e}),w4=e=>e.status==="aborted",N4=e=>e.status==="dirty",Wu=e=>e.status==="valid",ip=e=>typeof Promise<"u"&&e instanceof Promise;var ct;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(ct||(ct={}));class tr{constructor(t,a,l,o){this._cachedPath=[],this.parent=t,this.data=a,this._path=l,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const k4=(e,t)=>{if(Wu(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const a=new Vr(e.common.issues);return this._error=a,this._error}}};function Pt(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:l,description:o}=e;if(t&&(a||l))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(f,m)=>{const{message:y}=e;return f.code==="invalid_enum_value"?{message:y??m.defaultError}:typeof m.data>"u"?{message:y??l??m.defaultError}:f.code!=="invalid_type"?{message:m.defaultError}:{message:y??a??m.defaultError}},description:o}}class rn{get description(){return this._def.description}_getType(t){return $l(t.data)}_getOrReturnCtx(t,a){return a||{common:t.parent.common,data:t.data,parsedType:$l(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ta,ctx:{common:t.parent.common,data:t.data,parsedType:$l(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const a=this._parse(t);if(ip(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(t){const a=this._parse(t);return Promise.resolve(a)}parse(t,a){const l=this.safeParse(t,a);if(l.success)return l.data;throw l.error}safeParse(t,a){const l={common:{issues:[],async:(a==null?void 0:a.async)??!1,contextualErrorMap:a==null?void 0:a.errorMap},path:(a==null?void 0:a.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$l(t)},o=this._parseSync({data:t,path:l.path,parent:l});return k4(l,o)}"~validate"(t){var l,o;const a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$l(t)};if(!this["~standard"].async)try{const u=this._parseSync({data:t,path:[],parent:a});return Wu(u)?{value:u.value}:{issues:a.common.issues}}catch(u){(o=(l=u==null?void 0:u.message)==null?void 0:l.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:a}).then(u=>Wu(u)?{value:u.value}:{issues:a.common.issues})}async parseAsync(t,a){const l=await this.safeParseAsync(t,a);if(l.success)return l.data;throw l.error}async safeParseAsync(t,a){const l={common:{issues:[],contextualErrorMap:a==null?void 0:a.errorMap,async:!0},path:(a==null?void 0:a.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$l(t)},o=this._parse({data:t,path:l.path,parent:l}),u=await(ip(o)?o:Promise.resolve(o));return k4(l,u)}refine(t,a){const l=o=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(o):a;return this._refinement((o,u)=>{const f=t(o),m=()=>u.addIssue({code:Be.custom,...l(o)});return typeof Promise<"u"&&f instanceof Promise?f.then(y=>y?!0:(m(),!1)):f?!0:(m(),!1)})}refinement(t,a){return this._refinement((l,o)=>t(l)?!0:(o.addIssue(typeof a=="function"?a(l,o):a),!1))}_refinement(t){return new Gu({schema:this,typeName:kt.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return ao.create(this,this._def)}nullable(){return Yu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return er.create(this)}promise(){return up.create(this,this._def)}or(t){return lp.create([this,t],this._def)}and(t){return op.create(this,t,this._def)}transform(t){return new Gu({...Pt(this._def),schema:this,typeName:kt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const a=typeof t=="function"?t:()=>t;return new g0({...Pt(this._def),innerType:this,defaultValue:a,typeName:kt.ZodDefault})}brand(){return new Fj({typeName:kt.ZodBranded,type:this,...Pt(this._def)})}catch(t){const a=typeof t=="function"?t:()=>t;return new _0({...Pt(this._def),innerType:this,catchValue:a,typeName:kt.ZodCatch})}describe(t){const a=this.constructor;return new a({...this._def,description:t})}pipe(t){return o_.create(this,t)}readonly(){return y0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const xj=/^c[^\s-]{8,}$/i,Sj=/^[0-9a-z]+$/,jj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wj=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Nj=/^[a-z0-9_-]{21}$/i,kj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ej=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Cj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let yg;const Rj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Aj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Dj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Oj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ij=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,f6="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Lj=new RegExp(`^${f6}$`);function h6(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const a=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${a}`}function Pj(e){return new RegExp(`^${h6(e)}$`)}function Uj(e){let t=`${f6}T${h6(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function zj(e,t){return!!((t==="v4"||!t)&&Rj.test(e)||(t==="v6"||!t)&&Aj.test(e))}function Bj(e,t){if(!kj.test(e))return!1;try{const[a]=e.split(".");if(!a)return!1;const l=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),o=JSON.parse(atob(l));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Hj(e,t){return!!((t==="v4"||!t)&&Mj.test(e)||(t==="v6"||!t)&&Dj.test(e))}class Wr extends rn{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==nt.string){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_type,expected:nt.string,received:u.parsedType}),Tt}const l=new ta;let o;for(const u of this._def.checks)if(u.kind==="min")t.data.length<u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if(u.kind==="max")t.data.length>u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if(u.kind==="length"){const f=t.data.length>u.value,m=t.data.length<u.value;(f||m)&&(o=this._getOrReturnCtx(t,o),f?Ge(o,{code:Be.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):m&&Ge(o,{code:Be.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),l.dirty())}else if(u.kind==="email")Cj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"email",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="emoji")yg||(yg=new RegExp(Tj,"u")),yg.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"emoji",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="uuid")wj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"uuid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="nanoid")Nj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"nanoid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="cuid")xj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"cuid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="cuid2")Sj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"cuid2",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="ulid")jj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"ulid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Ge(o,{validation:"url",code:Be.invalid_string,message:u.message}),l.dirty()}else u.kind==="regex"?(u.regex.lastIndex=0,u.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"regex",code:Be.invalid_string,message:u.message}),l.dirty())):u.kind==="trim"?t.data=t.data.trim():u.kind==="includes"?t.data.includes(u.value,u.position)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),l.dirty()):u.kind==="toLowerCase"?t.data=t.data.toLowerCase():u.kind==="toUpperCase"?t.data=t.data.toUpperCase():u.kind==="startsWith"?t.data.startsWith(u.value)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:{startsWith:u.value},message:u.message}),l.dirty()):u.kind==="endsWith"?t.data.endsWith(u.value)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:{endsWith:u.value},message:u.message}),l.dirty()):u.kind==="datetime"?Uj(u).test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:"datetime",message:u.message}),l.dirty()):u.kind==="date"?Lj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:"date",message:u.message}),l.dirty()):u.kind==="time"?Pj(u).test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:"time",message:u.message}),l.dirty()):u.kind==="duration"?Ej.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"duration",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="ip"?zj(t.data,u.version)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"ip",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="jwt"?Bj(t.data,u.alg)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"jwt",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="cidr"?Hj(t.data,u.version)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"cidr",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="base64"?Oj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"base64",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="base64url"?Ij.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"base64url",code:Be.invalid_string,message:u.message}),l.dirty()):mn.assertNever(u);return{status:l.value,value:t.data}}_regex(t,a,l){return this.refinement(o=>t.test(o),{validation:a,code:Be.invalid_string,...ct.errToObj(l)})}_addCheck(t){return new Wr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ct.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ct.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ct.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ct.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ct.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ct.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ct.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ct.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ct.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ct.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ct.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ct.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ct.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...ct.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...ct.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...ct.errToObj(t)})}regex(t,a){return this._addCheck({kind:"regex",regex:t,...ct.errToObj(a)})}includes(t,a){return this._addCheck({kind:"includes",value:t,position:a==null?void 0:a.position,...ct.errToObj(a==null?void 0:a.message)})}startsWith(t,a){return this._addCheck({kind:"startsWith",value:t,...ct.errToObj(a)})}endsWith(t,a){return this._addCheck({kind:"endsWith",value:t,...ct.errToObj(a)})}min(t,a){return this._addCheck({kind:"min",value:t,...ct.errToObj(a)})}max(t,a){return this._addCheck({kind:"max",value:t,...ct.errToObj(a)})}length(t,a){return this._addCheck({kind:"length",value:t,...ct.errToObj(a)})}nonempty(t){return this.min(1,ct.errToObj(t))}trim(){return new Wr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t}get maxLength(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t}}Wr.create=e=>new Wr({checks:[],typeName:kt.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Pt(e)});function $j(e,t){const a=(e.toString().split(".")[1]||"").length,l=(t.toString().split(".")[1]||"").length,o=a>l?a:l,u=Number.parseInt(e.toFixed(o).replace(".","")),f=Number.parseInt(t.toFixed(o).replace(".",""));return u%f/10**o}class Ku extends rn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==nt.number){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_type,expected:nt.number,received:u.parsedType}),Tt}let l;const o=new ta;for(const u of this._def.checks)u.kind==="int"?mn.isInteger(t.data)||(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.invalid_type,expected:"integer",received:"float",message:u.message}),o.dirty()):u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_small,minimum:u.value,type:"number",inclusive:u.inclusive,exact:!1,message:u.message}),o.dirty()):u.kind==="max"?(u.inclusive?t.data>u.value:t.data>=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_big,maximum:u.value,type:"number",inclusive:u.inclusive,exact:!1,message:u.message}),o.dirty()):u.kind==="multipleOf"?$j(t.data,u.value)!==0&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):u.kind==="finite"?Number.isFinite(t.data)||(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.not_finite,message:u.message}),o.dirty()):mn.assertNever(u);return{status:o.value,value:t.data}}gte(t,a){return this.setLimit("min",t,!0,ct.toString(a))}gt(t,a){return this.setLimit("min",t,!1,ct.toString(a))}lte(t,a){return this.setLimit("max",t,!0,ct.toString(a))}lt(t,a){return this.setLimit("max",t,!1,ct.toString(a))}setLimit(t,a,l,o){return new Ku({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:l,message:ct.toString(o)}]})}_addCheck(t){return new Ku({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ct.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ct.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ct.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ct.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ct.toString(t)})}multipleOf(t,a){return this._addCheck({kind:"multipleOf",value:t,message:ct.toString(a)})}finite(t){return this._addCheck({kind:"finite",message:ct.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ct.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ct.toString(t)})}get minValue(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t}get maxValue(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&mn.isInteger(t.value))}get isFinite(){let t=null,a=null;for(const l of this._def.checks){if(l.kind==="finite"||l.kind==="int"||l.kind==="multipleOf")return!0;l.kind==="min"?(a===null||l.value>a)&&(a=l.value):l.kind==="max"&&(t===null||l.value<t)&&(t=l.value)}return Number.isFinite(a)&&Number.isFinite(t)}}Ku.create=e=>new Ku({checks:[],typeName:kt.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Pt(e)});class qf extends rn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==nt.bigint)return this._getInvalidInput(t);let l;const o=new ta;for(const u of this._def.checks)u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_small,type:"bigint",minimum:u.value,inclusive:u.inclusive,message:u.message}),o.dirty()):u.kind==="max"?(u.inclusive?t.data>u.value:t.data>=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_big,type:"bigint",maximum:u.value,inclusive:u.inclusive,message:u.message}),o.dirty()):u.kind==="multipleOf"?t.data%u.value!==BigInt(0)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):mn.assertNever(u);return{status:o.value,value:t.data}}_getInvalidInput(t){const a=this._getOrReturnCtx(t);return Ge(a,{code:Be.invalid_type,expected:nt.bigint,received:a.parsedType}),Tt}gte(t,a){return this.setLimit("min",t,!0,ct.toString(a))}gt(t,a){return this.setLimit("min",t,!1,ct.toString(a))}lte(t,a){return this.setLimit("max",t,!0,ct.toString(a))}lt(t,a){return this.setLimit("max",t,!1,ct.toString(a))}setLimit(t,a,l,o){return new qf({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:l,message:ct.toString(o)}]})}_addCheck(t){return new qf({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ct.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ct.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ct.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ct.toString(t)})}multipleOf(t,a){return this._addCheck({kind:"multipleOf",value:t,message:ct.toString(a)})}get minValue(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t}get maxValue(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t}}qf.create=e=>new qf({checks:[],typeName:kt.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Pt(e)});class f0 extends rn{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==nt.boolean){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.boolean,received:l.parsedType}),Tt}return Xa(t.data)}}f0.create=e=>new f0({typeName:kt.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Pt(e)});class rp extends rn{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==nt.date){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_type,expected:nt.date,received:u.parsedType}),Tt}if(Number.isNaN(t.data.getTime())){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_date}),Tt}const l=new ta;let o;for(const u of this._def.checks)u.kind==="min"?t.data.getTime()<u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_small,message:u.message,inclusive:!0,exact:!1,minimum:u.value,type:"date"}),l.dirty()):u.kind==="max"?t.data.getTime()>u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_big,message:u.message,inclusive:!0,exact:!1,maximum:u.value,type:"date"}),l.dirty()):mn.assertNever(u);return{status:l.value,value:new Date(t.data.getTime())}}_addCheck(t){return new rp({...this._def,checks:[...this._def.checks,t]})}min(t,a){return this._addCheck({kind:"min",value:t.getTime(),message:ct.toString(a)})}max(t,a){return this._addCheck({kind:"max",value:t.getTime(),message:ct.toString(a)})}get minDate(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t!=null?new Date(t):null}}rp.create=e=>new rp({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:kt.ZodDate,...Pt(e)});class E4 extends rn{_parse(t){if(this._getType(t)!==nt.symbol){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.symbol,received:l.parsedType}),Tt}return Xa(t.data)}}E4.create=e=>new E4({typeName:kt.ZodSymbol,...Pt(e)});class C4 extends rn{_parse(t){if(this._getType(t)!==nt.undefined){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.undefined,received:l.parsedType}),Tt}return Xa(t.data)}}C4.create=e=>new C4({typeName:kt.ZodUndefined,...Pt(e)});class T4 extends rn{_parse(t){if(this._getType(t)!==nt.null){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.null,received:l.parsedType}),Tt}return Xa(t.data)}}T4.create=e=>new T4({typeName:kt.ZodNull,...Pt(e)});class h0 extends rn{constructor(){super(...arguments),this._any=!0}_parse(t){return Xa(t.data)}}h0.create=e=>new h0({typeName:kt.ZodAny,...Pt(e)});class R4 extends rn{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Xa(t.data)}}R4.create=e=>new R4({typeName:kt.ZodUnknown,...Pt(e)});class ro extends rn{_parse(t){const a=this._getOrReturnCtx(t);return Ge(a,{code:Be.invalid_type,expected:nt.never,received:a.parsedType}),Tt}}ro.create=e=>new ro({typeName:kt.ZodNever,...Pt(e)});class M4 extends rn{_parse(t){if(this._getType(t)!==nt.undefined){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.void,received:l.parsedType}),Tt}return Xa(t.data)}}M4.create=e=>new M4({typeName:kt.ZodVoid,...Pt(e)});class er extends rn{_parse(t){const{ctx:a,status:l}=this._processInputParams(t),o=this._def;if(a.parsedType!==nt.array)return Ge(a,{code:Be.invalid_type,expected:nt.array,received:a.parsedType}),Tt;if(o.exactLength!==null){const f=a.data.length>o.exactLength.value,m=a.data.length<o.exactLength.value;(f||m)&&(Ge(a,{code:f?Be.too_big:Be.too_small,minimum:m?o.exactLength.value:void 0,maximum:f?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),l.dirty())}if(o.minLength!==null&&a.data.length<o.minLength.value&&(Ge(a,{code:Be.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),l.dirty()),o.maxLength!==null&&a.data.length>o.maxLength.value&&(Ge(a,{code:Be.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),l.dirty()),a.common.async)return Promise.all([...a.data].map((f,m)=>o.type._parseAsync(new tr(a,f,a.path,m)))).then(f=>ta.mergeArray(l,f));const u=[...a.data].map((f,m)=>o.type._parseSync(new tr(a,f,a.path,m)));return ta.mergeArray(l,u)}get element(){return this._def.type}min(t,a){return new er({...this._def,minLength:{value:t,message:ct.toString(a)}})}max(t,a){return new er({...this._def,maxLength:{value:t,message:ct.toString(a)}})}length(t,a){return new er({...this._def,exactLength:{value:t,message:ct.toString(a)}})}nonempty(t){return this.min(1,t)}}er.create=(e,t)=>new er({type:e,minLength:null,maxLength:null,exactLength:null,typeName:kt.ZodArray,...Pt(t)});function bu(e){if(e instanceof fs){const t={};for(const a in e.shape){const l=e.shape[a];t[a]=ao.create(bu(l))}return new fs({...e._def,shape:()=>t})}else return e instanceof er?new er({...e._def,type:bu(e.element)}):e instanceof ao?ao.create(bu(e.unwrap())):e instanceof Yu?Yu.create(bu(e.unwrap())):e instanceof uc?uc.create(e.items.map(t=>bu(t))):e}class fs extends rn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),a=mn.objectKeys(t);return this._cached={shape:t,keys:a},this._cached}_parse(t){if(this._getType(t)!==nt.object){const g=this._getOrReturnCtx(t);return Ge(g,{code:Be.invalid_type,expected:nt.object,received:g.parsedType}),Tt}const{status:l,ctx:o}=this._processInputParams(t),{shape:u,keys:f}=this._getCached(),m=[];if(!(this._def.catchall instanceof ro&&this._def.unknownKeys==="strip"))for(const g in o.data)f.includes(g)||m.push(g);const y=[];for(const g of f){const S=u[g],p=o.data[g];y.push({key:{status:"valid",value:g},value:S._parse(new tr(o,p,o.path,g)),alwaysSet:g in o.data})}if(this._def.catchall instanceof ro){const g=this._def.unknownKeys;if(g==="passthrough")for(const S of m)y.push({key:{status:"valid",value:S},value:{status:"valid",value:o.data[S]}});else if(g==="strict")m.length>0&&(Ge(o,{code:Be.unrecognized_keys,keys:m}),l.dirty());else if(g!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const g=this._def.catchall;for(const S of m){const p=o.data[S];y.push({key:{status:"valid",value:S},value:g._parse(new tr(o,p,o.path,S)),alwaysSet:S in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const g=[];for(const S of y){const p=await S.key,b=await S.value;g.push({key:p,value:b,alwaysSet:S.alwaysSet})}return g}).then(g=>ta.mergeObjectSync(l,g)):ta.mergeObjectSync(l,y)}get shape(){return this._def.shape()}strict(t){return ct.errToObj,new fs({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(a,l)=>{var u,f;const o=((f=(u=this._def).errorMap)==null?void 0:f.call(u,a,l).message)??l.defaultError;return a.code==="unrecognized_keys"?{message:ct.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new fs({...this._def,unknownKeys:"strip"})}passthrough(){return new fs({...this._def,unknownKeys:"passthrough"})}extend(t){return new fs({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new fs({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:kt.ZodObject})}setKey(t,a){return this.augment({[t]:a})}catchall(t){return new fs({...this._def,catchall:t})}pick(t){const a={};for(const l of mn.objectKeys(t))t[l]&&this.shape[l]&&(a[l]=this.shape[l]);return new fs({...this._def,shape:()=>a})}omit(t){const a={};for(const l of mn.objectKeys(this.shape))t[l]||(a[l]=this.shape[l]);return new fs({...this._def,shape:()=>a})}deepPartial(){return bu(this)}partial(t){const a={};for(const l of mn.objectKeys(this.shape)){const o=this.shape[l];t&&!t[l]?a[l]=o:a[l]=o.optional()}return new fs({...this._def,shape:()=>a})}required(t){const a={};for(const l of mn.objectKeys(this.shape))if(t&&!t[l])a[l]=this.shape[l];else{let u=this.shape[l];for(;u instanceof ao;)u=u._def.innerType;a[l]=u}return new fs({...this._def,shape:()=>a})}keyof(){return m6(mn.objectKeys(this.shape))}}fs.create=(e,t)=>new fs({shape:()=>e,unknownKeys:"strip",catchall:ro.create(),typeName:kt.ZodObject,...Pt(t)});fs.strictCreate=(e,t)=>new fs({shape:()=>e,unknownKeys:"strict",catchall:ro.create(),typeName:kt.ZodObject,...Pt(t)});fs.lazycreate=(e,t)=>new fs({shape:e,unknownKeys:"strip",catchall:ro.create(),typeName:kt.ZodObject,...Pt(t)});class lp extends rn{_parse(t){const{ctx:a}=this._processInputParams(t),l=this._def.options;function o(u){for(const m of u)if(m.result.status==="valid")return m.result;for(const m of u)if(m.result.status==="dirty")return a.common.issues.push(...m.ctx.common.issues),m.result;const f=u.map(m=>new Vr(m.ctx.common.issues));return Ge(a,{code:Be.invalid_union,unionErrors:f}),Tt}if(a.common.async)return Promise.all(l.map(async u=>{const f={...a,common:{...a.common,issues:[]},parent:null};return{result:await u._parseAsync({data:a.data,path:a.path,parent:f}),ctx:f}})).then(o);{let u;const f=[];for(const y of l){const g={...a,common:{...a.common,issues:[]},parent:null},S=y._parseSync({data:a.data,path:a.path,parent:g});if(S.status==="valid")return S;S.status==="dirty"&&!u&&(u={result:S,ctx:g}),g.common.issues.length&&f.push(g.common.issues)}if(u)return a.common.issues.push(...u.ctx.common.issues),u.result;const m=f.map(y=>new Vr(y));return Ge(a,{code:Be.invalid_union,unionErrors:m}),Tt}}get options(){return this._def.options}}lp.create=(e,t)=>new lp({options:e,typeName:kt.ZodUnion,...Pt(t)});function m0(e,t){const a=$l(e),l=$l(t);if(e===t)return{valid:!0,data:e};if(a===nt.object&&l===nt.object){const o=mn.objectKeys(t),u=mn.objectKeys(e).filter(m=>o.indexOf(m)!==-1),f={...e,...t};for(const m of u){const y=m0(e[m],t[m]);if(!y.valid)return{valid:!1};f[m]=y.data}return{valid:!0,data:f}}else if(a===nt.array&&l===nt.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let u=0;u<e.length;u++){const f=e[u],m=t[u],y=m0(f,m);if(!y.valid)return{valid:!1};o.push(y.data)}return{valid:!0,data:o}}else return a===nt.date&&l===nt.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class op extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t),o=(u,f)=>{if(w4(u)||w4(f))return Tt;const m=m0(u.value,f.value);return m.valid?((N4(u)||N4(f))&&a.dirty(),{status:a.value,value:m.data}):(Ge(l,{code:Be.invalid_intersection_types}),Tt)};return l.common.async?Promise.all([this._def.left._parseAsync({data:l.data,path:l.path,parent:l}),this._def.right._parseAsync({data:l.data,path:l.path,parent:l})]).then(([u,f])=>o(u,f)):o(this._def.left._parseSync({data:l.data,path:l.path,parent:l}),this._def.right._parseSync({data:l.data,path:l.path,parent:l}))}}op.create=(e,t,a)=>new op({left:e,right:t,typeName:kt.ZodIntersection,...Pt(a)});class uc extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.array)return Ge(l,{code:Be.invalid_type,expected:nt.array,received:l.parsedType}),Tt;if(l.data.length<this._def.items.length)return Ge(l,{code:Be.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Tt;!this._def.rest&&l.data.length>this._def.items.length&&(Ge(l,{code:Be.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());const u=[...l.data].map((f,m)=>{const y=this._def.items[m]||this._def.rest;return y?y._parse(new tr(l,f,l.path,m)):null}).filter(f=>!!f);return l.common.async?Promise.all(u).then(f=>ta.mergeArray(a,f)):ta.mergeArray(a,u)}get items(){return this._def.items}rest(t){return new uc({...this._def,rest:t})}}uc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new uc({items:e,typeName:kt.ZodTuple,rest:null,...Pt(t)})};class cp extends rn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.object)return Ge(l,{code:Be.invalid_type,expected:nt.object,received:l.parsedType}),Tt;const o=[],u=this._def.keyType,f=this._def.valueType;for(const m in l.data)o.push({key:u._parse(new tr(l,m,l.path,m)),value:f._parse(new tr(l,l.data[m],l.path,m)),alwaysSet:m in l.data});return l.common.async?ta.mergeObjectAsync(a,o):ta.mergeObjectSync(a,o)}get element(){return this._def.valueType}static create(t,a,l){return a instanceof rn?new cp({keyType:t,valueType:a,typeName:kt.ZodRecord,...Pt(l)}):new cp({keyType:Wr.create(),valueType:t,typeName:kt.ZodRecord,...Pt(a)})}}class A4 extends rn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.map)return Ge(l,{code:Be.invalid_type,expected:nt.map,received:l.parsedType}),Tt;const o=this._def.keyType,u=this._def.valueType,f=[...l.data.entries()].map(([m,y],g)=>({key:o._parse(new tr(l,m,l.path,[g,"key"])),value:u._parse(new tr(l,y,l.path,[g,"value"]))}));if(l.common.async){const m=new Map;return Promise.resolve().then(async()=>{for(const y of f){const g=await y.key,S=await y.value;if(g.status==="aborted"||S.status==="aborted")return Tt;(g.status==="dirty"||S.status==="dirty")&&a.dirty(),m.set(g.value,S.value)}return{status:a.value,value:m}})}else{const m=new Map;for(const y of f){const g=y.key,S=y.value;if(g.status==="aborted"||S.status==="aborted")return Tt;(g.status==="dirty"||S.status==="dirty")&&a.dirty(),m.set(g.value,S.value)}return{status:a.value,value:m}}}}A4.create=(e,t,a)=>new A4({valueType:t,keyType:e,typeName:kt.ZodMap,...Pt(a)});class Wf extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.set)return Ge(l,{code:Be.invalid_type,expected:nt.set,received:l.parsedType}),Tt;const o=this._def;o.minSize!==null&&l.data.size<o.minSize.value&&(Ge(l,{code:Be.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),a.dirty()),o.maxSize!==null&&l.data.size>o.maxSize.value&&(Ge(l,{code:Be.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),a.dirty());const u=this._def.valueType;function f(y){const g=new Set;for(const S of y){if(S.status==="aborted")return Tt;S.status==="dirty"&&a.dirty(),g.add(S.value)}return{status:a.value,value:g}}const m=[...l.data.values()].map((y,g)=>u._parse(new tr(l,y,l.path,g)));return l.common.async?Promise.all(m).then(y=>f(y)):f(m)}min(t,a){return new Wf({...this._def,minSize:{value:t,message:ct.toString(a)}})}max(t,a){return new Wf({...this._def,maxSize:{value:t,message:ct.toString(a)}})}size(t,a){return this.min(t,a).max(t,a)}nonempty(t){return this.min(1,t)}}Wf.create=(e,t)=>new Wf({valueType:e,minSize:null,maxSize:null,typeName:kt.ZodSet,...Pt(t)});class D4 extends rn{get schema(){return this._def.getter()}_parse(t){const{ctx:a}=this._processInputParams(t);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}}D4.create=(e,t)=>new D4({getter:e,typeName:kt.ZodLazy,...Pt(t)});class p0 extends rn{_parse(t){if(t.data!==this._def.value){const a=this._getOrReturnCtx(t);return Ge(a,{received:a.data,code:Be.invalid_literal,expected:this._def.value}),Tt}return{status:"valid",value:t.data}}get value(){return this._def.value}}p0.create=(e,t)=>new p0({value:e,typeName:kt.ZodLiteral,...Pt(t)});function m6(e,t){return new Qu({values:e,typeName:kt.ZodEnum,...Pt(t)})}class Qu extends rn{_parse(t){if(typeof t.data!="string"){const a=this._getOrReturnCtx(t),l=this._def.values;return Ge(a,{expected:mn.joinValues(l),received:a.parsedType,code:Be.invalid_type}),Tt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const a=this._getOrReturnCtx(t),l=this._def.values;return Ge(a,{received:a.data,code:Be.invalid_enum_value,options:l}),Tt}return Xa(t.data)}get options(){return this._def.values}get enum(){const t={};for(const a of this._def.values)t[a]=a;return t}get Values(){const t={};for(const a of this._def.values)t[a]=a;return t}get Enum(){const t={};for(const a of this._def.values)t[a]=a;return t}extract(t,a=this._def){return Qu.create(t,{...this._def,...a})}exclude(t,a=this._def){return Qu.create(this.options.filter(l=>!t.includes(l)),{...this._def,...a})}}Qu.create=m6;class O4 extends rn{_parse(t){const a=mn.getValidEnumValues(this._def.values),l=this._getOrReturnCtx(t);if(l.parsedType!==nt.string&&l.parsedType!==nt.number){const o=mn.objectValues(a);return Ge(l,{expected:mn.joinValues(o),received:l.parsedType,code:Be.invalid_type}),Tt}if(this._cache||(this._cache=new Set(mn.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=mn.objectValues(a);return Ge(l,{received:l.data,code:Be.invalid_enum_value,options:o}),Tt}return Xa(t.data)}get enum(){return this._def.values}}O4.create=(e,t)=>new O4({values:e,typeName:kt.ZodNativeEnum,...Pt(t)});class up extends rn{unwrap(){return this._def.type}_parse(t){const{ctx:a}=this._processInputParams(t);if(a.parsedType!==nt.promise&&a.common.async===!1)return Ge(a,{code:Be.invalid_type,expected:nt.promise,received:a.parsedType}),Tt;const l=a.parsedType===nt.promise?a.data:Promise.resolve(a.data);return Xa(l.then(o=>this._def.type.parseAsync(o,{path:a.path,errorMap:a.common.contextualErrorMap})))}}up.create=(e,t)=>new up({type:e,typeName:kt.ZodPromise,...Pt(t)});class Gu extends rn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===kt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:a,ctx:l}=this._processInputParams(t),o=this._def.effect||null,u={addIssue:f=>{Ge(l,f),f.fatal?a.abort():a.dirty()},get path(){return l.path}};if(u.addIssue=u.addIssue.bind(u),o.type==="preprocess"){const f=o.transform(l.data,u);if(l.common.async)return Promise.resolve(f).then(async m=>{if(a.value==="aborted")return Tt;const y=await this._def.schema._parseAsync({data:m,path:l.path,parent:l});return y.status==="aborted"?Tt:y.status==="dirty"||a.value==="dirty"?kf(y.value):y});{if(a.value==="aborted")return Tt;const m=this._def.schema._parseSync({data:f,path:l.path,parent:l});return m.status==="aborted"?Tt:m.status==="dirty"||a.value==="dirty"?kf(m.value):m}}if(o.type==="refinement"){const f=m=>{const y=o.refinement(m,u);if(l.common.async)return Promise.resolve(y);if(y instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return m};if(l.common.async===!1){const m=this._def.schema._parseSync({data:l.data,path:l.path,parent:l});return m.status==="aborted"?Tt:(m.status==="dirty"&&a.dirty(),f(m.value),{status:a.value,value:m.value})}else return this._def.schema._parseAsync({data:l.data,path:l.path,parent:l}).then(m=>m.status==="aborted"?Tt:(m.status==="dirty"&&a.dirty(),f(m.value).then(()=>({status:a.value,value:m.value}))))}if(o.type==="transform")if(l.common.async===!1){const f=this._def.schema._parseSync({data:l.data,path:l.path,parent:l});if(!Wu(f))return Tt;const m=o.transform(f.value,u);if(m instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:m}}else return this._def.schema._parseAsync({data:l.data,path:l.path,parent:l}).then(f=>Wu(f)?Promise.resolve(o.transform(f.value,u)).then(m=>({status:a.value,value:m})):Tt);mn.assertNever(o)}}Gu.create=(e,t,a)=>new Gu({schema:e,typeName:kt.ZodEffects,effect:t,...Pt(a)});Gu.createWithPreprocess=(e,t,a)=>new Gu({schema:t,effect:{type:"preprocess",transform:e},typeName:kt.ZodEffects,...Pt(a)});class ao extends rn{_parse(t){return this._getType(t)===nt.undefined?Xa(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ao.create=(e,t)=>new ao({innerType:e,typeName:kt.ZodOptional,...Pt(t)});class Yu extends rn{_parse(t){return this._getType(t)===nt.null?Xa(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Yu.create=(e,t)=>new Yu({innerType:e,typeName:kt.ZodNullable,...Pt(t)});class g0 extends rn{_parse(t){const{ctx:a}=this._processInputParams(t);let l=a.data;return a.parsedType===nt.undefined&&(l=this._def.defaultValue()),this._def.innerType._parse({data:l,path:a.path,parent:a})}removeDefault(){return this._def.innerType}}g0.create=(e,t)=>new g0({innerType:e,typeName:kt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Pt(t)});class _0 extends rn{_parse(t){const{ctx:a}=this._processInputParams(t),l={...a,common:{...a.common,issues:[]}},o=this._def.innerType._parse({data:l.data,path:l.path,parent:{...l}});return ip(o)?o.then(u=>({status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new Vr(l.common.issues)},input:l.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Vr(l.common.issues)},input:l.data})}}removeCatch(){return this._def.innerType}}_0.create=(e,t)=>new _0({innerType:e,typeName:kt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Pt(t)});class I4 extends rn{_parse(t){if(this._getType(t)!==nt.nan){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.nan,received:l.parsedType}),Tt}return{status:"valid",value:t.data}}}I4.create=e=>new I4({typeName:kt.ZodNaN,...Pt(e)});class Fj extends rn{_parse(t){const{ctx:a}=this._processInputParams(t),l=a.data;return this._def.type._parse({data:l,path:a.path,parent:a})}unwrap(){return this._def.type}}class o_ extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.common.async)return(async()=>{const u=await this._def.in._parseAsync({data:l.data,path:l.path,parent:l});return u.status==="aborted"?Tt:u.status==="dirty"?(a.dirty(),kf(u.value)):this._def.out._parseAsync({data:u.value,path:l.path,parent:l})})();{const o=this._def.in._parseSync({data:l.data,path:l.path,parent:l});return o.status==="aborted"?Tt:o.status==="dirty"?(a.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:l.path,parent:l})}}static create(t,a){return new o_({in:t,out:a,typeName:kt.ZodPipeline})}}class y0 extends rn{_parse(t){const a=this._def.innerType._parse(t),l=o=>(Wu(o)&&(o.value=Object.freeze(o.value)),o);return ip(a)?a.then(o=>l(o)):l(a)}unwrap(){return this._def.innerType}}y0.create=(e,t)=>new y0({innerType:e,typeName:kt.ZodReadonly,...Pt(t)});var kt;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(kt||(kt={}));const E=Wr.create,We=Ku.create,At=f0.create,qj=h0.create;ro.create;const at=er.create,Ae=fs.create;lp.create;op.create;uc.create;const dp=cp.create,oo=p0.create,vt=Qu.create;up.create;ao.create;Yu.create;const p6=vt(["codex","claude"]),Wj=vt(["managed","attached-live","history-only"]),Kj=vt(["active","idle","attention","offline"]),g6=vt(["idle","running","completed"]),_6=vt(["image","file"]),Qj=vt(["user","repo","system","admin"]),Gj=Ae({can_stream_live:At(),can_send_input:At(),can_interrupt:At(),can_approve:At(),can_reject:At(),can_show_git:At(),can_show_terminal:At()}),y6=Ae({used_tokens:We(),total_tokens:We(),remaining_tokens:We(),percent_used:We(),cached_input_tokens:We(),output_tokens:We(),reasoning_output_tokens:We(),updated_at:E()}),Yj=vt(["pending","in_progress","completed"]),Vj=Ae({id:E(),step:E(),status:Yj}),c_=Ae({session_id:E(),turn_id:E().nullable(),source:vt(["rollout","app-server"]),updated_at:E(),explanation:E().nullable().default(null),steps:at(Vj),completed_count:We().int().nonnegative(),total_count:We().int().nonnegative(),is_active:At()}),Zj=Ae({parent_session_id:E(),root_session_id:E().nullable().default(null),nickname:E().nullable().default(null),role:E().nullable().default(null),depth:We().int().nonnegative()}),Xj=vt(["user_input","command_execution_approval","file_change_approval","permissions_approval","mcp_elicitation"]),Jj=vt(["pending","submitting","resolved"]),v6=Ae({id:E(),label:E(),description:E().nullable().default(null),emphasis:vt(["default","primary","danger"]).default("default")}),ew=Ae({id:E(),header:E().nullable().default(null),question:E(),options:at(v6).default([]),allow_other:At().default(!1),is_secret:At().default(!1)}),u_=Ae({id:E(),session_id:E(),turn_id:E().nullable().default(null),item_id:E().nullable().default(null),kind:Xj,status:Jj,title:E(),description:E().nullable().default(null),created_at:E(),updated_at:E(),options:at(v6).default([]),questions:at(ew).default([]),allow_freeform:At().default(!1),freeform_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null)}),tw=Ae({id:E(),kind:_6,name:E().nullable().default(null),mime_type:E().nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null),content_url:E().nullable().default(null)}),L4=Ae({id:E(),kind:_6,name:E(),mime_type:E().nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null),data_url:E()}),nw=Ae({name:E(),description:E(),path:E(),scope:Qj,enabled:At()}),sw=vt(["supported","unsupported"]),aw=Ae({name:E(),description:E(),availability:sw.default("supported")}),P4=Ae({cli_version:E().nullable().default(null),loaded_at:E(),cache_ttl_ms:We().int().nonnegative(),commands:at(aw)});Ae({id:E(),label:E(),description:E(),isDefault:At(),defaultReasoningEffort:E().nullable().default(null),supportedReasoningEfforts:at(E()).default([])});const iw=vt(["running","awaiting_input","completed","failed"]),rw=vt(["none","choice","text"]),lw=Ae({id:E(),label:E(),description:E().nullable().default(null)}),ow=Ae({type:oo("set_session_model"),model:E(),reasoning_effort:E().nullable().default(null)}).nullable().default(null),cw=Ae({panel_id:E(),session_id:E(),command_name:E(),command_text:E(),title:E(),description:E().nullable().default(null),status:iw,body:E(),submitted_at:E(),updated_at:E(),input_type:rw,options:at(lw).default([]),input_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null),effect:ow}),U4=Ae({panel:cw}),uw=vt(["online","offline"]),Rp=Ae({id:E(),name:E(),display_name:E().nullable().default(null),host:E(),tailscale_ip:E().nullable().default(null),tailscale_dns_name:E().nullable().default(null),direct_base_url:E(),ws_base_url:E(),status:uw,provider_availability:at(p6),project_count:We(),session_count:We(),transport:vt(["direct-agent","hub-routed"]),version:E().nullable().default(null),registered_at:E().nullable().default(null),last_seen_at:E().nullable().default(null)}),d_=Ae({id:E(),agent_id:E(),name:E(),display_name:E().nullable(),pinned:At(),path:E(),branch:E(),worktree:E(),runtime_profiles:at(E()),preview_url:E().nullable()}),oh=Ae({id:E(),agent_id:E(),project_id:E(),provider:p6,archived:At(),title:E(),mode:Wj,health:Kj,branch:E(),worktree:E(),summary:E(),latest_assistant_message:E().nullable().default(null),last_event_at:E(),pinned:At(),run_state:g6,run_state_changed_at:E().nullable(),context_usage:y6.nullable().default(null),subagent:Zj.nullable().default(null),capability:Gj}),dw=Ae({path:E(),additions:We(),deletions:We()}),fw=Ae({files:at(dw),additions:We(),deletions:We()}),Kf=Ae({id:E(),kind:vt(["user","assistant","thinking","tool","system"]),title:E(),body:E(),body_truncated:At().default(!1),detail_available:At().default(!1),patch_summary:fw.nullable().default(null),session_ids:at(E()).default([]),timestamp:E(),accent:vt(["primary","secondary","muted"]),attachments:at(tw).default([])}),hw=vt(["tail","full_compact"]),b6=Ae({session_id:E(),generated_at:E(),view:hw,anchor_entry_id:E().nullable().default(null),has_earlier_entries:At().default(!1),entries:at(Kf)}),mw=vt(["app-server","rollout-fallback"]),pw=vt(["running","completed"]),gw=vt(["add","delete","update"]),f_=Ae({path:E(),kind:gw,move_path:E().nullable(),additions:We(),deletions:We(),diff:E(),item_id:E().nullable()}),_w=f_.omit({diff:!0}).extend({diff_available:At().default(!1)}),x6=Ae({id:E(),session_id:E(),turn_id:E(),source:mw,status:pw,started_at:E(),completed_at:E().nullable(),updated_at:E(),aggregated_diff:E(),files:at(f_)}),S6=x6.omit({aggregated_diff:!0,files:!0}).extend({aggregated_diff_available:At().default(!1),files:at(_w)}),yw=Ae({session_id:E(),change_set_id:E(),file:f_,empty_message:E().default("此变更没有可展示的补丁内容")}),vw=Ae({path:E(),status:vt(["modified","added","deleted","renamed"]),additions:We(),deletions:We()}),j6=vt(["modified","added","deleted","renamed","untracked"]),bw=Ae({path:E(),previous_path:E().nullable().default(null),status:j6,additions:We().int().nonnegative(),deletions:We().int().nonnegative()}),xw=Ae({session_id:E(),project_id:E(),path:E(),previous_path:E().nullable().default(null),additions:We().int().nonnegative(),deletions:We().int().nonnegative(),diff:E()}),h_=Ae({session_id:E(),project_id:E(),branch:E(),branches:at(E()),upstream_branch:E().nullable().default(null),ahead_count:We().int().nonnegative(),behind_count:We().int().nonnegative(),files:at(bw),updated_at:E()}),Sw=Ae({path:E(),previous_path:E().nullable().default(null),status:j6}),jw=Ae({oid:E(),short_oid:E(),subject:E(),author_name:E(),authored_at:E(),committed_at:E(),parent_oids:at(E()).default([]),refs:at(E()).default([]),files:at(Sw)}),ww=Ae({session_id:E(),project_id:E(),commit_oid:E(),path:E(),previous_path:E().nullable().default(null),additions:We().int().nonnegative(),deletions:We().int().nonnegative(),diff:E()}),Nw=Ae({session_id:E(),project_id:E(),branch:E(),upstream_branch:E().nullable().default(null),head_oid:E().nullable().default(null),upstream_head_oid:E().nullable().default(null),commits:at(jw),updated_at:E()});vt(["discard-file","discard-all","commit-all","switch-branch","push"]);const kw=Ae({ok:oo(!0),workspace:h_});vt(["rollback"]);const Ew=Ae({ok:oo(!0),turn_id:E(),change_set_id:E(),workspace:h_}),Cw=vt(["directory","file"]),w6=vt(["markdown","code","text","image","binary"]),Tw=Ae({path:E(),name:E(),kind:Cw,has_children:At(),extension:E().nullable().default(null),file_kind:w6.nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null)}),Rw=Ae({session_id:E(),project_id:E(),root_path:E(),parent_path:E().nullable().default(null),nodes:at(Tw),loaded_at:E()}),Mw=Ae({session_id:E(),project_id:E(),path:E(),name:E(),extension:E().nullable().default(null),file_kind:w6,mime_type:E().nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null),encoding:vt(["utf8","base64"]).nullable().default(null),is_truncated:At(),content_text:E().nullable().default(null),content_base64:E().nullable().default(null),loaded_at:E()}),N6=vt(["auto","powershell","cmd","bash"]),Aw=vt(["user","codex"]),Dw=Ae({id:E(),name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:N6.default("auto"),node_version:E().nullable().default(null),port:We().int().positive().nullable().default(null),source:Aw.default("user"),created_at:E(),updated_at:E()}),Ow=Ae({name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:N6.default("auto"),node_version:E().nullable().default(null),port:We().int().positive().nullable().default(null)}),m_=Ae({session_id:E(),project_id:E(),config_path:E(),commands:at(Dw),updated_at:E()}),Iw=vt(["user","codex"]),Lw=Ae({id:E(),name:E(),description:E().nullable().default(null),url:E(),source:Iw.default("user"),created_at:E(),updated_at:E()}),Pw=Ae({name:E(),description:E().nullable().default(null),url:E()}),p_=Ae({session_id:E(),project_id:E(),config_path:E(),websites:at(Lw),updated_at:E()}),Uw=vt(["queued","running","completed","failed","stopped"]),zw=vt(["stdout","stderr","system"]),Bw=Ae({cursor:We().int().nonnegative(),stream:zw,text:E(),timestamp:E()}),g_=Ae({id:E(),session_id:E(),project_id:E(),command_id:E().nullable().default(null),title:E(),command:E(),cwd:E(),status:Uw,exit_code:We().int().nullable().default(null),created_at:E(),started_at:E().nullable().default(null),completed_at:E().nullable().default(null),updated_at:E(),last_output_at:E().nullable().default(null),output_cursor:We().int().nonnegative(),preview:E().nullable().default(null)}),__=Ae({session_id:E(),project_id:E(),active_terminal_id:E().nullable().default(null),terminals:at(g_),updated_at:E()}),Hw=Ae({session_id:E(),project_id:E(),terminal:g_,chunks:at(Bw),next_cursor:We().int().nonnegative(),truncated:At().default(!1)}),k6=Ae({run_state:g6.optional(),run_state_changed_at:E().nullable().optional(),summary:E().optional(),latest_assistant_message:E().nullable().optional(),last_event_at:E().optional(),context_usage:y6.nullable().optional()}),$w=Ae({session_id:E(),recovered_at:E(),session_patch:k6,timeline:at(Kf),interactions:at(u_),plan_snapshot:c_.nullable().default(null),change_sets:at(x6),terminal_snapshot:__.nullable().default(null)}),E6=Ae({manager:vt(["none","nvm-windows"]).default("none"),versions:at(E()).default([]),error:E().nullable().default(null)}),C6=Ae({command_catalog:m_,website_catalog:p_,node_runtime:E6,terminal_snapshot:__}),Fw=Ae({session_id:E(),generated_at:E(),session_patch:k6,timeline:b6,interactions:at(u_),plan_snapshot:c_.nullable().default(null),run_workbench:C6.nullable().default(null),change_sets:at(S6).default([])}),qw=Ae({catalog:m_}),Ww=Ae({catalog:p_}),Kw=Ae({commands:at(Ow),reason:E().nullable().default(null)}),Qw=Ae({generation:Kw,catalog:m_}),Gw=Ae({websites:at(Pw),reason:E().nullable().default(null)}),Yw=Ae({generation:Gw,catalog:p_}),Vw=Ae({snapshot:__,terminal:g_.nullable().default(null)}),Zw=vt(["dev-hub","dev-agent","dev-web","release-hub","release-agent"]),Xw=vt(["unknown","running","stopped","degraded"]),Jw=vt(["process","windows-service"]),eN=vt(["missing","running","stopped","unknown"]),tN=vt(["dev-start","dev-restart","dev-stop","dev-probe","npm-publish","release-service-install","release-service-uninstall","release-install-package","release-restart","release-install-run","apk-build"]),nN=vt(["running","succeeded","failed"]),sN=vt(["info","success","warn","error"]),T6=Ae({repo_path:E().nullable().default(null),nvm_version:E().nullable().default(null),dev_hub_port:We().int().positive().nullable().default(null),dev_hub_args:E().default(""),dev_agent_port:We().int().positive().nullable().default(null),dev_agent_hub_url:E().default(""),dev_agent_direct_base_url:E().default(""),dev_agent_ws_base_url:E().default(""),dev_agent_name:E().default(""),dev_agent_args:E().default(""),dev_web_port:We().int().positive().nullable().default(null),dev_web_hub_url:E().default(""),dev_web_args:E().default(""),release_hub_port:We().int().positive().nullable().default(null),release_hub_service_name:E().default("PandaHub"),release_hub_args:E().default(""),release_agent_port:We().int().positive().nullable().default(null),release_agent_service_name:E().default("PandaAgent"),release_agent_hub_url:E().default(""),release_agent_direct_base_url:E().default(""),release_agent_ws_base_url:E().default(""),release_agent_name:E().default(""),release_agent_args:E().default(""),updated_at:E().nullable().default(null)}),aN=T6.extend({npm_token:E().nullable().default(null),clear_npm_token:At().default(!1)}),iN=Ae({has_npm_token:At(),npm_token_hint:E().nullable().default(null)}),rN=Ae({checked_at:E(),url:E().nullable().default(null),ok:At(),status_code:We().int().nullable().default(null),duration_ms:We().int().nonnegative().nullable().default(null),message:E().nullable().default(null)}),lN=Ae({key:Zw,label:E(),status:Xw,manager:Jw.default("process"),service_name:E().nullable().default(null),service_registered:At().default(!1),service_status:eN.nullable().default(null),configured_port:We().int().positive().nullable().default(null),detected_pids:at(We().int().positive()).default([]),probe:rN.nullable().default(null)}),oN=Ae({id:E(),timestamp:E(),level:sN,message:E()}),R6=Ae({id:E(),kind:tN,title:E(),status:nN,created_at:E(),started_at:E().nullable().default(null),finished_at:E().nullable().default(null),summary:E().nullable().default(null),error:E().nullable().default(null),disconnect_expected:At().default(!1),logs:at(oN).default([])}),cN=Ae({artifact_id:E(),file_name:E(),size_bytes:We().int().nonnegative(),built_at:E(),published_at:E().nullable().default(null),version_name:E().nullable().default(null),version_code:We().int().nullable().default(null),download_path:E()}),v0=Ae({generated_at:E(),config:T6,credentials:iN,node_runtime:E6,services:at(lN),current_version:E().nullable().default(null),apk_artifact:cN.nullable().default(null),jobs:at(R6).default([])});Ae({action:vt(["start-development","restart-development","stop-development","probe-development","publish-npm","install-release-services","uninstall-release-services","install-latest-release-package","restart-release-services","install-latest-release","build-apk"])});const uN=Ae({ok:oo(!0),snapshot:v0,job:R6.nullable().default(null)}),dN=Ae({id:E(),name:E(),command:E(),port:We().nullable(),status:vt(["running","stopped","degraded"]),log_excerpt:E()}),fN=Ae({id:E(),label:E(),url:E(),status:vt(["ready","starting","stopped"])}),M6=Ae({path:E(),name:E(),has_children:At()}),hN=Ae({directory:M6}),mN=Ae({id:E(),title:E(),description:E(),status:vt(["pending","approved","rejected"])}),pN=Ae({project_id:E(),visible_session_count:We().int().nonnegative(),archived_session_count:We().int().nonnegative(),hidden_history_count:We().int().nonnegative()}),gN=d_.pick({id:!0,agent_id:!0,name:!0,display_name:!0,pinned:!0,path:!0}),_N=Rp.pick({id:!0,name:!0,display_name:!0,status:!0}),A6=oh.pick({id:!0,agent_id:!0,project_id:!0,archived:!0,title:!0,last_event_at:!0,pinned:!0,run_state:!0,run_state_changed_at:!0,subagent:!0}),yN=oh.pick({id:!0,agent_id:!0,project_id:!0,archived:!0,title:!0,provider:!0,mode:!0,health:!0,branch:!0,worktree:!0,summary:!0,latest_assistant_message:!0,last_event_at:!0,pinned:!0,run_state:!0,run_state_changed_at:!0,context_usage:!0,subagent:!0,capability:!0}),vN=Ae({generated_at:E(),session:yN}),bN=Ae({generated_at:E(),agents:at(Rp)}),xN=oh.pick({id:!0,title:!0,run_state:!0,run_state_changed_at:!0,latest_assistant_message:!0}),SN=Ae({generated_at:E(),recent_sessions:at(xN)}),jN=Ae({session_id:E(),agent_id:E(),project_id:E(),direct_base_url:E(),ws_base_url:E()}),wN=Ae({generated_at:E(),agent:_N.nullable().default(null),projects:at(gN),project_stats:at(pN).default([]),sessions:at(A6),active_session_id:E()}),D6=vt(["archived","history"]),NN=Ae({bucket:D6,project_id:E().nullable().default(null),sessions:at(A6),next_cursor:E().nullable().default(null),total_count:We().int().nonnegative()}),kN=Ae({session_id:E(),entry_id:E(),command_entry:Kf,output_entries:at(Kf).default([])}),EN=Ae({generated_at:E(),agents:at(Rp),projects:at(d_),sessions:at(oh),active_session_id:E(),timeline:at(Kf),changed_files:at(vw),runtime_processes:at(dN),previews:at(fN),approvals:at(mN)});Ae({agent:Rp,projects:at(d_),sessions:at(oh),active_session_id:E().default(""),generated_at:E()});const z4=Ae({ok:oo(!0),agent_id:E(),heartbeat_interval_ms:We().int().positive(),heartbeat_timeout_ms:We().int().positive(),registered_at:E(),received_at:E()}),CN=vt(["rename","delete"]);Ae({action:CN,display_name:E().nullable().default(null)});const TN=Ae({ok:oo(!0)}),y_=Ae({completion_notifications_enabled:At().default(!1)}),RN=Ae({p256dh:E(),auth:E()}),MN=Ae({endpoint:E().url(),expirationTime:We().nullable().default(null),keys:RN}),AN=Ae({label:E().nullable().default(null),user_agent:E().nullable().default(null)});Ae({subscription:MN,settings:y_.default({}),device:AN.default({})});const DN=Ae({endpoint:E().url()}),ON=Ae({endpoint:E().url()}),IN=Ae({supported:At(),vapid_public_key:E().nullable().default(null),subject:E().nullable().default(null),reason:E().nullable().default(null)}),LN=Ae({ok:oo(!0),subscription_id:E(),endpoint:E().url(),settings:y_,created_at:E(),updated_at:E()}),PN=Ae({ok:oo(!0),endpoint:E().url(),delivered_at:E()}),UN=Ae({type:vt(["agent.online","agent.offline","snapshot.changed","session.updated","thread.updated","timeline.delta","timeline.reset","interaction.delta","interaction.reset","plan.delta","plan.reset","changeset.delta","changeset.reset","terminal.snapshot","terminal.delta","turn.delta","turn.completed","approval.requested"]),timestamp:E(),payload:dp(qj())}),zN=Ae({width:We().nonnegative(),height:We().nonnegative(),device_pixel_ratio:We().nonnegative(),visual_width:We().nonnegative().nullable().default(null),visual_height:We().nonnegative().nullable().default(null),screen_width:We().nonnegative().nullable().default(null),screen_height:We().nonnegative().nullable().default(null)}),BN=Ae({user_agent:E(),language:E().nullable().default(null),languages:at(E()).default([]),platform:E().nullable().default(null),vendor:E().nullable().default(null),online:At().nullable().default(null),cookie_enabled:At().nullable().default(null),secure_context:At(),standalone_display_mode:At(),hardware_concurrency:We().int().nonnegative().nullable().default(null),device_memory_gb:We().nonnegative().nullable().default(null),max_touch_points:We().int().nonnegative().nullable().default(null)}),HN=Ae({href:E(),pathname:E(),referrer:E().nullable().default(null),visibility_state:E().nullable().default(null)}),$N=Ae({scope:E(),active_script_url:E().nullable().default(null),waiting_script_url:E().nullable().default(null),installing_script_url:E().nullable().default(null)}),FN=Ae({supported:At(),controller:At(),registrations:at($N).default([])}),qN=Ae({supported:At(),keys:at(E()).default([])}),WN=Ae({href:E().nullable().default(null),rel:E().nullable().default(null)}),KN=Ae({href:E().nullable().default(null),owner_node:E().nullable().default(null),media:E().nullable().default(null),disabled:At(),css_rule_count:We().int().nonnegative().nullable().default(null)}),QN=Ae({url:E(),kind:vt(["stylesheet","script","manifest","icon","other"]),ok:At(),status:We().int().nonnegative().nullable().default(null),content_type:E().nullable().default(null),cache_control:E().nullable().default(null),error:E().nullable().default(null)}),GN=Ae({name:E(),initiator_type:E().nullable().default(null),duration_ms:We().nonnegative().nullable().default(null),transfer_size:We().nonnegative().nullable().default(null),decoded_body_size:We().nonnegative().nullable().default(null)}),YN=Ae({x:We(),y:We(),width:We().nonnegative(),height:We().nonnegative()}),VN=Ae({selector:E(),found:At(),text_preview:E().nullable().default(null),rect:YN.nullable().default(null),computed:dp(E()).default({})});Ae({captured_at:E(),page:HN,environment:BN,viewport:zN,feature_support:dp(At()).default({}),service_worker:FN,cache:qN,manifest:WN,stylesheets:at(KN).default([]),resource_probes:at(QN).default([]),performance_entries:at(GN).default([]),theme_variables:dp(E()).default({}),element_snapshots:at(VN).default([]),notes:at(E()).default([])});const ZN=/^(?:image|img|photo|picture|screenshot|图片|照片|截图)(?:[-_ ]?\d+)?\.(?:avif|bmp|gif|heic|heif|jpe?g|png|svg|webp)$/i,Ls=e=>(e==null?void 0:e.trim())??"",B4="\0",H4=e=>{const t=Ls(e);return t?ZN.test(t)?1:2+Math.min(t.length,64)/100:0},XN=(e,t)=>{const a=H4(e),l=H4(t);if(l>a)return Ls(t)||null;if(a>l)return Ls(e)||null;const o=Ls(e),u=Ls(t);return u.length>o.length?u||null:o||null},JN=e=>{const t=Ls(e.content_url);return t?[e.kind,"content",t].join(B4):[e.kind,"meta",Ls(e.mime_type).toLowerCase(),typeof e.size_bytes=="number"&&Number.isFinite(e.size_bytes)?String(Math.max(0,Math.round(e.size_bytes))):"",Ls(e.name).toLowerCase()].join(B4)},ek=(e,t)=>{const a=Ls(e.name),l=Ls(t.name),o=Ls(e.mime_type),u=Ls(t.mime_type);return{id:e.id||t.id,kind:e.kind==="image"||t.kind==="image"?"image":e.kind,name:XN(a,l),mime_type:o||u||null,size_bytes:e.size_bytes??t.size_bytes??null,content_url:Ls(e.content_url)||Ls(t.content_url)||null}},O6=e=>{if(!e||e.length===0)return[];const t=[],a=new Map;for(const l of e){const o=JN(l),u=a.get(o);if(u===void 0){a.set(o,t.length),t.push({...l,name:Ls(l.name)||null,mime_type:Ls(l.mime_type)||null,size_bytes:typeof l.size_bytes=="number"&&Number.isFinite(l.size_bytes)?Math.max(0,Math.round(l.size_bytes)):null,content_url:Ls(l.content_url)||null});continue}t[u]=ek(t[u],l)}return t},I6=(e,t)=>O6([...e??[],...t??[]]),ba=e=>new Date(e).toISOString(),tk=()=>({generated_at:new Date().toISOString(),active_session_id:"session-managed-1",agents:[{id:"agent-shanghai-main",name:"studio-main",display_name:null,host:"100.88.10.14",tailscale_ip:"100.88.10.14",tailscale_dns_name:"studio-main.tail-scale.ts.net",direct_base_url:"http://100.88.10.14:4242",ws_base_url:"ws://100.88.10.14:4242/ws",status:"online",provider_availability:["codex"],project_count:2,session_count:2,transport:"direct-agent",version:"0.1.0",registered_at:ba("2026-03-18T10:30:00+08:00"),last_seen_at:ba("2026-03-18T10:58:00+08:00")},{id:"agent-macbook",name:"macbook-air",display_name:null,host:"100.89.20.77",tailscale_ip:"100.89.20.77",tailscale_dns_name:"macbook-air.tail-scale.ts.net",direct_base_url:"http://100.89.20.77:4242",ws_base_url:"ws://100.89.20.77:4242/ws",status:"online",provider_availability:["codex"],project_count:1,session_count:1,transport:"hub-routed",version:"0.1.0",registered_at:ba("2026-03-18T10:20:00+08:00"),last_seen_at:ba("2026-03-18T10:55:00+08:00")}],projects:[{id:"project-panda",agent_id:"agent-shanghai-main",name:"panda",display_name:null,pinned:!1,path:"D:/ai/panda",branch:"main",worktree:"default",runtime_profiles:["dev","storybook","test"],preview_url:"https://panda.tailnet.ts.net"},{id:"project-remodex-lab",agent_id:"agent-shanghai-main",name:"remodex",display_name:null,pinned:!1,path:"D:/ai/remodex",branch:"phase1-ui",worktree:"mobile-lab",runtime_profiles:["dev"],preview_url:null},{id:"project-notes",agent_id:"agent-macbook",name:"notes",display_name:null,pinned:!1,path:"D:/Users/dev/notes",branch:"research",worktree:"default",runtime_profiles:["dev"],preview_url:null}],sessions:[{id:"session-managed-1",agent_id:"agent-shanghai-main",project_id:"project-panda",provider:"codex",archived:!1,title:"Stage 1 buildout",mode:"managed",health:"active",branch:"main",worktree:"default",summary:"Monorepo scaffold, PWA shell, agent bootstrap API",latest_assistant_message:"Wiring the shell.",last_event_at:ba("2026-03-18T10:58:00+08:00"),pinned:!1,run_state:"running",run_state_changed_at:ba("2026-03-18T10:57:20+08:00"),context_usage:null,subagent:null,capability:{can_stream_live:!0,can_send_input:!0,can_interrupt:!0,can_approve:!0,can_reject:!0,can_show_git:!0,can_show_terminal:!0}},{id:"session-live-2",agent_id:"agent-shanghai-main",project_id:"project-remodex-lab",provider:"codex",archived:!1,title:"Remote attach",mode:"attached-live",health:"idle",branch:"phase1-ui",worktree:"mobile-lab",summary:"",latest_assistant_message:null,last_event_at:ba("2026-03-18T10:48:00+08:00"),pinned:!1,run_state:"completed",run_state_changed_at:ba("2026-03-18T10:48:00+08:00"),context_usage:null,subagent:null,capability:{can_stream_live:!0,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!0,can_show_terminal:!0}},{id:"session-history-3",agent_id:"agent-macbook",project_id:"project-notes",provider:"codex",archived:!1,title:"Research notes",mode:"history-only",health:"offline",branch:"research",worktree:"default",summary:"",latest_assistant_message:null,last_event_at:ba("2026-03-17T19:12:00+08:00"),pinned:!1,run_state:"idle",run_state_changed_at:null,context_usage:null,subagent:null,capability:{can_stream_live:!1,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!0,can_show_terminal:!1}}],timeline:[{id:"entry-1",kind:"system",title:"Session ready",body:"Managed session attached.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:40:00+08:00"),accent:"muted",attachments:[]},{id:"entry-2",kind:"user",title:"Prompt",body:"Start stage one.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:44:00+08:00"),accent:"primary",attachments:[]},{id:"entry-3",kind:"thinking",title:"Plan",body:"Aligning routes and session state.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:45:30+08:00"),accent:"secondary",attachments:[]},{id:"entry-4",kind:"tool",title:"Tool activity",body:"Scanned docs/, checked runtime versions, and created the initial workspace directories.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:48:00+08:00"),accent:"secondary",attachments:[]},{id:"entry-5",kind:"assistant",title:"Focus",body:"Wiring the shell.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:58:00+08:00"),accent:"primary",attachments:[]}],changed_files:[{path:"apps/web/src/components/dashboard.tsx",status:"added",additions:248,deletions:0},{path:"packages/protocol/src/index.ts",status:"modified",additions:94,deletions:12},{path:"apps/agent/src/index.ts",status:"modified",additions:77,deletions:3}],runtime_processes:[{id:"runtime-dev",name:"dev",command:"pnpm --filter @panda/web dev --host 0.0.0.0 --port 4173",port:4173,status:"running",log_excerpt:"Vite server ready on 0.0.0.0:4173 and previewed over the tailnet."},{id:"runtime-agent",name:"agent",command:"pnpm --filter @panda/agent dev",port:4242,status:"running",log_excerpt:"Fastify listening on http://0.0.0.0:4242 with WebSocket events enabled."}],previews:[{id:"preview-main",label:"PWA preview",url:"https://panda.tailnet.ts.net",status:"ready"},{id:"preview-storybook",label:"Design lab",url:"https://storybook.tailnet.ts.net",status:"starting"}],approvals:[{id:"approval-1",title:"Write workspace files",description:"Create monorepo config, React app shell, and Fastify agent entrypoints.",status:"approved"},{id:"approval-2",title:"Attach external Codex session",description:"External session controls remain experimental until app-server transport is available.",status:"pending"}]}),nk=()=>tk(),sk=()=>nk(),L6=e=>{const t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.pathname="/ws",t.toString()};class ak{constructor(t,a=L6(t)){this.baseUrl=t,this.wsBaseUrl=a}getConnectionKey(){return`${this.baseUrl}::${this.wsBaseUrl}`}async readJson(t,a){const l=await fetch(t);if(!l.ok)throw new Error(`Request failed with ${l.status}`);return a.parse(await l.json())}async postJson(t,a,l){const o=await fetch(new URL(t,this.baseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a)}),u=await o.json().catch(()=>null);if(!o.ok)throw new Error((u==null?void 0:u.error)??`Request failed with ${o.status}`);return l?l.parse(u):u}async getPhaseOneSnapshot(t){const{fallbackToMock:a=!0,fallbackSnapshot:l=sk}=t??{};try{const o=await fetch(new URL("/api/bootstrap",this.baseUrl));if(!o.ok)throw new Error(`Bootstrap request failed with ${o.status}`);const u=await o.json();return EN.parse(u)}catch(o){if(!a)throw o;return l()}}async getHubDirectory(){return this.readJson(new URL("/api/hub/directory",this.baseUrl),bN)}async getHubRecentSessions(){return this.readJson(new URL("/api/hub/recent-sessions",this.baseUrl),SN)}async getSessionLocation(t){return this.readJson(new URL(`/api/sessions/${t}/location`,this.baseUrl),jN)}async getWorkspaceDirectory(t){const a=new URL("/api/workspace",this.baseUrl);return t!=null&&t.selectedSessionId&&a.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(a,wN)}async getWorkspaceSessionPage(t){const a=new URL("/api/workspace/sessions",this.baseUrl);return a.searchParams.set("bucket",D6.parse(t.bucket)),t.projectId&&a.searchParams.set("projectId",t.projectId),t.cursor&&a.searchParams.set("cursor",t.cursor),typeof t.limit=="number"&&Number.isFinite(t.limit)&&a.searchParams.set("limit",String(Math.max(1,Math.floor(t.limit)))),t.selectedSessionId&&a.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(a,NN)}async getWorkspaceSessionDetail(t){const a=new URL("/api/workspace/session-detail",this.baseUrl);return a.searchParams.set("sessionId",t),this.readJson(a,vN)}async getSessionTimeline(t,a){const l=new URL(`/api/sessions/${t}/timeline`,this.baseUrl);return a!=null&&a.view&&l.searchParams.set("view",a.view),this.readJson(l,b6)}async getSessionChangeSets(t){return this.readJson(new URL(`/api/sessions/${t}/change-sets`,this.baseUrl),{parse:a=>Array.isArray(a)?a.map(l=>S6.parse(l)):[]})}async getSessionBootstrap(t){return this.readJson(new URL(`/api/sessions/${t}/bootstrap`,this.baseUrl),Fw)}async getSessionToolCallDetail(t,a){const l=new URL(`/api/sessions/${t}/tool-detail`,this.baseUrl);return l.searchParams.set("entryId",a),this.readJson(l,kN)}async getSessionChangeSetFileDiff(t,a){const l=new URL(`/api/sessions/${t}/change-set-file-diff`,this.baseUrl);return l.searchParams.set("changeSetId",a.changeSetId),l.searchParams.set("path",a.path),a.itemId&&l.searchParams.set("itemId",a.itemId),this.readJson(l,yw)}async getSessionGitWorkspace(t){return this.readJson(new URL(`/api/sessions/${t}/git-workspace`,this.baseUrl),h_)}async getSessionGitWorkspaceFileDiff(t,a){const l=new URL(`/api/sessions/${t}/git-workspace/file-diff`,this.baseUrl);return l.searchParams.set("path",a.path),a.previousPath&&l.searchParams.set("previousPath",a.previousPath),this.readJson(l,xw)}async getSessionGitHistory(t){return this.readJson(new URL(`/api/sessions/${t}/git/history`,this.baseUrl),Nw)}async getSessionFilePreviewTree(t,a){var u;const l=new URL(`/api/sessions/${t}/file-preview/tree`,this.baseUrl),o=(u=a==null?void 0:a.path)==null?void 0:u.trim();return o&&l.searchParams.set("path",o),this.readJson(l,Rw)}async getSessionFilePreviewContent(t,a){const l=new URL(`/api/sessions/${t}/file-preview/content`,this.baseUrl);return l.searchParams.set("path",a.path),this.readJson(l,Mw)}async getSessionGitHistoryFileDiff(t,a){const l=new URL(`/api/sessions/${t}/git/history/file-diff`,this.baseUrl);return l.searchParams.set("commitOid",a.commitOid),l.searchParams.set("path",a.path),a.previousPath&&l.searchParams.set("previousPath",a.previousPath),this.readJson(l,ww)}async getSessionRunWorkbench(t){return this.readJson(new URL(`/api/sessions/${t}/run-workbench`,this.baseUrl),C6)}async saveSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands`,{action:t.action,commandId:t.commandId??null,command:t.command??null},qw)}async generateSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands/generate`,{prompt:t.prompt,model:t.model},Qw)}async saveSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites`,{action:t.action,websiteId:t.websiteId??null,website:t.website??null},Ww)}async generateSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites/generate`,{prompt:t.prompt,model:t.model},Yw)}async executeSessionTerminalAction(t){return this.postJson(`/api/sessions/${t.sessionId}/terminals`,{action:t.action,commandId:t.commandId??null,terminalId:t.terminalId??null},Vw)}async getSessionTerminalOutput(t){const a=new URL(`/api/sessions/${t.sessionId}/terminals/${t.terminalId}/output`,this.baseUrl);return typeof t.cursor=="number"&&Number.isFinite(t.cursor)&&a.searchParams.set("cursor",String(Math.max(0,Math.floor(t.cursor)))),this.readJson(a,Hw)}async getSessionPlan(t){return this.readJson(new URL(`/api/sessions/${t}/plan`,this.baseUrl),{parse:a=>a==null?null:c_.parse(a)})}async getSessionInteractions(t){return this.readJson(new URL(`/api/sessions/${t}/interactions`,this.baseUrl),{parse:a=>Array.isArray(a)?a.map(l=>u_.parse(l)):[]})}async getSessionRecoverySnapshot(t){return this.readJson(new URL(`/api/sessions/${t}/recovery`,this.baseUrl),$w)}async getProjectSkills(t){return this.readJson(new URL(`/api/projects/${t}/skills`,this.baseUrl),{parse:a=>Array.isArray(a)?a.map(l=>nw.parse(l)):[]})}async getCodexCommands(){return this.readJson(new URL("/api/codex/commands",this.baseUrl),P4)}async refreshCodexCommands(){return this.postJson("/api/codex/commands/refresh",{},P4)}async listDirectories(t){const a=new URL("/api/directories",this.baseUrl);return t.agentId&&a.searchParams.set("agentId",t.agentId),t.path&&a.searchParams.set("path",t.path),this.readJson(a,{parse:l=>Array.isArray(l)?l.map(o=>M6.parse(o)):[]})}async createDirectory(t){return this.postJson("/api/directories",t,hN)}async createProject(t){return this.postJson("/api/projects",t)}async createSession(t){var a;return this.postJson("/api/sessions",{...t,attachments:(a=t.attachments)==null?void 0:a.map(l=>L4.parse(l)),serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async updateSession(t){return this.postJson(`/api/sessions/${t.sessionId}/actions`,{action:t.action,name:t.name})}async updateThread(t){return this.postJson(`/api/threads/${t.projectId}/actions`,{action:t.action,name:t.name,orderedProjectIds:t.orderedProjectIds})}async sendSessionInput(t){var a;return this.postJson(`/api/sessions/${t.sessionId}/input`,{input:t.input,attachments:(a=t.attachments)==null?void 0:a.map(l=>L4.parse(l)),model:t.model,reasoningEffort:t.reasoningEffort,serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async executeSessionCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/commands/execute`,{input:t.input},U4)}async respondToSessionCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/commands/respond`,{panelId:t.panelId,optionId:t.optionId??null,text:t.text??null},U4)}async respondToSessionInteraction(t){return this.postJson(`/api/sessions/${t.sessionId}/interactions/${t.requestId}/respond`,{optionId:t.optionId??null,text:t.text??null,answers:t.answers??null})}async interruptSession(t){return this.postJson(`/api/sessions/${t}/interrupt`,{})}async registerAgent(t){return this.postJson("/api/agents/register",t,z4)}async heartbeatAgent(t){return this.postJson("/api/agents/heartbeat",t,z4)}async updateAgent(t){return this.postJson(`/api/agents/${t.agentId}/actions`,{action:t.action,display_name:t.displayName??null},TN)}async getWebPushPublicConfig(){return this.readJson(new URL("/api/push/public-key",this.baseUrl),IN)}async upsertWebPushSubscription(t){return this.postJson("/api/push/subscriptions",{subscription:t.subscription,settings:y_.parse(t.settings),device:t.device??null},LN)}async removeWebPushSubscription(t){return this.postJson("/api/push/subscriptions/remove",DN.parse(t))}async sendWebPushTest(t){return this.postJson("/api/push/test",ON.parse(t),PN)}async executeSessionGitAction(t){return this.postJson(`/api/sessions/${t.sessionId}/git/actions`,{action:t.action,path:t.path,branch:t.branch,message:t.message},kw)}async executeSessionTurnAction(t){return this.postJson(`/api/sessions/${t.sessionId}/turns/${t.turnId}/actions`,{action:t.action},Ew)}async getDevManagerSnapshot(t){const a=new URL("/api/dev-manager",this.baseUrl);return t!=null&&t.includeServiceProbe&&a.searchParams.set("includeServiceProbe","1"),this.readJson(a,v0)}async saveDevManagerConfig(t){return this.postJson("/api/dev-manager/config",aN.parse(t),v0)}async executeDevManagerAction(t){return this.postJson("/api/dev-manager/actions",t,uN)}createEventStream(t,a){var xe;let m=null,y=((xe=a==null?void 0:a.sessionId)==null?void 0:xe.trim())??"",g="",S=!1,p=0,b=null,w=!1,N=!1,j=!1,T=0;const D=typeof document<"u"&&typeof document.visibilityState=="string",z=()=>D&&document.visibilityState==="hidden",I=(a==null?void 0:a.reconnectWhenHidden)===!0,k=C=>(C==null?void 0:C.readyState)===WebSocket.OPEN||(C==null?void 0:C.readyState)===WebSocket.CONNECTING,P=()=>{b!==null&&(globalThis.clearTimeout(b),b=null)},Q=(C,q)=>{var ie;(ie=a==null?void 0:a.onStatus)==null||ie.call(a,{state:C,attempt:p,maxAttempts:5,error:q})},se=C=>{const q=m;!q||q.readyState!==WebSocket.OPEN||(g&&g!==C&&(q.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g=""),!(!C||g===C)&&(g=C,q.send(JSON.stringify({type:"session.subscribe",sessionId:C}))))},W=C=>{if(S||w)return;if(!I&&z()){w=!1,j=!0,P(),Q("failed",C);return}if(p+=1,!I&&p>5){p=5,j=!0,Q("failed",C);return}w=!0,j=!1,Q("reconnecting",C),P();const q=I?Math.min(p,5):p,ie=Math.min(1e4,1200*2**Math.max(0,q-1));b=globalThis.setTimeout(()=>{w=!1,V()},ie)},V=()=>{if(S||k(m))return;P(),w=!1,j=!1;const C=new WebSocket(this.wsBaseUrl);m=C,C.addEventListener("open",()=>{S||m!==C||(w=!1,N=!1,p=0,Q("connected"),se(y))}),C.addEventListener("message",q=>{if(m!==C)return;const ie=UN.safeParse(JSON.parse(q.data));ie.success&&t(ie.data)}),C.addEventListener("error",()=>{if(S||m!==C)return;const q=`无法连接到 ${this.wsBaseUrl}`;C.readyState!==WebSocket.OPEN&&W(q)}),C.addEventListener("close",q=>{var he;if(m===C&&(m=null),S||m!==null)return;const ie=((he=q.reason)==null?void 0:he.trim())||`WebSocket 已断开(code ${q.code||"unknown"})`;W(ie)})},Y=C=>{if(S||k(m)||N)return;const q=Date.now();q-T<1500||(T=q,N=!0,p=0,w=!1,j=!1,P(),Q("reconnecting",C),V())},ee=()=>{document.visibilityState==="visible"&&(j||!k(m))&&Y("应用回到前台,正在恢复连接")},me=()=>{(j||!k(m))&&Y("页面恢复显示,正在恢复连接")},ge=()=>{(j||!k(m))&&Y("窗口重新聚焦,正在恢复连接")},te=()=>{(j||!k(m))&&Y("网络已恢复,正在重新连接")};return typeof window<"u"&&(window.addEventListener("pageshow",me),window.addEventListener("focus",ge),window.addEventListener("online",te)),typeof document<"u"&&document.addEventListener("visibilitychange",ee),V(),{setSessionId:C=>{y=(C==null?void 0:C.trim())??"",!S&&se(y)},close:()=>{S=!0,w=!1,N=!1,j=!1,P(),typeof window<"u"&&(window.removeEventListener("pageshow",me),window.removeEventListener("focus",ge),window.removeEventListener("online",te)),typeof document<"u"&&document.removeEventListener("visibilitychange",ee);const C=m;if((C==null?void 0:C.readyState)===WebSocket.OPEN&&g&&C.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g="",m=null,(C==null?void 0:C.readyState)===WebSocket.CONNECTING){const q=()=>{try{C.close()}catch{}};C.addEventListener("open",q,{once:!0});return}C==null||C.close()}}}connectEvents(t,a){const l=this.createEventStream(t,a);return()=>{l.close()}}}const P6=(e,t)=>new ak(e,(t==null?void 0:t.wsBaseUrl)??L6(e)),U6=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return null;try{const a=new URL(t);return a.port?`${a.hostname}:${a.port}`:a.hostname}catch{return t.replace(/\/+$/,"")||null}},dc=e=>{var t;return((t=e.display_name)==null?void 0:t.trim())||e.name.trim()||U6(e.direct_base_url)||"未命名节点"},ik=e=>{var a;const t=((a=e.display_name)==null?void 0:a.trim())??"";return!t||t===e.name?null:e.name},vg=e=>U6(e.direct_base_url)||e.host||e.tailscale_ip||e.tailscale_dns_name||e.direct_base_url,fp="panda:last-agent-id",hp="panda:last-session-id",Qf="panda:pending-session-id",Gf="panda:pending-project-id",Yf="panda:pending-directory-picker",Vu="panda:pending-session-handoff",Vf="panda:selected-agent-connection-hint",rk=3e4,lk=1800*1e3,Ef=e=>typeof e=="object"&&e!==null,ok=e=>{if(!Ef(e))return null;const{sessionId:t,agentId:a,projectId:l,createdAt:o,session:u,project:f,optimisticEntry:m}=e;return typeof t!="string"||typeof a!="string"||typeof l!="string"||typeof o!="string"||!Ef(u)||u.id!==t||u.agent_id!==a||u.project_id!==l||f!==null&&(!Ef(f)||f.id!==l||f.agent_id!==a||typeof f.name!="string"||typeof f.path!="string")||m!==null&&(!Ef(m)||typeof m.id!="string"||typeof m.kind!="string"||typeof m.body!="string"||typeof m.timestamp!="string")?null:{sessionId:t,agentId:a,projectId:l,createdAt:o,session:u,project:f??null,optimisticEntry:m??null}},ck=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>rk:!0},uk=e=>{if(!Ef(e))return null;const{agentId:t,name:a,displayName:l,directBaseUrl:o,wsBaseUrl:u,createdAt:f}=e;return typeof t!="string"||typeof a!="string"||l!==null&&typeof l!="string"||typeof o!="string"||typeof u!="string"||typeof f!="string"?null:{agentId:t,name:a,displayName:l,directBaseUrl:o,wsBaseUrl:u,createdAt:f}},dk=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>lk:!0},fk=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(Vu);return}window.sessionStorage.setItem(Vu,JSON.stringify(e))}catch{}},v_=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(Vu);if(!t)return null;const a=ok(JSON.parse(t));return!a||ck(a)?(window.sessionStorage.removeItem(Vu),null):e&&a.sessionId!==e?null:a}catch{return null}},hk=e=>{if(!(typeof window>"u"))try{const t=v_();if(e&&(t!=null&&t.sessionId)&&t.sessionId!==e)return;window.sessionStorage.removeItem(Vu)}catch{}},mk=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(Vf);return}window.sessionStorage.setItem(Vf,JSON.stringify(e))}catch{}},ch=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(Vf);if(!t)return null;const a=uk(JSON.parse(t));return!a||dk(a)?(window.sessionStorage.removeItem(Vf),null):e&&a.agentId!==e?null:a}catch{return null}},pc=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(fp)}catch{return null}},Ji=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(fp,e);return}window.localStorage.removeItem(fp)}catch{}},mp=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(hp)}catch{return null}},Js=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(hp,e);return}window.localStorage.removeItem(hp)}catch{}},Kr=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(Qf,e);return}window.sessionStorage.removeItem(Qf)}catch{}},pk=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(Qf);return e&&window.sessionStorage.removeItem(Qf),e}catch{return null}},ku=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(Gf,e);return}window.sessionStorage.removeItem(Gf)}catch{}},gk=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(Gf);return e&&window.sessionStorage.removeItem(Gf),e}catch{return null}},Cf=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(Yf,"1");return}window.sessionStorage.removeItem(Yf)}catch{}},_k=()=>{if(typeof window>"u")return!1;try{const e=window.sessionStorage.getItem(Yf);return e&&window.sessionStorage.removeItem(Yf),e==="1"}catch{return!1}},z6=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(fp),window.localStorage.removeItem(hp),window.sessionStorage.removeItem(Qf),window.sessionStorage.removeItem(Gf),window.sessionStorage.removeItem(Yf),window.sessionStorage.removeItem(Vu),window.sessionStorage.removeItem(Vf)}catch{}},pp=mc("Preferences",{web:()=>Zr(()=>import("./web-eR1IoQga.js"),[]).then(e=>new e.PreferencesWeb)}),yk=new Set(["4173","4174"]),vk="PandaMobile",B6="hub_url",H6="onboarding_completed",b0=new Set;let Xi={platform:qu(),hubUrl:"",onboardingCompleted:!1};const $6=()=>{for(const e of b0)e()},bk=e=>(b0.add(e),()=>{b0.delete(e)}),fc=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{return new URL(t).toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}},xk=()=>typeof window>"u"?null:window.location.origin||null,F6=e=>{if(typeof window>"u")return`http://localhost:${e}`;const t=window.location.protocol==="https:"?"https:":"http:",a=window.location.hostname||"localhost";return`${t}//${a}:${e}`},Sk=()=>fc(F6(4242)),jk=()=>{const e=fc(void 0);if(e)return e;const t=xk();if(!t)return"http://localhost:4343";const a=window.location.port.trim();return yk.has(a)?F6(4343):fc(t)},wk=()=>fc(void 0),Nk=()=>!1,kk=()=>{const e=qu();if(e==="web")return{platform:e,hubUrl:jk(),onboardingCompleted:!0};const t=wk();return{platform:e,hubUrl:t,onboardingCompleted:!!t}},$4=async e=>{if(qs()){const{value:t}=await pp.get({key:e});return t}if(typeof window>"u")return null;try{return window.localStorage.getItem(`panda:runtime:${e}`)}catch{return null}},F4=async(e,t)=>{if(qs()){if(t===null){await pp.remove({key:e});return}await pp.set({key:e,value:t});return}if(!(typeof window>"u"))try{if(t===null){window.localStorage.removeItem(`panda:runtime:${e}`);return}window.localStorage.setItem(`panda:runtime:${e}`,t)}catch{}},Ek=async()=>{const e=kk();qs()&&await pp.configure({group:vk});const[t,a]=await Promise.all([$4(B6),$4(H6)]),l=e.platform==="web"?e.hubUrl:fc(t)||e.hubUrl,o=e.platform==="web"?!0:a==="true"||!!(l&&e.onboardingCompleted);return Xi={platform:e.platform,hubUrl:l,onboardingCompleted:o},$6(),Xi},x0=()=>Xi,Ck=()=>fc(Xi.hubUrl),Tk=()=>{const e=x0();return e.platform==="web"?Nk():!e.hubUrl||!e.onboardingCompleted},q6=async e=>{const t=e.hubUrl===void 0?Xi.hubUrl:fc(e.hubUrl),a=e.onboardingCompleted??Xi.onboardingCompleted;return Xi={...Xi,hubUrl:t,onboardingCompleted:a},Xi.platform!=="web"&&await Promise.all([F4(B6,t||null),F4(H6,a?"true":"false")]),$6(),Xi},Mp=()=>_.useSyncExternalStore(bk,x0,x0),Rk=new Set(["localhost","127.0.0.1","::1"]),W6=()=>Sk(),id=()=>Ck(),q4=new Map,Mk={direct:"Agent 直连",hub:"Hub 聚合"},Ak=1e4,Dk=1e4,K6=1e4,Ok=1e4,W4=1200,K4=5e3;let zm=null,S0=0,xu=null,Eu=null,gp=0,Su=null,Bm=null,j0=0,ju=null;const w0=new Map,Hm=new Map,$m=new Map,Va=e=>(e==null?void 0:e.trim())??"",Q6=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase():""},G6=e=>Rk.has(Q6(e)),Zu=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{const a=new URL(t),l=Q6(a.hostname);return l&&(a.hostname=l),a.toString().replace(/\/+$/,"")}catch{return t}},Xu=()=>typeof window>"u"||qs()?!1:G6(window.location.hostname),Ik=e=>{const t=e.trim();if(!t)return W4;try{const a=new URL(t);return G6(a.hostname)?W4:K4}catch{return K4}},Ju=async e=>{const t=e.trim();if(!t)return!1;const a=$m.get(t),l=Date.now();if(a&&l-a.checkedAt<Ok)return a.reachable;const o=new AbortController,u=globalThis.setTimeout(()=>o.abort(),Ik(t));try{const m=(await fetch(`${t}/health`,{signal:o.signal})).ok;return $m.set(t,{reachable:m,checkedAt:Date.now()}),m}catch{return $m.set(t,{reachable:!1,checkedAt:Date.now()}),!1}finally{clearTimeout(u)}},rd=(e,t)=>{const a=`${e}::${(t==null?void 0:t.trim())??""}`,l=q4.get(a);if(l)return l;const o=P6(e,{wsBaseUrl:t});return q4.set(a,o),o},Q4=()=>rd(Y6()),G4=e=>{const t=e(Eu);Eu=t,gp=t?Date.now():0},b_=(e,t,a)=>({mode:"direct",label:e,baseUrl:t,client:rd(t,a)}),Y6=()=>{const e=id();if(!e)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");return e},Pf=e=>{const t=e==="hub"?Y6():W6();return{mode:e,label:Mk[e],baseUrl:t,client:rd(t)}},V6=e=>Zu(e.direct_base_url),Lk=e=>Zu(e.ws_base_url),Y4=e=>{const t=V6(e)||e.tailscale_dns_name||e.tailscale_ip||e.host;return`无法直连节点 ${dc(e)}(${t})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`},Pk=async()=>{if(!Xu())return null;const e=Date.now();if(Bm&&e-j0<K6)return Bm;if(ju)return ju;ju=(async()=>{const t=W6();if(!await Ju(t))return null;const a=await rd(t).getPhaseOneSnapshot({fallbackToMock:!1});return Bm=a,j0=Date.now(),a})().catch(()=>null);try{return await ju}finally{ju=null}},Z6=async e=>{var l,o;const t=await Pk(),a=((o=(l=t==null?void 0:t.agents[0])==null?void 0:l.id)==null?void 0:o.trim())??"";return!!(a&&a===e.trim())},X6=async e=>{if(await Z6(e.id))return{...Pf("direct"),label:`Agent 直连 · ${dc(e)}(本机)`};const t=V6(e),a=Lk(e);return b_(`Agent 直连 · ${dc(e)}`,t,a||void 0)},Uk=async e=>{if(await Z6(e.agent_id))return{...Pf("direct"),label:`Agent 直连 · ${e.agent_id}(本机)`};const t=Zu(e.direct_base_url),a=Zu(e.ws_base_url);return b_(`Agent 直连 · ${e.agent_id}`,t,a||void 0)},J6=e=>{var l;const t=Va(e.agentId);if(!t)return null;const a=ch(t);return a!=null&&a.directBaseUrl.trim()?b_(`Agent 直连 · ${((l=a.displayName)==null?void 0:l.trim())||a.name.trim()||t}`,Zu(a.directBaseUrl),Zu(a.wsBaseUrl)||void 0):null},V4=async e=>{const t=J6(e);if(t!=null&&t.baseUrl&&(await Ju(t.baseUrl)||!Xu()))return t;const a=await t3(),l=a?e3(a,e):null;if(!l)return null;const o=await X6(l);return o.baseUrl&&(await Ju(o.baseUrl)||!Xu())?o:null},e3=(e,t)=>{const a=Va(t.agentId);return a?e.agents.find(l=>l.id===a)??null:null},zk=e=>{const t=Va(e.sessionId),a=Va(e.projectId),l=Va(e.agentId);return l?`agent:${l}`:a?`project:${a}`:t?`session:${t}`:""},t3=async()=>{const e=Date.now();if(Eu&&e-gp<K6)return Eu;if(Su)return Su;Su=(async()=>{const t=id();if(!t)return null;const a=await rd(t).getHubDirectory();return Eu=a,gp=Date.now(),a})().catch(()=>null);try{return await Su}finally{Su=null}},Bk=async()=>{if(!Xu())return Pf("hub");const e=Date.now();if(zm&&e-S0<Ak)return zm;if(xu)return xu;xu=(async()=>{const t=id(),a=t&&await Ju(t)?Pf("hub"):Pf("direct");return zm=a,S0=Date.now(),a})();try{return await xu}finally{xu=null}},Hk=async e=>{const t=zk(e),a=Date.now(),l=t?w0.get(t):null;if(l&&a-l.cachedAt<Dk)return l.target;const o=t?Hm.get(t):null;if(o)return o;const u=(async()=>{const f=Va(e.sessionId),m=Va(e.agentId),y=J6(e),g=id();if(!g&&!y&&!m)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");const S=g?rd(g):null;if(m){const N=await V4(e);if(N)return N}if(f){const N=S?await S.getSessionLocation(f).catch(()=>null):null;if(!N){const T=m?await V4(e):null;if(T)return T;throw new Error("Hub 未返回目标会话位置,无法建立直连。")}const j=await Uk(N);if(!j.baseUrl)throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`);if(await Ju(j.baseUrl)||!Xu())return j;throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`)}if(Va(e.projectId)&&!Va(e.agentId))throw new Error("Project-scoped connection resolution now requires agentId.");const p=await t3(),b=p?e3(p,e):null;if(!b)throw new Error("Hub 未返回目标节点信息,无法建立直连。");const w=await X6(b);if(!w.baseUrl)throw new Error(Y4(b));if(await Ju(w.baseUrl)||!Xu())return w;throw new Error(Y4(b))})();t&&Hm.set(t,u);try{const f=await u;return t&&w0.set(t,{target:f,cachedAt:Date.now()}),f}finally{t&&Hm.delete(t)}},wn=async e=>!(Va(e==null?void 0:e.sessionId)||Va(e==null?void 0:e.projectId)||Va(e==null?void 0:e.agentId))?Bk():Hk(e??{}),$k=()=>{zm=null,S0=0,xu=null,Eu=null,gp=0,Su=null,Bm=null,j0=0,ju=null,w0.clear(),Hm.clear(),$m.clear()},n3="panda:notification-settings",s3="panda:notified-completions",x_="panda:web-push-subscription-state",Fk=280,a3="session-completions",bg={completionNotificationsEnabled:!1};let Zf=qs()?"default":"unsupported";const uh=()=>{const e=id();if(!e)throw new Error("尚未配置 Panda Hub 地址。");return P6(e)},i3=e=>({completionNotificationsEnabled:(e==null?void 0:e.completionNotificationsEnabled)===!0}),qk=(e,t)=>e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`,r3=()=>{if(typeof window>"u")return{};try{const e=window.localStorage.getItem(s3);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(a=>typeof a[0]=="string"&&typeof a[1]=="string"))}catch{return{}}},Wk=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(s3,JSON.stringify(e))}catch{}},Kk=e=>{if(!e||typeof e!="object")return null;const t=typeof e.endpoint=="string"?e.endpoint.trim():"",a=typeof e.updatedAt=="string"?e.updatedAt.trim():"";return!t||!a?null:{completionNotificationsEnabled:e.completionNotificationsEnabled===!0,endpoint:t,updatedAt:a}},l3=()=>{if(typeof window>"u")return null;try{return Kk(JSON.parse(window.localStorage.getItem(x_)??"null"))}catch{return null}},o3=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(x_,JSON.stringify(e))}catch{}},_p=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(x_)}catch{}},c3=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))throw new Error("当前环境没有可用的 Service Worker。");return navigator.serviceWorker.ready},Qk=e=>{const t="=".repeat((4-e.length%4)%4),a=(e+t).replace(/-/g,"+").replace(/_/g,"/"),l=window.atob(a),o=new Uint8Array(l.length);for(let u=0;u<l.length;u+=1)o[u]=l.charCodeAt(u);return o},S_=async()=>{const e=await c3();return"pushManager"in e?e.pushManager.getSubscription():null},u3=e=>{var u,f;const t=e.toJSON(),a=e.endpoint.trim(),l=typeof((u=t.keys)==null?void 0:u.p256dh)=="string"?t.keys.p256dh.trim():"",o=typeof((f=t.keys)==null?void 0:f.auth)=="string"?t.keys.auth.trim():"";if(!a||!l||!o)throw new Error("浏览器返回的推送订阅信息不完整。");return{endpoint:a,expirationTime:typeof e.expirationTime=="number"?e.expirationTime:null,keys:{p256dh:l,auth:o}}},d3=async()=>{try{return await uh().getWebPushPublicConfig()}catch(e){throw new Error(e instanceof Error?e.message:"无法读取 Hub Web Push 配置。")}},N0=()=>{if(typeof window>"u")return bg;try{const e=window.localStorage.getItem(n3);return e?i3(JSON.parse(e)):bg}catch{return bg}},Ho=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(n3,JSON.stringify(i3(e)))}catch{}},dh=()=>qs()?!0:typeof window>"u"?!1:window.isSecureContext&&"Notification"in window&&"serviceWorker"in navigator,ed=()=>qs()||!dh()?!1:"PushManager"in window,Cu=()=>qs()?Zf:dh()?Notification.permission:"unsupported",f3=e=>e==="granted"?"granted":e==="denied"?"denied":e==="prompt"?"default":"unsupported",h3=async()=>{Tp()&&await lh.createChannel({id:a3,name:"任务完成提醒",description:"Panda 对话和任务完成提醒",importance:4,visibility:1,vibration:!0,lights:!0}).catch(()=>{})},j_=async()=>{if(qs()){const e=await lh.checkPermissions();return Zf=f3(e.display),Zf}return dh()?Notification.permission:"unsupported"},k0=async()=>{if(qs()){await h3();const e=await lh.requestPermissions();return Zf=f3(e.display),Zf}return dh()?Notification.requestPermission():"unsupported"},E0=()=>{var e;return((e=l3())==null?void 0:e.completionNotificationsEnabled)===!0},Gk=async e=>{if(!e.completionNotificationsEnabled||Cu()!=="granted")return{synced:!1,reason:"notifications-disabled"};if(!ed())return{synced:!1,reason:"unsupported"};const t=await d3();if(!t.supported||!t.vapid_public_key)return _p(),{synced:!1,reason:"hub-unsupported"};const a=await S_();if(!a)return _p(),{synced:!1,reason:"missing-browser-subscription"};const l=await uh().upsertWebPushSubscription({subscription:u3(a),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:Nu()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return o3({completionNotificationsEnabled:l.settings.completion_notifications_enabled,endpoint:l.endpoint,updatedAt:l.updated_at}),{synced:!0,endpoint:l.endpoint}},Z4=async e=>{if(!ed())throw new Error("当前环境不支持 Web Push。");const t=await d3();if(!t.supported||!t.vapid_public_key)throw new Error(t.reason??"Hub 当前没有可用的 Web Push 配置。");const a=await c3(),o=await a.pushManager.getSubscription()??null??await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Qk(t.vapid_public_key)}),u=await uh().upsertWebPushSubscription({subscription:u3(o),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:Nu()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return o3({completionNotificationsEnabled:u.settings.completion_notifications_enabled,endpoint:u.endpoint,updatedAt:u.updated_at}),u},Yk=async()=>{if(!ed())return _p(),{removed:!1};const e=await S_();if(e){try{await uh().removeWebPushSubscription({endpoint:e.endpoint})}catch{}try{await e.unsubscribe()}catch{}}return _p(),{removed:!!e}},Vk=async()=>{var l,o;if(!ed())throw new Error("当前环境不支持 Web Push。");if(Cu()!=="granted")throw new Error("请先授予系统通知权限。");const e=await S_(),t=l3(),a=((l=e==null?void 0:e.endpoint)==null?void 0:l.trim())||((o=t==null?void 0:t.endpoint)==null?void 0:o.trim())||"";if(!a)throw new Error("当前设备还没有可用的 Web Push 订阅。");return await uh().sendWebPushTest({endpoint:a}),{ok:!0,endpoint:a}},Nu=()=>{if(typeof window>"u")return!1;const e=navigator;return window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0},X4=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent),Zk=e=>{if(typeof e!="string")return"";const t=e.replace(/\r\n/g,`
|
|
67
|
-
`).replace(/\s+/g," ").trim();return t?qk(t,Fk):""},Xk=(e,t)=>r3()[e]===t,xg=(e,t)=>{const a=r3();a[e]!==t&&Wk({...a,[e]:t})},m3=async e=>{if(!dh())return!1;if(qs()){if(await j_()!=="granted")return!1;await h3();try{return await lh.schedule({notifications:[{id:Math.abs(Array.from(`${e.sessionId}:${e.completedAt}`).reduce((a,l)=>a*31+l.charCodeAt(0)|0,17)),title:e.title,body:e.body,channelId:a3,schedule:{at:new Date(Date.now()+250),allowWhileIdle:!0},extra:{url:e.url,sessionId:e.sessionId,completedAt:e.completedAt}}]}),!0}catch{return!1}}if(typeof window>"u")return!1;const t={body:e.body,tag:`session-completed:${e.sessionId}:${e.completedAt}`,icon:"/pwa-512.png",badge:"/pwa-192.png",data:{sessionId:e.sessionId,url:e.url,completedAt:e.completedAt}};try{return await(await navigator.serviceWorker.ready).showNotification(e.title,t),!0}catch{try{const a=new Notification(e.title,t);return a.onclick=()=>{window.focus(),window.location.assign(e.url)},!0}catch{return!1}}},Jk=async e=>{if(!qs())return()=>{};const t=await lh.addListener("localNotificationActionPerformed",a=>{var o;const l=typeof((o=a.notification.extra)==null?void 0:o.url)=="string"?a.notification.extra.url.trim():"";l&&e(l)});return()=>{t.remove()}},p3=1,eE=10080*60*1e3,g3="panda-web-cache",td="app-state",_3="react-query",J4="panda:storage-persist-result",tE=new Set(["directory","bootstrap","timeline","timeline-optimistic","change-sets","plan","interactions","codex-commands","project-skills","settings-connection"]),w_=()=>typeof window<"u"&&typeof window.indexedDB<"u",nE=e=>typeof e[0]=="string"&&tE.has(e[0]),y3=async()=>w_()?await new Promise((e,t)=>{const a=window.indexedDB.open(g3,1);a.onupgradeneeded=()=>{const l=a.result;l.objectStoreNames.contains(td)||l.createObjectStore(td)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error??new Error("Unable to open Panda cache database."))}):null,sE=async()=>{const e=await y3();if(!e)return null;try{return await new Promise((t,a)=>{const u=e.transaction(td,"readonly").objectStore(td).get(_3);u.onsuccess=()=>t(u.result??null),u.onerror=()=>a(u.error??new Error("Unable to read Panda cache record."))})}finally{e.close()}},aE=async e=>{const t=await y3();if(t)try{await new Promise((a,l)=>{const o=t.transaction(td,"readwrite");o.objectStore(td).put(e,_3),o.oncomplete=()=>a(),o.onerror=()=>l(o.error??new Error("Unable to write Panda cache record.")),o.onabort=()=>l(o.error??new Error("Writing Panda cache record was aborted."))})}finally{t.close()}},yp=async()=>{w_()&&await new Promise(e=>{const t=window.indexedDB.deleteDatabase(g3);t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})},iE=async e=>{if(w_())try{const t=await sE();if(!t)return;const a=Date.now()-t.persistedAt>eE;if(t.version!==p3||a){await yp();return}C9(e,t.clientState)}catch{await yp().catch(()=>{})}},rE=async()=>{if(!(typeof navigator>"u"||typeof window>"u"||!("storage"in navigator)||typeof navigator.storage.persist!="function"))try{if(window.localStorage.getItem(J4))return;const t=await navigator.storage.persist();window.localStorage.setItem(J4,t?"granted":"denied")}catch{}},lE=e=>{if(typeof window>"u")return()=>{};rE();let t=null,a=null,l=!1,o=!1;const u=async()=>{if(!o){if(a){l=!0;return}a=(async()=>{const S=E9(e,{shouldDehydrateQuery:p=>nE(p.queryKey)});await aE({version:p3,persistedAt:Date.now(),clientState:S})})();try{await a}catch{}finally{a=null,l&&(l=!1,u())}}},f=(S=!1)=>{if(!o){if(t!==null&&(window.clearTimeout(t),t=null),S){u();return}t=window.setTimeout(()=>{t=null,u()},1200)}},m=e.getQueryCache().subscribe(()=>{f(!1)}),y=()=>{document.visibilityState==="hidden"&&f(!0)},g=()=>{f(!0)};return document.addEventListener("visibilitychange",y),window.addEventListener("pagehide",g),()=>{o=!0,m(),document.removeEventListener("visibilitychange",y),window.removeEventListener("pagehide",g),t!==null&&(window.clearTimeout(t),t=null)}},v3=async e=>{$k(),z6(),await yp().catch(()=>{}),e.removeQueries({predicate:t=>typeof t.queryKey[0]=="string"&&t.queryKey[0]!=="pwa-install-diagnostics"})},oE=()=>{const e=ki(),t=La(),a=Mp();return i.jsx("main",{className:"runtime-onboarding",children:i.jsxs("div",{className:"runtime-onboarding__shell",children:[i.jsxs("section",{className:"runtime-onboarding__hero",children:[i.jsx("span",{className:"runtime-onboarding__eyebrow",children:"首次连接"}),i.jsx("h1",{className:"runtime-onboarding__title",children:"输入 Panda 访问地址"}),i.jsx("p",{className:"runtime-onboarding__summary",children:"填一次,之后打开就能直接进入。也支持扫码。"})]}),i.jsx("section",{className:"settings-panel runtime-onboarding__panel",children:i.jsx(d6,{title:"Hub 地址",description:"填写电脑上显示的访问地址。",initialHubUrl:a.hubUrl,hint:"手机能直接打开这个地址就可以。",saveLabel:"保存并进入",savingLabel:"连接中",saveDescription:"保存后立即进入,之后也能在设置里修改。",saveSuccessMessage:"地址已保存,正在进入 Panda。",onSaveSuccess:async l=>{await q6({hubUrl:l.url,onboardingCompleted:!0}),qs()&&await k0().catch(()=>"unsupported")==="granted"&&Ho({completionNotificationsEnabled:!0}),await v3(t),await e({to:"/nodes",replace:!0})}})})]})})},Gi=["directory","hub"],cE=["directory","hub","recent-sessions"],os=["directory","workspace"],uE=["bootstrap","hub"],dE=os,eb=e=>{if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},fE=(e,t)=>{if(e.length!==t.length)return!1;for(let a=0;a<e.length;a+=1)if(!N_(e[a],t[a]))return!1;return!0},N_=(e,t)=>{if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return fE(e,t);if(eb(e)&&eb(t)){const a=Object.keys(e),l=Object.keys(t);if(a.length!==l.length)return!1;for(const o of a)if(!(o in t)||!N_(e[o],t[o]))return!1;return!0}return!1},Uf=(e,t)=>e!==void 0&&N_(e,t)?e:t,Fm=(e,t,a)=>{if(!e||e.length===0)return t;const l=new Map(e.map(u=>[a(u),u])),o=t.map(u=>Uf(l.get(a(u)),u));return e.length===o.length&&e.every((u,f)=>u===o[f])?e:o},tb=(e,t,a,l=new Date().toISOString())=>{if(!e)return e;let o=!1;const u=e.agents.map(f=>{if(f.id!==t||!Object.entries(a).some(([g,S])=>f[g]!==S))return f;const y={...f,...a};return o=!0,y});return o?{...e,generated_at:l,agents:u}:e},b3=(e,t)=>{if(!e)return t;const a=Fm(e.agents,t.agents,o=>o.id),l=Uf(e.generated_at,t.generated_at);return e.agents===a&&e.generated_at===l?e:{...t,generated_at:l,agents:a}},hE=180,mE=()=>{const e=La(),{hubUrl:t}=Mp(),a=_.useRef(null),l=pc(),o=ch(l),u=!!(l&&o);return _.useEffect(()=>{if(!t||u)return;let f=!1,m,y=!1,g=!1,S=!1;const p=()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},b=(T,D)=>{const z=new Date().toISOString();e.setQueryData(Gi,I=>tb(I,T,{status:D},z)??I),G4(I=>tb(I,T,{status:D},z)??I)},w=async()=>{try{const T=await Q4().getHubDirectory();if(f)return;G4(()=>T),e.setQueryData(Gi,D=>b3(D,T))}catch{}},N=()=>{p(),a.current=window.setTimeout(()=>{a.current=null,w()},hE)},j=T=>{var D,z;if(T.type==="agent.online"){if(S){S=!1;return}const I=typeof((D=T.payload)==null?void 0:D.agentId)=="string"?T.payload.agentId.trim():"";if(!I)return;b(I,"online"),N();return}if(T.type==="agent.offline"){const I=typeof((z=T.payload)==null?void 0:z.agentId)=="string"?T.payload.agentId.trim():"";if(!I)return;b(I,"offline"),N();return}T.type==="snapshot.changed"&&N()};w();try{m=Q4().connectEvents(j,{reconnectWhenHidden:!0,onStatus:T=>{if(T.state==="connected"){S=!0,y&&g&&(g=!1,N()),y=!0;return}y&&(g=!0)}})}catch{}return()=>{f=!0,p(),m==null||m()}},[t,e,u]),null},fh=e=>[...e].sort((t,a)=>{const l=Number(a.pinned)-Number(t.pinned);return l!==0?l:+new Date(a.last_event_at)-+new Date(t.last_event_at)}),co=e=>{if(!e)return e;const t=new Map(e.project_stats.map(a=>[a.project_id,a]));return{...e,project_stats:e.projects.map(a=>{const l=e.sessions.filter(u=>u.project_id===a.id),o=t.get(a.id);return{project_id:a.id,visible_session_count:l.filter(u=>!u.archived).length,archived_session_count:(o==null?void 0:o.archived_session_count)??0,hidden_history_count:(o==null?void 0:o.hidden_history_count)??0}})}},pE=e=>({id:e.id,agent_id:e.agent_id,project_id:e.project_id,archived:e.archived,title:e.title,last_event_at:e.last_event_at,pinned:e.pinned,run_state:e.run_state,run_state_changed_at:e.run_state_changed_at,subagent:e.subagent}),gE=e=>({id:e.id,agent_id:e.agent_id,name:e.name,display_name:e.display_name,pinned:e.pinned,path:e.path}),C0=e=>{if(!e)return null;const t={};return typeof e.title=="string"&&(t.title=e.title),typeof e.archived=="boolean"&&(t.archived=e.archived),typeof e.pinned=="boolean"&&(t.pinned=e.pinned),typeof e.last_event_at=="string"&&(t.last_event_at=e.last_event_at),(e.run_state==="idle"||e.run_state==="running"||e.run_state==="completed")&&(t.run_state=e.run_state),(e.run_state_changed_at===null||typeof e.run_state_changed_at=="string")&&(t.run_state_changed_at=e.run_state_changed_at),(e.subagent===null||typeof e.subagent=="object"&&e.subagent!==null)&&(t.subagent=e.subagent),Object.keys(t).length>0?t:null},vp=(e,t)=>!!(e!=null&&e.sessions.some(a=>a.id===t)),bp=(e,t,a)=>!e||!vp(e,t)?e:co({...e,sessions:fh(e.sessions.map(l=>l.id===t?{...l,...a}:l))}),T0=(e,t,a)=>{if(!e)return e;const l=e.sessions.find(f=>f.id===t);if(!l)return e;const o=new Date(a).getTime(),u=new Date(l.last_event_at).getTime();return!Number.isFinite(o)||Number.isFinite(u)&&o<=u?e:bp(e,t,{last_event_at:a})},Tf=(e,t,a)=>{if(!e)return e;const{last_event_at:l,...o}=a;let u=bp(e,t,o);return typeof l=="string"&&l.trim()&&(u=T0(u,t,l)),u},x3=(e,t,a)=>{if(!e||t.length===0)return e;const l=new Set(t);return co({...e,sessions:fh(e.sessions.map(o=>l.has(o.id)?{...o,...a}:o))})},S3=(e,t)=>{var u;if(!e||t.length===0)return e;const a=new Set(t),l=e.sessions.filter(f=>!a.has(f.id)),o=a.has(e.active_session_id)?((u=l[0])==null?void 0:u.id)??"":e.active_session_id;return co({...e,active_session_id:o,sessions:fh(l)})},Tu=(e,t,a)=>!e||!e.projects.some(l=>l.id===t)?e:co({...e,projects:e.projects.map(l=>l.id===t?{...l,...a}:l)}),xp=(e,t)=>{if(!e||t.length===0||e.projects.length<=1)return e;const a=new Map(e.projects.map(u=>[u.id,u])),l=new Set,o=[];for(const u of t){const f=a.get(u);!f||l.has(u)||(l.add(u),o.push(f))}for(const u of e.projects)l.has(u.id)||o.push(u);return o.every((u,f)=>{var m;return u.id===((m=e.projects[f])==null?void 0:m.id)})?e:co({...e,projects:o})},Sp=(e,t)=>{var o;if(!e)return e;const a=e.sessions.filter(u=>u.project_id!==t),l=a.some(u=>u.id===e.active_session_id)?e.active_session_id:((o=a[0])==null?void 0:o.id)??"";return co({...e,active_session_id:l,projects:e.projects.filter(u=>u.id!==t),sessions:fh(a)})},j3=(e,t)=>{if(!e)return e;const a=pE(t),l=[a,...e.sessions.filter(o=>o.id!==a.id)];return co({...e,generated_at:new Date().toISOString(),active_session_id:a.id,sessions:fh(l)})},_E=(e,t)=>{if(!e)return e;const a=gE(t),l=[a,...e.projects.filter(o=>o.id!==a.id)];return co({...e,generated_at:new Date().toISOString(),projects:l})},yE=(e,t)=>{if(!e)return t;const a=t.agent?Uf(e.agent??void 0,t.agent):e.agent===null?e.agent:null,l=Fm(e.projects,t.projects,y=>y.id),o=Fm(e.project_stats,t.project_stats,y=>y.project_id),u=Fm(e.sessions,t.sessions,y=>y.id),f=Uf(e.generated_at,t.generated_at),m=Uf(e.active_session_id,t.active_session_id);return e.agent===a&&e.projects===l&&e.project_stats===o&&e.sessions===u&&e.generated_at===f&&e.active_session_id===m?e:{...t,generated_at:f,agent:a,projects:l,project_stats:o,sessions:u,active_session_id:m}},vE=async()=>{const e=await wn();if(e.mode==="direct"){const t=await e.client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:t.generated_at,agents:t.agents}}return e.client.getHubDirectory()},bE=async()=>{const e=await wn();if(e.mode==="direct"){const t=await e.client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:t.generated_at,recent_sessions:[...t.sessions].sort((a,l)=>+new Date(l.last_event_at)-+new Date(a.last_event_at)).slice(0,24).map(a=>({id:a.id,title:a.title,run_state:a.run_state,run_state_changed_at:a.run_state_changed_at,latest_assistant_message:a.latest_assistant_message}))}}return e.client.getHubRecentSessions()},xE=async e=>(await wn(e==null?void 0:e.scope)).client.getWorkspaceDirectory({selectedSessionId:(e==null?void 0:e.selectedSessionId)??null}),SE=(e,t)=>b3(e,t),jE=(e,t)=>yE(e,t),R0=e=>{var t,a,l;return[...os,((t=e==null?void 0:e.scope)==null?void 0:t.agentId)??"",(a=e==null?void 0:e.scope)!=null&&a.agentId?"":((l=e==null?void 0:e.scope)==null?void 0:l.sessionId)??""]},w3=e=>({queryKey:Gi,enabled:(e==null?void 0:e.enabled)??!0,queryFn:vE,structuralSharing:SE,staleTime:3e4,refetchInterval:3e5,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),wE=()=>({queryKey:cE,queryFn:bE,staleTime:3e4,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),N3=e=>({queryKey:R0(e),enabled:(e==null?void 0:e.enabled)??!0,queryFn:()=>xE(e),placeholderData:g9,structuralSharing:jE,staleTime:1e4,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),k3=async e=>e.fetchQuery(w3()),NE=async e=>e.fetchQuery(wE()),Rf=async(e,t)=>e.fetchQuery(N3(t)),kE=1200,EE=e=>typeof document>"u"?!1:document.visibilityState==="visible"&&mp()===e,E3=e=>{var t;return((t=e==null?void 0:e.title)==null?void 0:t.trim())||"当前会话"},CE=e=>e.run_state!=="completed"?null:(typeof e.run_state_changed_at=="string"?e.run_state_changed_at.trim():"")||null,TE=(e,t)=>{if(!e||(typeof e.completionReason=="string"?e.completionReason:"completed")!=="completed")return null;const l=typeof e.sessionId=="string"?e.sessionId.trim():"",o=typeof e.completedAt=="string"?e.completedAt.trim():"";if(!l||!o)return null;const u=(t==null?void 0:t.recent_sessions.find(y=>y.id===l))??null,f=typeof e.sessionTitle=="string"&&e.sessionTitle.trim()||E3(u),m=(typeof e.finalReply=="string"?e.finalReply:"")||(u==null?void 0:u.latest_assistant_message)||"";return{sessionId:l,completedAt:o,sessionTitle:f,finalReply:m}},RE=(e,t)=>{const a=new Map(((e==null?void 0:e.recent_sessions)??[]).map(l=>[l.id,l]));return t.recent_sessions.flatMap(l=>{var m;const o=CE(l);if(!o)return[];const u=((m=l.latest_assistant_message)==null?void 0:m.trim())??"";if(!u)return[];const f=a.get(l.id);return(f==null?void 0:f.run_state)==="completed"&&f.run_state_changed_at===o?[]:[{sessionId:l.id,completedAt:o,sessionTitle:E3(l),finalReply:u}]})},ME=(e,t,a)=>{if(!e||!a)return e;let l=!1;const o=e.recent_sessions.map(u=>{if(u.id!==t)return u;const f=a.run_state==="idle"||a.run_state==="running"||a.run_state==="completed"?a.run_state:null,m={...u,...typeof a.title=="string"?{title:a.title}:null,...f?{run_state:f}:null,...a.run_state_changed_at===null||typeof a.run_state_changed_at=="string"?{run_state_changed_at:a.run_state_changed_at}:null,...a.latest_assistant_message===null||typeof a.latest_assistant_message=="string"?{latest_assistant_message:a.latest_assistant_message}:null};return l=l||m.title!==u.title||m.run_state!==u.run_state||m.run_state_changed_at!==u.run_state_changed_at||m.latest_assistant_message!==u.latest_assistant_message,m});return l?{...e,recent_sessions:o}:e},AE=({})=>{const e=La(),t=_.useRef(void 0),a=_.useRef(new Set),l=_.useRef(null),o=_.useRef(!1),u=pc(),f=ch(u),m=u&&f?u:null;return _.useEffect(()=>{const y=async I=>{const k=N0();if(!qs()&&!k.completionNotificationsEnabled||Cu()!=="granted")return;if(E0()){xg(I.sessionId,I.completedAt);return}const P=`${I.sessionId}:${I.completedAt}`;if(!a.current.has(P)&&!Xk(I.sessionId,I.completedAt)){if(EE(I.sessionId)){xg(I.sessionId,I.completedAt);return}a.current.add(P);try{await m3({sessionId:I.sessionId,completedAt:I.completedAt,title:I.sessionTitle,body:Zk(I.finalReply),url:`/session/${I.sessionId}`})&&xg(I.sessionId,I.completedAt)}finally{a.current.delete(P)}}},g=async I=>{for(const k of I)await y(k)};let S=!1,p,b=!1,w=!1,N=!1;const j=async()=>{if(!m)return NE(e);const k=await(await wn({agentId:m})).client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:k.generated_at,recent_sessions:[...k.sessions].sort((P,Q)=>+new Date(Q.last_event_at)-+new Date(P.last_event_at)).slice(0,24).map(P=>({id:P.id,title:P.title,run_state:P.run_state,run_state_changed_at:P.run_state_changed_at,latest_assistant_message:P.latest_assistant_message}))}};j().then(I=>{S||(t.current=I)}).catch(()=>{});const T=async()=>{if(!o.current){o.current=!0;try{const I=await j();if(S)return;const k=t.current;if(t.current=I,!k)return;await g(RE(k,I))}catch{}finally{o.current=!1}}},D=()=>{l.current!==null&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,T()},kE)},z=I=>{var k,P;if(I.type==="turn.completed"){const Q=TE(I.payload,t.current);Q&&y(Q);return}if(I.type==="session.updated"){const Q=typeof((k=I.payload)==null?void 0:k.sessionId)=="string"?I.payload.sessionId.trim():"",se=(P=I.payload)!=null&&P.sessionPatch&&typeof I.payload.sessionPatch=="object"?I.payload.sessionPatch:null;Q&&se&&(t.current=ME(t.current,Q,se));return}I.type==="agent.online"&&N&&(N=!1)};return wn(m?{agentId:m}:void 0).then(I=>{S||(p=I.client.connectEvents(z,{reconnectWhenHidden:!0,onStatus:k=>{if(k.state==="connected"){N=!0,b&&w&&(w=!1,D()),b=!0;return}b&&(w=!0)}}))}),()=>{S=!0,l.current!==null&&(clearTimeout(l.current),l.current=null),p==null||p()}},[e,m]),null},k_=e=>e.replace(/[\\/]+$/,""),jp=e=>k_(e).replace(/\\/g,"/").toLowerCase(),DE=e=>{const t=k_(e.trim());if(!t)return"新线程";const a=t.split(/[\\/]+/).filter(Boolean),l=a[a.length-1];return l?l.endsWith(":")?t:l:t},C3=e=>{if(!e)return null;const t=e.trim();if(!t||t==="/"||/^[A-Za-z]:[\\/]?$/.test(t))return null;const a=k_(t),l=Math.max(a.lastIndexOf("/"),a.lastIndexOf("\\"));if(l<0)return null;const o=a.slice(0,l);return o?/^[A-Za-z]:$/.test(o)?`${o}\\`:o:a.startsWith("/")?"/":null},T3=async e=>(await wn({agentId:e.agentId})).client.listDirectories(e),OE=async e=>(await wn({agentId:e.agentId})).client.createDirectory(e),IE=async e=>{const t=e.bootstrapQueryKey??["bootstrap"],a=e.projects.find(u=>u.agent_id===e.agentId&&jp(u.path)===jp(e.path));if(a)return a;const o=await(await wn({agentId:e.agentId})).client.createProject({agentId:e.agentId,name:DE(e.path),path:e.path});return e.queryClient.invalidateQueries({queryKey:t}),o.project},nb=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H10l2 2h6.5A2.5 2.5 0 0 1 21 9.5v8A2.5 2.5 0 0 1 18.5 20h-13A2.5 2.5 0 0 1 3 17.5z"})}),LE=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m9 6 6 6-6 6"})}),PE=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m5 12 4.5 4.5L19 7"})}),sb=e=>!!(e&&/^[A-Za-z]:[\\/]?$/.test(e.trim())),UE=({agentId:e,initialPath:t=null,title:a="选择开发版代码目录",subtitle:l="按需展开目录,只在你进入某一层时加载它的子目录。",confirmLabel:o="使用这个目录",onClose:u,onSelect:f})=>{const[m,y]=_.useState(t),[g,S]=_.useState(t),[p,b]=_.useState([]),[w,N]=_.useState(!0),[j,T]=_.useState(null);_.useEffect(()=>{y(t),S(t)},[t]),_.useEffect(()=>{let P=!1;return N(!0),T(null),T3({agentId:e,path:m}).then(Q=>{P||b(Q)}).catch(Q=>{P||(T(Q instanceof Error?Q.message:"目录列表加载失败。"),b([]))}).finally(()=>{P||N(!1)}),()=>{P=!0}},[e,m]);const D=C3(m),z=D!==null||sb(m),I=()=>{if(D!==null){y(D),S(D);return}sb(m)&&(y(null),S(null))},k=P=>{y(P),S(P)};return i.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true","aria-label":a,children:[i.jsx("button",{type:"button",className:"sheet-wrap__scrim","aria-label":"关闭目录选择",onClick:u}),i.jsx("div",{className:"sheet-wrap__center",children:i.jsx("section",{className:"directory-picker settings-directory-picker",children:i.jsxs("div",{className:"directory-picker__panel",children:[i.jsx("header",{className:"directory-picker__header",children:i.jsxs("div",{className:"directory-picker__heading",children:[i.jsx("h2",{children:a}),l?i.jsx("p",{children:l}):null]})}),i.jsxs("div",{className:"directory-picker__field",children:[i.jsx("span",{className:"directory-picker__field-label",children:"当前路径"}),i.jsxs("button",{type:"button",className:`directory-picker__path ${g===m?"is-selected":""}`,onClick:()=>{m&&S(m)},disabled:!m,"aria-pressed":g===m,children:[i.jsx("span",{className:"directory-picker__path-icon",children:i.jsx(nb,{})}),i.jsx("span",{className:"directory-picker__path-value",children:m??"根目录"})]})]}),i.jsxs("div",{className:"directory-picker__field",children:[i.jsx("span",{className:"directory-picker__field-label",children:"目录"}),i.jsx("div",{className:"directory-picker__list",role:"listbox","aria-label":"目录列表",children:w?i.jsx("div",{className:"directory-picker__state",children:"正在读取目录…"}):j?i.jsx("div",{className:"directory-picker__state is-error",children:j}):p.length===0?i.jsx("div",{className:"directory-picker__state",children:"当前目录下没有可用子目录"}):p.map(P=>{const Q=g===P.path;return i.jsxs("div",{className:`directory-picker__row ${Q?"is-selected":""}`,children:[i.jsxs("button",{type:"button",className:"directory-picker__row-main",onClick:()=>{S(P.path)},onDoubleClick:()=>{P.has_children&&k(P.path)},"aria-selected":Q,children:[i.jsx("span",{className:"directory-picker__row-icon",children:i.jsx(nb,{})}),i.jsx("span",{className:"directory-picker__row-name",children:P.name}),Q?i.jsx("span",{className:"directory-picker__row-check",children:i.jsx(PE,{})}):null]}),P.has_children?i.jsx("button",{type:"button",className:"directory-picker__row-enter-button","aria-label":`进入 ${P.name}`,onClick:()=>k(P.path),children:i.jsx("span",{className:"directory-picker__row-enter","aria-hidden":"true",children:i.jsx(LE,{})})}):null]},P.path)})})]}),i.jsx("footer",{className:"directory-picker__footer",children:i.jsxs("div",{className:"directory-picker__footer-actions",children:[z?i.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:I,children:i.jsx("span",{children:"返回上级"})}):null,i.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:u,children:i.jsx("span",{children:"取消"})}),i.jsx("button",{type:"button",className:"directory-picker__primary",disabled:!g,onClick:()=>{g&&f(g)},children:o})]})})]})})})]})},R3="panda-dev-manager-last-apk-download",zE=9e4,Sm=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},BE=e=>typeof e!="number"||!Number.isFinite(e)||e<=0?"未知":e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/1024/1024*10)/10} MB`,HE=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(R3);if(!e)return null;const t=JSON.parse(e);return typeof t.artifactId!="string"||typeof t.triggeredAt!="number"||!Number.isFinite(t.triggeredAt)?null:{artifactId:t.artifactId,triggeredAt:t.triggeredAt}}catch{return null}},$E=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(R3,JSON.stringify({artifactId:e,triggeredAt:Date.now()}))}catch{}},Uo=e=>e==="succeeded"?"通过":e==="failed"?"异常":"进行中",fu=e=>e==="succeeded"?"is-success":e==="failed"?"is-danger":"is-muted",ab=e=>e==null?"未测试":e?"通过":"异常",ib=e=>e==null?"is-muted":e?"is-success":"is-danger",FE=e=>e?e==="running"?"运行中":e==="stopped"?"已停止":e==="missing"?"未注册":"未知":"未注册",Ll=e=>e?`http://127.0.0.1:${e}`:"",jm=e=>e?`ws://127.0.0.1:${e}/ws`:"",rb=e=>({...e}),Sg=(e,t)=>{if(!e||e.config.updated_at!==t.config.updated_at)return t;const a=new Map(e.services.map(l=>[l.key,l]));return{...t,services:t.services.map(l=>{if(l.probe)return l;const o=a.get(l.key);return o!=null&&o.probe?{...l,probe:o.probe}:l})}},qE=({isActive:e,agentId:t})=>{var ke;const a=La(),[l,o]=_.useState(null),[u,f]=_.useState(null),[m,y]=_.useState(""),[g,S]=_.useState(!1),[p,b]=_.useState(null),[w,N]=_.useState(!1),j=t?{agentId:t}:void 0,T=["settings-dev-manager",t??"no-agent"],D=ls({queryKey:T,queryFn:async()=>{const U=await wn(j),ve=a.getQueryData(T),Z=await U.client.getDevManagerSnapshot({includeServiceProbe:!1});return{baseUrl:U.baseUrl,snapshot:Sg(ve==null?void 0:ve.snapshot,Z)}},enabled:e&&!!t,refetchOnWindowFocus:!1,staleTime:0,refetchInterval:U=>{const ve=U.state.data;return ve!=null&&ve.snapshot.jobs.some(Z=>Z.status==="running")?2e3:!1}});_.useEffect(()=>{var ve;const U=(ve=D.data)==null?void 0:ve.snapshot.config;U&&(l&&u===U.updated_at||(o(rb(U)),f(U.updated_at),y(""),S(!1)))},[D.data,l,u]);const z=Vn({mutationFn:async()=>{if(!j)throw new Error("当前没有可用的开发节点,暂时无法保存开发版配置。");if(!l)throw new Error("开发版配置还没有加载完成。");return(await wn(j)).client.saveDevManagerConfig({...l,npm_token:m||null,clear_npm_token:g})},onSuccess:U=>{a.setQueryData(T,ve=>({baseUrl:(ve==null?void 0:ve.baseUrl)??"",snapshot:Sg(ve==null?void 0:ve.snapshot,U)})),o(rb(U.config)),f(U.config.updated_at),y(""),S(!1),b("开发版配置已保存。")},onError:U=>{b(U instanceof Error?U.message:"保存配置失败。")}}),I=Vn({mutationFn:async U=>{if(!j)throw new Error("当前没有可用的开发节点,暂时无法执行开发版管理操作。");return(await wn(j)).client.executeDevManagerAction({action:U})},onSuccess:(U,ve)=>{var Z,Se,je,Oe;a.setQueryData(T,Ie=>({baseUrl:(Ie==null?void 0:Ie.baseUrl)??"",snapshot:Sg(Ie==null?void 0:Ie.snapshot,U.snapshot)})),b(ve==="restart-release-services"?"后台重启助手已启动,当前连接会短时断开,请等待正式版自动恢复。":ve==="install-latest-release"?"后台升级助手已启动,当前连接会短时断开,请等待正式版自动恢复。":ve==="install-latest-release-package"?((Z=U.job)==null?void 0:Z.summary)??"正式版 npm 安装任务已启动。":ve==="install-release-services"?((Se=U.job)==null?void 0:Se.summary)??"正式版服务注册任务已启动。":ve==="uninstall-release-services"?((je=U.job)==null?void 0:je.summary)??"正式版服务移除任务已启动。":((Oe=U.job)==null?void 0:Oe.summary)??"任务已启动。")},onError:U=>{b(U instanceof Error?U.message:"执行操作失败。")}}),k=((ke=D.data)==null?void 0:ke.snapshot)??null,P=(k==null?void 0:k.jobs[0])??null,Q=(k==null?void 0:k.jobs.find(U=>U.status==="running"))??null,se=(k==null?void 0:k.jobs.find(U=>U.kind==="npm-publish"))??null,W=(k==null?void 0:k.jobs.find(U=>U.kind==="release-service-install"))??null,V=(k==null?void 0:k.jobs.find(U=>U.kind==="release-service-uninstall"))??null,Y=(k==null?void 0:k.jobs.find(U=>U.kind==="release-install-package"))??null,ee=(k==null?void 0:k.jobs.find(U=>U.kind==="release-restart"))??(k==null?void 0:k.jobs.find(U=>U.kind==="release-install-run"))??null,me=P,ge=_.useMemo(()=>(k==null?void 0:k.services.filter(U=>U.key.startsWith("dev-")))??[],[k]),te=_.useMemo(()=>(k==null?void 0:k.services.filter(U=>U.key.startsWith("release-")))??[],[k]),xe=_.useMemo(()=>ge.some(U=>U.status==="running")?"部分或全部运行中":ge.some(U=>U.status==="degraded")?"存在异常":"未运行",[ge]),C=(U,ve)=>{o(Z=>Z&&{...Z,[U]:ve})},q=(U,ve)=>{const Z=Number(ve)||null;o(Se=>{if(!Se)return Se;const je={...Se,[U]:Z};if(U==="dev_hub_port"){const Oe=Ll(Se.dev_hub_port),Ie=Ll(Z);Se.dev_agent_hub_url===Oe&&(je.dev_agent_hub_url=Ie),Se.dev_web_hub_url===Oe&&(je.dev_web_hub_url=Ie)}if(U==="dev_agent_port"){const Oe=Ll(Se.dev_agent_port),Ie=Ll(Z),wt=jm(Se.dev_agent_port),qe=jm(Z);Se.dev_agent_direct_base_url===Oe&&(je.dev_agent_direct_base_url=Ie),Se.dev_agent_ws_base_url===wt&&(je.dev_agent_ws_base_url=qe)}if(U==="release_hub_port"){const Oe=Ll(Se.release_hub_port),Ie=Ll(Z);Se.release_agent_hub_url===Oe&&(je.release_agent_hub_url=Ie)}if(U==="release_agent_port"){const Oe=Ll(Se.release_agent_port),Ie=Ll(Z),wt=jm(Se.release_agent_port),qe=jm(Z);Se.release_agent_direct_base_url===Oe&&(je.release_agent_direct_base_url=Ie),Se.release_agent_ws_base_url===wt&&(je.release_agent_ws_base_url=qe)}return je})},ie=async()=>{if(!(k!=null&&k.apk_artifact)){b("当前还没有可下载的 APK。");return}if(!j){b("当前没有可用的开发节点,暂时无法下载 APK。");return}const U=HE();if((U==null?void 0:U.artifactId)===k.apk_artifact.artifact_id&&Date.now()-U.triggeredAt<zE){b("同一个 APK 刚刚已经触发过下载。如果安装确认没有弹出,请先查看系统下载列表或等待浏览器处理完成。");return}const ve=await wn(j),Z=new URL(k.apk_artifact.download_path,ve.baseUrl).toString();$E(k.apk_artifact.artifact_id),window.open(Z,"_blank","noopener,noreferrer"),b("APK 下载已触发。")},he=U=>{C("repo_path",U),N(!1),b(`已选中开发版目录:${U}`)},re=I.isPending;if(D.isLoading&&!k)return i.jsx("p",{className:"settings-block__status",children:"正在加载开发版管理信息…"});if(D.error instanceof Error)return i.jsx("p",{className:"settings-block__status",children:D.error.message});if(!t)return i.jsx("p",{className:"settings-block__status",children:"当前没有可用的代码线程节点,请先在会话里连接到目标 agent,再使用开发版管理。"});if(!k||!l)return i.jsx("p",{className:"settings-block__status",children:"当前还没有可用的开发版管理数据。"});const L=I.variables,ae=k.node_runtime.versions.length>0;return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"开发版与正式版双环境"}),i.jsx("p",{className:"settings-panel__subtitle",children:"正式版保持默认可用,开发版走独立端口和独立命令。首屏只读取轻量快照,状态测试按端口连通性快测。"})]})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"开发版代码"}),i.jsx("strong",{children:k.config.repo_path??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"正式版版本"}),i.jsx("strong",{children:k.current_version??"未检测到"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"开发版状态"}),i.jsx("strong",{children:xe})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"最新 APK"}),i.jsx("strong",{children:k.apk_artifact?Sm(k.apk_artifact.built_at):"尚未生成"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"基础配置"}),i.jsx("p",{className:"settings-panel__subtitle",children:"保存开发版路径、nvm 版本、启动参数,以及正式版升级后自动恢复所需配置。"})]}),i.jsx("div",{className:"settings-actions-row",children:i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void z.mutateAsync(),disabled:z.isPending,children:z.isPending?"保存中…":"保存配置"})})]}),i.jsxs("div",{className:"dev-manager-form-grid",children:[i.jsxs("div",{className:"dev-manager-form-section dev-manager-field--wide",children:[i.jsx("strong",{children:"开发版运行配置"}),i.jsx("p",{children:"这些配置直接用于启动、重启、停止开发版 Hub + Agent + Web。启动参数会追加到对应启动命令末尾。"})]}),i.jsxs("div",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版代码路径"}),i.jsx("input",{type:"text",className:`dev-manager-path-display ${l.repo_path?"is-selected":""}`,value:l.repo_path??"",placeholder:t?"点击下方按钮选择目录":"当前没有可用节点,暂时无法浏览目录",readOnly:!0,onClick:()=>{t&&N(!0)}}),i.jsxs("div",{className:"settings-actions-row dev-manager-path-actions",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>N(!0),disabled:!t,children:"选择目录"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>C("repo_path",null),disabled:!l.repo_path,children:"清空"})]}),i.jsx("small",{className:"dev-manager-field-hint",children:"使用内置目录弹层懒加载浏览;这里只保存最终选中的开发版仓库路径。"})]}),i.jsxs("div",{className:"settings-field",children:[i.jsx("span",{children:"Node 版本"}),i.jsxs("select",{value:l.nvm_version??"",onChange:U=>C("nvm_version",U.target.value||null),children:[i.jsx("option",{value:"",children:"保持系统默认"}),k.node_runtime.versions.map(U=>i.jsx("option",{value:U,children:U},U))]}),i.jsx("small",{className:`dev-manager-field-hint ${ae?"":"is-danger"}`,children:ae?k.node_runtime.manager==="nvm-windows"?"下拉内容包含当前正在运行的 Node 版本,以及这台电脑上 nvm-windows 已安装的版本。":"下拉内容至少包含当前正在运行的 Node 版本;如果这台电脑安装了 nvm-windows,也会一并列出。":k.node_runtime.error||"当前没有检测到可用的 Node 版本。"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"npm 令牌"}),i.jsx("input",{type:"password",value:m,onChange:U=>{S(!1),y(U.target.value)},placeholder:k.credentials.has_npm_token?`已保存:${k.credentials.npm_token_hint??"******"}`:"输入新的 npm token"})]}),i.jsx("div",{className:"settings-actions-row dev-manager-token-actions",children:i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{y(""),S(!0)},children:"清空令牌"})}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Hub 端口"}),i.jsx("input",{type:"number",value:l.dev_hub_port??"",onChange:U=>q("dev_hub_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent 端口"}),i.jsx("input",{type:"number",value:l.dev_agent_port??"",onChange:U=>q("dev_agent_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Web 端口"}),i.jsx("input",{type:"number",value:l.dev_web_port??"",onChange:U=>q("dev_web_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent -> Hub URL"}),i.jsx("input",{type:"text",value:l.dev_agent_hub_url,onChange:U=>C("dev_agent_hub_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent 直连 URL"}),i.jsx("input",{type:"text",value:l.dev_agent_direct_base_url,onChange:U=>C("dev_agent_direct_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent WS URL"}),i.jsx("input",{type:"text",value:l.dev_agent_ws_base_url,onChange:U=>C("dev_agent_ws_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent 名称"}),i.jsx("input",{type:"text",value:l.dev_agent_name,onChange:U=>C("dev_agent_name",U.target.value),placeholder:"留空后默认显示为直连地址 host:port"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Web -> Hub URL"}),i.jsx("input",{type:"text",value:l.dev_web_hub_url,onChange:U=>C("dev_web_hub_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版 Hub 追加参数"}),i.jsx("textarea",{value:l.dev_hub_args,onChange:U=>C("dev_hub_args",U.target.value),placeholder:"会直接追加到 corepack pnpm dev:hub 后面"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版 Agent 追加参数"}),i.jsx("textarea",{value:l.dev_agent_args,onChange:U=>C("dev_agent_args",U.target.value),placeholder:"会直接追加到 corepack pnpm dev:agent 后面"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版 Web 追加参数"}),i.jsx("textarea",{value:l.dev_web_args,onChange:U=>C("dev_web_args",U.target.value),placeholder:"会直接追加到开发版 Web 的 vite 命令后面"})]}),i.jsxs("div",{className:"dev-manager-form-section dev-manager-field--wide",children:[i.jsx("strong",{children:"正式版自动恢复配置"}),i.jsx("p",{children:"这些配置不是给当前已运行的正式版实时改端口,而是点击“重启正式版”后,后台助手用它重新拉起正式版 Hub + Agent。"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Hub 端口(自动恢复)"}),i.jsx("input",{type:"number",value:l.release_hub_port??"",onChange:U=>q("release_hub_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 端口(自动恢复)"}),i.jsx("input",{type:"number",value:l.release_agent_port??"",onChange:U=>q("release_agent_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Hub 服务名"}),i.jsx("input",{type:"text",value:l.release_hub_service_name,onChange:U=>C("release_hub_service_name",U.target.value),placeholder:"PandaHub"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 服务名"}),i.jsx("input",{type:"text",value:l.release_agent_service_name,onChange:U=>C("release_agent_service_name",U.target.value),placeholder:"PandaAgent"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent -> Hub URL(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_hub_url,onChange:U=>C("release_agent_hub_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 直连 URL(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_direct_base_url,onChange:U=>C("release_agent_direct_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent WS URL(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_ws_base_url,onChange:U=>C("release_agent_ws_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 名称(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_name,onChange:U=>C("release_agent_name",U.target.value),placeholder:"留空后默认显示为直连地址 host:port"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"正式版 Hub 追加参数(自动恢复)"}),i.jsx("textarea",{value:l.release_hub_args,onChange:U=>C("release_hub_args",U.target.value),placeholder:"会直接追加到 panda hub 后面"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"正式版 Agent 追加参数(自动恢复)"}),i.jsx("textarea",{value:l.release_agent_args,onChange:U=>C("release_agent_args",U.target.value),placeholder:"会直接注入 panda agent 命令后面"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"开发版运行控制"}),i.jsx("p",{className:"settings-panel__subtitle",children:"启动、重启、停止开发版 Hub / Agent / Web。进入页面默认不做探测,点击状态测试后仅按端口连通性快速判断。"})]}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("start-development"),disabled:re,children:L==="start-development"&&I.isPending?"启动中…":"启动"}),i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("restart-development"),disabled:re,children:L==="restart-development"&&I.isPending?"重启中…":"重启"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("stop-development"),disabled:re,children:L==="stop-development"&&I.isPending?"停止中…":"停止"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("probe-development"),disabled:re,children:L==="probe-development"&&I.isPending?"测试中…":"状态测试"})]})]}),i.jsx("div",{className:"dev-manager-service-grid",children:ge.map(U=>{var ve,Z;return i.jsxs("article",{className:`settings-diagnostic-list__item dev-manager-service-card is-${U.status}`,children:[i.jsx("strong",{children:U.label}),i.jsxs("span",{children:["上次测试:"," ",i.jsx("strong",{className:ib((ve=U.probe)==null?void 0:ve.ok),children:ab((Z=U.probe)==null?void 0:Z.ok)})]}),i.jsxs("span",{children:["端口:",U.configured_port??"未配置"]}),U.detected_pids.length>0?i.jsxs("span",{children:["PID:",U.detected_pids.join(", ")]}):null]},U.key)})})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"npm 发布、安装与正式版恢复"}),i.jsx("p",{className:"settings-panel__subtitle",children:"发布最新 npm 包后,可以单独安装正式版包,再按服务优先重启正式版 Hub + Agent。"})]}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("publish-npm"),disabled:I.isPending,children:L==="publish-npm"&&I.isPending?"发布中…":"发布"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("install-latest-release-package"),disabled:I.isPending,children:L==="install-latest-release-package"&&I.isPending?"安装中…":"安装最新正式版"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("restart-release-services"),disabled:I.isPending,children:L==="restart-release-services"&&I.isPending?"重启中…":"重启正式版"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("install-release-services"),disabled:I.isPending,children:L==="install-release-services"&&I.isPending?"注册中…":"注册/更新服务"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("uninstall-release-services"),disabled:I.isPending,children:L==="uninstall-release-services"&&I.isPending?"移除中…":"移除服务"})]})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前正式版版本"}),i.jsx("span",{children:k.current_version??"未检测到"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近 npm 发布"}),i.jsx("span",{className:se?fu(se.status):"is-muted",children:se?Uo(se.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近正式版安装"}),i.jsx("span",{className:Y?fu(Y.status):"is-muted",children:Y?Uo(Y.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近正式版恢复"}),i.jsx("span",{className:ee?fu(ee.status):"is-muted",children:ee?Uo(ee.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近服务注册"}),i.jsx("span",{className:W?fu(W.status):"is-muted",children:W?Uo(W.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近服务移除"}),i.jsx("span",{className:V?fu(V.status):"is-muted",children:V?Uo(V.status):"未执行"})]}),te.map(U=>{var ve,Z;return i.jsxs("article",{className:`settings-diagnostic-list__item dev-manager-service-card is-${U.status}`,children:[i.jsx("strong",{children:U.label}),i.jsxs("span",{children:["当前模式:"," ",i.jsx("strong",{children:U.manager==="windows-service"?"Windows 服务":"普通进程"})]}),i.jsxs("span",{children:["服务名:",U.service_name??"未配置"]}),i.jsxs("span",{children:["服务控制器:"," ",i.jsx("strong",{className:U.service_registered?"":"is-muted",children:FE(U.service_registered?U.service_status:"missing")})]}),i.jsxs("span",{children:["探测结果:"," ",i.jsx("strong",{className:ib((ve=U.probe)==null?void 0:ve.ok),children:ab((Z=U.probe)==null?void 0:Z.ok)})]}),i.jsxs("span",{children:["端口:",U.configured_port??"未配置"]})]},U.key)})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"APK 编译与下载"}),i.jsx("p",{className:"settings-panel__subtitle",children:"直接用开发版源码产出 release APK,并提供下载入口。"})]}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("build-apk"),disabled:I.isPending,children:L==="build-apk"&&I.isPending?"编译中…":"编译 APK"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void ie(),disabled:!k.apk_artifact,children:"下载 APK"})]})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近构建时间"}),i.jsx("span",{children:k.apk_artifact?Sm(k.apk_artifact.built_at):"尚未构建"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"版本"}),i.jsx("span",{children:k.apk_artifact?`${k.apk_artifact.version_name??"未知"}${k.apk_artifact.version_code?` (${k.apk_artifact.version_code})`:""}`:"尚未构建"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"文件大小"}),i.jsx("span",{children:k.apk_artifact?BE(k.apk_artifact.size_bytes):"尚未构建"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"任务日志"}),i.jsx("p",{className:"settings-panel__subtitle",children:"这里只显示最近一次任务的日志;更早的历史记录仍会保留在后台状态文件中。"})]})}),p?i.jsx("p",{className:"settings-block__status",children:p}):null,Q?i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前运行中"}),i.jsxs("span",{children:[Q.title," · ",Uo(Q.status)]})]}):null,me?i.jsx("div",{className:"settings-log-list",children:i.jsxs("article",{className:"settings-log-item dev-manager-job",children:[i.jsxs("div",{className:"settings-log-item__meta",children:[i.jsx("strong",{children:me.title}),i.jsx("span",{children:Sm(me.started_at??me.created_at)})]}),i.jsxs("div",{className:`settings-log-item__kind ${fu(me.status)}`,children:[Uo(me.status),me.disconnect_expected?" · 会中断连接":""]}),me.summary?i.jsx("div",{className:"dev-manager-job__summary",children:me.summary}):null,me.logs.length>0?i.jsx("pre",{className:"settings-log-item__detail",children:me.logs.slice(-16).map(U=>`[${Sm(U.timestamp)}] ${U.message}`).join(`
|
|
68
|
-
`)}):null]},me.id)}):i.jsx("p",{className:"settings-block__status",children:"还没有开发版管理任务记录。"})]}),w&&t?i.jsx(UE,{agentId:t,initialPath:l.repo_path,onClose:()=>N(!1),onSelect:he}):null]})},M3=mc("App",{web:()=>Zr(()=>import("./web-DuZa6nLj.js"),[]).then(e=>new e.AppWeb)}),WE=mc("Browser",{web:()=>Zr(()=>import("./web-Cx7LKGTD.js"),[]).then(e=>new e.BrowserWeb)}),KE=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/\/+$/,""):""},QE=async()=>{if(!Tp())return{platform:qu(),version:null,build:null,appId:null};const e=await M3.getInfo();return{platform:qu(),version:e.version??null,build:e.build??null,appId:e.id??null}},A3=e=>{const t=KE(e);return t?new URL("/downloads/android/latest.json",t).toString():""},GE=async e=>{const t=A3(e);if(!t)throw new Error("当前还没有配置可用的 Hub 地址。");const a=await fetch(t,{cache:"no-store"});if(!a.ok)throw new Error(`更新清单请求失败(HTTP ${a.status})。`);const l=await a.json(),o=Array.isArray(l.release_notes)?l.release_notes.filter(f=>typeof f=="string"&&f.trim().length>0):[];if(l.platform!=="android"||typeof l.version_name!="string"||typeof l.version_code!="number"||typeof l.published_at!="string"||typeof l.apk_url!="string")throw new Error("Hub 返回的 Android 更新清单格式无效。");const u=new URL(l.apk_url,t).toString();return{platform:"android",version_name:l.version_name,version_code:l.version_code,published_at:l.published_at,apk_url:u,release_notes:o}},YE=e=>{const t=Number(e);return Number.isFinite(t)?t:null},VE=(e,t)=>{if(!e||!t)return!1;const a=YE(e.build);return typeof a=="number"?t.version_code>a:t.version_name!==e.version},ZE=async e=>{if(!e.trim())throw new Error("当前没有可用的 APK 下载地址。");await WE.open({url:e})},D3="panda:session-model",O3="panda:command-execution-model",I3="panda:title-generation-model",E_="panda:session-model-options",M0="panda:session-model-options-updated",L3="panda:session-reasoning",P3="panda:session-fast-mode",U3="panda:session-plan-mode",z3="panda:session-yolo-mode",nd=[{id:"gpt-5.4",label:"gpt-5.4",value:"gpt-5.4"},{id:"gpt-5.3-codex",label:"gpt-5.3-codex",value:"gpt-5.3-codex"},{id:"gpt-5.3",label:"gpt-5.3",value:"gpt-5.3"},{id:"gpt-5.4-mini",label:"gpt-5.4-mini",value:"gpt-5.4-mini"},{id:"gpt-5.2",label:"gpt-5.2",value:"gpt-5.2"}],Xf=[{label:"低",value:"low"},{label:"中",value:"medium"},{label:"高",value:"high"},{label:"极高",value:"xhigh"}];var C2;const B3=((C2=nd[0])==null?void 0:C2.value)??"gpt-5.4",lb="gpt-5.4-mini",ob="gpt-5.4-mini",XE=Xf[2].value,Fr=e=>typeof e=="string"?e.trim():"",JE=(e,t)=>{if(!e||typeof e!="object")return null;const a=e,l=Fr(a.value),o=Fr(a.label)||l,u=Fr(a.id)||l||`custom-model-${t+1}`;if(!o||!l)return null;const f=Fr(a.description);return{id:u,label:o,value:l,description:f||null}},eC=e=>{const t=new Set,a=new Set;return e.flatMap(l=>{const o=l.value.toLowerCase();if(a.has(o))return[];a.add(o);let u=l.id,f=2;for(;t.has(u);)u=`${l.id}-${f}`,f+=1;return t.add(u),[{...l,id:u}]})},H3=e=>{if(!Array.isArray(e))return nd;const t=eC(e.flatMap((a,l)=>{const o=JE(a,l);return o?[o]:[]}));return t.length>0?t:nd},ld=e=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}},tC=()=>{typeof window>"u"||window.dispatchEvent(new Event(M0))},od=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}},C_=(e,t=!1)=>{const a=ld(e);return a==="true"?!0:a==="false"?!1:t},T_=(e,t)=>{od(e,t?"true":"false")},cd=(e,t)=>{const a=t==null?void 0:t.trim();return a?`${e}:${a}`:null},xf=e=>{const t=Fr(e==null?void 0:e.value)||"",a=Fr(e==null?void 0:e.label)||t;return{id:Fr(e==null?void 0:e.id)||Fr(e==null?void 0:e.value)||`custom-model-${Date.now()}`,label:a,value:t,description:Fr(e==null?void 0:e.description)||null}},nC=()=>hh().map(({id:e,...t})=>t),hh=()=>{const e=ld(E_);if(!e)return nd;try{return H3(JSON.parse(e))}catch{return nd}},sC=e=>{const t=H3(e);od(E_,JSON.stringify(t)),tC()},aC=e=>Xf.some(t=>t.value===e),R_=()=>{var a;const e=ld(D3),t=hh();return t.some(l=>l.value===e)?e:((a=t[0])==null?void 0:a.value)??B3},qm=()=>{const e=ld(O3),t=hh();if(t.some(l=>l.value===e))return e;const a=t.find(l=>l.value===lb)??t[0];return(a==null?void 0:a.value)??lb},$3=()=>{const e=ld(I3),t=hh();if(t.some(l=>l.value===e))return e;const a=t.find(l=>l.value===ob)??t[0];return(a==null?void 0:a.value)??ob},F3=()=>{const e=ld(L3);return aC(e)?e:XE},zf=e=>{od(D3,e)},jg=e=>{od(O3,e)},wg=e=>{od(I3,e)},q3=e=>{od(L3,e)},cb=e=>{const t=cd(P3,e);return t?C_(t):!1},ub=e=>{const t=cd(U3,e);return t?C_(t):!1},db=e=>{const t=cd(z3,e);return t?C_(t):!1},W3=(e,t)=>{const a=cd(P3,e);a&&T_(a,t)},K3=(e,t)=>{const a=cd(U3,e);a&&T_(a,t)},Q3=(e,t)=>{const a=cd(z3,e);a&&T_(a,t)},iC=(e,t)=>{W3(e,t.isFastModeEnabled),K3(e,t.isPlanModeEnabled),Q3(e,t.isYoloModeEnabled)},wp=(e,t=nC())=>{var a,l;return((a=t.find(o=>o.value===e))==null?void 0:a.label)??(typeof e=="string"&&e.trim()?e.trim():((l=t[0])==null?void 0:l.label)??B3)},rC=e=>{var t;return((t=Xf.find(a=>a.value===e))==null?void 0:t.label)??Xf[2].label},lC=JSON.parse('[{"id":"absolutely","light":{"codeThemeId":"absolutely","theme":{"accent":"#cc7d5e","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#2d2d2b","opaqueWindows":true,"semanticColors":{"diffAdded":"#00c853","diffRemoved":"#ff5f38","skill":"#cc7d5e"},"surface":"#f9f9f7"},"variant":"light"},"dark":{"codeThemeId":"absolutely","theme":{"accent":"#cc7d5e","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#f9f9f7","opaqueWindows":false,"semanticColors":{"diffAdded":"#00c853","diffRemoved":"#ff5f38","skill":"#cc7d5e"},"surface":"#2d2d2b"},"variant":"dark"}},{"id":"ayu","dark":{"codeThemeId":"ayu","theme":{"accent":"#e6b450","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#bfbdb6","opaqueWindows":false,"semanticColors":{"diffAdded":"#7fd962","diffRemoved":"#ea6c73","skill":"#cda1fa"},"surface":"#0b0e14"},"variant":"dark"}},{"id":"catppuccin","light":{"codeThemeId":"catppuccin","theme":{"accent":"#8839ef","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#4c4f69","opaqueWindows":true,"semanticColors":{"diffAdded":"#40a02b","diffRemoved":"#d20f39","skill":"#8839ef"},"surface":"#eff1f5"},"variant":"light"},"dark":{"codeThemeId":"catppuccin","theme":{"accent":"#cba6f7","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#cdd6f4","opaqueWindows":false,"semanticColors":{"diffAdded":"#a6e3a1","diffRemoved":"#f38ba8","skill":"#cba6f7"},"surface":"#1e1e2e"},"variant":"dark"}},{"id":"codex","light":{"codeThemeId":"codex","theme":{"accent":"#0169cc","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#0d0d0d","opaqueWindows":true,"semanticColors":{"diffAdded":"#00a240","diffRemoved":"#e02e2a","skill":"#751ed9"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"codex","theme":{"accent":"#0169cc","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#fcfcfc","opaqueWindows":false,"semanticColors":{"diffAdded":"#00a240","diffRemoved":"#e02e2a","skill":"#b06dff"},"surface":"#111111"},"variant":"dark"}},{"id":"dracula","dark":{"codeThemeId":"dracula","theme":{"accent":"#ff79c6","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#f8f8f2","opaqueWindows":false,"semanticColors":{"diffAdded":"#50fa7b","diffRemoved":"#ff5555","skill":"#ff79c6"},"surface":"#282a36"},"variant":"dark"}},{"id":"everforest","light":{"codeThemeId":"everforest","theme":{"accent":"#93b259","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#5c6a72","opaqueWindows":true,"semanticColors":{"diffAdded":"#8da101","diffRemoved":"#f85552","skill":"#df69ba"},"surface":"#fdf6e3"},"variant":"light"},"dark":{"codeThemeId":"everforest","theme":{"accent":"#a7c080","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#d3c6aa","opaqueWindows":false,"semanticColors":{"diffAdded":"#a7c080","diffRemoved":"#e67e80","skill":"#d699b6"},"surface":"#2d353b"},"variant":"dark"}},{"id":"github","light":{"codeThemeId":"github","theme":{"accent":"#0969da","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#1f2328","opaqueWindows":true,"semanticColors":{"diffAdded":"#1a7f37","diffRemoved":"#cf222e","skill":"#8250df"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"github","theme":{"accent":"#1f6feb","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e6edf3","opaqueWindows":false,"semanticColors":{"diffAdded":"#3fb950","diffRemoved":"#f85149","skill":"#bc8cff"},"surface":"#0d1117"},"variant":"dark"}},{"id":"gruvbox","light":{"codeThemeId":"gruvbox","theme":{"accent":"#458588","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#3c3836","opaqueWindows":true,"semanticColors":{"diffAdded":"#3c3836","diffRemoved":"#cc241d","skill":"#b16286"},"surface":"#fbf1c7"},"variant":"light"},"dark":{"codeThemeId":"gruvbox","theme":{"accent":"#458588","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#ebdbb2","opaqueWindows":false,"semanticColors":{"diffAdded":"#ebdbb2","diffRemoved":"#cc241d","skill":"#b16286"},"surface":"#282828"},"variant":"dark"}},{"id":"linear","light":{"codeThemeId":"linear","theme":{"accent":"#5e6ad2","contrast":45,"fonts":{"code":null,"ui":"Inter"},"ink":"#2a3140","opaqueWindows":true,"semanticColors":{"diffAdded":"#00a240","diffRemoved":"#ba2623","skill":"#8160d8"},"surface":"#f7f8fa"},"variant":"light"},"dark":{"codeThemeId":"linear","theme":{"accent":"#5e6ad2","contrast":60,"fonts":{"code":null,"ui":"Inter"},"ink":"#e6e9ef","opaqueWindows":true,"semanticColors":{"diffAdded":"#7ad9c0","diffRemoved":"#fa423e","skill":"#c2a1ff"},"surface":"#17181d"},"variant":"dark"}},{"id":"lobster","dark":{"codeThemeId":"lobster","theme":{"accent":"#ff5c5c","contrast":60,"fonts":{"code":null,"ui":"Satoshi"},"ink":"#e4e4e7","opaqueWindows":true,"semanticColors":{"diffAdded":"#22c55e","diffRemoved":"#ff5c5c","skill":"#3b82f6"},"surface":"#111827"},"variant":"dark"}},{"id":"material","dark":{"codeThemeId":"material","theme":{"accent":"#80cbc4","contrast":60,"fonts":{"code":null,"ui":"Satoshi"},"ink":"#eeffff","opaqueWindows":true,"semanticColors":{"diffAdded":"#c3e88d","diffRemoved":"#f07178","skill":"#c792ea"},"surface":"#212121"},"variant":"dark"}},{"id":"matrix","dark":{"codeThemeId":"matrix","theme":{"accent":"#1eff5a","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#b8ffca","opaqueWindows":true,"semanticColors":{"diffAdded":"#1eff5a","diffRemoved":"#fa423e","skill":"#1eff5a"},"surface":"#040805"},"variant":"dark"}},{"id":"monokai","dark":{"codeThemeId":"monokai","theme":{"accent":"#99947c","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#f8f8f2","opaqueWindows":true,"semanticColors":{"diffAdded":"#86b42b","diffRemoved":"#c4265e","skill":"#8c6bc8"},"surface":"#272822"},"variant":"dark"}},{"id":"night-owl","dark":{"codeThemeId":"night-owl","theme":{"accent":"#44596b","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#d6deeb","opaqueWindows":true,"semanticColors":{"diffAdded":"#c5e478","diffRemoved":"#ef5350","skill":"#c792ea"},"surface":"#011627"},"variant":"dark"}},{"id":"nord","dark":{"codeThemeId":"nord","theme":{"accent":"#88c0d0","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#d8dee9","opaqueWindows":true,"semanticColors":{"diffAdded":"#a3be8c","diffRemoved":"#bf616a","skill":"#b48ead"},"surface":"#2e3440"},"variant":"dark"}},{"id":"notion","light":{"codeThemeId":"notion","theme":{"accent":"#3183d8","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#37352f","opaqueWindows":true,"semanticColors":{"diffAdded":"#008000","diffRemoved":"#a31515","skill":"#0000ff"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"notion","theme":{"accent":"#3183d8","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#d9d9d8","opaqueWindows":true,"semanticColors":{"diffAdded":"#4ec9b0","diffRemoved":"#fa423e","skill":"#3183d8"},"surface":"#191919"},"variant":"dark"}},{"id":"one","light":{"codeThemeId":"one","theme":{"accent":"#526fff","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#383a42","opaqueWindows":true,"semanticColors":{"diffAdded":"#3bba54","diffRemoved":"#e45649","skill":"#526fff"},"surface":"#fafafa"},"variant":"light"},"dark":{"codeThemeId":"one","theme":{"accent":"#4d78cc","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#abb2bf","opaqueWindows":true,"semanticColors":{"diffAdded":"#8cc265","diffRemoved":"#e05561","skill":"#c162de"},"surface":"#282c34"},"variant":"dark"}},{"id":"oscurange","dark":{"codeThemeId":"oscurange","theme":{"accent":"#f9b98c","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e6e6e6","opaqueWindows":true,"semanticColors":{"diffAdded":"#40c977","diffRemoved":"#fa423e","skill":"#479ffa"},"surface":"#0b0b0f"},"variant":"dark"}},{"id":"proof","light":{"codeThemeId":"proof","theme":{"accent":"#3d755d","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#2f312d","opaqueWindows":false,"semanticColors":{"diffAdded":"#3d755d","diffRemoved":"#ba2623","skill":"#5f6ac2"},"surface":"#f5f3ed"},"variant":"light"}},{"id":"rose-pine","light":{"codeThemeId":"rose-pine","theme":{"accent":"#d7827e","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#575279","opaqueWindows":false,"semanticColors":{"diffAdded":"#56949f","diffRemoved":"#797593","skill":"#907aa9"},"surface":"#faf4ed"},"variant":"light"},"dark":{"codeThemeId":"rose-pine","theme":{"accent":"#ea9a97","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e0def4","opaqueWindows":true,"semanticColors":{"diffAdded":"#9ccfd8","diffRemoved":"#908caa","skill":"#c4a7e7"},"surface":"#232136"},"variant":"dark"}},{"id":"sentry","dark":{"codeThemeId":"sentry","theme":{"accent":"#7055f6","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e6dff9","opaqueWindows":true,"semanticColors":{"diffAdded":"#8ee6d7","diffRemoved":"#fa423e","skill":"#7055f6"},"surface":"#2d2935"},"variant":"dark"}},{"id":"solarized","light":{"codeThemeId":"solarized","theme":{"accent":"#b58900","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#657b83","opaqueWindows":false,"semanticColors":{"diffAdded":"#859900","diffRemoved":"#dc322f","skill":"#d33682"},"surface":"#fdf6e3"},"variant":"light"},"dark":{"codeThemeId":"solarized","theme":{"accent":"#d30102","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#839496","opaqueWindows":true,"semanticColors":{"diffAdded":"#859900","diffRemoved":"#dc322f","skill":"#d33682"},"surface":"#002b36"},"variant":"dark"}},{"id":"temple","dark":{"codeThemeId":"temple","theme":{"accent":"#e4f222","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#c7e6da","opaqueWindows":true,"semanticColors":{"diffAdded":"#40c977","diffRemoved":"#fa423e","skill":"#e4f222"},"surface":"#02120c"},"variant":"dark"}},{"id":"tokyo-night","dark":{"codeThemeId":"tokyo-night","theme":{"accent":"#3d59a1","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#a9b1d6","opaqueWindows":true,"semanticColors":{"diffAdded":"#449dab","diffRemoved":"#914c54","skill":"#9d7cd8"},"surface":"#1a1b26"},"variant":"dark"}},{"id":"vscode-plus","light":{"codeThemeId":"vscode-plus","theme":{"accent":"#007acc","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#000000","opaqueWindows":false,"semanticColors":{"diffAdded":"#008000","diffRemoved":"#ee0000","skill":"#0000ff"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"vscode-plus","theme":{"accent":"#007acc","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#d4d4d4","opaqueWindows":true,"semanticColors":{"diffAdded":"#369432","diffRemoved":"#f44747","skill":"#000080"},"surface":"#1e1e1e"},"variant":"dark"}}]'),oC={themes:lC},G3="panda:theme-settings",cC=13,uC=12,Y3="codex",M_="codex",dC='-apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", sans-serif',fC='ui-monospace, "SFMono-Regular", "SF Mono", "Cascadia Mono", "Cascadia Code", Consolas, monospace',hC=/\b(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|emoji|math|fangsong|ui-serif|ui-sans-serif|ui-monospace|ui-rounded)\b/i,fb=(e,t)=>{const a=e==null?void 0:e.trim();return a?hC.test(a)?a:`${a}, ${t}`:t},mC={absolutely:"Absolutely",ayu:"Ayu",catppuccin:"Catppuccin",codex:"Codex",dracula:"Dracula",everforest:"Everforest",github:"GitHub",gruvbox:"Gruvbox",linear:"Linear",lobster:"Lobster",material:"Material",matrix:"Matrix",monokai:"Monokai","night-owl":"Night Owl",nord:"Nord",notion:"Notion",one:"One",oscurange:"Oscurange",proof:"Proof","rose-pine":"Rose Pine",sentry:"Sentry",solarized:"Solarized",temple:"Temple","tokyo-night":"Tokyo Night","vscode-plus":"VSCode Plus"},ud=(e,t,a)=>Math.min(a,Math.max(t,e)),$o=(e,t)=>{const l=e.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!l)return t;const[,o]=l;return`#${(o.length===3?o.split("").map(f=>`${f}${f}`).join(""):o).toUpperCase()}`},Pr=e=>{const t=$o(e,"#000000").slice(1);return{r:Number.parseInt(t.slice(0,2),16),g:Number.parseInt(t.slice(2,4),16),b:Number.parseInt(t.slice(4,6),16)}},pC=(e,t,a)=>`#${[e,t,a].map(l=>ud(Math.round(l),0,255).toString(16).padStart(2,"0")).join("").toUpperCase()}`,pt=(e,t,a)=>{const l=Pr(e),o=Pr(t),u=ud(a,0,1);return pC(l.r+(o.r-l.r)*u,l.g+(o.g-l.g)*u,l.b+(o.b-l.b)*u)},gC=e=>{const{r:t,g:a,b:l}=Pr(e),o=u=>{const f=u/255;return f<=.03928?f/12.92:((f+.055)/1.055)**2.4};return o(t)*.2126+o(a)*.7152+o(l)*.0722},_C=e=>gC(e)>.5?"#0D1117":"#FFFFFF",Or=(e,t)=>{const a=Math.round(ud(t,0,1)*100);return a>=100?e:`color-mix(in srgb, ${e} ${a}%, transparent)`},V3=oC.themes,Z3=(e,t)=>{var l,o;const a=t==="light"?e.light:e.dark;return a?{id:e.id,label:mC[e.id]??e.id,codeThemeId:a.codeThemeId,variant:t,accent:$o(a.theme.accent,"#0169CC"),background:$o(a.theme.surface,"#FFFFFF"),foreground:$o(a.theme.ink,"#0D0D0D"),contrast:ud(Number(a.theme.contrast),0,100),opaqueWindows:!!a.theme.opaqueWindows,semanticColors:{diffAdded:$o(a.theme.semanticColors.diffAdded,"#00A240"),diffRemoved:$o(a.theme.semanticColors.diffRemoved,"#E02E2A"),skill:$o(a.theme.semanticColors.skill,"#751ED9")},fonts:{ui:((l=a.theme.fonts.ui)==null?void 0:l.trim())||null,code:((o=a.theme.fonts.code)==null?void 0:o.trim())||null}}:null},A0=V3.map(e=>Z3(e,"light")).filter(e=>!!e),Jf=V3.map(e=>Z3(e,"dark")).filter(e=>!!e);Jf.find(e=>e.id===M_)??Jf[0];const lc={mode:"system",lightThemeId:Y3,darkThemeId:M_,uiFontSize:cC,codeFontSize:uC},X3=e=>ud(Number(e),11,18),J3=e=>ud(Number(e),10,18),A_=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Ap=e=>A0.find(t=>t.id===e)??A0[0],Dp=e=>Jf.find(t=>t.id===e)??Jf[0],hb=(e,t=lc,a="light")=>a==="dark"?{...t,darkThemeId:Dp(e).id}:{...t,lightThemeId:Ap(e).id},Fl=e=>({mode:(e==null?void 0:e.mode)==="light"||(e==null?void 0:e.mode)==="dark"||(e==null?void 0:e.mode)==="system"?e.mode:lc.mode,lightThemeId:Ap((e==null?void 0:e.lightThemeId)??Y3).id,darkThemeId:Dp((e==null?void 0:e.darkThemeId)??M_).id,uiFontSize:X3((e==null?void 0:e.uiFontSize)??lc.uiFontSize),codeFontSize:J3((e==null?void 0:e.codeFontSize)??lc.codeFontSize)}),ex=()=>{if(typeof window>"u")return lc;try{const e=window.localStorage.getItem(G3);return e?Fl(JSON.parse(e)):lc}catch{return lc}},Sf=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(G3,JSON.stringify(Fl(e)))}catch{}},yC=(e,t)=>e==="system"?t:e,Lr=(e,t=A_())=>{const a=Fl(e),l=yC(a.mode,t),o=Ap(a.lightThemeId),u=Dp(a.darkThemeId),f=l==="dark"?u:o;return{...a,appearance:l,lightTheme:o,darkTheme:u,activeTheme:f,uiFontFamily:fb(f.fonts.ui,dC),codeFontFamily:fb(f.fonts.code,fC)}},vC=e=>{if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>{e(t.matches?"dark":"light")};return a(),t.addEventListener("change",a),()=>{t.removeEventListener("change",a)}},bC=(e,t)=>{const a=Lr(e,t),l=a.activeTheme,o=t==="dark",u=(l.contrast-(o?60:45))/100,f=l.semanticColors.diffAdded,m=l.semanticColors.diffRemoved,y=l.semanticColors.skill,g=Pr(f),S=Pr(m),p=Pr(y),b=Pr(l.accent),w=Pr(l.background),N=Pr(l.foreground),j=l.background,T=o?pt(l.background,"#FFFFFF",.05+u*.08):pt(l.background,"#FFFFFF",.42+u*.16),D=o?pt(l.background,"#FFFFFF",.07+u*.08):pt(l.background,"#FFFFFF",.78+u*.1),z=o?pt(l.background,"#FFFFFF",.1+u*.08):pt(l.background,"#FFFFFF",.56+u*.14),I=o?pt(l.background,"#FFFFFF",.14+u*.08):pt(l.background,l.foreground,.1+u*.12),k=o?pt(l.background,"#000000",.08-u*.06):pt(l.background,l.foreground,.03+u*.08),P=o?pt(l.background,"#FFFFFF",.08+u*.06):pt(l.background,l.foreground,.06+u*.08),Q=o?pt(l.background,"#FFFFFF",.14+u*.08):pt(l.background,l.foreground,.14+u*.1),se=o?pt(l.background,"#FFFFFF",.22+u*.08):pt(l.background,l.foreground,.22+u*.1),W=o?pt(l.background,"#FFFFFF",.08+u*.04):pt(l.background,l.foreground,.1+u*.08),V=l.foreground,Y=o?pt(l.foreground,l.background,.28-u*.1):pt(l.foreground,l.background,.5-u*.14),ee=o?pt(l.foreground,l.background,.46-u*.1):pt(l.foreground,l.background,.64-u*.14),me=pt(l.foreground,l.background,o?.58:.74),ge=l.accent,te=o?pt(l.accent,"#FFFFFF",.18):pt(l.accent,"#FFFFFF",.24),xe=o?pt(l.accent,l.background,.78):pt(l.accent,l.background,.88),C=o?pt(l.accent,l.background,.84):pt(l.accent,l.background,.92),q=_C(ge),ie=o?pt(l.background,"#FFFFFF",.1):pt(l.background,l.foreground,.08),he=o?pt(l.background,"#000000",.06):pt(l.background,l.foreground,.035),re=o?pt(l.background,"#FFFFFF",.05):pt(l.background,l.foreground,.06),L=o?pt(l.background,"#FFFFFF",.03):pt(l.background,l.foreground,.085),ae=o?pt(l.background,"#FFFFFF",.065):pt(l.background,l.foreground,.05),ke=pt(l.foreground,l.background,o?.42:.68),U=o?pt(l.background,"#FFFFFF",.08):pt(l.foreground,l.background,.18),ve=o?pt(l.background,"#FFFFFF",.08):pt(l.background,l.foreground,.06),Z=o?pt(l.background,"#FFFFFF",.12):pt(l.background,l.foreground,.1),Se=o?pt(l.background,"#FFFFFF",.14+u*.05):pt(l.background,l.foreground,.12+u*.08),je=l.opaqueWindows?1:o?.92:.95,Oe=l.opaqueWindows?1:o?.94:.965,Ie=l.opaqueWindows?1:.94;return{"--theme-id":l.id,"--theme-code-theme-id":l.codeThemeId,"--theme-window-opaque":l.opaqueWindows?"1":"0","--theme-accent":ge,"--theme-accent-rgb":`${b.r} ${b.g} ${b.b}`,"--theme-background":l.background,"--theme-background-rgb":`${w.r} ${w.g} ${w.b}`,"--theme-foreground":l.foreground,"--theme-foreground-rgb":`${N.r} ${N.g} ${N.b}`,"--theme-shadow-rgb":o?"0 0 0":"39 28 17","--theme-ui-font":a.uiFontFamily,"--theme-code-font":a.codeFontFamily,"--theme-ui-font-size":`${a.uiFontSize}px`,"--theme-code-font-size":`${a.codeFontSize}px`,"--color-surface-base":j,"--color-surface-elevated":T,"--color-surface-panel":D,"--color-surface-raised":z,"--color-surface-panel-strong":I,"--color-surface-sidebar":Or(k,Oe),"--color-surface-sidebar-elevated":Or(P,Oe),"--color-surface-border":Q,"--color-surface-border-strong":se,"--color-surface-border-soft":W,"--color-surface-overlay":Or(I,je),"--color-surface-floating":Or(D,je),"--color-surface-tooltip":Or(U,Ie),"--color-surface-code":he,"--color-surface-code-muted":re,"--color-surface-code-gutter":L,"--color-surface-code-meta":ae,"--color-surface-inline-code":ie,"--color-surface-hover":ve,"--color-surface-pressed":Z,"--color-surface-danger-soft":Or(m,o?.14:.08),"--color-surface-success-soft":Or(f,o?.14:.08),"--color-text-primary":V,"--color-text-secondary":Y,"--color-text-muted":ee,"--color-text-tertiary":me,"--color-text-on-accent":q,"--color-text-link":ge,"--color-text-link-hover":te,"--color-text-danger":m,"--color-text-success":f,"--color-accent-primary":ge,"--color-accent-primary-soft":xe,"--color-accent-secondary":te,"--color-accent-secondary-soft":C,"--color-accent-contrast":q,"--color-accent-primary-rgb":`${b.r} ${b.g} ${b.b}`,"--color-success":f,"--color-warning":pt(l.accent,f,.35),"--color-danger":m,"--color-status-online":ge,"--color-status-offline":o?"#76808A":"#A5ACA4","--color-skill":y,"--color-skill-rgb":`${p.r} ${p.g} ${p.b}`,"--color-code-keyword":y,"--color-code-title":ge,"--color-code-string":pt(f,l.foreground,o?.26:.18),"--color-code-number":pt(y,ge,.36),"--color-code-comment":pt(l.foreground,l.background,o?.52:.72),"--color-code-meta-text":ke,"--color-code-add":f,"--color-code-add-rgb":`${g.r} ${g.g} ${g.b}`,"--color-code-add-bg":Or(f,o?.16:.11),"--color-code-remove":m,"--color-code-remove-rgb":`${S.r} ${S.g} ${S.b}`,"--color-code-remove-bg":Or(m,o?.18:.11),"--color-divider":Se,"--color-overlay-scrim":l.opaqueWindows?o?"rgba(8, 10, 12, 0.66)":"rgba(23, 20, 17, 0.14)":o?"rgba(8, 10, 12, 0.54)":"rgba(23, 20, 17, 0.09)","--shadow-soft":o?"0 24px 54px rgba(0, 0, 0, 0.34)":"0 24px 54px rgba(24, 18, 12, 0.08)","--shadow-panel":o?"0 10px 26px rgba(0, 0, 0, 0.24)":"0 10px 26px rgba(37, 23, 10, 0.06)","--shadow-sm":o?"0 2px 12px rgba(0, 0, 0, 0.18)":"0 2px 12px rgba(37, 23, 10, 0.05)","--shadow-overlay":o?"0 20px 44px rgba(0, 0, 0, 0.36)":"0 18px 40px rgba(42, 26, 12, 0.1)","--font-display":a.uiFontFamily,"--font-sans":a.uiFontFamily,"--font-mono":a.codeFontFamily,"--font-size-ui-base":`${a.uiFontSize}px`,"--font-size-code-base":`${a.codeFontSize}px`}},tx=(e,t=A_())=>{if(typeof document>"u")return;const a=Lr(e,t),l=bC(a,a.appearance),o=document.documentElement;o.dataset.theme=a.appearance,o.dataset.uiTheme=a.appearance,o.dataset.themeId=a.activeTheme.id,o.dataset.codeThemeId=a.activeTheme.codeThemeId,o.dataset.windowStyle=a.activeTheme.opaqueWindows?"opaque":"soft",o.style.colorScheme=a.appearance;for(const[u,f]of Object.entries(l))o.style.setProperty(u,f)},xC=async()=>{if(await yp().catch(()=>{}),"serviceWorker"in navigator){const t=await navigator.serviceWorker.getRegistrations();await Promise.all(t.map(a=>a.unregister()))}if("caches"in window){const t=await window.caches.keys();await Promise.all(t.map(a=>window.caches.delete(a)))}const e=window.indexedDB;if(typeof e.databases=="function"){const t=await e.databases();await Promise.all(t.map(a=>a.name).filter(a=>!!a).map(a=>new Promise(l=>{const o=e.deleteDatabase(a);o.onsuccess=()=>l(),o.onerror=()=>l(),o.onblocked=()=>l()})))}window.localStorage.clear(),window.sessionStorage.clear()},D_="panda:pwa-install-log",SC=48,Cs=e=>((e==null?void 0:e.trim())??"")||null,nx=()=>{if(typeof window>"u")return[];try{const e=window.localStorage.getItem(D_);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.map(a=>{if(!a||typeof a!="object")return null;const l=a;return typeof l.id!="string"||typeof l.timestamp!="string"||typeof l.kind!="string"||typeof l.message!="string"?null:{id:l.id,timestamp:l.timestamp,kind:l.kind,message:l.message,detail:Cs(l.detail)}}).filter(a=>!!a).sort((a,l)=>+new Date(l.timestamp)-+new Date(a.timestamp)):[]}catch{return[]}},jC=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(D_,JSON.stringify(e.slice(0,SC)))}catch{}},wC=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(D_)}catch{}},Pl=e=>{const t=nx(),a={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),kind:e.kind,message:e.message.trim(),detail:Cs(e.detail)};return jC([a,...t]),a},mb=(e,t)=>{var a;return((a=e.find(l=>l.kind===t))==null?void 0:a.timestamp)??null},NC=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()},kC=async e=>{try{let t=await fetch(e,{method:"HEAD",cache:"no-store"});return(t.status===405||t.status===501)&&(t=await fetch(e,{method:"GET",cache:"no-store"})),{ok:t.ok,status:t.status,error:null}}catch(t){return{ok:!1,status:null,error:t instanceof Error?t.message:"Unknown fetch failure"}}},EC=async()=>{if(typeof document>"u"||typeof window>"u")return{href:null,present:!1,ok:!1,error:"Document is unavailable.",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]};const e=document.querySelector('link[rel~="manifest"]'),t=Cs(e==null?void 0:e.href);if(!t)return{href:null,present:!1,ok:!1,error:"页面没有 manifest 链接。",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]};try{const a=await NC(t),l=Array.isArray(a.icons)?a.icons:[],o=await Promise.all(l.slice(0,8).map(async u=>{const f=u,m=Cs(typeof f.src=="string"?f.src:null);if(!m)return{src:"(missing)",purpose:Cs(typeof f.purpose=="string"?f.purpose:null),sizes:Cs(typeof f.sizes=="string"?f.sizes:null),type:Cs(typeof f.type=="string"?f.type:null),ok:!1,status:null,error:"Icon src is missing."};const y=new URL(m,t).toString(),g=await kC(y);return{src:y,purpose:Cs(typeof f.purpose=="string"?f.purpose:null),sizes:Cs(typeof f.sizes=="string"?f.sizes:null),type:Cs(typeof f.type=="string"?f.type:null),ok:g.ok,status:g.status,error:g.error}}));return{href:t,present:!0,ok:!0,error:null,id:Cs(typeof a.id=="string"?a.id:null),name:Cs(typeof a.name=="string"?a.name:null),shortName:Cs(typeof a.short_name=="string"?a.short_name:null),startUrl:Cs(typeof a.start_url=="string"?a.start_url:null),scope:Cs(typeof a.scope=="string"?a.scope:null),display:Cs(typeof a.display=="string"?a.display:null),displayOverride:Array.isArray(a.display_override)?a.display_override.filter(u=>typeof u=="string"):[],themeColor:Cs(typeof a.theme_color=="string"?a.theme_color:null),backgroundColor:Cs(typeof a.background_color=="string"?a.background_color:null),icons:o}}catch(a){return{href:t,present:!0,ok:!1,error:a instanceof Error?a.message:"Manifest fetch failed.",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]}}},CC=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return{supported:!1,controller:!1,registrations:[]};try{const e=await navigator.serviceWorker.getRegistrations();return{supported:!0,controller:!!navigator.serviceWorker.controller,registrations:e.map(t=>{var a,l,o;return{scope:t.scope,activeScriptUrl:((a=t.active)==null?void 0:a.scriptURL)??null,waitingScriptUrl:((l=t.waiting)==null?void 0:l.scriptURL)??null,installingScriptUrl:((o=t.installing)==null?void 0:o.scriptURL)??null}})}}catch{return{supported:!0,controller:!!navigator.serviceWorker.controller,registrations:[]}}},TC=e=>{const t=e.standaloneDisplayMode||e.navigatorStandalone;return t&&e.appInstalledSeen?{label:"较像已安装应用",confidence:"medium",detail:"当前页面正以独立窗口打开,并且这个站点记录到过 appinstalled 事件,更像是真正安装后的应用入口。"}:t?{label:"更像主屏幕快捷方式",confidence:"medium",detail:"当前页面虽然已脱离浏览器标签页,但站点本地没有观测到 appinstalled 事件,无法证明系统级安装已经完成,更像是主屏幕快捷方式。"}:e.installPromptAvailable?{label:"可触发安装流程",confidence:"high",detail:"浏览器已经提供 beforeinstallprompt 事件,设置页里的安装按钮可以主动弹出安装流程。"}:e.beforeInstallPromptSeen?{label:"浏览器曾允许安装",confidence:"low",detail:"站点历史上收到过 beforeinstallprompt,但当前页面没有可用的安装事件,可能需要刷新页面、重新访问或等待浏览器重新评估。"}:{label:"当前不像可安装应用",confidence:"medium",detail:"浏览器当前没有给出可用的安装事件,页面更像普通标签页或只能走“添加到主屏幕”的快捷方式链路。"}},RC=e=>{const t=[];if(e.secureContext||t.push("当前页面不是安全上下文,Chrome 不会提供完整的 PWA 安装链路。"),!e.manifest.present)t.push("页面没有 manifest 链接,浏览器无法把当前站点识别为可安装 Web App。");else if(!e.manifest.ok)t.push(`manifest 读取失败:${e.manifest.error??"未知错误"}。`);else{(!e.manifest.display||e.manifest.display==="browser")&&t.push("manifest 没有声明 standalone/minimal-ui 显示模式,浏览器更可能只给快捷方式。"),!e.manifest.name&&!e.manifest.shortName&&t.push("manifest 缺少 name/short_name,安装身份信息不完整。");const l=e.manifest.icons.some(f=>f.ok&&(f.sizes??"").includes("192x192")),o=e.manifest.icons.some(f=>f.ok&&(f.sizes??"").includes("512x512"));(!l||!o)&&t.push("manifest 图标里缺少可访问的 192x192 或 512x512 图标,Android 安装链路可能会退化。");const u=e.manifest.icons.filter(f=>!f.ok);u.length>0&&t.push(`有 ${u.length} 个 manifest 图标资源探测失败,安装时可能因为图标拉取失败而退化或失败。`)}return e.serviceWorker.supported?e.serviceWorker.registrations.length===0&&t.push("当前页面没有检测到 Service Worker 注册,Chrome 往往不会提供完整安装流程。"):t.push("当前浏览器不支持 Service Worker,无法满足完整的 PWA 安装条件。"),!e.installPromptAvailable&&!e.launchedStandalone&&e.secureContext&&e.manifest.ok&&e.serviceWorker.registrations.length>0&&t.push("浏览器当前没有下发 beforeinstallprompt,设置页按钮无法主动触发安装,只能走浏览器菜单的安装/添加到主屏幕入口。"),e.logs.find(l=>{var o;return l.kind==="install-choice"&&((o=l.detail)==null?void 0:o.toLowerCase().includes("accepted"))})&&!e.appInstalledSeen&&t.push("站点记录到用户接受过安装请求,但没有后续 appinstalled 事件,更像是浏览器回退成快捷方式,或系统级安装没有完成。"),e.launchedStandalone&&!e.appInstalledSeen&&t.push("当前虽然是独立窗口形态,但没有观测到 appinstalled,不能把它视为已经完成系统级安装。"),t},MC=async e=>{const t=nx(),[a,l]=await Promise.all([EC(),CC()]),o=navigator,u=typeof window<"u"&&window.matchMedia("(display-mode: standalone)").matches,f=o.standalone===!0,m=t.some(w=>w.kind==="beforeinstallprompt"),y=t.some(w=>w.kind==="appinstalled"),g=(e==null?void 0:e.installPromptAvailable)===!0,S=u||f,p=[];window.isSecureContext&&p.push("当前是安全上下文。"),a.ok&&p.push("manifest 可读取。"),l.registrations.length>0&&p.push(`检测到 ${l.registrations.length} 个 Service Worker 注册。`),g&&p.push("浏览器已提供可调用的安装事件。"),y&&p.push("站点本地记录到过 appinstalled 事件。");const b=["从桌面图标打开后,确认没有浏览器地址栏或标签栏。","到 Android“设置 -> 应用”里搜索 Panda,若能搜到,更像系统级安装。","到应用抽屉里搜索 Panda;若只在桌面可见而应用抽屉里没有,更像快捷方式。","如果日志里只有“添加到主屏幕”链路,没有 appinstalled,通常不能认定为真正安装完成。"];return{capturedAt:new Date().toISOString(),environment:{href:typeof window>"u"?null:window.location.href,origin:typeof window>"u"?null:window.location.origin,secureContext:typeof window<"u"?window.isSecureContext:!1,online:typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,isAndroid:typeof navigator<"u"?/Android/i.test(navigator.userAgent):!1,standaloneDisplayMode:u,navigatorStandalone:f},promptState:{installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y,lastBeforeInstallPromptAt:mb(t,"beforeinstallprompt"),lastAppInstalledAt:mb(t,"appinstalled")},manifest:a,serviceWorker:l,assessment:TC({standaloneDisplayMode:u,navigatorStandalone:f,installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y}),failureReasons:RC({secureContext:typeof window<"u"?window.isSecureContext:!1,manifest:a,serviceWorker:l,installPromptAvailable:g,appInstalledSeen:y,launchedStandalone:S,logs:t}),successSignals:p,confirmationChecklist:b,logs:t}},AC=e=>{if(typeof window>"u")return()=>{};const t=l=>{(l.key===null||l.key===E_)&&e()},a=()=>{e()};return window.addEventListener("storage",t),window.addEventListener(M0,a),()=>{window.removeEventListener("storage",t),window.removeEventListener(M0,a)}},DC=()=>hh(),OC=()=>nd,O_=()=>_.useSyncExternalStore(AC,DC,OC);function I_(e){return ls(w3(e))}const sx=e=>{var t,a,l;return["codex-commands",((t=e==null?void 0:e.agentId)==null?void 0:t.trim())??"",((a=e==null?void 0:e.projectId)==null?void 0:a.trim())??"",((l=e==null?void 0:e.sessionId)==null?void 0:l.trim())??""]},ax=e=>{const t=(e==null?void 0:e.enabled)??!0;return ls({queryKey:sx(e==null?void 0:e.scope),enabled:t,queryFn:async()=>(await wn(e==null?void 0:e.scope)).client.getCodexCommands(),staleTime:0,gcTime:30*6e4,refetchOnWindowFocus:!1,retry:1})},pb=e=>{let t;const a=new Set,l=(g,S)=>{const p=typeof g=="function"?g(t):g;if(!Object.is(p,t)){const b=t;t=S??(typeof p!="object"||p===null)?p:Object.assign({},t,p),a.forEach(w=>w(t,b))}},o=()=>t,m={setState:l,getState:o,getInitialState:()=>y,subscribe:g=>(a.add(g),()=>a.delete(g))},y=t=e(l,o,m);return m},IC=(e=>e?pb(e):pb),LC=e=>e;function PC(e,t=LC){const a=qr.useSyncExternalStore(e.subscribe,qr.useCallback(()=>t(e.getState()),[e,t]),qr.useCallback(()=>t(e.getInitialState()),[e,t]));return qr.useDebugValue(a),a}const gb=e=>{const t=IC(e),a=l=>PC(t,l);return Object.assign(a,t),a},UC=(e=>e?gb(e):gb),_b=ex(),yb=A_(),ja=UC(e=>({panelTab:"git",composerText:"",activeSessionId:null,bottomNavVisible:!0,isSettingsOverlayOpen:!1,themeSettings:_b,systemAppearance:yb,resolvedTheme:Lr(_b,yb),setPanelTab:t=>e({panelTab:t}),setComposerText:t=>e({composerText:t}),setActiveSessionId:t=>e({activeSessionId:t}),setBottomNavVisible:t=>e({bottomNavVisible:t}),openSettingsOverlay:()=>e({isSettingsOverlayOpen:!0}),closeSettingsOverlay:()=>e({isSettingsOverlayOpen:!1}),setThemeMode:t=>e(a=>{const l=Fl({...a.themeSettings,mode:t});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setLightThemeId:t=>e(a=>{const l=Fl(hb(Ap(t).id,a.themeSettings,"light"));return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setDarkThemeId:t=>e(a=>{const l=Fl({...hb(Dp(t).id,a.themeSettings,"dark")});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setUiFontSize:t=>e(a=>{const l=Fl({...a.themeSettings,uiFontSize:t});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setCodeFontSize:t=>e(a=>{const l=Fl({...a.themeSettings,codeFontSize:t});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setSystemAppearance:t=>e(a=>({systemAppearance:t,resolvedTheme:Lr(a.themeSettings,t)}))})),vb=980,wm=[{id:"theme",title:"主题",description:"调整界面的颜色风格。",icon:"theme"},{id:"models",title:"模型维护",description:"维护可选模型、默认模型和展示顺序。",icon:"models"},{id:"cache",title:"缓存",description:"解决页面没更新的问题。",icon:"cache"},{id:"notifications",title:"移动提醒",description:"安装到桌面,并在对话完成后接收系统通知。",icon:"notifications"},{id:"installation",title:"安装诊断",description:"判断当前是不是安装版,并分析为什么安装失败。",icon:"installation"},{id:"connection",title:"连接状态",description:"查看现在连到哪台设备。",icon:"connection"},{id:"dev-manager",title:"开发版管理",description:"维护开发版、npm 发布、自升级和 APK 编译下载。",icon:"dev-manager"}],zC=[{id:"appearance",label:"外观与模型",sections:["theme","models","cache"]},{id:"notifications",label:"提醒与安装",sections:["notifications","installation"]},{id:"connection",label:"连接与设备",sections:["connection","dev-manager"]}],BC=[{value:"light",label:"浅色",icon:"sun"},{value:"dark",label:"深色",icon:"moon"},{value:"system",label:"系统",icon:"system"}],HC=(e,t,a,l)=>["const pandaTheme = {",` codeThemeId: "${e}",`,` accent: "${t.toLowerCase()}",`,` contrast: ${a},`,` opaqueWindows: ${l},`,"}"],$C=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m15 6-6 6 6 6"})}),FC=({open:e})=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:e?"m6 9 6 6 6-6":"m9 6 6 6-6 6"})}),qC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01"})}),WC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M12 5v14M5 12h14"})}),KC=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m4 20 4.2-1 9.2-9.2a1.8 1.8 0 0 0 0-2.6l-.6-.6a1.8 1.8 0 0 0-2.6 0L5 15.8 4 20Z"}),i.jsx("path",{d:"m13.5 6.5 4 4"})]}),QC=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M4.5 7h15"}),i.jsx("path",{d:"M9.5 4.5h5"}),i.jsx("path",{d:"M7 7l.6 11a1.8 1.8 0 0 0 1.8 1.7h5.2a1.8 1.8 0 0 0 1.8-1.7L17 7"}),i.jsx("path",{d:"M10 10.5v5.2"}),i.jsx("path",{d:"M14 10.5v5.2"})]}),GC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m12 6-5 5M12 6l5 5M12 6v12"})}),YC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m12 18-5-5M12 18l5-5M12 18V6"})}),bb=({icon:e})=>e==="cache"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M5 8.5C5 6.57 8.13 5 12 5s7 1.57 7 3.5S15.87 12 12 12 5 10.43 5 8.5Z"}),i.jsx("path",{d:"M5 8.5v7c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5v-7"}),i.jsx("path",{d:"M5 12c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5"})]}):e==="models"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M5 7.5h14M5 12h14M5 16.5h14"}),i.jsx("path",{d:"M8 5.5h.01M8 10h.01M8 14.5h.01"})]}):e==="connection"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9.5 14.5a3.5 3.5 0 0 1 0-5l1.5-1.5a3.5 3.5 0 0 1 5 5L15 14"}),i.jsx("path",{d:"M14.5 9.5a3.5 3.5 0 0 1 0 5L13 16a3.5 3.5 0 0 1-5-5L9 10"})]}):e==="dev-manager"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 3.75v4.5"}),i.jsx("path",{d:"M12 15.75v4.5"}),i.jsx("path",{d:"M3.75 12h4.5"}),i.jsx("path",{d:"M15.75 12h4.5"}),i.jsx("path",{d:"m6.7 6.7 3.1 3.1"}),i.jsx("path",{d:"m14.2 14.2 3.1 3.1"}),i.jsx("path",{d:"m17.3 6.7-3.1 3.1"}),i.jsx("path",{d:"m9.8 14.2-3.1 3.1"}),i.jsx("circle",{cx:"12",cy:"12",r:"2.9"})]}):e==="notifications"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6.5 9.5a5.5 5.5 0 0 1 11 0c0 5.25 1.9 6.83 1.9 6.83H4.6S6.5 14.75 6.5 9.5Z"}),i.jsx("path",{d:"M10 18.25a2.1 2.1 0 0 0 4 0"})]}):e==="installation"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 3.75v10.5"}),i.jsx("path",{d:"m8.5 10.75 3.5 3.5 3.5-3.5"}),i.jsx("path",{d:"M5.25 16.75h13.5"}),i.jsx("path",{d:"M6 19.25h12"})]}):i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 4.75v2.1M12 17.15v2.1M4.78 4.78l1.49 1.49M17.73 17.73l1.49 1.49M2.75 12h2.1M19.15 12h2.1M4.78 19.22l1.49-1.49M17.73 6.27l1.49-1.49"}),i.jsx("circle",{cx:"12",cy:"12",r:"3.85"})]}),VC=({icon:e,active:t})=>{const a=t?2:1.8;return e==="sun"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"4.1"}),i.jsx("path",{d:"M12 2.75v2.1M12 19.15v2.1M4.78 4.78l1.49 1.49M17.73 17.73l1.49 1.49M2.75 12h2.1M19.15 12h2.1M4.78 19.22l1.49-1.49M17.73 6.27l1.49-1.49"})]}):e==="moon"?i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M20.2 14.1A8.5 8.5 0 1 1 9.9 3.8a6.9 6.9 0 0 0 10.3 10.3Z"})}):i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"3.5",y:"5",width:"17",height:"12",rx:"2.4"}),i.jsx("path",{d:"M8 19h8"})]})},ZC=({title:e,caption:t,accent:a,background:l,foreground:o,lines:u})=>i.jsxs("div",{className:"theme-preview-panel",style:{"--preview-accent":a,"--preview-background":l,"--preview-foreground":o},children:[i.jsxs("div",{className:"theme-preview-panel__meta",children:[i.jsx("span",{children:e}),i.jsx("span",{children:t})]}),i.jsx("pre",{className:"theme-preview-panel__code","aria-label":`${e} 主题预览`,children:u.map(f=>i.jsx("code",{children:f},f))})]}),hu=({label:e,value:t})=>i.jsxs("div",{className:"settings-row settings-row--token",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsxs("div",{className:"theme-token",children:[i.jsx("span",{className:"theme-token__swatch",style:{"--token-color":t}}),i.jsx("span",{children:t})]})]}),Nm=({label:e,value:t})=>i.jsxs("div",{className:"settings-row settings-row--token",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsx("div",{className:"theme-token",children:t})]}),xb=({label:e,value:t,mono:a})=>i.jsxs("div",{className:"settings-row settings-row--token",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsx("div",{className:`theme-token theme-token--font ${a?"is-mono":""}`,children:t})]}),Sb=({label:e,value:t,onChange:a,min:l,max:o})=>i.jsxs("div",{className:"settings-row settings-row--size",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsxs("div",{className:"theme-stepper",children:[i.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>a(t-1),"aria-label":`${e} 减小 1px`,children:"-"}),i.jsxs("label",{className:"theme-stepper__input-wrap",children:[i.jsx("input",{className:"theme-stepper__input",type:"number",min:l,max:o,step:1,value:t,onChange:u=>a(Number(u.target.value))}),i.jsx("span",{children:"px"})]}),i.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>a(t+1),"aria-label":`${e} 增大 1px`,children:"+"})]})]}),jb=(e,t,a,l)=>{if(t===a)return e;const o=e.findIndex(S=>S.id===t),u=e.findIndex(S=>S.id===a);if(o<0||u<0)return e;const f=[...e],[m]=f.splice(o,1);if(!m)return e;const y=f.findIndex(S=>S.id===a),g=l==="before"?y:y+1;return f.splice(g,0,m),f},mu=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},km=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,Ng=async(e,t)=>{const a=await u0(t);return{label:e,...a}},ix=({mode:e="page",onRequestClose:t}={})=>{var yn,Zn;const a=ki(),l=La(),o=Mp(),{data:u}=I_(),[f,m]=_.useState(!1),[y,g]=_.useState(null),[S,p]=_.useState(null),[b,w]=_.useState("theme"),[N,j]=_.useState(null),[T,D]=_.useState(()=>typeof window<"u"&&window.innerWidth>=vb),[z,I]=_.useState(()=>N0()),[k,P]=_.useState(()=>Cu()),[Q,se]=_.useState(()=>ed()),[W,V]=_.useState(()=>E0()),[Y,ee]=_.useState(!1),[me,ge]=_.useState(!1),[te,xe]=_.useState(null),[C,q]=_.useState(!1),[ie,he]=_.useState(()=>Nu()),[re,L]=_.useState(()=>X4()),[ae,ke]=_.useState(0),U=ja(A=>A.themeSettings),ve=ja(A=>A.resolvedTheme),Z=ja(A=>A.systemAppearance),Se=ja(A=>A.setThemeMode),je=ja(A=>A.setLightThemeId),Oe=ja(A=>A.setDarkThemeId),Ie=ja(A=>A.setUiFontSize),wt=ja(A=>A.setCodeFontSize),qe=O_(),[bt,Ut]=_.useState(()=>R_()),[$t,zt]=_.useState(()=>qm()),[xt,it]=_.useState(()=>$3()),[ot,ln]=_.useState(null),[on,kn]=_.useState(()=>xf()),[En,ht]=_.useState(null),[Ve,Ke]=_.useState(null),[Nt,Bt]=_.useState(null),Jt=typeof window>"u"?null:pc(),Dt=typeof window>"u"?null:mp(),Ze=(u==null?void 0:u.agents.find(A=>A.id===Jt))??(u==null?void 0:u.agents[0]),un=((yn=Ze==null?void 0:Ze.direct_base_url)==null?void 0:yn.trim().replace(/\/+$/,""))??"",ut=o.platform!=="web",_e=b==="cache"||N==="cache",Fe=Ze!=null&&Ze.id?{agentId:Ze.id}:void 0,X=sx(Fe),B=ls({queryKey:["settings-connection",o.hubUrl,(Ze==null?void 0:Ze.id)??"",un],queryFn:async()=>{const A=await wn(),[le,tt,Ht]=await Promise.all([Ng(A.label,A.baseUrl),Ng("Panda Hub",id()),un?Ng((Ze==null?void 0:Ze.name)??"当前节点",un):Promise.resolve(null)]);return{modeLabel:A.mode==="hub"?"通过 Panda Hub":"直接连接",backendLabel:A.label,backendUrl:A.baseUrl,healthOk:le.healthOk,latencyMs:le.latencyMs,checkedAt:le.checkedAt,activeProbe:le,hubProbe:tt,agentProbe:Ht}},enabled:b==="connection"||N==="connection",staleTime:0,refetchOnWindowFocus:!1}),oe=ls({queryKey:["installed-app-info",o.platform],queryFn:()=>QE(),enabled:ut,staleTime:3e4,refetchOnWindowFocus:!1}),ue=ls({queryKey:["android-release-manifest",o.hubUrl],queryFn:()=>GE(o.hubUrl),enabled:o.platform==="android"&&!!o.hubUrl&&(b==="connection"||N==="connection"),staleTime:0,refetchOnWindowFocus:!1}),we=ax({enabled:_e&&!!Fe,scope:Fe}),Re=()=>{ke(A=>A+1)},He=ls({queryKey:["pwa-install-diagnostics",ae,!!te,ie],queryFn:async()=>MC({installPromptAvailable:!!te}),enabled:b==="installation"||N==="installation",staleTime:0,refetchOnWindowFocus:!1}),ze=Vn({mutationFn:async()=>{if(!Fe)throw new Error("当前没有可用节点,无法刷新命令目录。");return(await wn(Fe)).client.refreshCodexCommands()},onMutate:()=>{g(null)},onSuccess:A=>{l.setQueryData(X,A),g(`命令目录已刷新,共 ${A.commands.length} 条,CLI 版本 ${A.cli_version??"未知"}。`)},onError:A=>{g(A instanceof Error?A.message:"刷新命令目录失败。")}});_.useEffect(()=>{if(typeof window>"u")return;const A=()=>{const le=window.innerWidth>=vb;D(le)};return A(),window.addEventListener("resize",A),()=>{window.removeEventListener("resize",A)}},[]),_.useEffect(()=>{g(null)},[(Zn=B.data)==null?void 0:Zn.backendUrl]),_.useEffect(()=>{T&&j(b)},[b,T]),_.useEffect(()=>{ht(null)},[b]),_.useEffect(()=>{if(typeof window>"u")return;const A=Ht=>{Ht.preventDefault(),xe(Ht),Pl({kind:"beforeinstallprompt",message:"浏览器提供了可调用的安装事件。",detail:window.location.href}),Re()},le=()=>{xe(null),he(!0),p("应用已安装到桌面。"),Pl({kind:"appinstalled",message:"站点收到 appinstalled 事件。",detail:"浏览器报告安装流程已经完成或被接受。"}),Re()},tt=()=>{P(Cu()),I(N0()),he(Nu()),L(X4()),Pl({kind:"visibilitychange",message:`页面切换为 ${document.visibilityState}。`,detail:`standalone=${Nu()?"yes":"no"}`}),Re()};return window.addEventListener("beforeinstallprompt",A),window.addEventListener("appinstalled",le),document.addEventListener("visibilitychange",tt),()=>{window.removeEventListener("beforeinstallprompt",A),window.removeEventListener("appinstalled",le),document.removeEventListener("visibilitychange",tt)}},[]),_.useEffect(()=>{if(qe.length===0||qe.some(le=>le.value===bt))return;const A=qe[0].value;zf(A),Ut(A)},[qe,bt]),_.useEffect(()=>{var le;if(qe.length===0||qe.some(tt=>tt.value===$t))return;const A=((le=qe.find(tt=>tt.value==="gpt-5.4-mini"))==null?void 0:le.value)??qe[0].value;jg(A),zt(A)},[$t,qe]),_.useEffect(()=>{var le;if(qe.length===0||qe.some(tt=>tt.value===xt))return;const A=((le=qe.find(tt=>tt.value==="gpt-5.4-mini"))==null?void 0:le.value)??qe[0].value;wg(A),it(A)},[qe,xt]),_.useEffect(()=>{const A=()=>{j_().then(le=>{P(le)}).catch(()=>{P(Cu())}),se(ed()),V(E0())};return A(),window.addEventListener("focus",A),document.addEventListener("visibilitychange",A),()=>{window.removeEventListener("focus",A),document.removeEventListener("visibilitychange",A)}},[]),_.useEffect(()=>{if(k!=="granted"||!z.completionNotificationsEnabled||!Q)return;let A=!1;return ee(!0),Gk(z).then(le=>{A||V(le.synced)}).catch(()=>{A||V(!1)}).finally(()=>{A||ee(!1)}),()=>{A=!0}},[Q,k,z]);const rt=()=>{if(e==="overlay"){t==null||t();return}if(Dt){Ji((Ze==null?void 0:Ze.id)??null),Js(Dt),a({to:"/"});return}a({to:"/nodes"})},It=A=>{e==="overlay"&&(t==null||t()),a({to:A})},Ft=async()=>{g(null),m(!0);try{await xC(),g("缓存已清理,正在重新载入…"),window.setTimeout(()=>{window.location.replace(`/settings?cache-reset=${Date.now()}`)},180)}catch{m(!1),g("清理失败,请在浏览器设置中手动清理站点数据。")}},Le=async()=>{if(p(null),ut){if(k==="granted"){p("当前已经拿到系统通知权限;完成提醒会自动跟随系统权限生效。");return}const A=await k0();if(P(A),A==="granted"){const le={completionNotificationsEnabled:!0};Ho(le),I(le),p("系统通知已开启,后续任务完成会直接走原生通知。");return}if(A==="denied"){p("系统通知已被拒绝,请到系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(k!=="granted"){const A=await k0();if(P(A),A==="granted"){if(!Q){const le={completionNotificationsEnabled:!0};Ho(le),I(le),p(ut?"系统通知已开启,任务完成时会直接走原生通知。":"系统通知已开启,但当前环境不支持后台 Web Push。");return}ee(!0);try{const le={completionNotificationsEnabled:!0};await Z4(le),Ho(le),I(le),V(!0),p("系统通知和后台 Web Push 都已开启。");return}catch(le){V(!1),p(le instanceof Error?le.message:"通知权限已开启,但 Web Push 订阅失败。");return}finally{ee(!1)}}if(A==="denied"){p("系统通知已被拒绝,请到浏览器或系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(z.completionNotificationsEnabled){ee(!0);try{await Yk();const A={completionNotificationsEnabled:!1};Ho(A),I(A),V(!1),p("完成提醒已关闭,后台推送订阅也已移除。")}catch(A){p(A instanceof Error?A.message:"关闭 Web Push 订阅失败。")}finally{ee(!1)}return}if(!Q){const A={completionNotificationsEnabled:!0};Ho(A),I(A),p(ut?"原生通知已开启,后续会沿用当前 App 的在线事件提醒。":"当前环境不支持后台 Web Push,只能在页面在线时提醒。");return}ee(!0);try{const A={completionNotificationsEnabled:!0};await Z4(A),Ho(A),I(A),V(!0),p("完成提醒已开启,Hub 会在会话完成后推送到这台手机。")}catch(A){V(!1),p(A instanceof Error?A.message:"开启 Web Push 失败。")}finally{ee(!1)}},Et=async()=>{p(null),ge(!0);try{if(ut){await m3({sessionId:"settings-test",completedAt:new Date().toISOString(),title:"Panda 测试提醒",body:"这是一条来自 Android 壳的本地通知测试。",url:"/settings"}),p("测试通知已发出,请看当前设备的系统通知栏。");return}await Vk(),p("测试推送已发出,请看手机或当前设备的通知栏。")}catch(A){p(A instanceof Error?A.message:"发送测试推送失败。")}finally{ge(!1)}},Cn=async()=>{if(!te){Pl({kind:"install-unavailable",message:"当前页面没有可用的安装事件。",detail:re?"浏览器没有下发 beforeinstallprompt,只能走菜单里的安装应用或添加到主屏幕。":"当前浏览器没有提供可调用的安装对话框。"}),Re(),p(re?"请在浏览器菜单里选择“安装应用”或“添加到主屏幕”。":"当前浏览器没有提供安装弹窗,请使用浏览器的“添加到主屏幕”。");return}q(!0),p(null),Pl({kind:"install-button-click",message:"用户点击了设置页里的安装按钮。",detail:"准备调用浏览器安装对话框。"}),Re();try{Pl({kind:"install-prompt-shown",message:"已调用浏览器安装对话框。",detail:"等待用户在系统安装弹窗里做出选择。"}),await te.prompt();const A=await te.userChoice;Pl({kind:"install-choice",message:A.outcome==="accepted"?"用户接受了安装请求。":"用户取消了安装请求。",detail:`outcome=${A.outcome}; platform=${A.platform}`}),Re(),A.outcome==="accepted"?p("安装请求已提交,请回到桌面查看。"):p("你取消了这次安装。")}catch(A){Pl({kind:"install-error",message:"调用浏览器安装流程时报错。",detail:A instanceof Error?A.message:"Unknown install error"}),Re(),p("浏览器没有完成安装流程,请查看下方安装诊断。")}finally{xe(null),q(!1),he(Nu()),Re()}},hs=A=>{var le,tt,Ht,cn,mt;if(sC(A),!A.some(St=>St.value===bt)){const St=((le=A[0])==null?void 0:le.value)??"";St&&(zf(St),Ut(St))}if(!A.some(St=>St.value===$t)){const St=((tt=A.find(Rn=>Rn.value==="gpt-5.4-mini"))==null?void 0:tt.value)??((Ht=A[0])==null?void 0:Ht.value)??"";St&&(jg(St),zt(St))}if(!A.some(St=>St.value===xt)){const St=((cn=A.find(Rn=>Rn.value==="gpt-5.4-mini"))==null?void 0:cn.value)??((mt=A[0])==null?void 0:mt.value)??"";St&&(wg(St),it(St))}},na=()=>{ln("new"),kn(xf()),ht(null)},Ws=A=>{ln(A.id),kn({...A}),ht(null)},Ja=()=>{ln(null),kn(xf()),ht(null)},Rs=()=>{var mt;const A=on.label.trim(),le=on.value.trim();if(!A||!le){ht("请填写显示名和模型 ID。");return}if(qe.find(St=>St.value.toLowerCase()===le.toLowerCase()&&St.id!==ot)){ht(`模型 ID ${le} 已存在。`);return}const Ht={...on,label:A,value:le,description:((mt=on.description)==null?void 0:mt.trim())||null},cn=ot==="new"?[...qe,Ht]:qe.map(St=>St.id===ot?Ht:St);hs(cn),ln(null),kn(xf()),ht(ot==="new"?"模型已添加。":"模型已更新。")},Na=A=>{const le=qe.filter(tt=>tt.id!==A);if(le.length===0){ht("至少保留一个模型。");return}hs(le),ot===A&&(ln(null),kn(xf())),ht("模型已删除。")},Pa=A=>{zf(A),Ut(A),ht(`默认模型已切换为 ${A}。`)},ms=A=>{jg(A),zt(A),ht(`命令执行模型已切换为 ${A}。`)},dn=A=>{wg(A),it(A),ht(`标题生成模型已切换为 ${A}。`)},pn=(A,le)=>{const tt=qe.findIndex(mt=>mt.id===A);if(tt<0)return;const Ht=le==="up"?tt-1:tt+1;if(Ht<0||Ht>=qe.length)return;const cn=qe[Ht];cn&&hs(jb(qe,A,cn.id,le==="up"?"before":"after"))},Un=(A,le)=>{Ke(le),Bt(null),A.dataTransfer.effectAllowed="move",A.dataTransfer.setData("text/plain",le)},ps=(A,le)=>{if(!Ve||Ve===le)return;A.preventDefault();const tt=A.currentTarget.getBoundingClientRect(),Ht=A.clientY<tt.top+tt.height/2?"before":"after";Bt(cn=>(cn==null?void 0:cn.modelId)===le&&cn.position===Ht?cn:{modelId:le,position:Ht})},Ps=A=>{!Ve||!Nt||Nt.modelId!==A||(hs(jb(qe,Ve,A,Nt.position)),Ke(null),Bt(null))},Us=()=>{Ke(null),Bt(null)},Ms=ve.appearance,xs=Ms==="light"?A0:Jf,As=Ms==="light"?U.lightThemeId:U.darkThemeId,Rt=xs.find(A=>A.id===As)??xs[0],J=ve.activeTheme,M=HC(Rt.codeThemeId,Rt.accent,Rt.contrast,Rt.opaqueWindows),G=U.mode==="system"?`当前跟随系统:${Z==="dark"?"深色":"浅色"}`:`当前固定为${ve.appearance==="dark"?"深色":"浅色"}模式`,Ee="当前正在显示",De=Rt.opaqueWindows?"不透明窗口":"半透明窗口",Pe=wm.find(A=>A.id===b)??wm[0],$e={"--settings-mobile-sticky-safe-area":ut?"0px":"var(--app-safe-area-top)"},Je=`${Rt.label} · ${De} · 对比度 ${Rt.contrast}`,Ye=qe.find(A=>A.value===bt)??qe[0]??null,en=qe.find(A=>A.value===$t)??qe.find(A=>A.value==="gpt-5.4-mini")??qe[0]??null,jt=qe.find(A=>A.value===xt)??qe.find(A=>A.value==="gpt-5.4-mini")??qe[0]??null,$n=A=>{var le;return A==="theme"?ve.activeTheme.label:A==="models"?(Ye==null?void 0:Ye.label)??`${qe.length} 个模型`:A==="cache"?y||(we.data?`${we.data.commands.length} 条命令`:"站点与命令目录"):A==="notifications"?z.completionNotificationsEnabled?"已开启":"未开启":A==="installation"?ie?"已安装":"检查状态":(le=B.data)!=null&&le.healthOk?B.data.modeLabel:(Ze==null?void 0:Ze.name)??"查看链路"},gn=()=>i.jsx("div",{className:"settings-mobile-layout",children:i.jsx("div",{className:"settings-mobile-sections",role:"list","aria-label":"设置分组",children:zC.map(A=>i.jsx("section",{className:"settings-mobile-group","aria-label":A.label,children:A.sections.map(le=>{const tt=wm.find(mt=>mt.id===le);if(!tt)return null;const Ht=N===tt.id,cn=$n(tt.id);return i.jsxs(_.Fragment,{children:[i.jsxs("button",{type:"button",className:`settings-mobile-row ${Ht?"is-active":""}`,"data-section":tt.id,onClick:()=>{w(tt.id),j(mt=>mt===tt.id?null:tt.id)},"aria-expanded":Ht,"aria-controls":`settings-mobile-detail-${tt.id}`,children:[i.jsx("span",{className:"settings-mobile-row__icon","data-section":tt.id,"aria-hidden":"true",children:i.jsx(bb,{icon:tt.icon})}),i.jsx("span",{className:"settings-mobile-row__copy",children:i.jsx("span",{className:"settings-mobile-row__title",children:tt.title})}),i.jsx("span",{className:"settings-mobile-row__summary",children:cn}),i.jsx("span",{className:"settings-mobile-row__chevron","aria-hidden":"true",children:i.jsx(FC,{open:!1})})]}),Ht?i.jsx("section",{className:"settings-mobile-detail settings-mobile-detail--inline",id:`settings-mobile-detail-${tt.id}`,children:qt(tt.id)}):null]},tt.id)})},A.id))})}),bn=()=>i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"外观"}),i.jsx("p",{className:"settings-panel__subtitle",children:"先选浅色或深色,再挑一个你喜欢的风格。"})]})}),i.jsx("div",{className:"settings-control-grid",children:i.jsxs("div",{className:"settings-control-block settings-control-block--full",children:[i.jsx("span",{className:"settings-control-block__label",children:"显示方式"}),i.jsx("div",{className:"theme-mode-switch",role:"tablist","aria-label":"主题模式",children:BC.map(A=>{const le=A.value===U.mode;return i.jsxs("button",{type:"button",className:`theme-mode-switch__button ${le?"is-active":""}`,onClick:()=>Se(A.value),role:"tab","aria-selected":le,children:[i.jsx(VC,{icon:A.icon,active:le}),i.jsx("span",{children:A.label})]},A.value)})}),i.jsx("p",{className:"settings-control-block__hint",children:G})]})})]}),i.jsxs("div",{className:"settings-theme-layout",children:[i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:Ms==="light"?"浅色风格":"深色风格"})})}),i.jsxs("div",{className:"settings-theme-selector",children:[i.jsx("label",{className:"settings-select settings-select--wide",children:i.jsx("select",{value:Rt.id,onChange:A=>{if(Ms==="light"){je(A.target.value);return}Oe(A.target.value)},"aria-label":Ms==="light"?"选择浅色主题":"选择深色主题",children:xs.map(A=>i.jsx("option",{value:A.id,children:A.label},`${A.variant}-${A.id}`))})}),i.jsxs("div",{className:"settings-theme-selector__summary",children:[i.jsxs("div",{className:"settings-theme-selector__swatches","aria-hidden":"true",children:[i.jsx("span",{style:{"--theme-card-color":Rt.background}}),i.jsx("span",{style:{"--theme-card-color":Rt.foreground}}),i.jsx("span",{style:{"--theme-card-color":Rt.accent}}),i.jsx("span",{style:{"--theme-card-color":Rt.semanticColors.diffAdded}}),i.jsx("span",{style:{"--theme-card-color":Rt.semanticColors.diffRemoved}})]}),i.jsxs("div",{className:"settings-theme-selector__copy",children:[i.jsx("strong",{children:Rt.label}),i.jsx("span",{children:Je})]}),Rt.id===J.id&&Rt.variant===ve.appearance?i.jsx("span",{className:"settings-theme-selector__badge",children:"当前"}):i.jsx("span",{className:"settings-theme-selector__badge is-muted",children:"已选"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"风格细节"})}),i.jsx("div",{className:"theme-status-badge",children:Ee})]}),i.jsx(ZC,{title:Ms==="light"?"浅色预览":"深色预览",caption:Rt.label,accent:Rt.accent,background:Rt.background,foreground:Rt.foreground,lines:M}),i.jsxs("div",{className:"settings-list",children:[i.jsx(Nm,{label:"代码风格",value:Rt.codeThemeId}),i.jsx(Nm,{label:"当前模式",value:Rt.variant}),i.jsx(Nm,{label:"对比度",value:String(Rt.contrast)}),i.jsx(Nm,{label:"面板质感",value:De}),i.jsx(hu,{label:"强调色",value:Rt.accent}),i.jsx(hu,{label:"背景色",value:Rt.background}),i.jsx(hu,{label:"文字色",value:Rt.foreground}),i.jsx(hu,{label:"新增颜色",value:Rt.semanticColors.diffAdded}),i.jsx(hu,{label:"删除颜色",value:Rt.semanticColors.diffRemoved}),i.jsx(hu,{label:"特殊强调",value:Rt.semanticColors.skill}),i.jsx(xb,{label:"界面字体",value:Rt.fonts.ui??"null"}),i.jsx(xb,{label:"代码字体",value:Rt.fonts.code??"null",mono:!0})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"字号"})})}),i.jsxs("div",{className:"settings-list",children:[i.jsx(Sb,{label:"界面字号",value:U.uiFontSize,onChange:A=>Ie(X3(A)),min:11,max:18}),i.jsx(Sb,{label:"代码字号",value:U.codeFontSize,onChange:A=>wt(J3(A)),min:10,max:18})]})]})]}),Tn=()=>{var A;return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"模型列表"})}),i.jsxs("button",{type:"button",className:"settings-inline-action",onClick:na,children:[i.jsx(WC,{}),"新增模型"]})]}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"首位模型"}),i.jsx("strong",{children:((A=qe[0])==null?void 0:A.label)??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前默认"}),i.jsx("strong",{children:(Ye==null?void 0:Ye.label)??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"命令执行模型"}),i.jsx("strong",{children:(en==null?void 0:en.label)??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"标题生成模型"}),i.jsx("strong",{children:(jt==null?void 0:jt.label)??"未配置"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"模型角色"})})}),i.jsxs("div",{className:"settings-model-editor__grid",children:[i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"默认模型"}),i.jsx("select",{value:bt,onChange:le=>Pa(le.target.value),children:qe.map(le=>i.jsx("option",{value:le.value,children:le.label},le.id))})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"命令执行模型"}),i.jsx("select",{value:$t,onChange:le=>ms(le.target.value),children:qe.map(le=>i.jsx("option",{value:le.value,children:le.label},le.id))})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"标题生成模型"}),i.jsx("select",{value:xt,onChange:le=>dn(le.target.value),children:qe.map(le=>i.jsx("option",{value:le.value,children:le.label},le.id))})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"维护模型"})})}),En?i.jsx("div",{className:"settings-inline-status",role:"alert",children:En}):null,i.jsx("div",{className:"settings-model-list",role:"list","aria-label":"模型列表",children:qe.map((le,tt)=>{const Ht=Ve===le.id,cn=(Nt==null?void 0:Nt.modelId)===le.id&&Nt.position==="before",mt=(Nt==null?void 0:Nt.modelId)===le.id&&Nt.position==="after",St=le.value===bt;return i.jsxs("article",{className:`settings-model-card ${Ht?"is-dragging":""} ${cn?"is-drop-before":""} ${mt?"is-drop-after":""}`,draggable:!0,onDragStart:Rn=>Un(Rn,le.id),onDragOver:Rn=>ps(Rn,le.id),onDrop:Rn=>{Rn.preventDefault(),Ps(le.id)},onDragEnd:Us,role:"listitem",children:[i.jsxs("div",{className:"settings-model-card__main",children:[i.jsx("span",{className:"settings-model-card__grip","aria-hidden":"true",children:i.jsx(qC,{})}),i.jsxs("div",{className:"settings-model-card__copy",children:[i.jsxs("div",{className:"settings-model-card__title-row",children:[i.jsx("strong",{children:le.label}),St?i.jsx("span",{className:"settings-model-card__badge",children:"默认"}):null]}),i.jsx("code",{className:"settings-model-card__value",children:le.value})]})]}),i.jsxs("div",{className:"settings-model-card__actions",children:[i.jsx("button",{type:"button",className:`settings-mini-button settings-model-card__primary-action ${St?"is-active":""}`,onClick:()=>Pa(le.value),children:"设为默认"}),i.jsxs("div",{className:"settings-model-card__icon-actions",children:[i.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>pn(le.id,"up"),disabled:tt===0,"aria-label":`上移 ${le.label}`,children:i.jsx(GC,{})}),i.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>pn(le.id,"down"),disabled:tt===qe.length-1,"aria-label":`下移 ${le.label}`,children:i.jsx(YC,{})}),i.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Ws(le),"aria-label":`编辑 ${le.label}`,children:i.jsx(KC,{})}),i.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>Na(le.id),disabled:qe.length<=1,"aria-label":`删除 ${le.label}`,children:i.jsx(QC,{})})]})]})]},le.id)})}),ot?i.jsxs("div",{className:"settings-model-editor",children:[i.jsx("div",{className:"settings-model-editor__header",children:i.jsx("strong",{children:ot==="new"?"新增模型":"编辑模型"})}),i.jsxs("div",{className:"settings-model-editor__grid",children:[i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"显示名"}),i.jsx("input",{type:"text",value:on.label,onChange:le=>kn(tt=>({...tt,label:le.target.value})),placeholder:"例如:gpt-5.4"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"模型 ID"}),i.jsx("input",{type:"text",value:on.value,onChange:le=>kn(tt=>({...tt,value:le.target.value})),placeholder:"例如:gpt-5.4"})]})]}),i.jsxs("div",{className:"settings-model-editor__actions",children:[i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:Ja,children:"取消"}),i.jsx("button",{type:"button",className:"settings-inline-action",onClick:Rs,children:"保存"})]})]}):null]})]})},xn=()=>{var A,le;return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"页面缓存"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"适合什么时候用"}),i.jsx("strong",{children:"页面资源或本地缓存异常"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"常见表现"}),i.jsx("strong",{children:"样式没更新、列表卡旧、页面反复异常"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"清理缓存"})})}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Ft(),disabled:f,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:"清理并刷新"}),i.jsx("span",{children:"删除页面资源缓存和本地会话缓存,强制重新加载最新页面。"})]}),i.jsx("span",{className:"settings-action__state",children:f?"处理中…":"→"})]}),y?i.jsx("p",{className:"settings-block__status",children:y}):null]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"移动端诊断"})})}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>It("/diagnostics"),children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:"打开安卓诊断页"}),i.jsx("span",{children:"在手机上检查样式能力、资源加载、Service Worker 和缓存状态,并可上传到后端日志。"})]}),i.jsx("span",{className:"settings-action__state",children:"→"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"命令目录缓存"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 CLI"}),i.jsx("span",{children:((A=we.data)==null?void 0:A.cli_version)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近刷新"}),i.jsx("span",{children:((le=we.data)==null?void 0:le.loaded_at)??"尚未生成"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"命令数量"}),i.jsx("span",{children:we.data?`${we.data.commands.length} 条`:"检测中…"})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void ze.mutateAsync(),disabled:ze.isPending,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:"刷新命令目录"}),i.jsx("span",{children:"重新从当前 Codex CLI 对应版本拉取命令并覆盖本地缓存文件。"})]}),i.jsx("span",{className:"settings-action__state",children:ze.isPending?"刷新中…":"→"})]})]})]})},zn=()=>{var mt,St,Rn,Ks,ei,zs,Qs,ka,ti,nr,ni,Gs,si,ai,sa,aa,ii,sr,ri,Ds,Bs,ar;const A=oe.data,le=ue.data,tt=!!(le!=null&&le.apk_url),Ht=VE(A,le),cn=A3(o.hubUrl);return i.jsxs("div",{className:"settings-content-stack",children:[ut?i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"Hub 连接配置"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前 Hub"}),i.jsx("strong",{children:o.hubUrl||"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"首启状态"}),i.jsx("strong",{children:o.onboardingCompleted?"已完成":"未完成"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"App 形态"}),i.jsx("strong",{children:"Capacitor Android"})]})]})]}):i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"网页端连接基线"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前网页入口"}),i.jsx("strong",{children:o.hubUrl||"未检测到"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"地址来源"}),i.jsx("strong",{children:"浏览器访问地址"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"缓存策略"}),i.jsx("strong",{children:"同源页面 + 本地查询缓存"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:ut?"重新设置 Hub":"当前访问方式"})})}),ut?i.jsx(d6,{title:"输入新的 Hub 地址",description:"扫码或手动输入后,保存即可让 APK 用新地址重新建立连接。",currentHubUrl:o.hubUrl,initialHubUrl:o.hubUrl,hint:"保存后会清理旧的查询缓存、会话定位和连接判定缓存,避免继续误连到旧 Hub。",saveLabel:"保存并重连",savingLabel:"正在保存地址",saveDescription:"新的 Hub 地址会持久化到本机,后续重新打开 APK 会继续沿用。",saveSuccessMessage:"Hub 地址已保存,连接缓存和旧会话定位已重置。",onSaveSuccess:async ia=>{await q6({hubUrl:ia.url,onboardingCompleted:!0}),await v3(l),B.refetch(),ue.refetch(),oe.refetch()}}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Hub 地址"}),i.jsx("span",{children:o.hubUrl||"未检测到"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"可修改性"}),i.jsx("span",{children:"网页端跟随浏览器打开的地址,不额外保存本地覆盖配置。"})]})]})]}),o.platform==="android"?i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"App 升级"})}),i.jsx("div",{className:"settings-actions-row",children:i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{oe.refetch(),ue.refetch()},children:"刷新版本"})})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前版本"}),i.jsx("span",{children:(A==null?void 0:A.version)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 build"}),i.jsx("span",{children:(A==null?void 0:A.build)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"应用包名"}),i.jsx("span",{children:(A==null?void 0:A.appId)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"更新清单"}),i.jsx("span",{children:cn||"等待 Hub 地址"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最新发布"}),i.jsx("span",{children:ue.isLoading?"检测中…":le?`${le.version_name} (${le.version_code})`:ue.error instanceof Error?ue.error.message:"未检测到"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"升级状态"}),i.jsx("span",{className:Ht?"is-ok":"is-muted",children:Ht?"发现新版本":tt?"当前已是最新":"等待发布 APK"})]}),le!=null&&le.published_at?i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"发布时间"}),i.jsx("span",{children:mu(le.published_at)})]}):null,i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>{le!=null&&le.apk_url&&ZE(le.apk_url)},disabled:!(le!=null&&le.apk_url),children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:Ht?"下载并覆盖安装新版 APK":"打开最新 APK 下载地址"}),i.jsx("span",{children:"通过同一个 `applicationId` 和固定签名覆盖安装,旧配置和本地数据会保留,不需要卸载重装。"})]}),i.jsx("span",{className:"settings-action__state",children:le!=null&&le.apk_url?"→":"未就绪"})]}),le!=null&&le.release_notes.length?i.jsx("div",{className:"settings-diagnostic-list",children:le.release_notes.map(ia=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsx("strong",{children:"发布说明"}),i.jsx("span",{children:ia})]},ia))}):null]}):null,i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"当前设备"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"设备名称"}),i.jsx("strong",{children:(Ze==null?void 0:Ze.name)??"未选择节点"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"连接方式"}),i.jsx("strong",{children:((mt=B.data)==null?void 0:mt.modeLabel)??"检测中…"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前链路延迟"}),i.jsx("strong",{className:(St=B.data)!=null&&St.healthOk?"is-ok":"is-muted",children:B.isLoading?"检测中…":km((Rn=B.data)==null?void 0:Rn.latencyMs)})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"当前链路"})}),i.jsx("div",{className:"settings-actions-row",children:i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{B.refetch()},children:"刷新延迟"})})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"服务名称"}),i.jsx("span",{children:((Ks=B.data)==null?void 0:Ks.backendLabel)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"服务地址"}),i.jsx("span",{children:((ei=B.data)==null?void 0:ei.backendUrl)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前状态"}),i.jsx("span",{className:(zs=B.data)!=null&&zs.healthOk?"is-ok":"is-muted",children:B.isLoading?"检测中…":(Qs=B.data)!=null&&Qs.healthOk?"在线":((ka=B.data)==null?void 0:ka.activeProbe.error)??"无法连接"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前延迟"}),i.jsx("span",{children:km((ti=B.data)==null?void 0:ti.latencyMs)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近探测"}),i.jsx("span",{children:mu((nr=B.data)==null?void 0:nr.checkedAt)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"设备标识"}),i.jsx("span",{children:(Ze==null?void 0:Ze.id)??"未选择节点"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近会话"}),i.jsx("span",{children:Dt??"未选择会话"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"延迟对比"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Hub 延迟"}),i.jsx("span",{children:km((ni=B.data)==null?void 0:ni.hubProbe.latencyMs)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Hub 状态"}),i.jsx("span",{className:(Gs=B.data)!=null&&Gs.hubProbe.healthOk?"is-ok":"is-muted",children:(si=B.data)!=null&&si.hubProbe.healthOk?"在线":((ai=B.data)==null?void 0:ai.hubProbe.error)??"无法连接"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Hub 地址"}),i.jsx("span",{children:((sa=B.data)==null?void 0:sa.hubProbe.url)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Agent 延迟"}),i.jsx("span",{children:km((ii=(aa=B.data)==null?void 0:aa.agentProbe)==null?void 0:ii.latencyMs)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Agent 状态"}),i.jsx("span",{className:(ri=(sr=B.data)==null?void 0:sr.agentProbe)!=null&&ri.healthOk?"is-ok":"is-muted",children:(Ds=B.data)!=null&&Ds.agentProbe?B.data.agentProbe.healthOk?"在线":B.data.agentProbe.error??"无法连接":"未选择节点"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Agent 地址"}),i.jsx("span",{children:((ar=(Bs=B.data)==null?void 0:Bs.agentProbe)==null?void 0:ar.url)||un||"未配置"})]})]})]})},Ss=()=>{const A=ut?"原生 APK":ie?"已安装":"未安装",le=k==="granted"?"已允许":k==="denied"?"已拒绝":k==="default"?"待授权":"不支持",tt=ut?k==="granted"?"原生通知":"等待授权":Q?Y?"同步中":W?"已连接":z.completionNotificationsEnabled&&k==="granted"?"待连接":"未连接":"不支持",Ht=ut?k==="granted"?"已开启":"待授权":k==="granted"&&z.completionNotificationsEnabled?W?"后台可达":Q?"前台兜底":"仅前台":"未开启",cn=ut?"原生系统通知":Q?W?"Hub Web Push + 系统通知":"系统通知,后台通道待建立":"系统通知(仅页面在线)",mt=ut?k==="granted"?"通常可见,细节取决于系统设置":"先授予通知权限":W?ie?"已具备条件":"大多可见,安装后更稳":Q?"先建立后台通道":"当前环境很难稳定锁屏提醒",St=k==="unsupported"||!ut&&Y,Rn=ut?k==="granted"?"系统通知已开启":"申请通知权限":k==="granted"&&z.completionNotificationsEnabled?"关闭完成提醒":Y?"正在建立后台提醒":"开启完成提醒",Ks=k==="unsupported"?"当前环境不支持系统通知,需要 HTTPS、Service Worker 和受支持浏览器。":ut?k==="granted"?"首次连接时也会自动申请;这里主要用于补检查权限状态。":"如果首次连接时错过了授权,这里可以补申请一次。":Q?"开启后会向 Hub 注册这台设备,后台或锁屏时也能收到完成提醒。":"当前环境只能在页面在线时提醒,建议安装到桌面并使用支持 Web Push 的浏览器。",ei=ut?k==="unsupported"?"不可用":k==="granted"?"已开启":"→":k==="unsupported"?"不可用":Y?"同步中…":k==="granted"&&z.completionNotificationsEnabled?W?"已连接":Q?"待连接":"已开启":"→",zs=ut?k==="granted":k==="granted"&&z.completionNotificationsEnabled&&W&&!Y,Qs=ut?"直接在当前 APK 里发一条本地测试通知,确认系统权限和展示链路正常。":W?"立刻让 Hub 给当前这台设备发一条测试通知,用来确认后台链路是否真的可达。":"只有当前设备已经完成 Web Push 注册后,才能发送测试通知。";return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"安卓优先提醒"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"桌面安装"}),i.jsx("strong",{children:A})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"系统通知权限"}),i.jsx("strong",{children:le})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"完成提醒"}),i.jsx("strong",{children:Ht})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"后台 Web Push"}),i.jsx("strong",{children:tt})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:ut?"当前交付形态":"安装到桌面"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"推荐平台"}),i.jsx("span",{children:ut?"当前已经是 Android APK":re?"Android 当前设备":"Android 效果最佳"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前形态"}),i.jsx("span",{children:ut?"本地前端壳 + 局域网后端":ie?"已是桌面应用":"浏览器标签页"})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Cn(),disabled:ut||ie||C,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:ut?"已经是可安装 APK":ie?"已经安装":"安装到桌面"}),i.jsx("span",{children:ut?"当前无需再走 PWA 安装链路,后续升级直接下载新版 APK 覆盖安装即可。":ie?"现在可以直接从桌面图标进入 Panda。":"安装后更像应用,系统通知和锁屏提醒也更稳定。"})]}),i.jsx("span",{className:"settings-action__state",children:ut||ie?"✓":C?"处理中…":"→"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"对话完成提醒"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"提醒方式"}),i.jsx("span",{children:cn})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"锁屏可见"}),i.jsx("span",{children:mt})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"后台通道"}),i.jsx("span",{children:tt})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"触发时机"}),i.jsx("span",{children:ut?"App 在线时收到完成事件后,直接发原生系统通知":Q?"Hub 收到对话完成后主动推送":"页面在线时收到完成事件后提醒"})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Le(),disabled:St,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:Rn}),i.jsx("span",{children:Ks})]}),i.jsx("span",{className:"settings-action__state",children:ei})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Et(),disabled:!zs||me,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:ut?me?"正在发送测试通知":"发送测试通知":me?"正在发送测试推送":"发送测试推送"}),i.jsx("span",{children:Qs})]}),i.jsx("span",{className:"settings-action__state",children:me?"发送中…":zs?"→":"未就绪"})]}),S?i.jsx("p",{className:"settings-block__status",children:S}):null]})]})},_n=()=>{const A=He.data,le=A!=null&&A.promptState.installPromptAvailable?"可主动触发":A!=null&&A.promptState.beforeInstallPromptSeen?"本地曾出现":"未出现",tt=A!=null&&A.promptState.appInstalledSeen?"记录到过":"未记录到",Ht=A!=null&&A.manifest.ok?"正常":A!=null&&A.manifest.present?"读取失败":"缺失",cn=A!=null&&A.serviceWorker.registrations.length?`${A.serviceWorker.registrations.length} 个注册`:A!=null&&A.serviceWorker.supported?"未注册":"不支持";return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"安装结果判断"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前研判"}),i.jsx("strong",{children:(A==null?void 0:A.assessment.label)??"检测中…"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"安装事件"}),i.jsx("strong",{children:le})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"appinstalled"}),i.jsx("strong",{children:tt})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"当前状态"})}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{He.refetch()},children:"刷新诊断"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{wC(),Re()},children:"清空日志"})]})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前窗口形态"}),i.jsx("span",{children:A?A.environment.standaloneDisplayMode||A.environment.navigatorStandalone?"独立窗口 / 主屏幕入口":"浏览器标签页":"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"系统级安装研判"}),i.jsx("span",{children:(A==null?void 0:A.assessment.label)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"研判置信度"}),i.jsx("span",{children:(A==null?void 0:A.assessment.confidence)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前说明"}),i.jsx("span",{children:(A==null?void 0:A.assessment.detail)??"正在分析…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近抓取时间"}),i.jsx("span",{children:mu(A==null?void 0:A.capturedAt)})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"PWA 条件与安装信号"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"安全上下文"}),i.jsx("span",{children:A!=null&&A.environment.secureContext?"是":"否"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"manifest"}),i.jsx("span",{children:Ht})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"manifest display"}),i.jsx("span",{children:(A==null?void 0:A.manifest.display)??"未声明"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Service Worker"}),i.jsx("span",{children:cn})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前可主动触发安装"}),i.jsx("span",{children:A!=null&&A.promptState.installPromptAvailable?"可以":"不可以"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近 beforeinstallprompt"}),i.jsx("span",{children:mu(A==null?void 0:A.promptState.lastBeforeInstallPromptAt)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近 appinstalled"}),i.jsx("span",{children:mu(A==null?void 0:A.promptState.lastAppInstalledAt)})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"为什么当前可能安装失败"})})}),He.isLoading?i.jsx("p",{className:"settings-block__status",children:"正在收集安装诊断…"}):A!=null&&A.failureReasons.length?i.jsx("div",{className:"settings-diagnostic-list",children:A.failureReasons.map((mt,St)=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsxs("strong",{children:["原因 ",St+1]}),i.jsx("span",{children:mt})]},`${St}-${mt}`))}):i.jsx("p",{className:"settings-block__status",children:"当前没有发现明显的前端侧阻断条件;如果仍无法完成系统级安装,更像是浏览器策略、安装链路回退或平台侧判断导致。"})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"成功信号与人工确认"})})}),A!=null&&A.successSignals.length?i.jsx("div",{className:"settings-diagnostic-list",children:A.successSignals.map((mt,St)=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsxs("strong",{children:["信号 ",St+1]}),i.jsx("span",{children:mt})]},`${St}-${mt}`))}):null,i.jsx("div",{className:"settings-diagnostic-list",children:(A==null?void 0:A.confirmationChecklist.map((mt,St)=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsxs("strong",{children:["确认 ",St+1]}),i.jsx("span",{children:mt})]},`${St}-${mt}`)))??null})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"浏览器安装事件日志"})})}),He.isLoading?i.jsx("p",{className:"settings-block__status",children:"正在读取日志…"}):A!=null&&A.logs.length?i.jsx("div",{className:"settings-log-list",children:A.logs.map(mt=>i.jsxs("article",{className:"settings-log-item",children:[i.jsxs("div",{className:"settings-log-item__meta",children:[i.jsx("strong",{children:mt.message}),i.jsx("span",{children:mu(mt.timestamp)})]}),i.jsx("div",{className:"settings-log-item__kind",children:mt.kind}),mt.detail?i.jsx("pre",{className:"settings-log-item__detail",children:mt.detail}):null]},mt.id))}):i.jsx("p",{className:"settings-block__status",children:"还没有本地安装日志。后续在这个页面触发安装、刷新页面、出现 beforeinstallprompt 或 appinstalled 后,这里会自动积累证据。"})]})]})},qt=A=>A==="models"?Tn():A==="cache"?xn():A==="notifications"?Ss():A==="installation"?_n():A==="connection"?zn():A==="dev-manager"?i.jsx(qE,{isActive:b==="dev-manager"||N==="dev-manager",agentId:(Ze==null?void 0:Ze.id)??null}):bn();return i.jsx("div",{className:"conversation-page settings-screen settings-screen--workspace",style:$e,children:i.jsx("div",{className:"conversation-main settings-screen__main settings-screen__workspace-main",children:i.jsx("div",{className:"settings-screen__body",children:i.jsxs("div",{className:"settings-shell",children:[i.jsxs("header",{className:"settings-page-header",children:[i.jsx("button",{type:"button",className:"settings-card__back",onClick:rt,"aria-label":"返回会话",children:i.jsx($C,{})}),i.jsx("div",{className:"settings-page-header__copy",children:i.jsx("h1",{className:"settings-page-header__title",children:"设置"})})]}),T?i.jsxs("div",{className:"settings-workspace",children:[i.jsxs("aside",{className:"settings-sidebar",children:[i.jsx("div",{className:"settings-sidebar__title",children:"设置"}),i.jsx("nav",{className:"settings-sidebar__nav","aria-label":"设置导航",children:wm.map(A=>{const le=A.id===b;return i.jsxs("button",{type:"button",className:`settings-sidebar__item ${le?"is-active":""}`,onClick:()=>w(A.id),children:[i.jsx(bb,{icon:A.icon}),i.jsx("span",{children:A.title})]},A.id)})})]}),i.jsxs("main",{className:"settings-stage",children:[i.jsx("header",{className:"settings-stage__header",children:i.jsxs("div",{children:[i.jsx("h2",{className:"settings-stage__title",children:Pe.title}),i.jsx("p",{className:"settings-stage__description",children:Pe.description})]})}),qt(b)]})]}):gn()]})})})})},XC=({onClose:e})=>{const t=_.useRef(null);return _.useEffect(()=>{var u;if(typeof document>"u")return;const a=document.documentElement.style.overflow,l=document.body.style.overflow;document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",(u=t.current)==null||u.focus();const o=f=>{f.key==="Escape"&&(f.preventDefault(),e())};return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o),document.documentElement.style.overflow=a,document.body.style.overflow=l}},[e]),i.jsx("div",{ref:t,className:"settings-overlay",role:"dialog","aria-modal":"true","aria-label":"设置",tabIndex:-1,children:i.jsx(ix,{mode:"overlay",onRequestClose:e})})},JC=()=>{const e=ki();Mp();const t=ja(p=>p.themeSettings),a=ja(p=>p.systemAppearance),l=ja(p=>p.setSystemAppearance),o=ja(p=>p.isSettingsOverlayOpen),u=ja(p=>p.closeSettingsOverlay),f=Ia({select:p=>p.location.pathname}),m=_.useRef(null),y=pc(),g=ch(y),S=!!(y&&g);return _.useEffect(()=>{tx(t,a)},[a,t]),_.useEffect(()=>vC(l),[l]),_.useEffect(()=>{j_().catch(()=>{})},[]),_.useEffect(()=>{let p;return Jk(b=>{e({to:b}).catch(()=>{typeof window<"u"&&window.location.assign(b)})}).then(b=>{p=b}),()=>{p==null||p()}},[e]),_.useEffect(()=>{if(!o){m.current=null;return}if(m.current===null){m.current=f;return}f!==m.current&&u()},[u,o,f]),Tk()?i.jsx(oE,{}):i.jsxs("div",{className:"app-shell",children:[S?null:i.jsx(mE,{}),i.jsx(AE,{}),i.jsx("div",{className:"app-shell__content","aria-hidden":o,children:i.jsx(l6,{})}),o?i.jsx(XC,{onClose:u}):null]})};/**
|
|
66
|
+
*/var r4;function k7(){if(r4)return fg;r4=1;var e=rh(),t=N7();function a(g,S){return g===S&&(g!==0||1/g===1/S)||g!==g&&S!==S}var l=typeof Object.is=="function"?Object.is:a,o=t.useSyncExternalStore,u=e.useRef,f=e.useEffect,m=e.useMemo,y=e.useDebugValue;return fg.useSyncExternalStoreWithSelector=function(g,S,p,b,w){var N=u(null);if(N.current===null){var j={hasValue:!1,value:null};N.current=j}else j=N.current;N=m(function(){function D(Q){if(!z){if(z=!0,I=Q,Q=b(Q),w!==void 0&&j.hasValue){var se=j.value;if(w(se,Q))return k=se}return k=Q}if(se=k,l(I,Q))return se;var W=b(Q);return w!==void 0&&w(se,W)?(I=Q,se):(I=Q,k=W)}var z=!1,I,k,P=p===void 0?null:p;return[function(){return D(S())},P===null?void 0:function(){return D(P())}]},[S,p,b,w]);var T=o(g,N[0],N[1]);return f(function(){j.hasValue=!0,j.value=T},[T]),y(T),T},fg}var l4;function E7(){return l4||(l4=1,dg.exports=k7()),dg.exports}var C7=E7();function T7(e,t){return e===t}function R7(e,t,a=T7){const l=_.useCallback(f=>{if(!e)return()=>{};const{unsubscribe:m}=e.subscribe(f);return m},[e]),o=_.useCallback(()=>e==null?void 0:e.get(),[e]);return C7.useSyncExternalStoreWithSelector(l,o,o,t,a)}function Ia(e){const t=Za({warn:(e==null?void 0:e.router)===void 0}),a=(e==null?void 0:e.router)||t,l=_.useRef(void 0);return R7(a.__store,o=>{if(e!=null&&e.select){if(e.structuralSharing??a.options.defaultStructuralSharing){const u=Wo(l.current,e.select(o));return l.current=u,u}return e.select(o)}return o})}var Cp=_.createContext(void 0),M7=_.createContext(void 0);function lo(e){const t=_.useContext(e.from?M7:Cp);return Ia({select:a=>{const l=a.matches.find(o=>e.from?e.from===o.routeId:o.id===t);if(io(!((e.shouldThrow??!0)&&!l),`Could not find ${e.from?`an active match from "${e.from}"`:"a nearest match!"}`),l!==void 0)return e.select?e.select(l):l},structuralSharing:e.structuralSharing})}function a_(e){return lo({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function i_(e){const{select:t,...a}=e;return lo({...a,select:l=>t?t(l.loaderDeps):l.loaderDeps})}function ad(e){return lo({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const a=e.strict===!1?t.params:t._strictParams;return e.select?e.select(a):a}})}function r_(e){return lo({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ki(e){const t=Za();return _.useCallback(a=>t.navigate({...a,from:a.from??(e==null?void 0:e.from)}),[e==null?void 0:e.from,t])}function l_(e){return lo({...e,select:t=>e.select?e.select(t.context):t.context})}var Ya=T2();function A7(e,t){const a=Za(),l=nS(t),{activeProps:o,inactiveProps:u,activeOptions:f,to:m,preload:y,preloadDelay:g,hashScrollIntoView:S,replace:p,startTransition:b,resetScroll:w,viewTransition:N,children:j,target:T,disabled:D,style:z,className:I,onClick:k,onBlur:P,onFocus:Q,onMouseEnter:se,onMouseLeave:W,onTouchStart:V,ignoreBlocker:Y,params:ee,search:me,hash:ge,state:te,mask:xe,reloadDocument:C,unsafeRelative:q,from:ie,_fromLocation:he,...re}=e,L=s6(),ae=Ia({select:Ve=>{const Ke=Ve.matches[Ve.matches.length-1];return{search:Ke==null?void 0:Ke.search,hash:Ve.location.hash,path:Ke==null?void 0:Ke.pathname}},structuralSharing:!0}),ke=e.from,U=_.useMemo(()=>({...e,from:ke}),[a,ae,ke,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),ve=_.useMemo(()=>a.buildLocation({...U}),[a,U]),Z=ve.maskedLocation?ve.maskedLocation.publicHref:ve.publicHref,Se=ve.maskedLocation?ve.maskedLocation.external:ve.external,je=_.useMemo(()=>U7(Z,Se,a.history,D),[D,Se,Z,a.history]),Oe=_.useMemo(()=>{if(je!=null&&je.external)return Vm(je.href,a.protocolAllowlist)?void 0:je.href;if(!z7(m)&&!(typeof m!="string"||m.indexOf(":")===-1))try{return new URL(m),Vm(m,a.protocolAllowlist)?void 0:m}catch{}},[m,je,a.protocolAllowlist]),Ie=Ia({select:Ve=>{if(Oe)return!1;if(f!=null&&f.exact){if(!xS(Ve.location.pathname,ve.pathname,a.basepath))return!1}else{const Ke=Xm(Ve.location.pathname,a.basepath),Nt=Xm(ve.pathname,a.basepath);if(!(Ke.startsWith(Nt)&&(Ke.length===Nt.length||Ke[Nt.length]==="/")))return!1}return((f==null?void 0:f.includeSearch)??!0)&&!sc(Ve.location.search,ve.search,{partial:!(f!=null&&f.exact),ignoreUndefined:!(f!=null&&f.explicitUndefined)})?!1:f!=null&&f.includeHash?L&&Ve.location.hash===ve.hash:!0}}),wt=Ie?Jl(o,{})??D7:pg,qe=Ie?pg:Jl(u,{})??pg,bt=[I,wt.className,qe.className].filter(Boolean).join(" "),Ut=(z||wt.style||qe.style)&&{...z,...wt.style,...qe.style},[$t,zt]=_.useState(!1),xt=_.useRef(!1),it=e.reloadDocument||Oe?!1:y??a.options.defaultPreload,ot=g??a.options.defaultPreloadDelay??0,ln=_.useCallback(()=>{a.preloadRoute({...U,_builtLocation:ve}).catch(Ve=>{console.warn(Ve),console.warn(v7)})},[a,U,ve]);tS(l,_.useCallback(Ve=>{Ve!=null&&Ve.isIntersecting&&ln()},[ln]),P7,{disabled:!!D||it!=="viewport"}),_.useEffect(()=>{xt.current||!D&&it==="render"&&(ln(),xt.current=!0)},[D,ln,it]);const on=Ve=>{const Ke=Ve.currentTarget.getAttribute("target"),Nt=T!==void 0?T:Ke;if(!D&&!B7(Ve)&&!Ve.defaultPrevented&&(!Nt||Nt==="_self")&&Ve.button===0){Ve.preventDefault(),Ya.flushSync(()=>{zt(!0)});const Bt=a.subscribe("onResolved",()=>{Bt(),zt(!1)});a.navigate({...U,replace:p,resetScroll:w,hashScrollIntoView:S,startTransition:b,viewTransition:N,ignoreBlocker:Y})}};if(Oe)return{...re,ref:l,href:Oe,...j&&{children:j},...T&&{target:T},...D&&{disabled:D},...z&&{style:z},...I&&{className:I},...k&&{onClick:k},...P&&{onBlur:P},...Q&&{onFocus:Q},...se&&{onMouseEnter:se},...W&&{onMouseLeave:W},...V&&{onTouchStart:V}};const kn=Ve=>{if(D||it!=="intent")return;if(!ot){ln();return}const Ke=Ve.currentTarget;if(bf.has(Ke))return;const Nt=setTimeout(()=>{bf.delete(Ke),ln()},ot);bf.set(Ke,Nt)},En=Ve=>{D||it!=="intent"||ln()},ht=Ve=>{if(D||!it||!ot)return;const Ke=Ve.currentTarget,Nt=bf.get(Ke);Nt&&(clearTimeout(Nt),bf.delete(Ke))};return{...re,...wt,...qe,href:je==null?void 0:je.href,ref:l,onClick:du([k,on]),onBlur:du([P,ht]),onFocus:du([Q,kn]),onMouseEnter:du([se,kn]),onMouseLeave:du([W,ht]),onTouchStart:du([V,En]),disabled:!!D,target:T,...Ut&&{style:Ut},...bt&&{className:bt},...D&&O7,...Ie&&I7,...L&&$t&&L7}}var pg={},D7={className:"active"},O7={role:"link","aria-disabled":!0},I7={"data-status":"active","aria-current":"page"},L7={"data-transitioning":"transitioning"},bf=new WeakMap,P7={rootMargin:"100px"},du=e=>t=>{for(const a of e)if(a){if(t.defaultPrevented)return;a(t)}};function U7(e,t,a,l){if(!l)return t?{href:e,external:!0}:{href:a.createHref(e)||"/",external:!1}}function z7(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var sp=_.forwardRef((e,t)=>{const{_asChild:a,...l}=e,{type:o,...u}=A7(l,t),f=typeof l.children=="function"?l.children({isActive:u["data-status"]==="active"}):l.children;if(!a){const{disabled:m,...y}=u;return _.createElement("a",y,f)}return _.createElement(a,u,f)});function B7(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var H7=class extends n6{constructor(e){super(e),this.useMatch=t=>lo({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>l_({...t,from:this.id}),this.useSearch=t=>r_({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>ad({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>i_({...t,from:this.id}),this.useLoaderData=t=>a_({...t,from:this.id}),this.useNavigate=()=>ki({from:this.fullPath}),this.Link=qr.forwardRef((t,a)=>i.jsx(sp,{ref:a,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function hc(e){return new H7(e)}var $7=class extends b7{constructor(e){super(e),this.useMatch=t=>lo({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>l_({...t,from:this.id}),this.useSearch=t=>r_({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>ad({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>i_({...t,from:this.id}),this.useLoaderData=t=>a_({...t,from:this.id}),this.useNavigate=()=>ki({from:this.fullPath}),this.Link=qr.forwardRef((t,a)=>i.jsx(sp,{ref:a,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function F7(e){return new $7(e)}function o4(e){return typeof e=="object"?new c4(e,{silent:!0}).createRoute(e):new c4(e,{silent:!0}).createRoute}var c4=class{constructor(e,t){this.path=e,this.createRoute=a=>{const l=hc(a);return l.isRoot=!1,l},this.silent=t==null?void 0:t.silent}},u4=class{constructor(e){this.useMatch=t=>lo({select:t==null?void 0:t.select,from:this.options.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>l_({...t,from:this.options.id}),this.useSearch=t=>r_({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useParams=t=>ad({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useLoaderDeps=t=>i_({...t,from:this.options.id}),this.useLoaderData=t=>a_({...t,from:this.options.id}),this.useNavigate=()=>ki({from:Za().routesById[this.options.id].fullPath}),this.options=e,this.$$typeof=Symbol.for("react.memo")}};function d4(e){return typeof e=="object"?new u4(e):t=>new u4({id:e,...t})}function q7(e){const t=Ia({select:a=>`not-found-${a.location.pathname}-${a.status}`});return i.jsx(n_,{getResetKey:()=>t,onCatch:(a,l)=>{var o;if(ea(a))(o=e.onCatch)==null||o.call(e,a,l);else throw a},errorComponent:({error:a})=>{var l;if(ea(a))return(l=e.fallback)==null?void 0:l.call(e,a);throw a},children:e.children})}function W7(){return i.jsx("p",{children:"Not Found"})}function vu(e){return i.jsx(i.Fragment,{children:e.children})}function i6(e,t,a){return t.options.notFoundComponent?i.jsx(t.options.notFoundComponent,{...a}):e.options.defaultNotFoundComponent?i.jsx(e.options.defaultNotFoundComponent,{...a}):i.jsx(W7,{})}function K7(){return Za().isScrollRestoring,null}var r6=_.memo(function({matchId:t}){var N,j;const a=Za(),l=Ia({select:T=>{var I;const D=T.matches.findIndex(k=>k.id===t),z=T.matches[D];return io(z),{routeId:z.routeId,ssr:z.ssr,_displayPending:z._displayPending,resetKey:T.loadedAt,parentRouteId:(I=T.matches[D-1])==null?void 0:I.routeId}},structuralSharing:!0}),o=a.routesById[l.routeId],u=o.options.pendingComponent??a.options.defaultPendingComponent,f=u?i.jsx(u,{}):null,m=o.options.errorComponent??a.options.defaultErrorComponent,y=o.options.onCatch??a.options.defaultOnCatch,g=o.isRoot?o.options.notFoundComponent??((N=a.options.notFoundRoute)==null?void 0:N.options.component):o.options.notFoundComponent,S=l.ssr===!1||l.ssr==="data-only",p=(!o.isRoot||o.options.wrapInSuspense||S)&&(o.options.wrapInSuspense??u??(((j=o.options.errorComponent)==null?void 0:j.preload)||S))?_.Suspense:vu,b=m?n_:vu,w=g?q7:vu;return i.jsxs(o.isRoot?o.options.shellComponent??vu:vu,{children:[i.jsx(Cp.Provider,{value:t,children:i.jsx(p,{fallback:f,children:i.jsx(b,{getResetKey:()=>l.resetKey,errorComponent:m||s_,onCatch:(T,D)=>{if(ea(T))throw T;y==null||y(T,D)},children:i.jsx(w,{fallback:T=>{if(!g||T.routeId&&T.routeId!==l.routeId||!T.routeId&&!o.isRoot)throw T;return _.createElement(g,T)},children:S||l._displayPending?i.jsx(S7,{fallback:f,children:i.jsx(f4,{matchId:t})}):i.jsx(f4,{matchId:t})})})})}),l.parentRouteId===ac&&a.options.scrollRestoration?i.jsxs(i.Fragment,{children:[i.jsx(Q7,{}),i.jsx(K7,{})]}):null]})});function Q7(){const e=Za(),t=_.useRef(void 0);return i.jsx("script",{suppressHydrationWarning:!0,ref:a=>{a&&(t.current===void 0||t.current.href!==e.latestLocation.href)&&(e.emit({type:"onRendered",...rc(e.state)}),t.current=e.latestLocation)}},e.latestLocation.state.__TSR_key)}var f4=_.memo(function({matchId:t}){var y,g,S,p;const a=Za(),{match:l,key:o,routeId:u}=Ia({select:b=>{var T;const w=b.matches.find(D=>D.id===t),N=w.routeId,j=(T=a.routesById[N].options.remountDeps??a.options.defaultRemountDeps)==null?void 0:T({routeId:N,loaderDeps:w.loaderDeps,params:w._strictParams,search:w._strictSearch});return{key:j?JSON.stringify(j):void 0,routeId:N,match:{id:w.id,status:w.status,error:w.error,_forcePending:w._forcePending,_displayPending:w._displayPending}}},structuralSharing:!0}),f=a.routesById[u],m=_.useMemo(()=>{const b=f.options.component??a.options.defaultComponent;return b?i.jsx(b,{},o):i.jsx(l6,{})},[o,f.options.component,a.options.defaultComponent]);if(l._displayPending)throw(y=a.getMatch(l.id))==null?void 0:y._nonReactive.displayPendingPromise;if(l._forcePending)throw(g=a.getMatch(l.id))==null?void 0:g._nonReactive.minPendingPromise;if(l.status==="pending"){const b=f.options.pendingMinMs??a.options.defaultPendingMinMs;if(b){const w=a.getMatch(l.id);if(w&&!w._nonReactive.minPendingPromise){const N=$u();w._nonReactive.minPendingPromise=N,setTimeout(()=>{N.resolve(),w._nonReactive.minPendingPromise=void 0},b)}}throw(S=a.getMatch(l.id))==null?void 0:S._nonReactive.loadPromise}if(l.status==="notFound")return io(ea(l.error)),i6(a,f,l.error);if(l.status==="redirected")throw io(wa(l.error)),(p=a.getMatch(l.id))==null?void 0:p._nonReactive.loadPromise;if(l.status==="error")throw l.error;return m}),l6=_.memo(function(){const t=Za(),a=_.useContext(Cp),l=Ia({select:g=>{var S;return(S=g.matches.find(p=>p.id===a))==null?void 0:S.routeId}}),o=t.routesById[l],u=Ia({select:g=>{const S=g.matches.find(p=>p.id===a);return io(S),S.globalNotFound}}),f=Ia({select:g=>{var p;const S=g.matches;return(p=S[S.findIndex(b=>b.id===a)+1])==null?void 0:p.id}}),m=t.options.defaultPendingComponent?i.jsx(t.options.defaultPendingComponent,{}):null;if(u)return i6(t,o,void 0);if(!f)return null;const y=i.jsx(r6,{matchId:f});return l===ac?i.jsx(_.Suspense,{fallback:m,children:y}):y});function G7(){const e=Za(),t=_.useRef({router:e,mounted:!1}),[a,l]=_.useState(!1),{hasPendingMatches:o,isLoading:u}=Ia({select:p=>({isLoading:p.isLoading,hasPendingMatches:p.matches.some(b=>b.status==="pending")}),structuralSharing:!0}),f=ig(u),m=u||a||o,y=ig(m),g=u||o,S=ig(g);return e.startTransition=p=>{l(!0),_.startTransition(()=>{p(),l(!1)})},_.useEffect(()=>{const p=e.history.subscribe(e.load),b=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return no(e.latestLocation.publicHref)!==no(b.publicHref)&&e.commitLocation({...b,replace:!0}),()=>{p()}},[e,e.history]),vm(()=>{if(typeof window<"u"&&e.ssr||t.current.router===e&&t.current.mounted)return;t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(b){console.error(b)}})()},[e]),vm(()=>{f&&!u&&e.emit({type:"onLoad",...rc(e.state)})},[f,e,u]),vm(()=>{S&&!g&&e.emit({type:"onBeforeRouteMount",...rc(e.state)})},[g,S,e]),vm(()=>{if(y&&!m){const p=rc(e.state);e.emit({type:"onResolved",...p}),e.__store.setState(b=>({...b,status:"idle",resolvedLocation:b.location})),p.hrefChanged&&MS(e)}},[m,y,e]),null}function Y7(){const e=Za(),t=e.routesById[ac].options.pendingComponent??e.options.defaultPendingComponent,a=t?i.jsx(t,{}):null,l=i.jsxs(typeof document<"u"&&e.ssr?vu:_.Suspense,{fallback:a,children:[i.jsx(G7,{}),i.jsx(V7,{})]});return e.options.InnerWrap?i.jsx(e.options.InnerWrap,{children:l}):l}function V7(){const e=Za(),t=Ia({select:o=>{var u;return(u=o.matches[0])==null?void 0:u.id}}),a=Ia({select:o=>o.loadedAt}),l=t?i.jsx(r6,{matchId:t}):null;return i.jsx(Cp.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?l:i.jsx(n_,{getResetKey:()=>a,errorComponent:s_,onCatch:void 0,children:l})})}var Z7=e=>new X7(e),X7=class extends f7{constructor(e){super(e)}};typeof globalThis<"u"?(globalThis.createFileRoute=o4,globalThis.createLazyFileRoute=d4):typeof window<"u"&&(window.createFileRoute=o4,window.createLazyFileRoute=d4);function J7({router:e,children:t,...a}){Object.keys(a).length>0&&e.update({...e.options,...a,context:{...e.options.context,...a.context}});const l=i.jsx(a6.Provider,{value:e,children:t});return e.options.Wrap?i.jsx(e.options.Wrap,{children:l}):l}function ej({router:e,...t}){return i.jsx(J7,{router:e,...t,children:i.jsx(Y7,{})})}/*! Capacitor: https://capacitorjs.com/ - MIT License */var Fu;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(Fu||(Fu={}));class gg extends Error{constructor(t,a,l){super(t),this.message=t,this.code=a,this.data=l}}const tj=e=>{var t,a;return e!=null&&e.androidBridge?"android":!((a=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||a===void 0)&&a.bridge?"ios":"web"},nj=e=>{const t=e.CapacitorCustomPlatform||null,a=e.Capacitor||{},l=a.Plugins=a.Plugins||{},o=()=>t!==null?t.name:tj(e),u=()=>o()!=="web",f=p=>{const b=g.get(p);return!!(b!=null&&b.platforms.has(o())||m(p))},m=p=>{var b;return(b=a.PluginHeaders)===null||b===void 0?void 0:b.find(w=>w.name===p)},y=p=>e.console.error(p),g=new Map,S=(p,b={})=>{const w=g.get(p);if(w)return console.warn(`Capacitor plugin "${p}" already registered. Cannot register plugins twice.`),w.proxy;const N=o(),j=m(p);let T;const D=async()=>(!T&&N in b?T=typeof b[N]=="function"?T=await b[N]():T=b[N]:t!==null&&!T&&"web"in b&&(T=typeof b.web=="function"?T=await b.web():T=b.web),T),z=(W,V)=>{var Y,ee;if(j){const me=j==null?void 0:j.methods.find(ge=>V===ge.name);if(me)return me.rtype==="promise"?ge=>a.nativePromise(p,V.toString(),ge):(ge,te)=>a.nativeCallback(p,V.toString(),ge,te);if(W)return(Y=W[V])===null||Y===void 0?void 0:Y.bind(W)}else{if(W)return(ee=W[V])===null||ee===void 0?void 0:ee.bind(W);throw new gg(`"${p}" plugin is not implemented on ${N}`,Fu.Unimplemented)}},I=W=>{let V;const Y=(...ee)=>{const me=D().then(ge=>{const te=z(ge,W);if(te){const xe=te(...ee);return V=xe==null?void 0:xe.remove,xe}else throw new gg(`"${p}.${W}()" is not implemented on ${N}`,Fu.Unimplemented)});return W==="addListener"&&(me.remove=async()=>V()),me};return Y.toString=()=>`${W.toString()}() { [capacitor code] }`,Object.defineProperty(Y,"name",{value:W,writable:!1,configurable:!1}),Y},k=I("addListener"),P=I("removeListener"),Q=(W,V)=>{const Y=k({eventName:W},V),ee=async()=>{const ge=await Y;P({eventName:W,callbackId:ge},V)},me=new Promise(ge=>Y.then(()=>ge({remove:ee})));return me.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await ee()},me},se=new Proxy({},{get(W,V){switch(V){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?Q:k;case"removeListener":return P;default:return I(V)}}});return l[p]=se,g.set(p,{name:p,proxy:se,platforms:new Set([...Object.keys(b),...j?[N]:[]])}),se};return a.convertFileSrc||(a.convertFileSrc=p=>p),a.getPlatform=o,a.handleError=y,a.isNativePlatform=u,a.isPluginAvailable=f,a.registerPlugin=S,a.Exception=gg,a.DEBUG=!!a.DEBUG,a.isLoggingEnabled=!!a.isLoggingEnabled,a},sj=e=>e.Capacitor=nj(e),Qr=sj(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),mc=Qr.registerPlugin;class o6{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,a){let l=!1;this.listeners[t]||(this.listeners[t]=[],l=!0),this.listeners[t].push(a);const u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),l&&this.sendRetainedArgumentsForEvent(t);const f=async()=>this.removeListener(t,a);return Promise.resolve({remove:f})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,a,l){const o=this.listeners[t];if(!o){if(l){let u=this.retainedEventArguments[t];u||(u=[]),u.push(a),this.retainedEventArguments[t]=u}return}o.forEach(u=>u(a))}hasListeners(t){var a;return!!(!((a=this.listeners[t])===null||a===void 0)&&a.length)}registerWindowListener(t,a){this.windowListeners[a]={registered:!1,windowEventName:t,pluginEventName:a,handler:l=>{this.notifyListeners(a,l)}}}unimplemented(t="not implemented"){return new Qr.Exception(t,Fu.Unimplemented)}unavailable(t="not available"){return new Qr.Exception(t,Fu.Unavailable)}async removeListener(t,a){const l=this.listeners[t];if(!l)return;const o=l.indexOf(a);this.listeners[t].splice(o,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const a=this.retainedEventArguments[t];a&&(delete this.retainedEventArguments[t],a.forEach(l=>{this.notifyListeners(t,l)}))}}const h4=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),m4=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class aj extends o6{async getCookies(){const t=document.cookie,a={};return t.split(";").forEach(l=>{if(l.length<=0)return;let[o,u]=l.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");o=m4(o).trim(),u=m4(u).trim(),a[o]=u}),a}async setCookie(t){try{const a=h4(t.key),l=h4(t.value),o=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),f=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${a}=${l||""}${o}; path=${u}; ${f};`}catch(a){return Promise.reject(a)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(a){return Promise.reject(a)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const a of t)document.cookie=a.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}mc("CapacitorCookies",{web:()=>new aj});const ij=async e=>new Promise((t,a)=>{const l=new FileReader;l.onload=()=>{const o=l.result;t(o.indexOf(",")>=0?o.split(",")[1]:o)},l.onerror=o=>a(o),l.readAsDataURL(e)}),rj=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(o=>o.toLocaleLowerCase()).reduce((o,u,f)=>(o[u]=e[t[f]],o),{})},lj=(e,t=!0)=>e?Object.entries(e).reduce((l,o)=>{const[u,f]=o;let m,y;return Array.isArray(f)?(y="",f.forEach(g=>{m=t?encodeURIComponent(g):g,y+=`${u}=${m}&`}),y.slice(0,-1)):(m=t?encodeURIComponent(f):f,y=`${u}=${m}`),`${l}&${y}`},"").substr(1):null,oj=(e,t={})=>{const a=Object.assign({method:e.method||"GET",headers:e.headers},t),o=rj(e.headers)["content-type"]||"";if(typeof e.data=="string")a.body=e.data;else if(o.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[f,m]of Object.entries(e.data||{}))u.set(f,m);a.body=u.toString()}else if(o.includes("multipart/form-data")||e.data instanceof FormData){const u=new FormData;if(e.data instanceof FormData)e.data.forEach((m,y)=>{u.append(y,m)});else for(const m of Object.keys(e.data))u.append(m,e.data[m]);a.body=u;const f=new Headers(a.headers);f.delete("content-type"),a.headers=f}else(o.includes("application/json")||typeof e.data=="object")&&(a.body=JSON.stringify(e.data));return a};class cj extends o6{async request(t){const a=oj(t,t.webFetchExtra),l=lj(t.params,t.shouldEncodeUrlParams),o=l?`${t.url}?${l}`:t.url,u=await fetch(o,a),f=u.headers.get("content-type")||"";let{responseType:m="text"}=u.ok?t:{};f.includes("application/json")&&(m="json");let y,g;switch(m){case"arraybuffer":case"blob":g=await u.blob(),y=await ij(g);break;case"json":y=await u.json();break;case"document":case"text":default:y=await u.text()}const S={};return u.headers.forEach((p,b)=>{S[b]=p}),{data:y,headers:S,status:u.status,url:u.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}mc("CapacitorHttp",{web:()=>new cj});var l0;(function(e){e.Aztec="AZTEC",e.Codabar="CODABAR",e.Code39="CODE_39",e.Code93="CODE_93",e.Code128="CODE_128",e.DataMatrix="DATA_MATRIX",e.Ean8="EAN_8",e.Ean13="EAN_13",e.Itf="ITF",e.Pdf417="PDF_417",e.QrCode="QR_CODE",e.UpcA="UPC_A",e.UpcE="UPC_E"})(l0||(l0={}));var p4;(function(e){e.CalendarEvent="CALENDAR_EVENT",e.ContactInfo="CONTACT_INFO",e.DriversLicense="DRIVERS_LICENSE",e.Email="EMAIL",e.Geo="GEO",e.Isbn="ISBN",e.Phone="PHONE",e.Product="PRODUCT",e.Sms="SMS",e.Text="TEXT",e.Url="URL",e.Wifi="WIFI",e.Unknown="UNKNOWN"})(p4||(p4={}));var o0;(function(e){e[e["640x480"]=0]="640x480",e[e["1280x720"]=1]="1280x720",e[e["1920x1080"]=2]="1920x1080",e[e["3840x2160"]=3]="3840x2160"})(o0||(o0={}));var c0;(function(e){e.Front="FRONT",e.Back="BACK"})(c0||(c0={}));var g4;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.PENDING=1]="PENDING",e[e.DOWNLOADING=2]="DOWNLOADING",e[e.CANCELED=3]="CANCELED",e[e.COMPLETED=4]="COMPLETED",e[e.FAILED=5]="FAILED",e[e.INSTALLING=6]="INSTALLING",e[e.DOWNLOAD_PAUSED=7]="DOWNLOAD_PAUSED"})(g4||(g4={}));var _4;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})(_4||(_4={}));var y4;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})(y4||(y4={}));var v4;(function(e){e[e.FAX=0]="FAX",e[e.HOME=1]="HOME",e[e.MOBILE=2]="MOBILE",e[e.UNKNOWN=3]="UNKNOWN",e[e.WORK=4]="WORK"})(v4||(v4={}));var b4;(function(e){e[e.OPEN=1]="OPEN",e[e.WEP=2]="WEP",e[e.WPA=3]="WPA"})(b4||(b4={}));const Po=mc("BarcodeScanner",{web:()=>Zr(()=>import("./web-DeqRViq6.js"),[]).then(e=>new e.BarcodeScannerWeb)}),uj=8e3,ap=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";const a=t.replace(/\/+$/,"");try{const l=new URL(a);return l.pathname==="/health"&&(l.pathname="",l.search="",l.hash=""),l.toString().replace(/\/+$/,"")}catch{return a.replace(/\/health$/i,"")}},c6=e=>new Error(`连接探测超时(${e} ms),请确认手机能直接访问该 Hub 地址。`),dj=(e,t)=>{if(!(e instanceof Error))return"连接失败";const a=e.message.trim();return e.name==="AbortError"||e.name==="TimeoutError"||/aborted/i.test(a)?c6(t).message:a||"连接失败"},u0=async(e,t)=>{const a=ap(e),l=new Date().toISOString();if(!a)return{url:"",healthOk:!1,latencyMs:null,checkedAt:l,error:"地址为空"};const o=uj,u=`${a}/health`,f=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),m=new AbortController,y=window.setTimeout(()=>m.abort(c6(o)),o);try{const g=await fetch(u,{cache:"no-store",signal:m.signal}),S=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return{url:a,healthOk:g.ok,latencyMs:S-f,checkedAt:l,error:g.ok?null:`HTTP ${g.status}`}}catch(g){return{url:a,healthOk:!1,latencyMs:null,checkedAt:l,error:dj(g,o)}}finally{clearTimeout(y)}},fj=()=>{var e;try{const t=(e=Qr.getPlatform)==null?void 0:e.call(Qr);if(t==="android"||t==="ios")return t}catch{}return"web"},qu=()=>fj(),u6=()=>{var e;try{return((e=Qr.isNativePlatform)==null?void 0:e.call(Qr))===!0}catch{return!1}},Tp=()=>qu()==="android"&&u6(),hj=()=>qu()==="ios"&&u6(),qs=()=>Tp()||hj(),x4=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,mj=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},_g=e=>{var l;const t=e.trim();if(!t)return"";try{const o=new URL(t);if(o.protocol==="http:"||o.protocol==="https:")return ap(o.toString())}catch{}const a=(l=t.match(/https?:\/\/[^\s]+/i))==null?void 0:l[0];return a?ap(a):""},pj=e=>{var a;const t=[e.rawValue,e.displayValue,(a=e.urlBookmark)==null?void 0:a.url];for(const l of t){const o=(l==null?void 0:l.trim())??"";if(o)try{const u=new URL(o);return u.protocol==="panda:"&&u.searchParams.get("url")?_g(u.searchParams.get("url")??""):_g(u.toString())}catch{return _g(o)}}return""},gj=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 4.75H5.9A1.9 1.9 0 0 0 4 6.65v1.1M17 4.75h1.1A1.9 1.9 0 0 1 20 6.65v1.1M20 16.25v1.1a1.9 1.9 0 0 1-1.9 1.9H17M7 19.25H5.9A1.9 1.9 0 0 1 4 17.35v-1.1"}),i.jsx("path",{d:"M8 9.25h8M8 12h8M8 14.75h5"})]}),_j=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M6 6 18 18M18 6 6 18"})}),d6=({title:e,description:t,currentHubUrl:a,initialHubUrl:l,hint:o,saveLabel:u,savingLabel:f,saveDescription:m,saveSuccessMessage:y,onSaveSuccess:g})=>{const[S,p]=_.useState(l),[b,w]=_.useState({loading:!1,result:null}),[N,j]=_.useState({saving:!1}),[T,D]=_.useState(null),[z,I]=_.useState({active:!1,starting:!1}),k=_.useRef([]),P=ap(S),Q=qs();_.useEffect(()=>{p(l)},[l]),_.useEffect(()=>{if(!(typeof document>"u"))return document.documentElement.classList.toggle("hub-scanner-active",z.active),document.body.classList.toggle("hub-scanner-active",z.active),()=>{document.documentElement.classList.remove("hub-scanner-active"),document.body.classList.remove("hub-scanner-active")}},[z.active]),_.useEffect(()=>()=>{(async()=>(await Promise.all(k.current.map(ge=>ge.remove().catch(()=>{}))),k.current=[],await Po.stopScan().catch(()=>{})))()},[]);const se=async()=>{const ge=[...k.current];k.current=[],await Promise.all(ge.map(te=>te.remove().catch(()=>{})))},W=async()=>{I(ge=>({...ge,active:!1})),await se(),await Po.stopScan().catch(()=>{})},V=async()=>{if(!P){D({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}D(null),w({loading:!0,result:null});const ge=await u0(P);w({loading:!1,result:ge}),D({tone:ge.healthOk?"success":"danger",text:ge.healthOk?`连接成功,延迟 ${x4(ge.latencyMs)}。`:ge.error??"连接测试失败。"})},Y=async()=>{var ge;if(!P){D({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}D(null),j({saving:!0});try{const te=((ge=b.result)==null?void 0:ge.url)===P?b.result:await u0(P);if(w({loading:!1,result:te}),!te.healthOk){D({tone:"danger",text:te.error??"请先确认 Hub 地址可访问,再继续保存。"});return}await g(te),D({tone:"success",text:y})}catch(te){D({tone:"danger",text:te instanceof Error?te.message:"保存 Hub 地址失败。"})}finally{j({saving:!1})}},ee=async()=>{if(Q){D(null),I({active:!1,starting:!0});try{if(!(await Po.isSupported()).supported){D({tone:"danger",text:"当前设备不支持扫码填入,请手动输入地址。"});return}const te=await Po.requestPermissions();if(te.camera!=="granted"&&te.camera!=="limited"){D({tone:"danger",text:"需要相机权限才能扫码,请在系统设置中允许 Panda 使用相机。"});return}const xe=await Promise.all([Po.addListener("barcodesScanned",C=>{const q=C.barcodes.map(pj).find(Boolean);if(!q){D({tone:"danger",text:"二维码已识别,但没有拿到可用的 Hub 地址。"}),W();return}p(q),w({loading:!1,result:null}),D({tone:"success",text:"已通过扫码填入地址,可以直接测试或保存。"}),W()}),Po.addListener("scanError",C=>{D({tone:"danger",text:C.message||"扫码失败,请稍后重试。"}),W()})]);k.current=xe,I({active:!0,starting:!1}),await Po.startScan({formats:[l0.QrCode],lensFacing:c0.Back,resolution:o0["1280x720"]})}catch(ge){await W(),D({tone:"danger",text:ge instanceof Error?ge.message:"无法启动扫码,请稍后重试。"})}finally{I(ge=>({...ge,starting:!1}))}}},me=z.active&&typeof document<"u"?Ya.createPortal(i.jsx("div",{className:"hub-scanner-sheet",role:"dialog","aria-modal":"true","aria-label":"扫描 Hub 地址二维码",children:i.jsxs("div",{className:"hub-scanner-sheet__content",children:[i.jsxs("div",{className:"hub-scanner-sheet__topbar",children:[i.jsx("span",{className:"hub-scanner-sheet__badge",children:"扫码填入"}),i.jsx("button",{type:"button",className:"hub-scanner-sheet__close",onClick:()=>{W()},"aria-label":"关闭扫码",children:i.jsx(_j,{})})]}),i.jsxs("div",{className:"hub-scanner-sheet__frame","aria-hidden":"true",children:[i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tl"}),i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tr"}),i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--bl"}),i.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--br"})]}),i.jsxs("div",{className:"hub-scanner-sheet__footer",children:[i.jsx("p",{children:"把电脑端显示的 Hub 二维码放进取景框,识别后会自动填入地址。"}),i.jsx("button",{type:"button",className:"settings-ghost-button hub-scanner-sheet__cancel",onClick:()=>{W()},children:"取消扫码"})]})]})}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"hub-connection-form",children:[i.jsxs("div",{className:"hub-connection-form__header",children:[i.jsxs("div",{className:"hub-connection-form__copy",children:[i.jsx("h3",{className:"hub-connection-form__title",children:e}),i.jsx("p",{className:"hub-connection-form__description",children:t})]}),a?i.jsxs("div",{className:"hub-connection-form__current",children:[i.jsx("span",{children:"当前"}),i.jsx("strong",{children:a})]}):null]}),i.jsxs("label",{className:"hub-connection-form__field",children:[i.jsx("span",{className:"hub-connection-form__label",children:"Hub 地址"}),i.jsxs("span",{className:"hub-connection-form__input-shell",children:[i.jsx("input",{className:"hub-connection-form__input",type:"url",inputMode:"url",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,placeholder:"例如 http://192.168.31.20:4343",value:S,onChange:ge=>{p(ge.target.value),w({loading:!1,result:null}),D(null)}}),Q?i.jsxs("button",{type:"button",className:"hub-connection-form__scan",onClick:()=>{ee()},disabled:z.starting||N.saving||b.loading,"aria-label":"扫码填入 Hub 地址",children:[i.jsx(gj,{}),i.jsx("span",{children:z.starting?"启动中":"扫码"})]}):null]})]}),i.jsx("p",{className:"hub-connection-form__hint",children:o}),i.jsxs("div",{className:"hub-connection-form__actions",children:[i.jsxs("button",{type:"button",className:"settings-action hub-connection-form__save",onClick:()=>{Y()},disabled:!P||N.saving||z.starting,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:N.saving?f:u}),i.jsx("span",{children:m})]}),i.jsx("span",{className:"settings-action__state",children:N.saving?"处理中…":"→"})]}),i.jsx("button",{type:"button",className:"settings-ghost-button hub-connection-form__test",onClick:()=>{V()},disabled:!P||b.loading||N.saving||z.starting,children:b.loading?"测试中…":"测试连接"})]}),b.result?i.jsxs("div",{className:"hub-connection-form__probe",children:[i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"探测地址"}),i.jsx("strong",{children:b.result.url})]}),i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"连通结果"}),i.jsx("strong",{className:b.result.healthOk?"is-ok":"is-danger",children:b.result.healthOk?"Hub 在线":b.result.error??"无法连接"})]}),i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"延迟"}),i.jsx("strong",{children:x4(b.result.latencyMs)})]}),i.jsxs("div",{className:"hub-connection-form__probe-item",children:[i.jsx("span",{children:"最近探测"}),i.jsx("strong",{children:mj(b.result.checkedAt)})]})]}):null,T?i.jsx("p",{className:`hub-connection-form__notice is-${T.tone}`,children:T.text}):null]}),me]})};var S4;(function(e){e[e.Sunday=1]="Sunday",e[e.Monday=2]="Monday",e[e.Tuesday=3]="Tuesday",e[e.Wednesday=4]="Wednesday",e[e.Thursday=5]="Thursday",e[e.Friday=6]="Friday",e[e.Saturday=7]="Saturday"})(S4||(S4={}));const lh=mc("LocalNotifications",{web:()=>Zr(()=>import("./web-D1pcnorX.js"),[]).then(e=>new e.LocalNotificationsWeb)});var mn;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function a(o){throw new Error}e.assertNever=a,e.arrayToEnum=o=>{const u={};for(const f of o)u[f]=f;return u},e.getValidEnumValues=o=>{const u=e.objectKeys(o).filter(m=>typeof o[o[m]]!="number"),f={};for(const m of u)f[m]=o[m];return e.objectValues(f)},e.objectValues=o=>e.objectKeys(o).map(function(u){return o[u]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const u=[];for(const f in o)Object.prototype.hasOwnProperty.call(o,f)&&u.push(f);return u},e.find=(o,u)=>{for(const f of o)if(u(f))return f},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function l(o,u=" | "){return o.map(f=>typeof f=="string"?`'${f}'`:f).join(u)}e.joinValues=l,e.jsonStringifyReplacer=(o,u)=>typeof u=="bigint"?u.toString():u})(mn||(mn={}));var j4;(function(e){e.mergeShapes=(t,a)=>({...t,...a})})(j4||(j4={}));const nt=mn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$l=e=>{switch(typeof e){case"undefined":return nt.undefined;case"string":return nt.string;case"number":return Number.isNaN(e)?nt.nan:nt.number;case"boolean":return nt.boolean;case"function":return nt.function;case"bigint":return nt.bigint;case"symbol":return nt.symbol;case"object":return Array.isArray(e)?nt.array:e===null?nt.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?nt.promise:typeof Map<"u"&&e instanceof Map?nt.map:typeof Set<"u"&&e instanceof Set?nt.set:typeof Date<"u"&&e instanceof Date?nt.date:nt.object;default:return nt.unknown}},Be=mn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Vr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=l=>{this.issues=[...this.issues,l]},this.addIssues=(l=[])=>{this.issues=[...this.issues,...l]};const a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=t}format(t){const a=t||function(u){return u.message},l={_errors:[]},o=u=>{for(const f of u.issues)if(f.code==="invalid_union")f.unionErrors.map(o);else if(f.code==="invalid_return_type")o(f.returnTypeError);else if(f.code==="invalid_arguments")o(f.argumentsError);else if(f.path.length===0)l._errors.push(a(f));else{let m=l,y=0;for(;y<f.path.length;){const g=f.path[y];y===f.path.length-1?(m[g]=m[g]||{_errors:[]},m[g]._errors.push(a(f))):m[g]=m[g]||{_errors:[]},m=m[g],y++}}};return o(this),l}static assert(t){if(!(t instanceof Vr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,mn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=a=>a.message){const a={},l=[];for(const o of this.issues)if(o.path.length>0){const u=o.path[0];a[u]=a[u]||[],a[u].push(t(o))}else l.push(t(o));return{formErrors:l,fieldErrors:a}}get formErrors(){return this.flatten()}}Vr.create=e=>new Vr(e);const d0=(e,t)=>{let a;switch(e.code){case Be.invalid_type:e.received===nt.undefined?a="Required":a=`Expected ${e.expected}, received ${e.received}`;break;case Be.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,mn.jsonStringifyReplacer)}`;break;case Be.unrecognized_keys:a=`Unrecognized key(s) in object: ${mn.joinValues(e.keys,", ")}`;break;case Be.invalid_union:a="Invalid input";break;case Be.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${mn.joinValues(e.options)}`;break;case Be.invalid_enum_value:a=`Invalid enum value. Expected ${mn.joinValues(e.options)}, received '${e.received}'`;break;case Be.invalid_arguments:a="Invalid function arguments";break;case Be.invalid_return_type:a="Invalid function return type";break;case Be.invalid_date:a="Invalid date";break;case Be.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:mn.assertNever(e.validation):e.validation!=="regex"?a=`Invalid ${e.validation}`:a="Invalid";break;case Be.too_small:e.type==="array"?a=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?a=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?a=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?a=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?a=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:a="Invalid input";break;case Be.too_big:e.type==="array"?a=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?a=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?a=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?a=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?a=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:a="Invalid input";break;case Be.custom:a="Invalid input";break;case Be.invalid_intersection_types:a="Intersection results could not be merged";break;case Be.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case Be.not_finite:a="Number must be finite";break;default:a=t.defaultError,mn.assertNever(e)}return{message:a}};let yj=d0;function vj(){return yj}const bj=e=>{const{data:t,path:a,errorMaps:l,issueData:o}=e,u=[...a,...o.path||[]],f={...o,path:u};if(o.message!==void 0)return{...o,path:u,message:o.message};let m="";const y=l.filter(g=>!!g).slice().reverse();for(const g of y)m=g(f,{data:t,defaultError:m}).message;return{...o,path:u,message:m}};function Ge(e,t){const a=vj(),l=bj({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===d0?void 0:d0].filter(o=>!!o)});e.common.issues.push(l)}class ta{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,a){const l=[];for(const o of a){if(o.status==="aborted")return Tt;o.status==="dirty"&&t.dirty(),l.push(o.value)}return{status:t.value,value:l}}static async mergeObjectAsync(t,a){const l=[];for(const o of a){const u=await o.key,f=await o.value;l.push({key:u,value:f})}return ta.mergeObjectSync(t,l)}static mergeObjectSync(t,a){const l={};for(const o of a){const{key:u,value:f}=o;if(u.status==="aborted"||f.status==="aborted")return Tt;u.status==="dirty"&&t.dirty(),f.status==="dirty"&&t.dirty(),u.value!=="__proto__"&&(typeof f.value<"u"||o.alwaysSet)&&(l[u.value]=f.value)}return{status:t.value,value:l}}}const Tt=Object.freeze({status:"aborted"}),kf=e=>({status:"dirty",value:e}),Xa=e=>({status:"valid",value:e}),w4=e=>e.status==="aborted",N4=e=>e.status==="dirty",Wu=e=>e.status==="valid",ip=e=>typeof Promise<"u"&&e instanceof Promise;var ct;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(ct||(ct={}));class tr{constructor(t,a,l,o){this._cachedPath=[],this.parent=t,this.data=a,this._path=l,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const k4=(e,t)=>{if(Wu(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const a=new Vr(e.common.issues);return this._error=a,this._error}}};function Pt(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:l,description:o}=e;if(t&&(a||l))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(f,m)=>{const{message:y}=e;return f.code==="invalid_enum_value"?{message:y??m.defaultError}:typeof m.data>"u"?{message:y??l??m.defaultError}:f.code!=="invalid_type"?{message:m.defaultError}:{message:y??a??m.defaultError}},description:o}}class rn{get description(){return this._def.description}_getType(t){return $l(t.data)}_getOrReturnCtx(t,a){return a||{common:t.parent.common,data:t.data,parsedType:$l(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ta,ctx:{common:t.parent.common,data:t.data,parsedType:$l(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const a=this._parse(t);if(ip(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(t){const a=this._parse(t);return Promise.resolve(a)}parse(t,a){const l=this.safeParse(t,a);if(l.success)return l.data;throw l.error}safeParse(t,a){const l={common:{issues:[],async:(a==null?void 0:a.async)??!1,contextualErrorMap:a==null?void 0:a.errorMap},path:(a==null?void 0:a.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$l(t)},o=this._parseSync({data:t,path:l.path,parent:l});return k4(l,o)}"~validate"(t){var l,o;const a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$l(t)};if(!this["~standard"].async)try{const u=this._parseSync({data:t,path:[],parent:a});return Wu(u)?{value:u.value}:{issues:a.common.issues}}catch(u){(o=(l=u==null?void 0:u.message)==null?void 0:l.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:a}).then(u=>Wu(u)?{value:u.value}:{issues:a.common.issues})}async parseAsync(t,a){const l=await this.safeParseAsync(t,a);if(l.success)return l.data;throw l.error}async safeParseAsync(t,a){const l={common:{issues:[],contextualErrorMap:a==null?void 0:a.errorMap,async:!0},path:(a==null?void 0:a.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:$l(t)},o=this._parse({data:t,path:l.path,parent:l}),u=await(ip(o)?o:Promise.resolve(o));return k4(l,u)}refine(t,a){const l=o=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(o):a;return this._refinement((o,u)=>{const f=t(o),m=()=>u.addIssue({code:Be.custom,...l(o)});return typeof Promise<"u"&&f instanceof Promise?f.then(y=>y?!0:(m(),!1)):f?!0:(m(),!1)})}refinement(t,a){return this._refinement((l,o)=>t(l)?!0:(o.addIssue(typeof a=="function"?a(l,o):a),!1))}_refinement(t){return new Gu({schema:this,typeName:kt.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return ao.create(this,this._def)}nullable(){return Yu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return er.create(this)}promise(){return up.create(this,this._def)}or(t){return lp.create([this,t],this._def)}and(t){return op.create(this,t,this._def)}transform(t){return new Gu({...Pt(this._def),schema:this,typeName:kt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const a=typeof t=="function"?t:()=>t;return new g0({...Pt(this._def),innerType:this,defaultValue:a,typeName:kt.ZodDefault})}brand(){return new Fj({typeName:kt.ZodBranded,type:this,...Pt(this._def)})}catch(t){const a=typeof t=="function"?t:()=>t;return new _0({...Pt(this._def),innerType:this,catchValue:a,typeName:kt.ZodCatch})}describe(t){const a=this.constructor;return new a({...this._def,description:t})}pipe(t){return o_.create(this,t)}readonly(){return y0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const xj=/^c[^\s-]{8,}$/i,Sj=/^[0-9a-z]+$/,jj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wj=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Nj=/^[a-z0-9_-]{21}$/i,kj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ej=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Cj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let yg;const Rj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Aj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Dj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Oj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ij=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,f6="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Lj=new RegExp(`^${f6}$`);function h6(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const a=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${a}`}function Pj(e){return new RegExp(`^${h6(e)}$`)}function Uj(e){let t=`${f6}T${h6(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function zj(e,t){return!!((t==="v4"||!t)&&Rj.test(e)||(t==="v6"||!t)&&Aj.test(e))}function Bj(e,t){if(!kj.test(e))return!1;try{const[a]=e.split(".");if(!a)return!1;const l=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),o=JSON.parse(atob(l));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Hj(e,t){return!!((t==="v4"||!t)&&Mj.test(e)||(t==="v6"||!t)&&Dj.test(e))}class Wr extends rn{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==nt.string){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_type,expected:nt.string,received:u.parsedType}),Tt}const l=new ta;let o;for(const u of this._def.checks)if(u.kind==="min")t.data.length<u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if(u.kind==="max")t.data.length>u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if(u.kind==="length"){const f=t.data.length>u.value,m=t.data.length<u.value;(f||m)&&(o=this._getOrReturnCtx(t,o),f?Ge(o,{code:Be.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):m&&Ge(o,{code:Be.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),l.dirty())}else if(u.kind==="email")Cj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"email",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="emoji")yg||(yg=new RegExp(Tj,"u")),yg.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"emoji",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="uuid")wj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"uuid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="nanoid")Nj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"nanoid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="cuid")xj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"cuid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="cuid2")Sj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"cuid2",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="ulid")jj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"ulid",code:Be.invalid_string,message:u.message}),l.dirty());else if(u.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Ge(o,{validation:"url",code:Be.invalid_string,message:u.message}),l.dirty()}else u.kind==="regex"?(u.regex.lastIndex=0,u.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"regex",code:Be.invalid_string,message:u.message}),l.dirty())):u.kind==="trim"?t.data=t.data.trim():u.kind==="includes"?t.data.includes(u.value,u.position)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),l.dirty()):u.kind==="toLowerCase"?t.data=t.data.toLowerCase():u.kind==="toUpperCase"?t.data=t.data.toUpperCase():u.kind==="startsWith"?t.data.startsWith(u.value)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:{startsWith:u.value},message:u.message}),l.dirty()):u.kind==="endsWith"?t.data.endsWith(u.value)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:{endsWith:u.value},message:u.message}),l.dirty()):u.kind==="datetime"?Uj(u).test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:"datetime",message:u.message}),l.dirty()):u.kind==="date"?Lj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:"date",message:u.message}),l.dirty()):u.kind==="time"?Pj(u).test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.invalid_string,validation:"time",message:u.message}),l.dirty()):u.kind==="duration"?Ej.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"duration",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="ip"?zj(t.data,u.version)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"ip",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="jwt"?Bj(t.data,u.alg)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"jwt",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="cidr"?Hj(t.data,u.version)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"cidr",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="base64"?Oj.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"base64",code:Be.invalid_string,message:u.message}),l.dirty()):u.kind==="base64url"?Ij.test(t.data)||(o=this._getOrReturnCtx(t,o),Ge(o,{validation:"base64url",code:Be.invalid_string,message:u.message}),l.dirty()):mn.assertNever(u);return{status:l.value,value:t.data}}_regex(t,a,l){return this.refinement(o=>t.test(o),{validation:a,code:Be.invalid_string,...ct.errToObj(l)})}_addCheck(t){return new Wr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ct.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ct.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ct.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ct.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ct.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ct.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ct.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ct.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ct.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ct.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ct.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ct.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ct.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...ct.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...ct.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...ct.errToObj(t)})}regex(t,a){return this._addCheck({kind:"regex",regex:t,...ct.errToObj(a)})}includes(t,a){return this._addCheck({kind:"includes",value:t,position:a==null?void 0:a.position,...ct.errToObj(a==null?void 0:a.message)})}startsWith(t,a){return this._addCheck({kind:"startsWith",value:t,...ct.errToObj(a)})}endsWith(t,a){return this._addCheck({kind:"endsWith",value:t,...ct.errToObj(a)})}min(t,a){return this._addCheck({kind:"min",value:t,...ct.errToObj(a)})}max(t,a){return this._addCheck({kind:"max",value:t,...ct.errToObj(a)})}length(t,a){return this._addCheck({kind:"length",value:t,...ct.errToObj(a)})}nonempty(t){return this.min(1,ct.errToObj(t))}trim(){return new Wr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t}get maxLength(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t}}Wr.create=e=>new Wr({checks:[],typeName:kt.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Pt(e)});function $j(e,t){const a=(e.toString().split(".")[1]||"").length,l=(t.toString().split(".")[1]||"").length,o=a>l?a:l,u=Number.parseInt(e.toFixed(o).replace(".","")),f=Number.parseInt(t.toFixed(o).replace(".",""));return u%f/10**o}class Ku extends rn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==nt.number){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_type,expected:nt.number,received:u.parsedType}),Tt}let l;const o=new ta;for(const u of this._def.checks)u.kind==="int"?mn.isInteger(t.data)||(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.invalid_type,expected:"integer",received:"float",message:u.message}),o.dirty()):u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_small,minimum:u.value,type:"number",inclusive:u.inclusive,exact:!1,message:u.message}),o.dirty()):u.kind==="max"?(u.inclusive?t.data>u.value:t.data>=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_big,maximum:u.value,type:"number",inclusive:u.inclusive,exact:!1,message:u.message}),o.dirty()):u.kind==="multipleOf"?$j(t.data,u.value)!==0&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):u.kind==="finite"?Number.isFinite(t.data)||(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.not_finite,message:u.message}),o.dirty()):mn.assertNever(u);return{status:o.value,value:t.data}}gte(t,a){return this.setLimit("min",t,!0,ct.toString(a))}gt(t,a){return this.setLimit("min",t,!1,ct.toString(a))}lte(t,a){return this.setLimit("max",t,!0,ct.toString(a))}lt(t,a){return this.setLimit("max",t,!1,ct.toString(a))}setLimit(t,a,l,o){return new Ku({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:l,message:ct.toString(o)}]})}_addCheck(t){return new Ku({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ct.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ct.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ct.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ct.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ct.toString(t)})}multipleOf(t,a){return this._addCheck({kind:"multipleOf",value:t,message:ct.toString(a)})}finite(t){return this._addCheck({kind:"finite",message:ct.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ct.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ct.toString(t)})}get minValue(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t}get maxValue(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&mn.isInteger(t.value))}get isFinite(){let t=null,a=null;for(const l of this._def.checks){if(l.kind==="finite"||l.kind==="int"||l.kind==="multipleOf")return!0;l.kind==="min"?(a===null||l.value>a)&&(a=l.value):l.kind==="max"&&(t===null||l.value<t)&&(t=l.value)}return Number.isFinite(a)&&Number.isFinite(t)}}Ku.create=e=>new Ku({checks:[],typeName:kt.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Pt(e)});class qf extends rn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==nt.bigint)return this._getInvalidInput(t);let l;const o=new ta;for(const u of this._def.checks)u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_small,type:"bigint",minimum:u.value,inclusive:u.inclusive,message:u.message}),o.dirty()):u.kind==="max"?(u.inclusive?t.data>u.value:t.data>=u.value)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.too_big,type:"bigint",maximum:u.value,inclusive:u.inclusive,message:u.message}),o.dirty()):u.kind==="multipleOf"?t.data%u.value!==BigInt(0)&&(l=this._getOrReturnCtx(t,l),Ge(l,{code:Be.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):mn.assertNever(u);return{status:o.value,value:t.data}}_getInvalidInput(t){const a=this._getOrReturnCtx(t);return Ge(a,{code:Be.invalid_type,expected:nt.bigint,received:a.parsedType}),Tt}gte(t,a){return this.setLimit("min",t,!0,ct.toString(a))}gt(t,a){return this.setLimit("min",t,!1,ct.toString(a))}lte(t,a){return this.setLimit("max",t,!0,ct.toString(a))}lt(t,a){return this.setLimit("max",t,!1,ct.toString(a))}setLimit(t,a,l,o){return new qf({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:l,message:ct.toString(o)}]})}_addCheck(t){return new qf({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ct.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ct.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ct.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ct.toString(t)})}multipleOf(t,a){return this._addCheck({kind:"multipleOf",value:t,message:ct.toString(a)})}get minValue(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t}get maxValue(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t}}qf.create=e=>new qf({checks:[],typeName:kt.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Pt(e)});class f0 extends rn{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==nt.boolean){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.boolean,received:l.parsedType}),Tt}return Xa(t.data)}}f0.create=e=>new f0({typeName:kt.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Pt(e)});class rp extends rn{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==nt.date){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_type,expected:nt.date,received:u.parsedType}),Tt}if(Number.isNaN(t.data.getTime())){const u=this._getOrReturnCtx(t);return Ge(u,{code:Be.invalid_date}),Tt}const l=new ta;let o;for(const u of this._def.checks)u.kind==="min"?t.data.getTime()<u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_small,message:u.message,inclusive:!0,exact:!1,minimum:u.value,type:"date"}),l.dirty()):u.kind==="max"?t.data.getTime()>u.value&&(o=this._getOrReturnCtx(t,o),Ge(o,{code:Be.too_big,message:u.message,inclusive:!0,exact:!1,maximum:u.value,type:"date"}),l.dirty()):mn.assertNever(u);return{status:l.value,value:new Date(t.data.getTime())}}_addCheck(t){return new rp({...this._def,checks:[...this._def.checks,t]})}min(t,a){return this._addCheck({kind:"min",value:t.getTime(),message:ct.toString(a)})}max(t,a){return this._addCheck({kind:"max",value:t.getTime(),message:ct.toString(a)})}get minDate(){let t=null;for(const a of this._def.checks)a.kind==="min"&&(t===null||a.value>t)&&(t=a.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const a of this._def.checks)a.kind==="max"&&(t===null||a.value<t)&&(t=a.value);return t!=null?new Date(t):null}}rp.create=e=>new rp({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:kt.ZodDate,...Pt(e)});class E4 extends rn{_parse(t){if(this._getType(t)!==nt.symbol){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.symbol,received:l.parsedType}),Tt}return Xa(t.data)}}E4.create=e=>new E4({typeName:kt.ZodSymbol,...Pt(e)});class C4 extends rn{_parse(t){if(this._getType(t)!==nt.undefined){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.undefined,received:l.parsedType}),Tt}return Xa(t.data)}}C4.create=e=>new C4({typeName:kt.ZodUndefined,...Pt(e)});class T4 extends rn{_parse(t){if(this._getType(t)!==nt.null){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.null,received:l.parsedType}),Tt}return Xa(t.data)}}T4.create=e=>new T4({typeName:kt.ZodNull,...Pt(e)});class h0 extends rn{constructor(){super(...arguments),this._any=!0}_parse(t){return Xa(t.data)}}h0.create=e=>new h0({typeName:kt.ZodAny,...Pt(e)});class R4 extends rn{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Xa(t.data)}}R4.create=e=>new R4({typeName:kt.ZodUnknown,...Pt(e)});class ro extends rn{_parse(t){const a=this._getOrReturnCtx(t);return Ge(a,{code:Be.invalid_type,expected:nt.never,received:a.parsedType}),Tt}}ro.create=e=>new ro({typeName:kt.ZodNever,...Pt(e)});class M4 extends rn{_parse(t){if(this._getType(t)!==nt.undefined){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.void,received:l.parsedType}),Tt}return Xa(t.data)}}M4.create=e=>new M4({typeName:kt.ZodVoid,...Pt(e)});class er extends rn{_parse(t){const{ctx:a,status:l}=this._processInputParams(t),o=this._def;if(a.parsedType!==nt.array)return Ge(a,{code:Be.invalid_type,expected:nt.array,received:a.parsedType}),Tt;if(o.exactLength!==null){const f=a.data.length>o.exactLength.value,m=a.data.length<o.exactLength.value;(f||m)&&(Ge(a,{code:f?Be.too_big:Be.too_small,minimum:m?o.exactLength.value:void 0,maximum:f?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),l.dirty())}if(o.minLength!==null&&a.data.length<o.minLength.value&&(Ge(a,{code:Be.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),l.dirty()),o.maxLength!==null&&a.data.length>o.maxLength.value&&(Ge(a,{code:Be.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),l.dirty()),a.common.async)return Promise.all([...a.data].map((f,m)=>o.type._parseAsync(new tr(a,f,a.path,m)))).then(f=>ta.mergeArray(l,f));const u=[...a.data].map((f,m)=>o.type._parseSync(new tr(a,f,a.path,m)));return ta.mergeArray(l,u)}get element(){return this._def.type}min(t,a){return new er({...this._def,minLength:{value:t,message:ct.toString(a)}})}max(t,a){return new er({...this._def,maxLength:{value:t,message:ct.toString(a)}})}length(t,a){return new er({...this._def,exactLength:{value:t,message:ct.toString(a)}})}nonempty(t){return this.min(1,t)}}er.create=(e,t)=>new er({type:e,minLength:null,maxLength:null,exactLength:null,typeName:kt.ZodArray,...Pt(t)});function bu(e){if(e instanceof fs){const t={};for(const a in e.shape){const l=e.shape[a];t[a]=ao.create(bu(l))}return new fs({...e._def,shape:()=>t})}else return e instanceof er?new er({...e._def,type:bu(e.element)}):e instanceof ao?ao.create(bu(e.unwrap())):e instanceof Yu?Yu.create(bu(e.unwrap())):e instanceof uc?uc.create(e.items.map(t=>bu(t))):e}class fs extends rn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),a=mn.objectKeys(t);return this._cached={shape:t,keys:a},this._cached}_parse(t){if(this._getType(t)!==nt.object){const g=this._getOrReturnCtx(t);return Ge(g,{code:Be.invalid_type,expected:nt.object,received:g.parsedType}),Tt}const{status:l,ctx:o}=this._processInputParams(t),{shape:u,keys:f}=this._getCached(),m=[];if(!(this._def.catchall instanceof ro&&this._def.unknownKeys==="strip"))for(const g in o.data)f.includes(g)||m.push(g);const y=[];for(const g of f){const S=u[g],p=o.data[g];y.push({key:{status:"valid",value:g},value:S._parse(new tr(o,p,o.path,g)),alwaysSet:g in o.data})}if(this._def.catchall instanceof ro){const g=this._def.unknownKeys;if(g==="passthrough")for(const S of m)y.push({key:{status:"valid",value:S},value:{status:"valid",value:o.data[S]}});else if(g==="strict")m.length>0&&(Ge(o,{code:Be.unrecognized_keys,keys:m}),l.dirty());else if(g!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const g=this._def.catchall;for(const S of m){const p=o.data[S];y.push({key:{status:"valid",value:S},value:g._parse(new tr(o,p,o.path,S)),alwaysSet:S in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const g=[];for(const S of y){const p=await S.key,b=await S.value;g.push({key:p,value:b,alwaysSet:S.alwaysSet})}return g}).then(g=>ta.mergeObjectSync(l,g)):ta.mergeObjectSync(l,y)}get shape(){return this._def.shape()}strict(t){return ct.errToObj,new fs({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(a,l)=>{var u,f;const o=((f=(u=this._def).errorMap)==null?void 0:f.call(u,a,l).message)??l.defaultError;return a.code==="unrecognized_keys"?{message:ct.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new fs({...this._def,unknownKeys:"strip"})}passthrough(){return new fs({...this._def,unknownKeys:"passthrough"})}extend(t){return new fs({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new fs({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:kt.ZodObject})}setKey(t,a){return this.augment({[t]:a})}catchall(t){return new fs({...this._def,catchall:t})}pick(t){const a={};for(const l of mn.objectKeys(t))t[l]&&this.shape[l]&&(a[l]=this.shape[l]);return new fs({...this._def,shape:()=>a})}omit(t){const a={};for(const l of mn.objectKeys(this.shape))t[l]||(a[l]=this.shape[l]);return new fs({...this._def,shape:()=>a})}deepPartial(){return bu(this)}partial(t){const a={};for(const l of mn.objectKeys(this.shape)){const o=this.shape[l];t&&!t[l]?a[l]=o:a[l]=o.optional()}return new fs({...this._def,shape:()=>a})}required(t){const a={};for(const l of mn.objectKeys(this.shape))if(t&&!t[l])a[l]=this.shape[l];else{let u=this.shape[l];for(;u instanceof ao;)u=u._def.innerType;a[l]=u}return new fs({...this._def,shape:()=>a})}keyof(){return m6(mn.objectKeys(this.shape))}}fs.create=(e,t)=>new fs({shape:()=>e,unknownKeys:"strip",catchall:ro.create(),typeName:kt.ZodObject,...Pt(t)});fs.strictCreate=(e,t)=>new fs({shape:()=>e,unknownKeys:"strict",catchall:ro.create(),typeName:kt.ZodObject,...Pt(t)});fs.lazycreate=(e,t)=>new fs({shape:e,unknownKeys:"strip",catchall:ro.create(),typeName:kt.ZodObject,...Pt(t)});class lp extends rn{_parse(t){const{ctx:a}=this._processInputParams(t),l=this._def.options;function o(u){for(const m of u)if(m.result.status==="valid")return m.result;for(const m of u)if(m.result.status==="dirty")return a.common.issues.push(...m.ctx.common.issues),m.result;const f=u.map(m=>new Vr(m.ctx.common.issues));return Ge(a,{code:Be.invalid_union,unionErrors:f}),Tt}if(a.common.async)return Promise.all(l.map(async u=>{const f={...a,common:{...a.common,issues:[]},parent:null};return{result:await u._parseAsync({data:a.data,path:a.path,parent:f}),ctx:f}})).then(o);{let u;const f=[];for(const y of l){const g={...a,common:{...a.common,issues:[]},parent:null},S=y._parseSync({data:a.data,path:a.path,parent:g});if(S.status==="valid")return S;S.status==="dirty"&&!u&&(u={result:S,ctx:g}),g.common.issues.length&&f.push(g.common.issues)}if(u)return a.common.issues.push(...u.ctx.common.issues),u.result;const m=f.map(y=>new Vr(y));return Ge(a,{code:Be.invalid_union,unionErrors:m}),Tt}}get options(){return this._def.options}}lp.create=(e,t)=>new lp({options:e,typeName:kt.ZodUnion,...Pt(t)});function m0(e,t){const a=$l(e),l=$l(t);if(e===t)return{valid:!0,data:e};if(a===nt.object&&l===nt.object){const o=mn.objectKeys(t),u=mn.objectKeys(e).filter(m=>o.indexOf(m)!==-1),f={...e,...t};for(const m of u){const y=m0(e[m],t[m]);if(!y.valid)return{valid:!1};f[m]=y.data}return{valid:!0,data:f}}else if(a===nt.array&&l===nt.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let u=0;u<e.length;u++){const f=e[u],m=t[u],y=m0(f,m);if(!y.valid)return{valid:!1};o.push(y.data)}return{valid:!0,data:o}}else return a===nt.date&&l===nt.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class op extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t),o=(u,f)=>{if(w4(u)||w4(f))return Tt;const m=m0(u.value,f.value);return m.valid?((N4(u)||N4(f))&&a.dirty(),{status:a.value,value:m.data}):(Ge(l,{code:Be.invalid_intersection_types}),Tt)};return l.common.async?Promise.all([this._def.left._parseAsync({data:l.data,path:l.path,parent:l}),this._def.right._parseAsync({data:l.data,path:l.path,parent:l})]).then(([u,f])=>o(u,f)):o(this._def.left._parseSync({data:l.data,path:l.path,parent:l}),this._def.right._parseSync({data:l.data,path:l.path,parent:l}))}}op.create=(e,t,a)=>new op({left:e,right:t,typeName:kt.ZodIntersection,...Pt(a)});class uc extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.array)return Ge(l,{code:Be.invalid_type,expected:nt.array,received:l.parsedType}),Tt;if(l.data.length<this._def.items.length)return Ge(l,{code:Be.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Tt;!this._def.rest&&l.data.length>this._def.items.length&&(Ge(l,{code:Be.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());const u=[...l.data].map((f,m)=>{const y=this._def.items[m]||this._def.rest;return y?y._parse(new tr(l,f,l.path,m)):null}).filter(f=>!!f);return l.common.async?Promise.all(u).then(f=>ta.mergeArray(a,f)):ta.mergeArray(a,u)}get items(){return this._def.items}rest(t){return new uc({...this._def,rest:t})}}uc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new uc({items:e,typeName:kt.ZodTuple,rest:null,...Pt(t)})};class cp extends rn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.object)return Ge(l,{code:Be.invalid_type,expected:nt.object,received:l.parsedType}),Tt;const o=[],u=this._def.keyType,f=this._def.valueType;for(const m in l.data)o.push({key:u._parse(new tr(l,m,l.path,m)),value:f._parse(new tr(l,l.data[m],l.path,m)),alwaysSet:m in l.data});return l.common.async?ta.mergeObjectAsync(a,o):ta.mergeObjectSync(a,o)}get element(){return this._def.valueType}static create(t,a,l){return a instanceof rn?new cp({keyType:t,valueType:a,typeName:kt.ZodRecord,...Pt(l)}):new cp({keyType:Wr.create(),valueType:t,typeName:kt.ZodRecord,...Pt(a)})}}class A4 extends rn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.map)return Ge(l,{code:Be.invalid_type,expected:nt.map,received:l.parsedType}),Tt;const o=this._def.keyType,u=this._def.valueType,f=[...l.data.entries()].map(([m,y],g)=>({key:o._parse(new tr(l,m,l.path,[g,"key"])),value:u._parse(new tr(l,y,l.path,[g,"value"]))}));if(l.common.async){const m=new Map;return Promise.resolve().then(async()=>{for(const y of f){const g=await y.key,S=await y.value;if(g.status==="aborted"||S.status==="aborted")return Tt;(g.status==="dirty"||S.status==="dirty")&&a.dirty(),m.set(g.value,S.value)}return{status:a.value,value:m}})}else{const m=new Map;for(const y of f){const g=y.key,S=y.value;if(g.status==="aborted"||S.status==="aborted")return Tt;(g.status==="dirty"||S.status==="dirty")&&a.dirty(),m.set(g.value,S.value)}return{status:a.value,value:m}}}}A4.create=(e,t,a)=>new A4({valueType:t,keyType:e,typeName:kt.ZodMap,...Pt(a)});class Wf extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.parsedType!==nt.set)return Ge(l,{code:Be.invalid_type,expected:nt.set,received:l.parsedType}),Tt;const o=this._def;o.minSize!==null&&l.data.size<o.minSize.value&&(Ge(l,{code:Be.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),a.dirty()),o.maxSize!==null&&l.data.size>o.maxSize.value&&(Ge(l,{code:Be.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),a.dirty());const u=this._def.valueType;function f(y){const g=new Set;for(const S of y){if(S.status==="aborted")return Tt;S.status==="dirty"&&a.dirty(),g.add(S.value)}return{status:a.value,value:g}}const m=[...l.data.values()].map((y,g)=>u._parse(new tr(l,y,l.path,g)));return l.common.async?Promise.all(m).then(y=>f(y)):f(m)}min(t,a){return new Wf({...this._def,minSize:{value:t,message:ct.toString(a)}})}max(t,a){return new Wf({...this._def,maxSize:{value:t,message:ct.toString(a)}})}size(t,a){return this.min(t,a).max(t,a)}nonempty(t){return this.min(1,t)}}Wf.create=(e,t)=>new Wf({valueType:e,minSize:null,maxSize:null,typeName:kt.ZodSet,...Pt(t)});class D4 extends rn{get schema(){return this._def.getter()}_parse(t){const{ctx:a}=this._processInputParams(t);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}}D4.create=(e,t)=>new D4({getter:e,typeName:kt.ZodLazy,...Pt(t)});class p0 extends rn{_parse(t){if(t.data!==this._def.value){const a=this._getOrReturnCtx(t);return Ge(a,{received:a.data,code:Be.invalid_literal,expected:this._def.value}),Tt}return{status:"valid",value:t.data}}get value(){return this._def.value}}p0.create=(e,t)=>new p0({value:e,typeName:kt.ZodLiteral,...Pt(t)});function m6(e,t){return new Qu({values:e,typeName:kt.ZodEnum,...Pt(t)})}class Qu extends rn{_parse(t){if(typeof t.data!="string"){const a=this._getOrReturnCtx(t),l=this._def.values;return Ge(a,{expected:mn.joinValues(l),received:a.parsedType,code:Be.invalid_type}),Tt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const a=this._getOrReturnCtx(t),l=this._def.values;return Ge(a,{received:a.data,code:Be.invalid_enum_value,options:l}),Tt}return Xa(t.data)}get options(){return this._def.values}get enum(){const t={};for(const a of this._def.values)t[a]=a;return t}get Values(){const t={};for(const a of this._def.values)t[a]=a;return t}get Enum(){const t={};for(const a of this._def.values)t[a]=a;return t}extract(t,a=this._def){return Qu.create(t,{...this._def,...a})}exclude(t,a=this._def){return Qu.create(this.options.filter(l=>!t.includes(l)),{...this._def,...a})}}Qu.create=m6;class O4 extends rn{_parse(t){const a=mn.getValidEnumValues(this._def.values),l=this._getOrReturnCtx(t);if(l.parsedType!==nt.string&&l.parsedType!==nt.number){const o=mn.objectValues(a);return Ge(l,{expected:mn.joinValues(o),received:l.parsedType,code:Be.invalid_type}),Tt}if(this._cache||(this._cache=new Set(mn.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=mn.objectValues(a);return Ge(l,{received:l.data,code:Be.invalid_enum_value,options:o}),Tt}return Xa(t.data)}get enum(){return this._def.values}}O4.create=(e,t)=>new O4({values:e,typeName:kt.ZodNativeEnum,...Pt(t)});class up extends rn{unwrap(){return this._def.type}_parse(t){const{ctx:a}=this._processInputParams(t);if(a.parsedType!==nt.promise&&a.common.async===!1)return Ge(a,{code:Be.invalid_type,expected:nt.promise,received:a.parsedType}),Tt;const l=a.parsedType===nt.promise?a.data:Promise.resolve(a.data);return Xa(l.then(o=>this._def.type.parseAsync(o,{path:a.path,errorMap:a.common.contextualErrorMap})))}}up.create=(e,t)=>new up({type:e,typeName:kt.ZodPromise,...Pt(t)});class Gu extends rn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===kt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:a,ctx:l}=this._processInputParams(t),o=this._def.effect||null,u={addIssue:f=>{Ge(l,f),f.fatal?a.abort():a.dirty()},get path(){return l.path}};if(u.addIssue=u.addIssue.bind(u),o.type==="preprocess"){const f=o.transform(l.data,u);if(l.common.async)return Promise.resolve(f).then(async m=>{if(a.value==="aborted")return Tt;const y=await this._def.schema._parseAsync({data:m,path:l.path,parent:l});return y.status==="aborted"?Tt:y.status==="dirty"||a.value==="dirty"?kf(y.value):y});{if(a.value==="aborted")return Tt;const m=this._def.schema._parseSync({data:f,path:l.path,parent:l});return m.status==="aborted"?Tt:m.status==="dirty"||a.value==="dirty"?kf(m.value):m}}if(o.type==="refinement"){const f=m=>{const y=o.refinement(m,u);if(l.common.async)return Promise.resolve(y);if(y instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return m};if(l.common.async===!1){const m=this._def.schema._parseSync({data:l.data,path:l.path,parent:l});return m.status==="aborted"?Tt:(m.status==="dirty"&&a.dirty(),f(m.value),{status:a.value,value:m.value})}else return this._def.schema._parseAsync({data:l.data,path:l.path,parent:l}).then(m=>m.status==="aborted"?Tt:(m.status==="dirty"&&a.dirty(),f(m.value).then(()=>({status:a.value,value:m.value}))))}if(o.type==="transform")if(l.common.async===!1){const f=this._def.schema._parseSync({data:l.data,path:l.path,parent:l});if(!Wu(f))return Tt;const m=o.transform(f.value,u);if(m instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:m}}else return this._def.schema._parseAsync({data:l.data,path:l.path,parent:l}).then(f=>Wu(f)?Promise.resolve(o.transform(f.value,u)).then(m=>({status:a.value,value:m})):Tt);mn.assertNever(o)}}Gu.create=(e,t,a)=>new Gu({schema:e,typeName:kt.ZodEffects,effect:t,...Pt(a)});Gu.createWithPreprocess=(e,t,a)=>new Gu({schema:t,effect:{type:"preprocess",transform:e},typeName:kt.ZodEffects,...Pt(a)});class ao extends rn{_parse(t){return this._getType(t)===nt.undefined?Xa(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ao.create=(e,t)=>new ao({innerType:e,typeName:kt.ZodOptional,...Pt(t)});class Yu extends rn{_parse(t){return this._getType(t)===nt.null?Xa(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Yu.create=(e,t)=>new Yu({innerType:e,typeName:kt.ZodNullable,...Pt(t)});class g0 extends rn{_parse(t){const{ctx:a}=this._processInputParams(t);let l=a.data;return a.parsedType===nt.undefined&&(l=this._def.defaultValue()),this._def.innerType._parse({data:l,path:a.path,parent:a})}removeDefault(){return this._def.innerType}}g0.create=(e,t)=>new g0({innerType:e,typeName:kt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Pt(t)});class _0 extends rn{_parse(t){const{ctx:a}=this._processInputParams(t),l={...a,common:{...a.common,issues:[]}},o=this._def.innerType._parse({data:l.data,path:l.path,parent:{...l}});return ip(o)?o.then(u=>({status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new Vr(l.common.issues)},input:l.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Vr(l.common.issues)},input:l.data})}}removeCatch(){return this._def.innerType}}_0.create=(e,t)=>new _0({innerType:e,typeName:kt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Pt(t)});class I4 extends rn{_parse(t){if(this._getType(t)!==nt.nan){const l=this._getOrReturnCtx(t);return Ge(l,{code:Be.invalid_type,expected:nt.nan,received:l.parsedType}),Tt}return{status:"valid",value:t.data}}}I4.create=e=>new I4({typeName:kt.ZodNaN,...Pt(e)});class Fj extends rn{_parse(t){const{ctx:a}=this._processInputParams(t),l=a.data;return this._def.type._parse({data:l,path:a.path,parent:a})}unwrap(){return this._def.type}}class o_ extends rn{_parse(t){const{status:a,ctx:l}=this._processInputParams(t);if(l.common.async)return(async()=>{const u=await this._def.in._parseAsync({data:l.data,path:l.path,parent:l});return u.status==="aborted"?Tt:u.status==="dirty"?(a.dirty(),kf(u.value)):this._def.out._parseAsync({data:u.value,path:l.path,parent:l})})();{const o=this._def.in._parseSync({data:l.data,path:l.path,parent:l});return o.status==="aborted"?Tt:o.status==="dirty"?(a.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:l.path,parent:l})}}static create(t,a){return new o_({in:t,out:a,typeName:kt.ZodPipeline})}}class y0 extends rn{_parse(t){const a=this._def.innerType._parse(t),l=o=>(Wu(o)&&(o.value=Object.freeze(o.value)),o);return ip(a)?a.then(o=>l(o)):l(a)}unwrap(){return this._def.innerType}}y0.create=(e,t)=>new y0({innerType:e,typeName:kt.ZodReadonly,...Pt(t)});var kt;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(kt||(kt={}));const E=Wr.create,We=Ku.create,At=f0.create,qj=h0.create;ro.create;const at=er.create,Ae=fs.create;lp.create;op.create;uc.create;const dp=cp.create,oo=p0.create,vt=Qu.create;up.create;ao.create;Yu.create;const p6=vt(["codex","claude"]),Wj=vt(["managed","attached-live","history-only"]),Kj=vt(["active","idle","attention","offline"]),g6=vt(["idle","running","completed"]),_6=vt(["image","file"]),Qj=vt(["user","repo","system","admin"]),Gj=Ae({can_stream_live:At(),can_send_input:At(),can_interrupt:At(),can_approve:At(),can_reject:At(),can_show_git:At(),can_show_terminal:At()}),y6=Ae({used_tokens:We(),total_tokens:We(),remaining_tokens:We(),percent_used:We(),cached_input_tokens:We(),output_tokens:We(),reasoning_output_tokens:We(),updated_at:E()}),Yj=vt(["pending","in_progress","completed"]),Vj=Ae({id:E(),step:E(),status:Yj}),c_=Ae({session_id:E(),turn_id:E().nullable(),source:vt(["rollout","app-server"]),updated_at:E(),explanation:E().nullable().default(null),steps:at(Vj),completed_count:We().int().nonnegative(),total_count:We().int().nonnegative(),is_active:At()}),Zj=Ae({parent_session_id:E(),root_session_id:E().nullable().default(null),nickname:E().nullable().default(null),role:E().nullable().default(null),depth:We().int().nonnegative()}),Xj=vt(["user_input","command_execution_approval","file_change_approval","permissions_approval","mcp_elicitation"]),Jj=vt(["pending","submitting","resolved"]),v6=Ae({id:E(),label:E(),description:E().nullable().default(null),emphasis:vt(["default","primary","danger"]).default("default")}),ew=Ae({id:E(),header:E().nullable().default(null),question:E(),options:at(v6).default([]),allow_other:At().default(!1),is_secret:At().default(!1)}),u_=Ae({id:E(),session_id:E(),turn_id:E().nullable().default(null),item_id:E().nullable().default(null),kind:Xj,status:Jj,title:E(),description:E().nullable().default(null),created_at:E(),updated_at:E(),options:at(v6).default([]),questions:at(ew).default([]),allow_freeform:At().default(!1),freeform_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null)}),tw=Ae({id:E(),kind:_6,name:E().nullable().default(null),mime_type:E().nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null),content_url:E().nullable().default(null)}),L4=Ae({id:E(),kind:_6,name:E(),mime_type:E().nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null),data_url:E()}),nw=Ae({name:E(),description:E(),path:E(),scope:Qj,enabled:At()}),sw=vt(["supported","unsupported"]),aw=Ae({name:E(),description:E(),availability:sw.default("supported")}),P4=Ae({cli_version:E().nullable().default(null),loaded_at:E(),cache_ttl_ms:We().int().nonnegative(),commands:at(aw)});Ae({id:E(),label:E(),description:E(),isDefault:At(),defaultReasoningEffort:E().nullable().default(null),supportedReasoningEfforts:at(E()).default([])});const iw=vt(["running","awaiting_input","completed","failed"]),rw=vt(["none","choice","text"]),lw=Ae({id:E(),label:E(),description:E().nullable().default(null)}),ow=Ae({type:oo("set_session_model"),model:E(),reasoning_effort:E().nullable().default(null)}).nullable().default(null),cw=Ae({panel_id:E(),session_id:E(),command_name:E(),command_text:E(),title:E(),description:E().nullable().default(null),status:iw,body:E(),submitted_at:E(),updated_at:E(),input_type:rw,options:at(lw).default([]),input_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null),effect:ow}),U4=Ae({panel:cw}),uw=vt(["online","offline"]),Rp=Ae({id:E(),name:E(),display_name:E().nullable().default(null),host:E(),tailscale_ip:E().nullable().default(null),tailscale_dns_name:E().nullable().default(null),direct_base_url:E(),ws_base_url:E(),status:uw,provider_availability:at(p6),project_count:We(),session_count:We(),transport:vt(["direct-agent","hub-routed"]),version:E().nullable().default(null),registered_at:E().nullable().default(null),last_seen_at:E().nullable().default(null)}),d_=Ae({id:E(),agent_id:E(),name:E(),display_name:E().nullable(),pinned:At(),path:E(),branch:E(),worktree:E(),runtime_profiles:at(E()),preview_url:E().nullable()}),oh=Ae({id:E(),agent_id:E(),project_id:E(),provider:p6,archived:At(),title:E(),mode:Wj,health:Kj,branch:E(),worktree:E(),summary:E(),latest_assistant_message:E().nullable().default(null),last_event_at:E(),pinned:At(),run_state:g6,run_state_changed_at:E().nullable(),context_usage:y6.nullable().default(null),subagent:Zj.nullable().default(null),capability:Gj}),dw=Ae({path:E(),additions:We(),deletions:We()}),fw=Ae({files:at(dw),additions:We(),deletions:We()}),Kf=Ae({id:E(),kind:vt(["user","assistant","thinking","tool","system"]),title:E(),body:E(),body_truncated:At().default(!1),detail_available:At().default(!1),patch_summary:fw.nullable().default(null),session_ids:at(E()).default([]),timestamp:E(),accent:vt(["primary","secondary","muted"]),attachments:at(tw).default([])}),hw=vt(["tail","full_compact"]),b6=Ae({session_id:E(),generated_at:E(),view:hw,anchor_entry_id:E().nullable().default(null),has_earlier_entries:At().default(!1),entries:at(Kf)}),mw=vt(["app-server","rollout-fallback"]),pw=vt(["running","completed"]),gw=vt(["add","delete","update"]),f_=Ae({path:E(),kind:gw,move_path:E().nullable(),additions:We(),deletions:We(),diff:E(),item_id:E().nullable()}),_w=f_.omit({diff:!0}).extend({diff_available:At().default(!1)}),x6=Ae({id:E(),session_id:E(),turn_id:E(),source:mw,status:pw,started_at:E(),completed_at:E().nullable(),updated_at:E(),aggregated_diff:E(),files:at(f_)}),S6=x6.omit({aggregated_diff:!0,files:!0}).extend({aggregated_diff_available:At().default(!1),files:at(_w)}),yw=Ae({session_id:E(),change_set_id:E(),file:f_,empty_message:E().default("此变更没有可展示的补丁内容")}),vw=Ae({path:E(),status:vt(["modified","added","deleted","renamed"]),additions:We(),deletions:We()}),j6=vt(["modified","added","deleted","renamed","untracked"]),bw=Ae({path:E(),previous_path:E().nullable().default(null),status:j6,additions:We().int().nonnegative(),deletions:We().int().nonnegative()}),xw=Ae({session_id:E(),project_id:E(),path:E(),previous_path:E().nullable().default(null),additions:We().int().nonnegative(),deletions:We().int().nonnegative(),diff:E()}),h_=Ae({session_id:E(),project_id:E(),branch:E(),branches:at(E()),upstream_branch:E().nullable().default(null),ahead_count:We().int().nonnegative(),behind_count:We().int().nonnegative(),files:at(bw),updated_at:E()}),Sw=Ae({path:E(),previous_path:E().nullable().default(null),status:j6}),jw=Ae({oid:E(),short_oid:E(),subject:E(),author_name:E(),authored_at:E(),committed_at:E(),parent_oids:at(E()).default([]),refs:at(E()).default([]),files:at(Sw)}),ww=Ae({session_id:E(),project_id:E(),commit_oid:E(),path:E(),previous_path:E().nullable().default(null),additions:We().int().nonnegative(),deletions:We().int().nonnegative(),diff:E()}),Nw=Ae({session_id:E(),project_id:E(),branch:E(),upstream_branch:E().nullable().default(null),head_oid:E().nullable().default(null),upstream_head_oid:E().nullable().default(null),commits:at(jw),updated_at:E()});vt(["discard-file","discard-all","commit-all","switch-branch","push"]);const kw=Ae({ok:oo(!0),workspace:h_});vt(["rollback"]);const Ew=Ae({ok:oo(!0),turn_id:E(),change_set_id:E(),workspace:h_}),Cw=vt(["directory","file"]),w6=vt(["markdown","code","text","image","binary"]),Tw=Ae({path:E(),name:E(),kind:Cw,has_children:At(),extension:E().nullable().default(null),file_kind:w6.nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null)}),Rw=Ae({session_id:E(),project_id:E(),root_path:E(),parent_path:E().nullable().default(null),nodes:at(Tw),loaded_at:E()}),Mw=Ae({session_id:E(),project_id:E(),path:E(),name:E(),extension:E().nullable().default(null),file_kind:w6,mime_type:E().nullable().default(null),size_bytes:We().int().nonnegative().nullable().default(null),encoding:vt(["utf8","base64"]).nullable().default(null),is_truncated:At(),content_text:E().nullable().default(null),content_base64:E().nullable().default(null),loaded_at:E()}),N6=vt(["auto","powershell","cmd","bash"]),Aw=vt(["user","codex"]),Dw=Ae({id:E(),name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:N6.default("auto"),node_version:E().nullable().default(null),port:We().int().positive().nullable().default(null),source:Aw.default("user"),created_at:E(),updated_at:E()}),Ow=Ae({name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:N6.default("auto"),node_version:E().nullable().default(null),port:We().int().positive().nullable().default(null)}),m_=Ae({session_id:E(),project_id:E(),config_path:E(),commands:at(Dw),updated_at:E()}),Iw=vt(["user","codex"]),Lw=Ae({id:E(),name:E(),description:E().nullable().default(null),url:E(),source:Iw.default("user"),created_at:E(),updated_at:E()}),Pw=Ae({name:E(),description:E().nullable().default(null),url:E()}),p_=Ae({session_id:E(),project_id:E(),config_path:E(),websites:at(Lw),updated_at:E()}),Uw=vt(["queued","running","completed","failed","stopped"]),zw=vt(["stdout","stderr","system"]),Bw=Ae({cursor:We().int().nonnegative(),stream:zw,text:E(),timestamp:E()}),g_=Ae({id:E(),session_id:E(),project_id:E(),command_id:E().nullable().default(null),title:E(),command:E(),cwd:E(),status:Uw,exit_code:We().int().nullable().default(null),created_at:E(),started_at:E().nullable().default(null),completed_at:E().nullable().default(null),updated_at:E(),last_output_at:E().nullable().default(null),output_cursor:We().int().nonnegative(),preview:E().nullable().default(null)}),__=Ae({session_id:E(),project_id:E(),active_terminal_id:E().nullable().default(null),terminals:at(g_),updated_at:E()}),Hw=Ae({session_id:E(),project_id:E(),terminal:g_,chunks:at(Bw),next_cursor:We().int().nonnegative(),truncated:At().default(!1)}),k6=Ae({run_state:g6.optional(),run_state_changed_at:E().nullable().optional(),summary:E().optional(),latest_assistant_message:E().nullable().optional(),last_event_at:E().optional(),context_usage:y6.nullable().optional()}),$w=Ae({session_id:E(),recovered_at:E(),session_patch:k6,timeline:at(Kf),interactions:at(u_),plan_snapshot:c_.nullable().default(null),change_sets:at(x6),terminal_snapshot:__.nullable().default(null)}),E6=Ae({manager:vt(["none","nvm-windows"]).default("none"),versions:at(E()).default([]),error:E().nullable().default(null)}),C6=Ae({command_catalog:m_,website_catalog:p_,node_runtime:E6,terminal_snapshot:__}),Fw=Ae({session_id:E(),generated_at:E(),session_patch:k6,timeline:b6,interactions:at(u_),plan_snapshot:c_.nullable().default(null),run_workbench:C6.nullable().default(null),change_sets:at(S6).default([])}),qw=Ae({catalog:m_}),Ww=Ae({catalog:p_}),Kw=Ae({commands:at(Ow),reason:E().nullable().default(null)}),Qw=Ae({generation:Kw,catalog:m_}),Gw=Ae({websites:at(Pw),reason:E().nullable().default(null)}),Yw=Ae({generation:Gw,catalog:p_}),Vw=Ae({snapshot:__,terminal:g_.nullable().default(null)}),Zw=vt(["dev-hub","dev-agent","dev-web","release-hub","release-agent"]),Xw=vt(["unknown","running","stopped","degraded"]),Jw=vt(["process","windows-service"]),eN=vt(["missing","running","stopped","unknown"]),tN=vt(["dev-start","dev-restart","dev-stop","dev-probe","npm-publish","release-service-install","release-service-uninstall","release-install-package","release-restart","release-install-run","apk-build"]),nN=vt(["running","succeeded","failed"]),sN=vt(["info","success","warn","error"]),T6=Ae({repo_path:E().nullable().default(null),nvm_version:E().nullable().default(null),dev_hub_port:We().int().positive().nullable().default(null),dev_hub_args:E().default(""),dev_agent_port:We().int().positive().nullable().default(null),dev_agent_hub_url:E().default(""),dev_agent_direct_base_url:E().default(""),dev_agent_ws_base_url:E().default(""),dev_agent_name:E().default(""),dev_agent_args:E().default(""),dev_web_port:We().int().positive().nullable().default(null),dev_web_hub_url:E().default(""),dev_web_args:E().default(""),release_hub_port:We().int().positive().nullable().default(null),release_hub_service_name:E().default("PandaHub"),release_hub_args:E().default(""),release_agent_port:We().int().positive().nullable().default(null),release_agent_service_name:E().default("PandaAgent"),release_agent_hub_url:E().default(""),release_agent_direct_base_url:E().default(""),release_agent_ws_base_url:E().default(""),release_agent_name:E().default(""),release_agent_args:E().default(""),updated_at:E().nullable().default(null)}),aN=T6.extend({npm_token:E().nullable().default(null),clear_npm_token:At().default(!1)}),iN=Ae({has_npm_token:At(),npm_token_hint:E().nullable().default(null)}),rN=Ae({checked_at:E(),url:E().nullable().default(null),ok:At(),status_code:We().int().nullable().default(null),duration_ms:We().int().nonnegative().nullable().default(null),message:E().nullable().default(null)}),lN=Ae({key:Zw,label:E(),status:Xw,manager:Jw.default("process"),service_name:E().nullable().default(null),service_registered:At().default(!1),service_status:eN.nullable().default(null),configured_port:We().int().positive().nullable().default(null),detected_pids:at(We().int().positive()).default([]),probe:rN.nullable().default(null)}),oN=Ae({id:E(),timestamp:E(),level:sN,message:E()}),R6=Ae({id:E(),kind:tN,title:E(),status:nN,created_at:E(),started_at:E().nullable().default(null),finished_at:E().nullable().default(null),summary:E().nullable().default(null),error:E().nullable().default(null),disconnect_expected:At().default(!1),logs:at(oN).default([])}),cN=Ae({artifact_id:E(),file_name:E(),size_bytes:We().int().nonnegative(),built_at:E(),published_at:E().nullable().default(null),version_name:E().nullable().default(null),version_code:We().int().nullable().default(null),download_path:E()}),v0=Ae({generated_at:E(),config:T6,credentials:iN,node_runtime:E6,services:at(lN),current_version:E().nullable().default(null),apk_artifact:cN.nullable().default(null),jobs:at(R6).default([])});Ae({action:vt(["start-development","restart-development","stop-development","probe-development","publish-npm","install-release-services","uninstall-release-services","install-latest-release-package","restart-release-services","install-latest-release","build-apk"])});const uN=Ae({ok:oo(!0),snapshot:v0,job:R6.nullable().default(null)}),dN=Ae({id:E(),name:E(),command:E(),port:We().nullable(),status:vt(["running","stopped","degraded"]),log_excerpt:E()}),fN=Ae({id:E(),label:E(),url:E(),status:vt(["ready","starting","stopped"])}),M6=Ae({path:E(),name:E(),has_children:At()}),hN=Ae({directory:M6}),mN=Ae({id:E(),title:E(),description:E(),status:vt(["pending","approved","rejected"])}),pN=Ae({project_id:E(),visible_session_count:We().int().nonnegative(),archived_session_count:We().int().nonnegative(),hidden_history_count:We().int().nonnegative()}),gN=d_.pick({id:!0,agent_id:!0,name:!0,display_name:!0,pinned:!0,path:!0}),_N=Rp.pick({id:!0,name:!0,display_name:!0,status:!0}),A6=oh.pick({id:!0,agent_id:!0,project_id:!0,archived:!0,title:!0,last_event_at:!0,pinned:!0,run_state:!0,run_state_changed_at:!0,subagent:!0}),yN=oh.pick({id:!0,agent_id:!0,project_id:!0,archived:!0,title:!0,provider:!0,mode:!0,health:!0,branch:!0,worktree:!0,summary:!0,latest_assistant_message:!0,last_event_at:!0,pinned:!0,run_state:!0,run_state_changed_at:!0,context_usage:!0,subagent:!0,capability:!0}),vN=Ae({generated_at:E(),session:yN}),bN=Ae({generated_at:E(),agents:at(Rp)}),xN=oh.pick({id:!0,title:!0,run_state:!0,run_state_changed_at:!0,latest_assistant_message:!0}),SN=Ae({generated_at:E(),recent_sessions:at(xN)}),jN=Ae({session_id:E(),agent_id:E(),project_id:E(),direct_base_url:E(),ws_base_url:E()}),wN=Ae({generated_at:E(),agent:_N.nullable().default(null),projects:at(gN),project_stats:at(pN).default([]),sessions:at(A6),active_session_id:E()}),D6=vt(["archived","history"]),NN=Ae({bucket:D6,project_id:E().nullable().default(null),sessions:at(A6),next_cursor:E().nullable().default(null),total_count:We().int().nonnegative()}),kN=Ae({session_id:E(),entry_id:E(),command_entry:Kf,output_entries:at(Kf).default([])}),EN=Ae({generated_at:E(),agents:at(Rp),projects:at(d_),sessions:at(oh),active_session_id:E(),timeline:at(Kf),changed_files:at(vw),runtime_processes:at(dN),previews:at(fN),approvals:at(mN)});Ae({agent:Rp,projects:at(d_),sessions:at(oh),active_session_id:E().default(""),generated_at:E()});const z4=Ae({ok:oo(!0),agent_id:E(),heartbeat_interval_ms:We().int().positive(),heartbeat_timeout_ms:We().int().positive(),registered_at:E(),received_at:E()}),CN=vt(["rename","delete"]);Ae({action:CN,display_name:E().nullable().default(null)});const TN=Ae({ok:oo(!0)}),y_=Ae({completion_notifications_enabled:At().default(!1)}),RN=Ae({p256dh:E(),auth:E()}),MN=Ae({endpoint:E().url(),expirationTime:We().nullable().default(null),keys:RN}),AN=Ae({label:E().nullable().default(null),user_agent:E().nullable().default(null)});Ae({subscription:MN,settings:y_.default({}),device:AN.default({})});const DN=Ae({endpoint:E().url()}),ON=Ae({endpoint:E().url()}),IN=Ae({supported:At(),vapid_public_key:E().nullable().default(null),subject:E().nullable().default(null),reason:E().nullable().default(null)}),LN=Ae({ok:oo(!0),subscription_id:E(),endpoint:E().url(),settings:y_,created_at:E(),updated_at:E()}),PN=Ae({ok:oo(!0),endpoint:E().url(),delivered_at:E()}),UN=Ae({type:vt(["agent.online","agent.offline","snapshot.changed","session.updated","thread.updated","timeline.delta","timeline.reset","interaction.delta","interaction.reset","plan.delta","plan.reset","changeset.delta","changeset.reset","terminal.snapshot","terminal.delta","turn.delta","turn.completed","approval.requested"]),timestamp:E(),payload:dp(qj())}),zN=Ae({width:We().nonnegative(),height:We().nonnegative(),device_pixel_ratio:We().nonnegative(),visual_width:We().nonnegative().nullable().default(null),visual_height:We().nonnegative().nullable().default(null),screen_width:We().nonnegative().nullable().default(null),screen_height:We().nonnegative().nullable().default(null)}),BN=Ae({user_agent:E(),language:E().nullable().default(null),languages:at(E()).default([]),platform:E().nullable().default(null),vendor:E().nullable().default(null),online:At().nullable().default(null),cookie_enabled:At().nullable().default(null),secure_context:At(),standalone_display_mode:At(),hardware_concurrency:We().int().nonnegative().nullable().default(null),device_memory_gb:We().nonnegative().nullable().default(null),max_touch_points:We().int().nonnegative().nullable().default(null)}),HN=Ae({href:E(),pathname:E(),referrer:E().nullable().default(null),visibility_state:E().nullable().default(null)}),$N=Ae({scope:E(),active_script_url:E().nullable().default(null),waiting_script_url:E().nullable().default(null),installing_script_url:E().nullable().default(null)}),FN=Ae({supported:At(),controller:At(),registrations:at($N).default([])}),qN=Ae({supported:At(),keys:at(E()).default([])}),WN=Ae({href:E().nullable().default(null),rel:E().nullable().default(null)}),KN=Ae({href:E().nullable().default(null),owner_node:E().nullable().default(null),media:E().nullable().default(null),disabled:At(),css_rule_count:We().int().nonnegative().nullable().default(null)}),QN=Ae({url:E(),kind:vt(["stylesheet","script","manifest","icon","other"]),ok:At(),status:We().int().nonnegative().nullable().default(null),content_type:E().nullable().default(null),cache_control:E().nullable().default(null),error:E().nullable().default(null)}),GN=Ae({name:E(),initiator_type:E().nullable().default(null),duration_ms:We().nonnegative().nullable().default(null),transfer_size:We().nonnegative().nullable().default(null),decoded_body_size:We().nonnegative().nullable().default(null)}),YN=Ae({x:We(),y:We(),width:We().nonnegative(),height:We().nonnegative()}),VN=Ae({selector:E(),found:At(),text_preview:E().nullable().default(null),rect:YN.nullable().default(null),computed:dp(E()).default({})});Ae({captured_at:E(),page:HN,environment:BN,viewport:zN,feature_support:dp(At()).default({}),service_worker:FN,cache:qN,manifest:WN,stylesheets:at(KN).default([]),resource_probes:at(QN).default([]),performance_entries:at(GN).default([]),theme_variables:dp(E()).default({}),element_snapshots:at(VN).default([]),notes:at(E()).default([])});const ZN=/^(?:image|img|photo|picture|screenshot|图片|照片|截图)(?:[-_ ]?\d+)?\.(?:avif|bmp|gif|heic|heif|jpe?g|png|svg|webp)$/i,Ls=e=>(e==null?void 0:e.trim())??"",B4="\0",H4=e=>{const t=Ls(e);return t?ZN.test(t)?1:2+Math.min(t.length,64)/100:0},XN=(e,t)=>{const a=H4(e),l=H4(t);if(l>a)return Ls(t)||null;if(a>l)return Ls(e)||null;const o=Ls(e),u=Ls(t);return u.length>o.length?u||null:o||null},JN=e=>{const t=Ls(e.content_url);return t?[e.kind,"content",t].join(B4):[e.kind,"meta",Ls(e.mime_type).toLowerCase(),typeof e.size_bytes=="number"&&Number.isFinite(e.size_bytes)?String(Math.max(0,Math.round(e.size_bytes))):"",Ls(e.name).toLowerCase()].join(B4)},ek=(e,t)=>{const a=Ls(e.name),l=Ls(t.name),o=Ls(e.mime_type),u=Ls(t.mime_type);return{id:e.id||t.id,kind:e.kind==="image"||t.kind==="image"?"image":e.kind,name:XN(a,l),mime_type:o||u||null,size_bytes:e.size_bytes??t.size_bytes??null,content_url:Ls(e.content_url)||Ls(t.content_url)||null}},O6=e=>{if(!e||e.length===0)return[];const t=[],a=new Map;for(const l of e){const o=JN(l),u=a.get(o);if(u===void 0){a.set(o,t.length),t.push({...l,name:Ls(l.name)||null,mime_type:Ls(l.mime_type)||null,size_bytes:typeof l.size_bytes=="number"&&Number.isFinite(l.size_bytes)?Math.max(0,Math.round(l.size_bytes)):null,content_url:Ls(l.content_url)||null});continue}t[u]=ek(t[u],l)}return t},I6=(e,t)=>O6([...e??[],...t??[]]),ba=e=>new Date(e).toISOString(),tk=()=>({generated_at:new Date().toISOString(),active_session_id:"session-managed-1",agents:[{id:"agent-shanghai-main",name:"studio-main",display_name:null,host:"100.88.10.14",tailscale_ip:"100.88.10.14",tailscale_dns_name:"studio-main.tail-scale.ts.net",direct_base_url:"http://100.88.10.14:4242",ws_base_url:"ws://100.88.10.14:4242/ws",status:"online",provider_availability:["codex"],project_count:2,session_count:2,transport:"direct-agent",version:"0.1.0",registered_at:ba("2026-03-18T10:30:00+08:00"),last_seen_at:ba("2026-03-18T10:58:00+08:00")},{id:"agent-macbook",name:"macbook-air",display_name:null,host:"100.89.20.77",tailscale_ip:"100.89.20.77",tailscale_dns_name:"macbook-air.tail-scale.ts.net",direct_base_url:"http://100.89.20.77:4242",ws_base_url:"ws://100.89.20.77:4242/ws",status:"online",provider_availability:["codex"],project_count:1,session_count:1,transport:"hub-routed",version:"0.1.0",registered_at:ba("2026-03-18T10:20:00+08:00"),last_seen_at:ba("2026-03-18T10:55:00+08:00")}],projects:[{id:"project-panda",agent_id:"agent-shanghai-main",name:"panda",display_name:null,pinned:!1,path:"D:/ai/panda",branch:"main",worktree:"default",runtime_profiles:["dev","storybook","test"],preview_url:"https://panda.tailnet.ts.net"},{id:"project-remodex-lab",agent_id:"agent-shanghai-main",name:"remodex",display_name:null,pinned:!1,path:"D:/ai/remodex",branch:"phase1-ui",worktree:"mobile-lab",runtime_profiles:["dev"],preview_url:null},{id:"project-notes",agent_id:"agent-macbook",name:"notes",display_name:null,pinned:!1,path:"D:/Users/dev/notes",branch:"research",worktree:"default",runtime_profiles:["dev"],preview_url:null}],sessions:[{id:"session-managed-1",agent_id:"agent-shanghai-main",project_id:"project-panda",provider:"codex",archived:!1,title:"Stage 1 buildout",mode:"managed",health:"active",branch:"main",worktree:"default",summary:"Monorepo scaffold, PWA shell, agent bootstrap API",latest_assistant_message:"Wiring the shell.",last_event_at:ba("2026-03-18T10:58:00+08:00"),pinned:!1,run_state:"running",run_state_changed_at:ba("2026-03-18T10:57:20+08:00"),context_usage:null,subagent:null,capability:{can_stream_live:!0,can_send_input:!0,can_interrupt:!0,can_approve:!0,can_reject:!0,can_show_git:!0,can_show_terminal:!0}},{id:"session-live-2",agent_id:"agent-shanghai-main",project_id:"project-remodex-lab",provider:"codex",archived:!1,title:"Remote attach",mode:"attached-live",health:"idle",branch:"phase1-ui",worktree:"mobile-lab",summary:"",latest_assistant_message:null,last_event_at:ba("2026-03-18T10:48:00+08:00"),pinned:!1,run_state:"completed",run_state_changed_at:ba("2026-03-18T10:48:00+08:00"),context_usage:null,subagent:null,capability:{can_stream_live:!0,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!0,can_show_terminal:!0}},{id:"session-history-3",agent_id:"agent-macbook",project_id:"project-notes",provider:"codex",archived:!1,title:"Research notes",mode:"history-only",health:"offline",branch:"research",worktree:"default",summary:"",latest_assistant_message:null,last_event_at:ba("2026-03-17T19:12:00+08:00"),pinned:!1,run_state:"idle",run_state_changed_at:null,context_usage:null,subagent:null,capability:{can_stream_live:!1,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!0,can_show_terminal:!1}}],timeline:[{id:"entry-1",kind:"system",title:"Session ready",body:"Managed session attached.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:40:00+08:00"),accent:"muted",attachments:[]},{id:"entry-2",kind:"user",title:"Prompt",body:"Start stage one.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:44:00+08:00"),accent:"primary",attachments:[]},{id:"entry-3",kind:"thinking",title:"Plan",body:"Aligning routes and session state.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:45:30+08:00"),accent:"secondary",attachments:[]},{id:"entry-4",kind:"tool",title:"Tool activity",body:"Scanned docs/, checked runtime versions, and created the initial workspace directories.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:48:00+08:00"),accent:"secondary",attachments:[]},{id:"entry-5",kind:"assistant",title:"Focus",body:"Wiring the shell.",body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:ba("2026-03-18T10:58:00+08:00"),accent:"primary",attachments:[]}],changed_files:[{path:"apps/web/src/components/dashboard.tsx",status:"added",additions:248,deletions:0},{path:"packages/protocol/src/index.ts",status:"modified",additions:94,deletions:12},{path:"apps/agent/src/index.ts",status:"modified",additions:77,deletions:3}],runtime_processes:[{id:"runtime-dev",name:"dev",command:"pnpm --filter @panda/web dev --host 0.0.0.0 --port 4173",port:4173,status:"running",log_excerpt:"Vite server ready on 0.0.0.0:4173 and previewed over the tailnet."},{id:"runtime-agent",name:"agent",command:"pnpm --filter @panda/agent dev",port:4242,status:"running",log_excerpt:"Fastify listening on http://0.0.0.0:4242 with WebSocket events enabled."}],previews:[{id:"preview-main",label:"PWA preview",url:"https://panda.tailnet.ts.net",status:"ready"},{id:"preview-storybook",label:"Design lab",url:"https://storybook.tailnet.ts.net",status:"starting"}],approvals:[{id:"approval-1",title:"Write workspace files",description:"Create monorepo config, React app shell, and Fastify agent entrypoints.",status:"approved"},{id:"approval-2",title:"Attach external Codex session",description:"External session controls remain experimental until app-server transport is available.",status:"pending"}]}),nk=()=>tk(),sk=()=>nk(),L6=e=>{const t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.pathname="/ws",t.toString()};class ak{constructor(t,a=L6(t)){this.baseUrl=t,this.wsBaseUrl=a}getConnectionKey(){return`${this.baseUrl}::${this.wsBaseUrl}`}async readJson(t,a){const l=await fetch(t);if(!l.ok)throw new Error(`Request failed with ${l.status}`);return a.parse(await l.json())}async postJson(t,a,l){const o=await fetch(new URL(t,this.baseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a)}),u=await o.json().catch(()=>null);if(!o.ok)throw new Error((u==null?void 0:u.error)??`Request failed with ${o.status}`);return l?l.parse(u):u}async getPhaseOneSnapshot(t){const{fallbackToMock:a=!0,fallbackSnapshot:l=sk}=t??{};try{const o=await fetch(new URL("/api/bootstrap",this.baseUrl));if(!o.ok)throw new Error(`Bootstrap request failed with ${o.status}`);const u=await o.json();return EN.parse(u)}catch(o){if(!a)throw o;return l()}}async getHubDirectory(){return this.readJson(new URL("/api/hub/directory",this.baseUrl),bN)}async getHubRecentSessions(){return this.readJson(new URL("/api/hub/recent-sessions",this.baseUrl),SN)}async getSessionLocation(t){return this.readJson(new URL(`/api/sessions/${t}/location`,this.baseUrl),jN)}async getWorkspaceDirectory(t){const a=new URL("/api/workspace",this.baseUrl);return t!=null&&t.selectedSessionId&&a.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(a,wN)}async getWorkspaceSessionPage(t){const a=new URL("/api/workspace/sessions",this.baseUrl);return a.searchParams.set("bucket",D6.parse(t.bucket)),t.projectId&&a.searchParams.set("projectId",t.projectId),t.cursor&&a.searchParams.set("cursor",t.cursor),typeof t.limit=="number"&&Number.isFinite(t.limit)&&a.searchParams.set("limit",String(Math.max(1,Math.floor(t.limit)))),t.selectedSessionId&&a.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(a,NN)}async getWorkspaceSessionDetail(t){const a=new URL("/api/workspace/session-detail",this.baseUrl);return a.searchParams.set("sessionId",t),this.readJson(a,vN)}async getSessionTimeline(t,a){const l=new URL(`/api/sessions/${t}/timeline`,this.baseUrl);return a!=null&&a.view&&l.searchParams.set("view",a.view),this.readJson(l,b6)}async getSessionChangeSets(t){return this.readJson(new URL(`/api/sessions/${t}/change-sets`,this.baseUrl),{parse:a=>Array.isArray(a)?a.map(l=>S6.parse(l)):[]})}async getSessionBootstrap(t){return this.readJson(new URL(`/api/sessions/${t}/bootstrap`,this.baseUrl),Fw)}async getSessionToolCallDetail(t,a){const l=new URL(`/api/sessions/${t}/tool-detail`,this.baseUrl);return l.searchParams.set("entryId",a),this.readJson(l,kN)}async getSessionChangeSetFileDiff(t,a){const l=new URL(`/api/sessions/${t}/change-set-file-diff`,this.baseUrl);return l.searchParams.set("changeSetId",a.changeSetId),l.searchParams.set("path",a.path),a.itemId&&l.searchParams.set("itemId",a.itemId),this.readJson(l,yw)}async getSessionGitWorkspace(t){return this.readJson(new URL(`/api/sessions/${t}/git-workspace`,this.baseUrl),h_)}async getSessionGitWorkspaceFileDiff(t,a){const l=new URL(`/api/sessions/${t}/git-workspace/file-diff`,this.baseUrl);return l.searchParams.set("path",a.path),a.previousPath&&l.searchParams.set("previousPath",a.previousPath),this.readJson(l,xw)}async getSessionGitHistory(t){return this.readJson(new URL(`/api/sessions/${t}/git/history`,this.baseUrl),Nw)}async getSessionFilePreviewTree(t,a){var u;const l=new URL(`/api/sessions/${t}/file-preview/tree`,this.baseUrl),o=(u=a==null?void 0:a.path)==null?void 0:u.trim();return o&&l.searchParams.set("path",o),this.readJson(l,Rw)}async getSessionFilePreviewContent(t,a){const l=new URL(`/api/sessions/${t}/file-preview/content`,this.baseUrl);return l.searchParams.set("path",a.path),this.readJson(l,Mw)}async getSessionGitHistoryFileDiff(t,a){const l=new URL(`/api/sessions/${t}/git/history/file-diff`,this.baseUrl);return l.searchParams.set("commitOid",a.commitOid),l.searchParams.set("path",a.path),a.previousPath&&l.searchParams.set("previousPath",a.previousPath),this.readJson(l,ww)}async getSessionRunWorkbench(t){return this.readJson(new URL(`/api/sessions/${t}/run-workbench`,this.baseUrl),C6)}async saveSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands`,{action:t.action,commandId:t.commandId??null,command:t.command??null},qw)}async generateSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands/generate`,{prompt:t.prompt,model:t.model},Qw)}async saveSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites`,{action:t.action,websiteId:t.websiteId??null,website:t.website??null},Ww)}async generateSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites/generate`,{prompt:t.prompt,model:t.model},Yw)}async executeSessionTerminalAction(t){return this.postJson(`/api/sessions/${t.sessionId}/terminals`,{action:t.action,commandId:t.commandId??null,terminalId:t.terminalId??null},Vw)}async getSessionTerminalOutput(t){const a=new URL(`/api/sessions/${t.sessionId}/terminals/${t.terminalId}/output`,this.baseUrl);return typeof t.cursor=="number"&&Number.isFinite(t.cursor)&&a.searchParams.set("cursor",String(Math.max(0,Math.floor(t.cursor)))),this.readJson(a,Hw)}async getSessionPlan(t){return this.readJson(new URL(`/api/sessions/${t}/plan`,this.baseUrl),{parse:a=>a==null?null:c_.parse(a)})}async getSessionInteractions(t){return this.readJson(new URL(`/api/sessions/${t}/interactions`,this.baseUrl),{parse:a=>Array.isArray(a)?a.map(l=>u_.parse(l)):[]})}async getSessionRecoverySnapshot(t){return this.readJson(new URL(`/api/sessions/${t}/recovery`,this.baseUrl),$w)}async getProjectSkills(t){return this.readJson(new URL(`/api/projects/${t}/skills`,this.baseUrl),{parse:a=>Array.isArray(a)?a.map(l=>nw.parse(l)):[]})}async getCodexCommands(){return this.readJson(new URL("/api/codex/commands",this.baseUrl),P4)}async refreshCodexCommands(){return this.postJson("/api/codex/commands/refresh",{},P4)}async listDirectories(t){const a=new URL("/api/directories",this.baseUrl);return t.agentId&&a.searchParams.set("agentId",t.agentId),t.path&&a.searchParams.set("path",t.path),this.readJson(a,{parse:l=>Array.isArray(l)?l.map(o=>M6.parse(o)):[]})}async createDirectory(t){return this.postJson("/api/directories",t,hN)}async createProject(t){return this.postJson("/api/projects",t)}async createSession(t){var a;return this.postJson("/api/sessions",{...t,attachments:(a=t.attachments)==null?void 0:a.map(l=>L4.parse(l)),serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async updateSession(t){return this.postJson(`/api/sessions/${t.sessionId}/actions`,{action:t.action,name:t.name})}async updateThread(t){return this.postJson(`/api/threads/${t.projectId}/actions`,{action:t.action,name:t.name,orderedProjectIds:t.orderedProjectIds})}async sendSessionInput(t){var a;return this.postJson(`/api/sessions/${t.sessionId}/input`,{input:t.input,attachments:(a=t.attachments)==null?void 0:a.map(l=>L4.parse(l)),model:t.model,reasoningEffort:t.reasoningEffort,serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async executeSessionCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/commands/execute`,{input:t.input},U4)}async respondToSessionCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/commands/respond`,{panelId:t.panelId,optionId:t.optionId??null,text:t.text??null},U4)}async respondToSessionInteraction(t){return this.postJson(`/api/sessions/${t.sessionId}/interactions/${t.requestId}/respond`,{optionId:t.optionId??null,text:t.text??null,answers:t.answers??null})}async interruptSession(t){return this.postJson(`/api/sessions/${t}/interrupt`,{})}async registerAgent(t){return this.postJson("/api/agents/register",t,z4)}async heartbeatAgent(t){return this.postJson("/api/agents/heartbeat",t,z4)}async updateAgent(t){return this.postJson(`/api/agents/${t.agentId}/actions`,{action:t.action,display_name:t.displayName??null},TN)}async getWebPushPublicConfig(){return this.readJson(new URL("/api/push/public-key",this.baseUrl),IN)}async upsertWebPushSubscription(t){return this.postJson("/api/push/subscriptions",{subscription:t.subscription,settings:y_.parse(t.settings),device:t.device??null},LN)}async removeWebPushSubscription(t){return this.postJson("/api/push/subscriptions/remove",DN.parse(t))}async sendWebPushTest(t){return this.postJson("/api/push/test",ON.parse(t),PN)}async executeSessionGitAction(t){return this.postJson(`/api/sessions/${t.sessionId}/git/actions`,{action:t.action,path:t.path,branch:t.branch,message:t.message},kw)}async executeSessionTurnAction(t){return this.postJson(`/api/sessions/${t.sessionId}/turns/${t.turnId}/actions`,{action:t.action},Ew)}async getDevManagerSnapshot(t){const a=new URL("/api/dev-manager",this.baseUrl);return t!=null&&t.includeServiceProbe&&a.searchParams.set("includeServiceProbe","1"),this.readJson(a,v0)}async saveDevManagerConfig(t){return this.postJson("/api/dev-manager/config",aN.parse(t),v0)}async executeDevManagerAction(t){return this.postJson("/api/dev-manager/actions",t,uN)}createEventStream(t,a){var xe;let m=null,y=((xe=a==null?void 0:a.sessionId)==null?void 0:xe.trim())??"",g="",S=!1,p=0,b=null,w=!1,N=!1,j=!1,T=0;const D=typeof document<"u"&&typeof document.visibilityState=="string",z=()=>D&&document.visibilityState==="hidden",I=(a==null?void 0:a.reconnectWhenHidden)===!0,k=C=>(C==null?void 0:C.readyState)===WebSocket.OPEN||(C==null?void 0:C.readyState)===WebSocket.CONNECTING,P=()=>{b!==null&&(globalThis.clearTimeout(b),b=null)},Q=(C,q)=>{var ie;(ie=a==null?void 0:a.onStatus)==null||ie.call(a,{state:C,attempt:p,maxAttempts:5,error:q})},se=C=>{const q=m;!q||q.readyState!==WebSocket.OPEN||(g&&g!==C&&(q.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g=""),!(!C||g===C)&&(g=C,q.send(JSON.stringify({type:"session.subscribe",sessionId:C}))))},W=C=>{if(S||w)return;if(!I&&z()){w=!1,j=!0,P(),Q("failed",C);return}if(p+=1,!I&&p>5){p=5,j=!0,Q("failed",C);return}w=!0,j=!1,Q("reconnecting",C),P();const q=I?Math.min(p,5):p,ie=Math.min(1e4,1200*2**Math.max(0,q-1));b=globalThis.setTimeout(()=>{w=!1,V()},ie)},V=()=>{if(S||k(m))return;P(),w=!1,j=!1;const C=new WebSocket(this.wsBaseUrl);m=C,C.addEventListener("open",()=>{S||m!==C||(w=!1,N=!1,p=0,Q("connected"),se(y))}),C.addEventListener("message",q=>{if(m!==C)return;const ie=UN.safeParse(JSON.parse(q.data));ie.success&&t(ie.data)}),C.addEventListener("error",()=>{if(S||m!==C)return;const q=`无法连接到 ${this.wsBaseUrl}`;C.readyState!==WebSocket.OPEN&&W(q)}),C.addEventListener("close",q=>{var he;if(m===C&&(m=null),S||m!==null)return;const ie=((he=q.reason)==null?void 0:he.trim())||`WebSocket 已断开(code ${q.code||"unknown"})`;W(ie)})},Y=C=>{if(S||k(m)||N)return;const q=Date.now();q-T<1500||(T=q,N=!0,p=0,w=!1,j=!1,P(),Q("reconnecting",C),V())},ee=()=>{document.visibilityState==="visible"&&(j||!k(m))&&Y("应用回到前台,正在恢复连接")},me=()=>{(j||!k(m))&&Y("页面恢复显示,正在恢复连接")},ge=()=>{(j||!k(m))&&Y("窗口重新聚焦,正在恢复连接")},te=()=>{(j||!k(m))&&Y("网络已恢复,正在重新连接")};return typeof window<"u"&&(window.addEventListener("pageshow",me),window.addEventListener("focus",ge),window.addEventListener("online",te)),typeof document<"u"&&document.addEventListener("visibilitychange",ee),V(),{setSessionId:C=>{y=(C==null?void 0:C.trim())??"",!S&&se(y)},close:()=>{S=!0,w=!1,N=!1,j=!1,P(),typeof window<"u"&&(window.removeEventListener("pageshow",me),window.removeEventListener("focus",ge),window.removeEventListener("online",te)),typeof document<"u"&&document.removeEventListener("visibilitychange",ee);const C=m;if((C==null?void 0:C.readyState)===WebSocket.OPEN&&g&&C.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g="",m=null,(C==null?void 0:C.readyState)===WebSocket.CONNECTING){const q=()=>{try{C.close()}catch{}};C.addEventListener("open",q,{once:!0});return}C==null||C.close()}}}connectEvents(t,a){const l=this.createEventStream(t,a);return()=>{l.close()}}}const P6=(e,t)=>new ak(e,(t==null?void 0:t.wsBaseUrl)??L6(e)),U6=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return null;try{const a=new URL(t);return a.port?`${a.hostname}:${a.port}`:a.hostname}catch{return t.replace(/\/+$/,"")||null}},dc=e=>{var t;return((t=e.display_name)==null?void 0:t.trim())||e.name.trim()||U6(e.direct_base_url)||"未命名节点"},ik=e=>{var a;const t=((a=e.display_name)==null?void 0:a.trim())??"";return!t||t===e.name?null:e.name},vg=e=>U6(e.direct_base_url)||e.host||e.tailscale_ip||e.tailscale_dns_name||e.direct_base_url,fp="panda:last-agent-id",hp="panda:last-session-id",Qf="panda:pending-session-id",Gf="panda:pending-project-id",Yf="panda:pending-directory-picker",Vu="panda:pending-session-handoff",Vf="panda:selected-agent-connection-hint",rk=3e4,lk=1800*1e3,Ef=e=>typeof e=="object"&&e!==null,ok=e=>{if(!Ef(e))return null;const{sessionId:t,agentId:a,projectId:l,createdAt:o,session:u,project:f,optimisticEntry:m}=e;return typeof t!="string"||typeof a!="string"||typeof l!="string"||typeof o!="string"||!Ef(u)||u.id!==t||u.agent_id!==a||u.project_id!==l||f!==null&&(!Ef(f)||f.id!==l||f.agent_id!==a||typeof f.name!="string"||typeof f.path!="string")||m!==null&&(!Ef(m)||typeof m.id!="string"||typeof m.kind!="string"||typeof m.body!="string"||typeof m.timestamp!="string")?null:{sessionId:t,agentId:a,projectId:l,createdAt:o,session:u,project:f??null,optimisticEntry:m??null}},ck=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>rk:!0},uk=e=>{if(!Ef(e))return null;const{agentId:t,name:a,displayName:l,directBaseUrl:o,wsBaseUrl:u,createdAt:f}=e;return typeof t!="string"||typeof a!="string"||l!==null&&typeof l!="string"||typeof o!="string"||typeof u!="string"||typeof f!="string"?null:{agentId:t,name:a,displayName:l,directBaseUrl:o,wsBaseUrl:u,createdAt:f}},dk=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>lk:!0},fk=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(Vu);return}window.sessionStorage.setItem(Vu,JSON.stringify(e))}catch{}},v_=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(Vu);if(!t)return null;const a=ok(JSON.parse(t));return!a||ck(a)?(window.sessionStorage.removeItem(Vu),null):e&&a.sessionId!==e?null:a}catch{return null}},hk=e=>{if(!(typeof window>"u"))try{const t=v_();if(e&&(t!=null&&t.sessionId)&&t.sessionId!==e)return;window.sessionStorage.removeItem(Vu)}catch{}},mk=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(Vf);return}window.sessionStorage.setItem(Vf,JSON.stringify(e))}catch{}},ch=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(Vf);if(!t)return null;const a=uk(JSON.parse(t));return!a||dk(a)?(window.sessionStorage.removeItem(Vf),null):e&&a.agentId!==e?null:a}catch{return null}},pc=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(fp)}catch{return null}},Ji=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(fp,e);return}window.localStorage.removeItem(fp)}catch{}},mp=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(hp)}catch{return null}},Js=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(hp,e);return}window.localStorage.removeItem(hp)}catch{}},Kr=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(Qf,e);return}window.sessionStorage.removeItem(Qf)}catch{}},pk=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(Qf);return e&&window.sessionStorage.removeItem(Qf),e}catch{return null}},ku=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(Gf,e);return}window.sessionStorage.removeItem(Gf)}catch{}},gk=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(Gf);return e&&window.sessionStorage.removeItem(Gf),e}catch{return null}},Cf=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(Yf,"1");return}window.sessionStorage.removeItem(Yf)}catch{}},_k=()=>{if(typeof window>"u")return!1;try{const e=window.sessionStorage.getItem(Yf);return e&&window.sessionStorage.removeItem(Yf),e==="1"}catch{return!1}},z6=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(fp),window.localStorage.removeItem(hp),window.sessionStorage.removeItem(Qf),window.sessionStorage.removeItem(Gf),window.sessionStorage.removeItem(Yf),window.sessionStorage.removeItem(Vu),window.sessionStorage.removeItem(Vf)}catch{}},pp=mc("Preferences",{web:()=>Zr(()=>import("./web-CwfmVur7.js"),[]).then(e=>new e.PreferencesWeb)}),yk=new Set(["4173","4174"]),vk="PandaMobile",B6="hub_url",H6="onboarding_completed",b0=new Set;let Xi={platform:qu(),hubUrl:"",onboardingCompleted:!1};const $6=()=>{for(const e of b0)e()},bk=e=>(b0.add(e),()=>{b0.delete(e)}),fc=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{return new URL(t).toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}},xk=()=>typeof window>"u"?null:window.location.origin||null,F6=e=>{if(typeof window>"u")return`http://localhost:${e}`;const t=window.location.protocol==="https:"?"https:":"http:",a=window.location.hostname||"localhost";return`${t}//${a}:${e}`},Sk=()=>fc(F6(4242)),jk=()=>{const e=fc(void 0);if(e)return e;const t=xk();if(!t)return"http://localhost:4343";const a=window.location.port.trim();return yk.has(a)?F6(4343):fc(t)},wk=()=>fc(void 0),Nk=()=>!1,kk=()=>{const e=qu();if(e==="web")return{platform:e,hubUrl:jk(),onboardingCompleted:!0};const t=wk();return{platform:e,hubUrl:t,onboardingCompleted:!!t}},$4=async e=>{if(qs()){const{value:t}=await pp.get({key:e});return t}if(typeof window>"u")return null;try{return window.localStorage.getItem(`panda:runtime:${e}`)}catch{return null}},F4=async(e,t)=>{if(qs()){if(t===null){await pp.remove({key:e});return}await pp.set({key:e,value:t});return}if(!(typeof window>"u"))try{if(t===null){window.localStorage.removeItem(`panda:runtime:${e}`);return}window.localStorage.setItem(`panda:runtime:${e}`,t)}catch{}},Ek=async()=>{const e=kk();qs()&&await pp.configure({group:vk});const[t,a]=await Promise.all([$4(B6),$4(H6)]),l=e.platform==="web"?e.hubUrl:fc(t)||e.hubUrl,o=e.platform==="web"?!0:a==="true"||!!(l&&e.onboardingCompleted);return Xi={platform:e.platform,hubUrl:l,onboardingCompleted:o},$6(),Xi},x0=()=>Xi,Ck=()=>fc(Xi.hubUrl),Tk=()=>{const e=x0();return e.platform==="web"?Nk():!e.hubUrl||!e.onboardingCompleted},q6=async e=>{const t=e.hubUrl===void 0?Xi.hubUrl:fc(e.hubUrl),a=e.onboardingCompleted??Xi.onboardingCompleted;return Xi={...Xi,hubUrl:t,onboardingCompleted:a},Xi.platform!=="web"&&await Promise.all([F4(B6,t||null),F4(H6,a?"true":"false")]),$6(),Xi},Mp=()=>_.useSyncExternalStore(bk,x0,x0),Rk=new Set(["localhost","127.0.0.1","::1"]),W6=()=>Sk(),id=()=>Ck(),q4=new Map,Mk={direct:"Agent 直连",hub:"Hub 聚合"},Ak=1e4,Dk=1e4,K6=1e4,Ok=1e4,W4=1200,K4=5e3;let zm=null,S0=0,xu=null,Eu=null,gp=0,Su=null,Bm=null,j0=0,ju=null;const w0=new Map,Hm=new Map,$m=new Map,Va=e=>(e==null?void 0:e.trim())??"",Q6=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase():""},G6=e=>Rk.has(Q6(e)),Zu=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{const a=new URL(t),l=Q6(a.hostname);return l&&(a.hostname=l),a.toString().replace(/\/+$/,"")}catch{return t}},Xu=()=>typeof window>"u"||qs()?!1:G6(window.location.hostname),Ik=e=>{const t=e.trim();if(!t)return W4;try{const a=new URL(t);return G6(a.hostname)?W4:K4}catch{return K4}},Ju=async e=>{const t=e.trim();if(!t)return!1;const a=$m.get(t),l=Date.now();if(a&&l-a.checkedAt<Ok)return a.reachable;const o=new AbortController,u=globalThis.setTimeout(()=>o.abort(),Ik(t));try{const m=(await fetch(`${t}/health`,{signal:o.signal})).ok;return $m.set(t,{reachable:m,checkedAt:Date.now()}),m}catch{return $m.set(t,{reachable:!1,checkedAt:Date.now()}),!1}finally{clearTimeout(u)}},rd=(e,t)=>{const a=`${e}::${(t==null?void 0:t.trim())??""}`,l=q4.get(a);if(l)return l;const o=P6(e,{wsBaseUrl:t});return q4.set(a,o),o},Q4=()=>rd(Y6()),G4=e=>{const t=e(Eu);Eu=t,gp=t?Date.now():0},b_=(e,t,a)=>({mode:"direct",label:e,baseUrl:t,client:rd(t,a)}),Y6=()=>{const e=id();if(!e)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");return e},Pf=e=>{const t=e==="hub"?Y6():W6();return{mode:e,label:Mk[e],baseUrl:t,client:rd(t)}},V6=e=>Zu(e.direct_base_url),Lk=e=>Zu(e.ws_base_url),Y4=e=>{const t=V6(e)||e.tailscale_dns_name||e.tailscale_ip||e.host;return`无法直连节点 ${dc(e)}(${t})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`},Pk=async()=>{if(!Xu())return null;const e=Date.now();if(Bm&&e-j0<K6)return Bm;if(ju)return ju;ju=(async()=>{const t=W6();if(!await Ju(t))return null;const a=await rd(t).getPhaseOneSnapshot({fallbackToMock:!1});return Bm=a,j0=Date.now(),a})().catch(()=>null);try{return await ju}finally{ju=null}},Z6=async e=>{var l,o;const t=await Pk(),a=((o=(l=t==null?void 0:t.agents[0])==null?void 0:l.id)==null?void 0:o.trim())??"";return!!(a&&a===e.trim())},X6=async e=>{if(await Z6(e.id))return{...Pf("direct"),label:`Agent 直连 · ${dc(e)}(本机)`};const t=V6(e),a=Lk(e);return b_(`Agent 直连 · ${dc(e)}`,t,a||void 0)},Uk=async e=>{if(await Z6(e.agent_id))return{...Pf("direct"),label:`Agent 直连 · ${e.agent_id}(本机)`};const t=Zu(e.direct_base_url),a=Zu(e.ws_base_url);return b_(`Agent 直连 · ${e.agent_id}`,t,a||void 0)},J6=e=>{var l;const t=Va(e.agentId);if(!t)return null;const a=ch(t);return a!=null&&a.directBaseUrl.trim()?b_(`Agent 直连 · ${((l=a.displayName)==null?void 0:l.trim())||a.name.trim()||t}`,Zu(a.directBaseUrl),Zu(a.wsBaseUrl)||void 0):null},V4=async e=>{const t=J6(e);if(t!=null&&t.baseUrl&&(await Ju(t.baseUrl)||!Xu()))return t;const a=await t3(),l=a?e3(a,e):null;if(!l)return null;const o=await X6(l);return o.baseUrl&&(await Ju(o.baseUrl)||!Xu())?o:null},e3=(e,t)=>{const a=Va(t.agentId);return a?e.agents.find(l=>l.id===a)??null:null},zk=e=>{const t=Va(e.sessionId),a=Va(e.projectId),l=Va(e.agentId);return l?`agent:${l}`:a?`project:${a}`:t?`session:${t}`:""},t3=async()=>{const e=Date.now();if(Eu&&e-gp<K6)return Eu;if(Su)return Su;Su=(async()=>{const t=id();if(!t)return null;const a=await rd(t).getHubDirectory();return Eu=a,gp=Date.now(),a})().catch(()=>null);try{return await Su}finally{Su=null}},Bk=async()=>{if(!Xu())return Pf("hub");const e=Date.now();if(zm&&e-S0<Ak)return zm;if(xu)return xu;xu=(async()=>{const t=id(),a=t&&await Ju(t)?Pf("hub"):Pf("direct");return zm=a,S0=Date.now(),a})();try{return await xu}finally{xu=null}},Hk=async e=>{const t=zk(e),a=Date.now(),l=t?w0.get(t):null;if(l&&a-l.cachedAt<Dk)return l.target;const o=t?Hm.get(t):null;if(o)return o;const u=(async()=>{const f=Va(e.sessionId),m=Va(e.agentId),y=J6(e),g=id();if(!g&&!y&&!m)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");const S=g?rd(g):null;if(m){const N=await V4(e);if(N)return N}if(f){const N=S?await S.getSessionLocation(f).catch(()=>null):null;if(!N){const T=m?await V4(e):null;if(T)return T;throw new Error("Hub 未返回目标会话位置,无法建立直连。")}const j=await Uk(N);if(!j.baseUrl)throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`);if(await Ju(j.baseUrl)||!Xu())return j;throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`)}if(Va(e.projectId)&&!Va(e.agentId))throw new Error("Project-scoped connection resolution now requires agentId.");const p=await t3(),b=p?e3(p,e):null;if(!b)throw new Error("Hub 未返回目标节点信息,无法建立直连。");const w=await X6(b);if(!w.baseUrl)throw new Error(Y4(b));if(await Ju(w.baseUrl)||!Xu())return w;throw new Error(Y4(b))})();t&&Hm.set(t,u);try{const f=await u;return t&&w0.set(t,{target:f,cachedAt:Date.now()}),f}finally{t&&Hm.delete(t)}},wn=async e=>!(Va(e==null?void 0:e.sessionId)||Va(e==null?void 0:e.projectId)||Va(e==null?void 0:e.agentId))?Bk():Hk(e??{}),$k=()=>{zm=null,S0=0,xu=null,Eu=null,gp=0,Su=null,Bm=null,j0=0,ju=null,w0.clear(),Hm.clear(),$m.clear()},n3="panda:notification-settings",s3="panda:notified-completions",x_="panda:web-push-subscription-state",Fk=280,a3="session-completions",bg={completionNotificationsEnabled:!1};let Zf=qs()?"default":"unsupported";const uh=()=>{const e=id();if(!e)throw new Error("尚未配置 Panda Hub 地址。");return P6(e)},i3=e=>({completionNotificationsEnabled:(e==null?void 0:e.completionNotificationsEnabled)===!0}),qk=(e,t)=>e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`,r3=()=>{if(typeof window>"u")return{};try{const e=window.localStorage.getItem(s3);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(a=>typeof a[0]=="string"&&typeof a[1]=="string"))}catch{return{}}},Wk=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(s3,JSON.stringify(e))}catch{}},Kk=e=>{if(!e||typeof e!="object")return null;const t=typeof e.endpoint=="string"?e.endpoint.trim():"",a=typeof e.updatedAt=="string"?e.updatedAt.trim():"";return!t||!a?null:{completionNotificationsEnabled:e.completionNotificationsEnabled===!0,endpoint:t,updatedAt:a}},l3=()=>{if(typeof window>"u")return null;try{return Kk(JSON.parse(window.localStorage.getItem(x_)??"null"))}catch{return null}},o3=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(x_,JSON.stringify(e))}catch{}},_p=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(x_)}catch{}},c3=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))throw new Error("当前环境没有可用的 Service Worker。");return navigator.serviceWorker.ready},Qk=e=>{const t="=".repeat((4-e.length%4)%4),a=(e+t).replace(/-/g,"+").replace(/_/g,"/"),l=window.atob(a),o=new Uint8Array(l.length);for(let u=0;u<l.length;u+=1)o[u]=l.charCodeAt(u);return o},S_=async()=>{const e=await c3();return"pushManager"in e?e.pushManager.getSubscription():null},u3=e=>{var u,f;const t=e.toJSON(),a=e.endpoint.trim(),l=typeof((u=t.keys)==null?void 0:u.p256dh)=="string"?t.keys.p256dh.trim():"",o=typeof((f=t.keys)==null?void 0:f.auth)=="string"?t.keys.auth.trim():"";if(!a||!l||!o)throw new Error("浏览器返回的推送订阅信息不完整。");return{endpoint:a,expirationTime:typeof e.expirationTime=="number"?e.expirationTime:null,keys:{p256dh:l,auth:o}}},d3=async()=>{try{return await uh().getWebPushPublicConfig()}catch(e){throw new Error(e instanceof Error?e.message:"无法读取 Hub Web Push 配置。")}},N0=()=>{if(typeof window>"u")return bg;try{const e=window.localStorage.getItem(n3);return e?i3(JSON.parse(e)):bg}catch{return bg}},Ho=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(n3,JSON.stringify(i3(e)))}catch{}},dh=()=>qs()?!0:typeof window>"u"?!1:window.isSecureContext&&"Notification"in window&&"serviceWorker"in navigator,ed=()=>qs()||!dh()?!1:"PushManager"in window,Cu=()=>qs()?Zf:dh()?Notification.permission:"unsupported",f3=e=>e==="granted"?"granted":e==="denied"?"denied":e==="prompt"?"default":"unsupported",h3=async()=>{Tp()&&await lh.createChannel({id:a3,name:"任务完成提醒",description:"Panda 对话和任务完成提醒",importance:4,visibility:1,vibration:!0,lights:!0}).catch(()=>{})},j_=async()=>{if(qs()){const e=await lh.checkPermissions();return Zf=f3(e.display),Zf}return dh()?Notification.permission:"unsupported"},k0=async()=>{if(qs()){await h3();const e=await lh.requestPermissions();return Zf=f3(e.display),Zf}return dh()?Notification.requestPermission():"unsupported"},E0=()=>{var e;return((e=l3())==null?void 0:e.completionNotificationsEnabled)===!0},Gk=async e=>{if(!e.completionNotificationsEnabled||Cu()!=="granted")return{synced:!1,reason:"notifications-disabled"};if(!ed())return{synced:!1,reason:"unsupported"};const t=await d3();if(!t.supported||!t.vapid_public_key)return _p(),{synced:!1,reason:"hub-unsupported"};const a=await S_();if(!a)return _p(),{synced:!1,reason:"missing-browser-subscription"};const l=await uh().upsertWebPushSubscription({subscription:u3(a),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:Nu()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return o3({completionNotificationsEnabled:l.settings.completion_notifications_enabled,endpoint:l.endpoint,updatedAt:l.updated_at}),{synced:!0,endpoint:l.endpoint}},Z4=async e=>{if(!ed())throw new Error("当前环境不支持 Web Push。");const t=await d3();if(!t.supported||!t.vapid_public_key)throw new Error(t.reason??"Hub 当前没有可用的 Web Push 配置。");const a=await c3(),o=await a.pushManager.getSubscription()??null??await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Qk(t.vapid_public_key)}),u=await uh().upsertWebPushSubscription({subscription:u3(o),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:Nu()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return o3({completionNotificationsEnabled:u.settings.completion_notifications_enabled,endpoint:u.endpoint,updatedAt:u.updated_at}),u},Yk=async()=>{if(!ed())return _p(),{removed:!1};const e=await S_();if(e){try{await uh().removeWebPushSubscription({endpoint:e.endpoint})}catch{}try{await e.unsubscribe()}catch{}}return _p(),{removed:!!e}},Vk=async()=>{var l,o;if(!ed())throw new Error("当前环境不支持 Web Push。");if(Cu()!=="granted")throw new Error("请先授予系统通知权限。");const e=await S_(),t=l3(),a=((l=e==null?void 0:e.endpoint)==null?void 0:l.trim())||((o=t==null?void 0:t.endpoint)==null?void 0:o.trim())||"";if(!a)throw new Error("当前设备还没有可用的 Web Push 订阅。");return await uh().sendWebPushTest({endpoint:a}),{ok:!0,endpoint:a}},Nu=()=>{if(typeof window>"u")return!1;const e=navigator;return window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0},X4=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent),Zk=e=>{if(typeof e!="string")return"";const t=e.replace(/\r\n/g,`
|
|
67
|
+
`).replace(/\s+/g," ").trim();return t?qk(t,Fk):""},Xk=(e,t)=>r3()[e]===t,xg=(e,t)=>{const a=r3();a[e]!==t&&Wk({...a,[e]:t})},m3=async e=>{if(!dh())return!1;if(qs()){if(await j_()!=="granted")return!1;await h3();try{return await lh.schedule({notifications:[{id:Math.abs(Array.from(`${e.sessionId}:${e.completedAt}`).reduce((a,l)=>a*31+l.charCodeAt(0)|0,17)),title:e.title,body:e.body,channelId:a3,schedule:{at:new Date(Date.now()+250),allowWhileIdle:!0},extra:{url:e.url,sessionId:e.sessionId,completedAt:e.completedAt}}]}),!0}catch{return!1}}if(typeof window>"u")return!1;const t={body:e.body,tag:`session-completed:${e.sessionId}:${e.completedAt}`,icon:"/pwa-512.png",badge:"/pwa-192.png",data:{sessionId:e.sessionId,url:e.url,completedAt:e.completedAt}};try{return await(await navigator.serviceWorker.ready).showNotification(e.title,t),!0}catch{try{const a=new Notification(e.title,t);return a.onclick=()=>{window.focus(),window.location.assign(e.url)},!0}catch{return!1}}},Jk=async e=>{if(!qs())return()=>{};const t=await lh.addListener("localNotificationActionPerformed",a=>{var o;const l=typeof((o=a.notification.extra)==null?void 0:o.url)=="string"?a.notification.extra.url.trim():"";l&&e(l)});return()=>{t.remove()}},p3=1,eE=10080*60*1e3,g3="panda-web-cache",td="app-state",_3="react-query",J4="panda:storage-persist-result",tE=new Set(["directory","bootstrap","timeline","timeline-optimistic","change-sets","plan","interactions","codex-commands","project-skills","settings-connection"]),w_=()=>typeof window<"u"&&typeof window.indexedDB<"u",nE=e=>typeof e[0]=="string"&&tE.has(e[0]),y3=async()=>w_()?await new Promise((e,t)=>{const a=window.indexedDB.open(g3,1);a.onupgradeneeded=()=>{const l=a.result;l.objectStoreNames.contains(td)||l.createObjectStore(td)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error??new Error("Unable to open Panda cache database."))}):null,sE=async()=>{const e=await y3();if(!e)return null;try{return await new Promise((t,a)=>{const u=e.transaction(td,"readonly").objectStore(td).get(_3);u.onsuccess=()=>t(u.result??null),u.onerror=()=>a(u.error??new Error("Unable to read Panda cache record."))})}finally{e.close()}},aE=async e=>{const t=await y3();if(t)try{await new Promise((a,l)=>{const o=t.transaction(td,"readwrite");o.objectStore(td).put(e,_3),o.oncomplete=()=>a(),o.onerror=()=>l(o.error??new Error("Unable to write Panda cache record.")),o.onabort=()=>l(o.error??new Error("Writing Panda cache record was aborted."))})}finally{t.close()}},yp=async()=>{w_()&&await new Promise(e=>{const t=window.indexedDB.deleteDatabase(g3);t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})},iE=async e=>{if(w_())try{const t=await sE();if(!t)return;const a=Date.now()-t.persistedAt>eE;if(t.version!==p3||a){await yp();return}C9(e,t.clientState)}catch{await yp().catch(()=>{})}},rE=async()=>{if(!(typeof navigator>"u"||typeof window>"u"||!("storage"in navigator)||typeof navigator.storage.persist!="function"))try{if(window.localStorage.getItem(J4))return;const t=await navigator.storage.persist();window.localStorage.setItem(J4,t?"granted":"denied")}catch{}},lE=e=>{if(typeof window>"u")return()=>{};rE();let t=null,a=null,l=!1,o=!1;const u=async()=>{if(!o){if(a){l=!0;return}a=(async()=>{const S=E9(e,{shouldDehydrateQuery:p=>nE(p.queryKey)});await aE({version:p3,persistedAt:Date.now(),clientState:S})})();try{await a}catch{}finally{a=null,l&&(l=!1,u())}}},f=(S=!1)=>{if(!o){if(t!==null&&(window.clearTimeout(t),t=null),S){u();return}t=window.setTimeout(()=>{t=null,u()},1200)}},m=e.getQueryCache().subscribe(()=>{f(!1)}),y=()=>{document.visibilityState==="hidden"&&f(!0)},g=()=>{f(!0)};return document.addEventListener("visibilitychange",y),window.addEventListener("pagehide",g),()=>{o=!0,m(),document.removeEventListener("visibilitychange",y),window.removeEventListener("pagehide",g),t!==null&&(window.clearTimeout(t),t=null)}},v3=async e=>{$k(),z6(),await yp().catch(()=>{}),e.removeQueries({predicate:t=>typeof t.queryKey[0]=="string"&&t.queryKey[0]!=="pwa-install-diagnostics"})},oE=()=>{const e=ki(),t=La(),a=Mp();return i.jsx("main",{className:"runtime-onboarding",children:i.jsxs("div",{className:"runtime-onboarding__shell",children:[i.jsxs("section",{className:"runtime-onboarding__hero",children:[i.jsx("span",{className:"runtime-onboarding__eyebrow",children:"首次连接"}),i.jsx("h1",{className:"runtime-onboarding__title",children:"输入 Panda 访问地址"}),i.jsx("p",{className:"runtime-onboarding__summary",children:"填一次,之后打开就能直接进入。也支持扫码。"})]}),i.jsx("section",{className:"settings-panel runtime-onboarding__panel",children:i.jsx(d6,{title:"Hub 地址",description:"填写电脑上显示的访问地址。",initialHubUrl:a.hubUrl,hint:"手机能直接打开这个地址就可以。",saveLabel:"保存并进入",savingLabel:"连接中",saveDescription:"保存后立即进入,之后也能在设置里修改。",saveSuccessMessage:"地址已保存,正在进入 Panda。",onSaveSuccess:async l=>{await q6({hubUrl:l.url,onboardingCompleted:!0}),qs()&&await k0().catch(()=>"unsupported")==="granted"&&Ho({completionNotificationsEnabled:!0}),await v3(t),await e({to:"/nodes",replace:!0})}})})]})})},Gi=["directory","hub"],cE=["directory","hub","recent-sessions"],os=["directory","workspace"],uE=["bootstrap","hub"],dE=os,eb=e=>{if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},fE=(e,t)=>{if(e.length!==t.length)return!1;for(let a=0;a<e.length;a+=1)if(!N_(e[a],t[a]))return!1;return!0},N_=(e,t)=>{if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return fE(e,t);if(eb(e)&&eb(t)){const a=Object.keys(e),l=Object.keys(t);if(a.length!==l.length)return!1;for(const o of a)if(!(o in t)||!N_(e[o],t[o]))return!1;return!0}return!1},Uf=(e,t)=>e!==void 0&&N_(e,t)?e:t,Fm=(e,t,a)=>{if(!e||e.length===0)return t;const l=new Map(e.map(u=>[a(u),u])),o=t.map(u=>Uf(l.get(a(u)),u));return e.length===o.length&&e.every((u,f)=>u===o[f])?e:o},tb=(e,t,a,l=new Date().toISOString())=>{if(!e)return e;let o=!1;const u=e.agents.map(f=>{if(f.id!==t||!Object.entries(a).some(([g,S])=>f[g]!==S))return f;const y={...f,...a};return o=!0,y});return o?{...e,generated_at:l,agents:u}:e},b3=(e,t)=>{if(!e)return t;const a=Fm(e.agents,t.agents,o=>o.id),l=Uf(e.generated_at,t.generated_at);return e.agents===a&&e.generated_at===l?e:{...t,generated_at:l,agents:a}},hE=180,mE=()=>{const e=La(),{hubUrl:t}=Mp(),a=_.useRef(null),l=pc(),o=ch(l),u=!!(l&&o);return _.useEffect(()=>{if(!t||u)return;let f=!1,m,y=!1,g=!1,S=!1;const p=()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},b=(T,D)=>{const z=new Date().toISOString();e.setQueryData(Gi,I=>tb(I,T,{status:D},z)??I),G4(I=>tb(I,T,{status:D},z)??I)},w=async()=>{try{const T=await Q4().getHubDirectory();if(f)return;G4(()=>T),e.setQueryData(Gi,D=>b3(D,T))}catch{}},N=()=>{p(),a.current=window.setTimeout(()=>{a.current=null,w()},hE)},j=T=>{var D,z;if(T.type==="agent.online"){if(S){S=!1;return}const I=typeof((D=T.payload)==null?void 0:D.agentId)=="string"?T.payload.agentId.trim():"";if(!I)return;b(I,"online"),N();return}if(T.type==="agent.offline"){const I=typeof((z=T.payload)==null?void 0:z.agentId)=="string"?T.payload.agentId.trim():"";if(!I)return;b(I,"offline"),N();return}T.type==="snapshot.changed"&&N()};w();try{m=Q4().connectEvents(j,{reconnectWhenHidden:!0,onStatus:T=>{if(T.state==="connected"){S=!0,y&&g&&(g=!1,N()),y=!0;return}y&&(g=!0)}})}catch{}return()=>{f=!0,p(),m==null||m()}},[t,e,u]),null},fh=e=>[...e].sort((t,a)=>{const l=Number(a.pinned)-Number(t.pinned);return l!==0?l:+new Date(a.last_event_at)-+new Date(t.last_event_at)}),co=e=>{if(!e)return e;const t=new Map(e.project_stats.map(a=>[a.project_id,a]));return{...e,project_stats:e.projects.map(a=>{const l=e.sessions.filter(u=>u.project_id===a.id),o=t.get(a.id);return{project_id:a.id,visible_session_count:l.filter(u=>!u.archived).length,archived_session_count:(o==null?void 0:o.archived_session_count)??0,hidden_history_count:(o==null?void 0:o.hidden_history_count)??0}})}},pE=e=>({id:e.id,agent_id:e.agent_id,project_id:e.project_id,archived:e.archived,title:e.title,last_event_at:e.last_event_at,pinned:e.pinned,run_state:e.run_state,run_state_changed_at:e.run_state_changed_at,subagent:e.subagent}),gE=e=>({id:e.id,agent_id:e.agent_id,name:e.name,display_name:e.display_name,pinned:e.pinned,path:e.path}),C0=e=>{if(!e)return null;const t={};return typeof e.title=="string"&&(t.title=e.title),typeof e.archived=="boolean"&&(t.archived=e.archived),typeof e.pinned=="boolean"&&(t.pinned=e.pinned),typeof e.last_event_at=="string"&&(t.last_event_at=e.last_event_at),(e.run_state==="idle"||e.run_state==="running"||e.run_state==="completed")&&(t.run_state=e.run_state),(e.run_state_changed_at===null||typeof e.run_state_changed_at=="string")&&(t.run_state_changed_at=e.run_state_changed_at),(e.subagent===null||typeof e.subagent=="object"&&e.subagent!==null)&&(t.subagent=e.subagent),Object.keys(t).length>0?t:null},vp=(e,t)=>!!(e!=null&&e.sessions.some(a=>a.id===t)),bp=(e,t,a)=>!e||!vp(e,t)?e:co({...e,sessions:fh(e.sessions.map(l=>l.id===t?{...l,...a}:l))}),T0=(e,t,a)=>{if(!e)return e;const l=e.sessions.find(f=>f.id===t);if(!l)return e;const o=new Date(a).getTime(),u=new Date(l.last_event_at).getTime();return!Number.isFinite(o)||Number.isFinite(u)&&o<=u?e:bp(e,t,{last_event_at:a})},Tf=(e,t,a)=>{if(!e)return e;const{last_event_at:l,...o}=a;let u=bp(e,t,o);return typeof l=="string"&&l.trim()&&(u=T0(u,t,l)),u},x3=(e,t,a)=>{if(!e||t.length===0)return e;const l=new Set(t);return co({...e,sessions:fh(e.sessions.map(o=>l.has(o.id)?{...o,...a}:o))})},S3=(e,t)=>{var u;if(!e||t.length===0)return e;const a=new Set(t),l=e.sessions.filter(f=>!a.has(f.id)),o=a.has(e.active_session_id)?((u=l[0])==null?void 0:u.id)??"":e.active_session_id;return co({...e,active_session_id:o,sessions:fh(l)})},Tu=(e,t,a)=>!e||!e.projects.some(l=>l.id===t)?e:co({...e,projects:e.projects.map(l=>l.id===t?{...l,...a}:l)}),xp=(e,t)=>{if(!e||t.length===0||e.projects.length<=1)return e;const a=new Map(e.projects.map(u=>[u.id,u])),l=new Set,o=[];for(const u of t){const f=a.get(u);!f||l.has(u)||(l.add(u),o.push(f))}for(const u of e.projects)l.has(u.id)||o.push(u);return o.every((u,f)=>{var m;return u.id===((m=e.projects[f])==null?void 0:m.id)})?e:co({...e,projects:o})},Sp=(e,t)=>{var o;if(!e)return e;const a=e.sessions.filter(u=>u.project_id!==t),l=a.some(u=>u.id===e.active_session_id)?e.active_session_id:((o=a[0])==null?void 0:o.id)??"";return co({...e,active_session_id:l,projects:e.projects.filter(u=>u.id!==t),sessions:fh(a)})},j3=(e,t)=>{if(!e)return e;const a=pE(t),l=[a,...e.sessions.filter(o=>o.id!==a.id)];return co({...e,generated_at:new Date().toISOString(),active_session_id:a.id,sessions:fh(l)})},_E=(e,t)=>{if(!e)return e;const a=gE(t),l=[a,...e.projects.filter(o=>o.id!==a.id)];return co({...e,generated_at:new Date().toISOString(),projects:l})},yE=(e,t)=>{if(!e)return t;const a=t.agent?Uf(e.agent??void 0,t.agent):e.agent===null?e.agent:null,l=Fm(e.projects,t.projects,y=>y.id),o=Fm(e.project_stats,t.project_stats,y=>y.project_id),u=Fm(e.sessions,t.sessions,y=>y.id),f=Uf(e.generated_at,t.generated_at),m=Uf(e.active_session_id,t.active_session_id);return e.agent===a&&e.projects===l&&e.project_stats===o&&e.sessions===u&&e.generated_at===f&&e.active_session_id===m?e:{...t,generated_at:f,agent:a,projects:l,project_stats:o,sessions:u,active_session_id:m}},vE=async()=>{const e=await wn();if(e.mode==="direct"){const t=await e.client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:t.generated_at,agents:t.agents}}return e.client.getHubDirectory()},bE=async()=>{const e=await wn();if(e.mode==="direct"){const t=await e.client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:t.generated_at,recent_sessions:[...t.sessions].sort((a,l)=>+new Date(l.last_event_at)-+new Date(a.last_event_at)).slice(0,24).map(a=>({id:a.id,title:a.title,run_state:a.run_state,run_state_changed_at:a.run_state_changed_at,latest_assistant_message:a.latest_assistant_message}))}}return e.client.getHubRecentSessions()},xE=async e=>(await wn(e==null?void 0:e.scope)).client.getWorkspaceDirectory({selectedSessionId:(e==null?void 0:e.selectedSessionId)??null}),SE=(e,t)=>b3(e,t),jE=(e,t)=>yE(e,t),R0=e=>{var t,a,l;return[...os,((t=e==null?void 0:e.scope)==null?void 0:t.agentId)??"",(a=e==null?void 0:e.scope)!=null&&a.agentId?"":((l=e==null?void 0:e.scope)==null?void 0:l.sessionId)??""]},w3=e=>({queryKey:Gi,enabled:(e==null?void 0:e.enabled)??!0,queryFn:vE,structuralSharing:SE,staleTime:3e4,refetchInterval:3e5,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),wE=()=>({queryKey:cE,queryFn:bE,staleTime:3e4,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),N3=e=>({queryKey:R0(e),enabled:(e==null?void 0:e.enabled)??!0,queryFn:()=>xE(e),placeholderData:g9,structuralSharing:jE,staleTime:1e4,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),k3=async e=>e.fetchQuery(w3()),NE=async e=>e.fetchQuery(wE()),Rf=async(e,t)=>e.fetchQuery(N3(t)),kE=1200,EE=e=>typeof document>"u"?!1:document.visibilityState==="visible"&&mp()===e,E3=e=>{var t;return((t=e==null?void 0:e.title)==null?void 0:t.trim())||"当前会话"},CE=e=>e.run_state!=="completed"?null:(typeof e.run_state_changed_at=="string"?e.run_state_changed_at.trim():"")||null,TE=(e,t)=>{if(!e||(typeof e.completionReason=="string"?e.completionReason:"completed")!=="completed")return null;const l=typeof e.sessionId=="string"?e.sessionId.trim():"",o=typeof e.completedAt=="string"?e.completedAt.trim():"";if(!l||!o)return null;const u=(t==null?void 0:t.recent_sessions.find(y=>y.id===l))??null,f=typeof e.sessionTitle=="string"&&e.sessionTitle.trim()||E3(u),m=(typeof e.finalReply=="string"?e.finalReply:"")||(u==null?void 0:u.latest_assistant_message)||"";return{sessionId:l,completedAt:o,sessionTitle:f,finalReply:m}},RE=(e,t)=>{const a=new Map(((e==null?void 0:e.recent_sessions)??[]).map(l=>[l.id,l]));return t.recent_sessions.flatMap(l=>{var m;const o=CE(l);if(!o)return[];const u=((m=l.latest_assistant_message)==null?void 0:m.trim())??"";if(!u)return[];const f=a.get(l.id);return(f==null?void 0:f.run_state)==="completed"&&f.run_state_changed_at===o?[]:[{sessionId:l.id,completedAt:o,sessionTitle:E3(l),finalReply:u}]})},ME=(e,t,a)=>{if(!e||!a)return e;let l=!1;const o=e.recent_sessions.map(u=>{if(u.id!==t)return u;const f=a.run_state==="idle"||a.run_state==="running"||a.run_state==="completed"?a.run_state:null,m={...u,...typeof a.title=="string"?{title:a.title}:null,...f?{run_state:f}:null,...a.run_state_changed_at===null||typeof a.run_state_changed_at=="string"?{run_state_changed_at:a.run_state_changed_at}:null,...a.latest_assistant_message===null||typeof a.latest_assistant_message=="string"?{latest_assistant_message:a.latest_assistant_message}:null};return l=l||m.title!==u.title||m.run_state!==u.run_state||m.run_state_changed_at!==u.run_state_changed_at||m.latest_assistant_message!==u.latest_assistant_message,m});return l?{...e,recent_sessions:o}:e},AE=({})=>{const e=La(),t=_.useRef(void 0),a=_.useRef(new Set),l=_.useRef(null),o=_.useRef(!1),u=pc(),f=ch(u),m=u&&f?u:null;return _.useEffect(()=>{const y=async I=>{const k=N0();if(!qs()&&!k.completionNotificationsEnabled||Cu()!=="granted")return;if(E0()){xg(I.sessionId,I.completedAt);return}const P=`${I.sessionId}:${I.completedAt}`;if(!a.current.has(P)&&!Xk(I.sessionId,I.completedAt)){if(EE(I.sessionId)){xg(I.sessionId,I.completedAt);return}a.current.add(P);try{await m3({sessionId:I.sessionId,completedAt:I.completedAt,title:I.sessionTitle,body:Zk(I.finalReply),url:`/session/${I.sessionId}`})&&xg(I.sessionId,I.completedAt)}finally{a.current.delete(P)}}},g=async I=>{for(const k of I)await y(k)};let S=!1,p,b=!1,w=!1,N=!1;const j=async()=>{if(!m)return NE(e);const k=await(await wn({agentId:m})).client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:k.generated_at,recent_sessions:[...k.sessions].sort((P,Q)=>+new Date(Q.last_event_at)-+new Date(P.last_event_at)).slice(0,24).map(P=>({id:P.id,title:P.title,run_state:P.run_state,run_state_changed_at:P.run_state_changed_at,latest_assistant_message:P.latest_assistant_message}))}};j().then(I=>{S||(t.current=I)}).catch(()=>{});const T=async()=>{if(!o.current){o.current=!0;try{const I=await j();if(S)return;const k=t.current;if(t.current=I,!k)return;await g(RE(k,I))}catch{}finally{o.current=!1}}},D=()=>{l.current!==null&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,T()},kE)},z=I=>{var k,P;if(I.type==="turn.completed"){const Q=TE(I.payload,t.current);Q&&y(Q);return}if(I.type==="session.updated"){const Q=typeof((k=I.payload)==null?void 0:k.sessionId)=="string"?I.payload.sessionId.trim():"",se=(P=I.payload)!=null&&P.sessionPatch&&typeof I.payload.sessionPatch=="object"?I.payload.sessionPatch:null;Q&&se&&(t.current=ME(t.current,Q,se));return}I.type==="agent.online"&&N&&(N=!1)};return wn(m?{agentId:m}:void 0).then(I=>{S||(p=I.client.connectEvents(z,{reconnectWhenHidden:!0,onStatus:k=>{if(k.state==="connected"){N=!0,b&&w&&(w=!1,D()),b=!0;return}b&&(w=!0)}}))}),()=>{S=!0,l.current!==null&&(clearTimeout(l.current),l.current=null),p==null||p()}},[e,m]),null},k_=e=>e.replace(/[\\/]+$/,""),jp=e=>k_(e).replace(/\\/g,"/").toLowerCase(),DE=e=>{const t=k_(e.trim());if(!t)return"新线程";const a=t.split(/[\\/]+/).filter(Boolean),l=a[a.length-1];return l?l.endsWith(":")?t:l:t},C3=e=>{if(!e)return null;const t=e.trim();if(!t||t==="/"||/^[A-Za-z]:[\\/]?$/.test(t))return null;const a=k_(t),l=Math.max(a.lastIndexOf("/"),a.lastIndexOf("\\"));if(l<0)return null;const o=a.slice(0,l);return o?/^[A-Za-z]:$/.test(o)?`${o}\\`:o:a.startsWith("/")?"/":null},T3=async e=>(await wn({agentId:e.agentId})).client.listDirectories(e),OE=async e=>(await wn({agentId:e.agentId})).client.createDirectory(e),IE=async e=>{const t=e.bootstrapQueryKey??["bootstrap"],a=e.projects.find(u=>u.agent_id===e.agentId&&jp(u.path)===jp(e.path));if(a)return a;const o=await(await wn({agentId:e.agentId})).client.createProject({agentId:e.agentId,name:DE(e.path),path:e.path});return e.queryClient.invalidateQueries({queryKey:t}),o.project},nb=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H10l2 2h6.5A2.5 2.5 0 0 1 21 9.5v8A2.5 2.5 0 0 1 18.5 20h-13A2.5 2.5 0 0 1 3 17.5z"})}),LE=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m9 6 6 6-6 6"})}),PE=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m5 12 4.5 4.5L19 7"})}),sb=e=>!!(e&&/^[A-Za-z]:[\\/]?$/.test(e.trim())),UE=({agentId:e,initialPath:t=null,title:a="选择开发版代码目录",subtitle:l="按需展开目录,只在你进入某一层时加载它的子目录。",confirmLabel:o="使用这个目录",onClose:u,onSelect:f})=>{const[m,y]=_.useState(t),[g,S]=_.useState(t),[p,b]=_.useState([]),[w,N]=_.useState(!0),[j,T]=_.useState(null);_.useEffect(()=>{y(t),S(t)},[t]),_.useEffect(()=>{let P=!1;return N(!0),T(null),T3({agentId:e,path:m}).then(Q=>{P||b(Q)}).catch(Q=>{P||(T(Q instanceof Error?Q.message:"目录列表加载失败。"),b([]))}).finally(()=>{P||N(!1)}),()=>{P=!0}},[e,m]);const D=C3(m),z=D!==null||sb(m),I=()=>{if(D!==null){y(D),S(D);return}sb(m)&&(y(null),S(null))},k=P=>{y(P),S(P)};return i.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true","aria-label":a,children:[i.jsx("button",{type:"button",className:"sheet-wrap__scrim","aria-label":"关闭目录选择",onClick:u}),i.jsx("div",{className:"sheet-wrap__center",children:i.jsx("section",{className:"directory-picker settings-directory-picker",children:i.jsxs("div",{className:"directory-picker__panel",children:[i.jsx("header",{className:"directory-picker__header",children:i.jsxs("div",{className:"directory-picker__heading",children:[i.jsx("h2",{children:a}),l?i.jsx("p",{children:l}):null]})}),i.jsxs("div",{className:"directory-picker__field",children:[i.jsx("span",{className:"directory-picker__field-label",children:"当前路径"}),i.jsxs("button",{type:"button",className:`directory-picker__path ${g===m?"is-selected":""}`,onClick:()=>{m&&S(m)},disabled:!m,"aria-pressed":g===m,children:[i.jsx("span",{className:"directory-picker__path-icon",children:i.jsx(nb,{})}),i.jsx("span",{className:"directory-picker__path-value",children:m??"根目录"})]})]}),i.jsxs("div",{className:"directory-picker__field",children:[i.jsx("span",{className:"directory-picker__field-label",children:"目录"}),i.jsx("div",{className:"directory-picker__list",role:"listbox","aria-label":"目录列表",children:w?i.jsx("div",{className:"directory-picker__state",children:"正在读取目录…"}):j?i.jsx("div",{className:"directory-picker__state is-error",children:j}):p.length===0?i.jsx("div",{className:"directory-picker__state",children:"当前目录下没有可用子目录"}):p.map(P=>{const Q=g===P.path;return i.jsxs("div",{className:`directory-picker__row ${Q?"is-selected":""}`,children:[i.jsxs("button",{type:"button",className:"directory-picker__row-main",onClick:()=>{S(P.path)},onDoubleClick:()=>{P.has_children&&k(P.path)},"aria-selected":Q,children:[i.jsx("span",{className:"directory-picker__row-icon",children:i.jsx(nb,{})}),i.jsx("span",{className:"directory-picker__row-name",children:P.name}),Q?i.jsx("span",{className:"directory-picker__row-check",children:i.jsx(PE,{})}):null]}),P.has_children?i.jsx("button",{type:"button",className:"directory-picker__row-enter-button","aria-label":`进入 ${P.name}`,onClick:()=>k(P.path),children:i.jsx("span",{className:"directory-picker__row-enter","aria-hidden":"true",children:i.jsx(LE,{})})}):null]},P.path)})})]}),i.jsx("footer",{className:"directory-picker__footer",children:i.jsxs("div",{className:"directory-picker__footer-actions",children:[z?i.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:I,children:i.jsx("span",{children:"返回上级"})}):null,i.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:u,children:i.jsx("span",{children:"取消"})}),i.jsx("button",{type:"button",className:"directory-picker__primary",disabled:!g,onClick:()=>{g&&f(g)},children:o})]})})]})})})]})},R3="panda-dev-manager-last-apk-download",zE=9e4,Sm=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},BE=e=>typeof e!="number"||!Number.isFinite(e)||e<=0?"未知":e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/1024/1024*10)/10} MB`,HE=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(R3);if(!e)return null;const t=JSON.parse(e);return typeof t.artifactId!="string"||typeof t.triggeredAt!="number"||!Number.isFinite(t.triggeredAt)?null:{artifactId:t.artifactId,triggeredAt:t.triggeredAt}}catch{return null}},$E=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(R3,JSON.stringify({artifactId:e,triggeredAt:Date.now()}))}catch{}},Uo=e=>e==="succeeded"?"通过":e==="failed"?"异常":"进行中",fu=e=>e==="succeeded"?"is-success":e==="failed"?"is-danger":"is-muted",ab=e=>e==null?"未测试":e?"通过":"异常",ib=e=>e==null?"is-muted":e?"is-success":"is-danger",FE=e=>e?e==="running"?"运行中":e==="stopped"?"已停止":e==="missing"?"未注册":"未知":"未注册",Ll=e=>e?`http://127.0.0.1:${e}`:"",jm=e=>e?`ws://127.0.0.1:${e}/ws`:"",rb=e=>({...e}),Sg=(e,t)=>{if(!e||e.config.updated_at!==t.config.updated_at)return t;const a=new Map(e.services.map(l=>[l.key,l]));return{...t,services:t.services.map(l=>{if(l.probe)return l;const o=a.get(l.key);return o!=null&&o.probe?{...l,probe:o.probe}:l})}},qE=({isActive:e,agentId:t})=>{var ke;const a=La(),[l,o]=_.useState(null),[u,f]=_.useState(null),[m,y]=_.useState(""),[g,S]=_.useState(!1),[p,b]=_.useState(null),[w,N]=_.useState(!1),j=t?{agentId:t}:void 0,T=["settings-dev-manager",t??"no-agent"],D=ls({queryKey:T,queryFn:async()=>{const U=await wn(j),ve=a.getQueryData(T),Z=await U.client.getDevManagerSnapshot({includeServiceProbe:!1});return{baseUrl:U.baseUrl,snapshot:Sg(ve==null?void 0:ve.snapshot,Z)}},enabled:e&&!!t,refetchOnWindowFocus:!1,staleTime:0,refetchInterval:U=>{const ve=U.state.data;return ve!=null&&ve.snapshot.jobs.some(Z=>Z.status==="running")?2e3:!1}});_.useEffect(()=>{var ve;const U=(ve=D.data)==null?void 0:ve.snapshot.config;U&&(l&&u===U.updated_at||(o(rb(U)),f(U.updated_at),y(""),S(!1)))},[D.data,l,u]);const z=Vn({mutationFn:async()=>{if(!j)throw new Error("当前没有可用的开发节点,暂时无法保存开发版配置。");if(!l)throw new Error("开发版配置还没有加载完成。");return(await wn(j)).client.saveDevManagerConfig({...l,npm_token:m||null,clear_npm_token:g})},onSuccess:U=>{a.setQueryData(T,ve=>({baseUrl:(ve==null?void 0:ve.baseUrl)??"",snapshot:Sg(ve==null?void 0:ve.snapshot,U)})),o(rb(U.config)),f(U.config.updated_at),y(""),S(!1),b("开发版配置已保存。")},onError:U=>{b(U instanceof Error?U.message:"保存配置失败。")}}),I=Vn({mutationFn:async U=>{if(!j)throw new Error("当前没有可用的开发节点,暂时无法执行开发版管理操作。");return(await wn(j)).client.executeDevManagerAction({action:U})},onSuccess:(U,ve)=>{var Z,Se,je,Oe;a.setQueryData(T,Ie=>({baseUrl:(Ie==null?void 0:Ie.baseUrl)??"",snapshot:Sg(Ie==null?void 0:Ie.snapshot,U.snapshot)})),b(ve==="restart-release-services"?"后台重启助手已启动,当前连接会短时断开,请等待正式版自动恢复。":ve==="install-latest-release"?"后台升级助手已启动,当前连接会短时断开,请等待正式版自动恢复。":ve==="install-latest-release-package"?((Z=U.job)==null?void 0:Z.summary)??"正式版 npm 安装任务已启动。":ve==="install-release-services"?((Se=U.job)==null?void 0:Se.summary)??"正式版服务注册任务已启动。":ve==="uninstall-release-services"?((je=U.job)==null?void 0:je.summary)??"正式版服务移除任务已启动。":((Oe=U.job)==null?void 0:Oe.summary)??"任务已启动。")},onError:U=>{b(U instanceof Error?U.message:"执行操作失败。")}}),k=((ke=D.data)==null?void 0:ke.snapshot)??null,P=(k==null?void 0:k.jobs[0])??null,Q=(k==null?void 0:k.jobs.find(U=>U.status==="running"))??null,se=(k==null?void 0:k.jobs.find(U=>U.kind==="npm-publish"))??null,W=(k==null?void 0:k.jobs.find(U=>U.kind==="release-service-install"))??null,V=(k==null?void 0:k.jobs.find(U=>U.kind==="release-service-uninstall"))??null,Y=(k==null?void 0:k.jobs.find(U=>U.kind==="release-install-package"))??null,ee=(k==null?void 0:k.jobs.find(U=>U.kind==="release-restart"))??(k==null?void 0:k.jobs.find(U=>U.kind==="release-install-run"))??null,me=P,ge=_.useMemo(()=>(k==null?void 0:k.services.filter(U=>U.key.startsWith("dev-")))??[],[k]),te=_.useMemo(()=>(k==null?void 0:k.services.filter(U=>U.key.startsWith("release-")))??[],[k]),xe=_.useMemo(()=>ge.some(U=>U.status==="running")?"部分或全部运行中":ge.some(U=>U.status==="degraded")?"存在异常":"未运行",[ge]),C=(U,ve)=>{o(Z=>Z&&{...Z,[U]:ve})},q=(U,ve)=>{const Z=Number(ve)||null;o(Se=>{if(!Se)return Se;const je={...Se,[U]:Z};if(U==="dev_hub_port"){const Oe=Ll(Se.dev_hub_port),Ie=Ll(Z);Se.dev_agent_hub_url===Oe&&(je.dev_agent_hub_url=Ie),Se.dev_web_hub_url===Oe&&(je.dev_web_hub_url=Ie)}if(U==="dev_agent_port"){const Oe=Ll(Se.dev_agent_port),Ie=Ll(Z),wt=jm(Se.dev_agent_port),qe=jm(Z);Se.dev_agent_direct_base_url===Oe&&(je.dev_agent_direct_base_url=Ie),Se.dev_agent_ws_base_url===wt&&(je.dev_agent_ws_base_url=qe)}if(U==="release_hub_port"){const Oe=Ll(Se.release_hub_port),Ie=Ll(Z);Se.release_agent_hub_url===Oe&&(je.release_agent_hub_url=Ie)}if(U==="release_agent_port"){const Oe=Ll(Se.release_agent_port),Ie=Ll(Z),wt=jm(Se.release_agent_port),qe=jm(Z);Se.release_agent_direct_base_url===Oe&&(je.release_agent_direct_base_url=Ie),Se.release_agent_ws_base_url===wt&&(je.release_agent_ws_base_url=qe)}return je})},ie=async()=>{if(!(k!=null&&k.apk_artifact)){b("当前还没有可下载的 APK。");return}if(!j){b("当前没有可用的开发节点,暂时无法下载 APK。");return}const U=HE();if((U==null?void 0:U.artifactId)===k.apk_artifact.artifact_id&&Date.now()-U.triggeredAt<zE){b("同一个 APK 刚刚已经触发过下载。如果安装确认没有弹出,请先查看系统下载列表或等待浏览器处理完成。");return}const ve=await wn(j),Z=new URL(k.apk_artifact.download_path,ve.baseUrl).toString();$E(k.apk_artifact.artifact_id),window.open(Z,"_blank","noopener,noreferrer"),b("APK 下载已触发。")},he=U=>{C("repo_path",U),N(!1),b(`已选中开发版目录:${U}`)},re=I.isPending;if(D.isLoading&&!k)return i.jsx("p",{className:"settings-block__status",children:"正在加载开发版管理信息…"});if(D.error instanceof Error)return i.jsx("p",{className:"settings-block__status",children:D.error.message});if(!t)return i.jsx("p",{className:"settings-block__status",children:"当前没有可用的代码线程节点,请先在会话里连接到目标 agent,再使用开发版管理。"});if(!k||!l)return i.jsx("p",{className:"settings-block__status",children:"当前还没有可用的开发版管理数据。"});const L=I.variables,ae=k.node_runtime.versions.length>0;return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"开发版与正式版双环境"}),i.jsx("p",{className:"settings-panel__subtitle",children:"正式版保持默认可用,开发版走独立端口和独立命令。首屏只读取轻量快照,状态测试按端口连通性快测。"})]})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"开发版代码"}),i.jsx("strong",{children:k.config.repo_path??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"正式版版本"}),i.jsx("strong",{children:k.current_version??"未检测到"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"开发版状态"}),i.jsx("strong",{children:xe})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"最新 APK"}),i.jsx("strong",{children:k.apk_artifact?Sm(k.apk_artifact.built_at):"尚未生成"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"基础配置"}),i.jsx("p",{className:"settings-panel__subtitle",children:"保存开发版路径、nvm 版本、启动参数,以及正式版升级后自动恢复所需配置。"})]}),i.jsx("div",{className:"settings-actions-row",children:i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void z.mutateAsync(),disabled:z.isPending,children:z.isPending?"保存中…":"保存配置"})})]}),i.jsxs("div",{className:"dev-manager-form-grid",children:[i.jsxs("div",{className:"dev-manager-form-section dev-manager-field--wide",children:[i.jsx("strong",{children:"开发版运行配置"}),i.jsx("p",{children:"这些配置直接用于启动、重启、停止开发版 Hub + Agent + Web。启动参数会追加到对应启动命令末尾。"})]}),i.jsxs("div",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版代码路径"}),i.jsx("input",{type:"text",className:`dev-manager-path-display ${l.repo_path?"is-selected":""}`,value:l.repo_path??"",placeholder:t?"点击下方按钮选择目录":"当前没有可用节点,暂时无法浏览目录",readOnly:!0,onClick:()=>{t&&N(!0)}}),i.jsxs("div",{className:"settings-actions-row dev-manager-path-actions",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>N(!0),disabled:!t,children:"选择目录"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>C("repo_path",null),disabled:!l.repo_path,children:"清空"})]}),i.jsx("small",{className:"dev-manager-field-hint",children:"使用内置目录弹层懒加载浏览;这里只保存最终选中的开发版仓库路径。"})]}),i.jsxs("div",{className:"settings-field",children:[i.jsx("span",{children:"Node 版本"}),i.jsxs("select",{value:l.nvm_version??"",onChange:U=>C("nvm_version",U.target.value||null),children:[i.jsx("option",{value:"",children:"保持系统默认"}),k.node_runtime.versions.map(U=>i.jsx("option",{value:U,children:U},U))]}),i.jsx("small",{className:`dev-manager-field-hint ${ae?"":"is-danger"}`,children:ae?k.node_runtime.manager==="nvm-windows"?"下拉内容包含当前正在运行的 Node 版本,以及这台电脑上 nvm-windows 已安装的版本。":"下拉内容至少包含当前正在运行的 Node 版本;如果这台电脑安装了 nvm-windows,也会一并列出。":k.node_runtime.error||"当前没有检测到可用的 Node 版本。"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"npm 令牌"}),i.jsx("input",{type:"password",value:m,onChange:U=>{S(!1),y(U.target.value)},placeholder:k.credentials.has_npm_token?`已保存:${k.credentials.npm_token_hint??"******"}`:"输入新的 npm token"})]}),i.jsx("div",{className:"settings-actions-row dev-manager-token-actions",children:i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{y(""),S(!0)},children:"清空令牌"})}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Hub 端口"}),i.jsx("input",{type:"number",value:l.dev_hub_port??"",onChange:U=>q("dev_hub_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent 端口"}),i.jsx("input",{type:"number",value:l.dev_agent_port??"",onChange:U=>q("dev_agent_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Web 端口"}),i.jsx("input",{type:"number",value:l.dev_web_port??"",onChange:U=>q("dev_web_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent -> Hub URL"}),i.jsx("input",{type:"text",value:l.dev_agent_hub_url,onChange:U=>C("dev_agent_hub_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent 直连 URL"}),i.jsx("input",{type:"text",value:l.dev_agent_direct_base_url,onChange:U=>C("dev_agent_direct_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent WS URL"}),i.jsx("input",{type:"text",value:l.dev_agent_ws_base_url,onChange:U=>C("dev_agent_ws_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Agent 名称"}),i.jsx("input",{type:"text",value:l.dev_agent_name,onChange:U=>C("dev_agent_name",U.target.value),placeholder:"留空后默认显示为直连地址 host:port"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"开发版 Web -> Hub URL"}),i.jsx("input",{type:"text",value:l.dev_web_hub_url,onChange:U=>C("dev_web_hub_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版 Hub 追加参数"}),i.jsx("textarea",{value:l.dev_hub_args,onChange:U=>C("dev_hub_args",U.target.value),placeholder:"会直接追加到 corepack pnpm dev:hub 后面"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版 Agent 追加参数"}),i.jsx("textarea",{value:l.dev_agent_args,onChange:U=>C("dev_agent_args",U.target.value),placeholder:"会直接追加到 corepack pnpm dev:agent 后面"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"开发版 Web 追加参数"}),i.jsx("textarea",{value:l.dev_web_args,onChange:U=>C("dev_web_args",U.target.value),placeholder:"会直接追加到开发版 Web 的 vite 命令后面"})]}),i.jsxs("div",{className:"dev-manager-form-section dev-manager-field--wide",children:[i.jsx("strong",{children:"正式版自动恢复配置"}),i.jsx("p",{children:"这些配置不是给当前已运行的正式版实时改端口,而是点击“重启正式版”后,后台助手用它重新拉起正式版 Hub + Agent。"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Hub 端口(自动恢复)"}),i.jsx("input",{type:"number",value:l.release_hub_port??"",onChange:U=>q("release_hub_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 端口(自动恢复)"}),i.jsx("input",{type:"number",value:l.release_agent_port??"",onChange:U=>q("release_agent_port",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Hub 服务名"}),i.jsx("input",{type:"text",value:l.release_hub_service_name,onChange:U=>C("release_hub_service_name",U.target.value),placeholder:"PandaHub"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 服务名"}),i.jsx("input",{type:"text",value:l.release_agent_service_name,onChange:U=>C("release_agent_service_name",U.target.value),placeholder:"PandaAgent"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent -> Hub URL(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_hub_url,onChange:U=>C("release_agent_hub_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 直连 URL(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_direct_base_url,onChange:U=>C("release_agent_direct_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent WS URL(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_ws_base_url,onChange:U=>C("release_agent_ws_base_url",U.target.value)})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"正式版 Agent 名称(自动恢复)"}),i.jsx("input",{type:"text",value:l.release_agent_name,onChange:U=>C("release_agent_name",U.target.value),placeholder:"留空后默认显示为直连地址 host:port"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"正式版 Hub 追加参数(自动恢复)"}),i.jsx("textarea",{value:l.release_hub_args,onChange:U=>C("release_hub_args",U.target.value),placeholder:"会直接追加到 panda hub 后面"})]}),i.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[i.jsx("span",{children:"正式版 Agent 追加参数(自动恢复)"}),i.jsx("textarea",{value:l.release_agent_args,onChange:U=>C("release_agent_args",U.target.value),placeholder:"会直接注入 panda agent 命令后面"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"开发版运行控制"}),i.jsx("p",{className:"settings-panel__subtitle",children:"启动、重启、停止开发版 Hub / Agent / Web。进入页面默认不做探测,点击状态测试后仅按端口连通性快速判断。"})]}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("start-development"),disabled:re,children:L==="start-development"&&I.isPending?"启动中…":"启动"}),i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("restart-development"),disabled:re,children:L==="restart-development"&&I.isPending?"重启中…":"重启"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("stop-development"),disabled:re,children:L==="stop-development"&&I.isPending?"停止中…":"停止"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("probe-development"),disabled:re,children:L==="probe-development"&&I.isPending?"测试中…":"状态测试"})]})]}),i.jsx("div",{className:"dev-manager-service-grid",children:ge.map(U=>{var ve,Z;return i.jsxs("article",{className:`settings-diagnostic-list__item dev-manager-service-card is-${U.status}`,children:[i.jsx("strong",{children:U.label}),i.jsxs("span",{children:["上次测试:"," ",i.jsx("strong",{className:ib((ve=U.probe)==null?void 0:ve.ok),children:ab((Z=U.probe)==null?void 0:Z.ok)})]}),i.jsxs("span",{children:["端口:",U.configured_port??"未配置"]}),U.detected_pids.length>0?i.jsxs("span",{children:["PID:",U.detected_pids.join(", ")]}):null]},U.key)})})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"npm 发布、安装与正式版恢复"}),i.jsx("p",{className:"settings-panel__subtitle",children:"发布最新 npm 包后,可以单独安装正式版包,再按服务优先重启正式版 Hub + Agent。"})]}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("publish-npm"),disabled:I.isPending,children:L==="publish-npm"&&I.isPending?"发布中…":"发布"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("install-latest-release-package"),disabled:I.isPending,children:L==="install-latest-release-package"&&I.isPending?"安装中…":"安装"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("restart-release-services"),disabled:I.isPending,children:L==="restart-release-services"&&I.isPending?"重启中…":"重启"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("install-release-services"),disabled:I.isPending,children:L==="install-release-services"&&I.isPending?"注册中…":"注册/更新服务"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("uninstall-release-services"),disabled:I.isPending,children:L==="uninstall-release-services"&&I.isPending?"移除中…":"移除服务"})]})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前正式版版本"}),i.jsx("span",{children:k.current_version??"未检测到"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近 npm 发布"}),i.jsx("span",{className:se?fu(se.status):"is-muted",children:se?Uo(se.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近正式版安装"}),i.jsx("span",{className:Y?fu(Y.status):"is-muted",children:Y?Uo(Y.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近正式版恢复"}),i.jsx("span",{className:ee?fu(ee.status):"is-muted",children:ee?Uo(ee.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近服务注册"}),i.jsx("span",{className:W?fu(W.status):"is-muted",children:W?Uo(W.status):"未执行"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近服务移除"}),i.jsx("span",{className:V?fu(V.status):"is-muted",children:V?Uo(V.status):"未执行"})]}),te.map(U=>{var ve,Z;return i.jsxs("article",{className:`settings-diagnostic-list__item dev-manager-service-card is-${U.status}`,children:[i.jsx("strong",{children:U.label}),i.jsxs("span",{children:["当前模式:"," ",i.jsx("strong",{children:U.manager==="windows-service"?"Windows 服务":"普通进程"})]}),i.jsxs("span",{children:["服务名:",U.service_name??"未配置"]}),i.jsxs("span",{children:["服务控制器:"," ",i.jsx("strong",{className:U.service_registered?"":"is-muted",children:FE(U.service_registered?U.service_status:"missing")})]}),i.jsxs("span",{children:["探测结果:"," ",i.jsx("strong",{className:ib((ve=U.probe)==null?void 0:ve.ok),children:ab((Z=U.probe)==null?void 0:Z.ok)})]}),i.jsxs("span",{children:["端口:",U.configured_port??"未配置"]})]},U.key)})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"APK 编译与下载"}),i.jsx("p",{className:"settings-panel__subtitle",children:"直接用开发版源码产出 release APK,并提供下载入口。"})]}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("build-apk"),disabled:I.isPending,children:L==="build-apk"&&I.isPending?"编译中…":"编译 APK"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void ie(),disabled:!k.apk_artifact,children:"下载 APK"})]})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近构建时间"}),i.jsx("span",{children:k.apk_artifact?Sm(k.apk_artifact.built_at):"尚未构建"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"版本"}),i.jsx("span",{children:k.apk_artifact?`${k.apk_artifact.version_name??"未知"}${k.apk_artifact.version_code?` (${k.apk_artifact.version_code})`:""}`:"尚未构建"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"文件大小"}),i.jsx("span",{children:k.apk_artifact?BE(k.apk_artifact.size_bytes):"尚未构建"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"任务日志"}),i.jsx("p",{className:"settings-panel__subtitle",children:"这里只显示最近一次任务的日志;更早的历史记录仍会保留在后台状态文件中。"})]})}),p?i.jsx("p",{className:"settings-block__status",children:p}):null,Q?i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前运行中"}),i.jsxs("span",{children:[Q.title," · ",Uo(Q.status)]})]}):null,me?i.jsx("div",{className:"settings-log-list",children:i.jsxs("article",{className:"settings-log-item dev-manager-job",children:[i.jsxs("div",{className:"settings-log-item__meta",children:[i.jsx("strong",{children:me.title}),i.jsx("span",{children:Sm(me.started_at??me.created_at)})]}),i.jsxs("div",{className:`settings-log-item__kind ${fu(me.status)}`,children:[Uo(me.status),me.disconnect_expected?" · 会中断连接":""]}),me.summary?i.jsx("div",{className:"dev-manager-job__summary",children:me.summary}):null,me.logs.length>0?i.jsx("pre",{className:"settings-log-item__detail",children:me.logs.slice(-16).map(U=>`[${Sm(U.timestamp)}] ${U.message}`).join(`
|
|
68
|
+
`)}):null]},me.id)}):i.jsx("p",{className:"settings-block__status",children:"还没有开发版管理任务记录。"})]}),w&&t?i.jsx(UE,{agentId:t,initialPath:l.repo_path,onClose:()=>N(!1),onSelect:he}):null]})},M3=mc("App",{web:()=>Zr(()=>import("./web-Dy_S-Kpy.js"),[]).then(e=>new e.AppWeb)}),WE=mc("Browser",{web:()=>Zr(()=>import("./web-vTFNt5EQ.js"),[]).then(e=>new e.BrowserWeb)}),KE=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/\/+$/,""):""},QE=async()=>{if(!Tp())return{platform:qu(),version:null,build:null,appId:null};const e=await M3.getInfo();return{platform:qu(),version:e.version??null,build:e.build??null,appId:e.id??null}},A3=e=>{const t=KE(e);return t?new URL("/downloads/android/latest.json",t).toString():""},GE=async e=>{const t=A3(e);if(!t)throw new Error("当前还没有配置可用的 Hub 地址。");const a=await fetch(t,{cache:"no-store"});if(!a.ok)throw new Error(`更新清单请求失败(HTTP ${a.status})。`);const l=await a.json(),o=Array.isArray(l.release_notes)?l.release_notes.filter(f=>typeof f=="string"&&f.trim().length>0):[];if(l.platform!=="android"||typeof l.version_name!="string"||typeof l.version_code!="number"||typeof l.published_at!="string"||typeof l.apk_url!="string")throw new Error("Hub 返回的 Android 更新清单格式无效。");const u=new URL(l.apk_url,t).toString();return{platform:"android",version_name:l.version_name,version_code:l.version_code,published_at:l.published_at,apk_url:u,release_notes:o}},YE=e=>{const t=Number(e);return Number.isFinite(t)?t:null},VE=(e,t)=>{if(!e||!t)return!1;const a=YE(e.build);return typeof a=="number"?t.version_code>a:t.version_name!==e.version},ZE=async e=>{if(!e.trim())throw new Error("当前没有可用的 APK 下载地址。");await WE.open({url:e})},D3="panda:session-model",O3="panda:command-execution-model",I3="panda:title-generation-model",E_="panda:session-model-options",M0="panda:session-model-options-updated",L3="panda:session-reasoning",P3="panda:session-fast-mode",U3="panda:session-plan-mode",z3="panda:session-yolo-mode",nd=[{id:"gpt-5.4",label:"gpt-5.4",value:"gpt-5.4"},{id:"gpt-5.3-codex",label:"gpt-5.3-codex",value:"gpt-5.3-codex"},{id:"gpt-5.3",label:"gpt-5.3",value:"gpt-5.3"},{id:"gpt-5.4-mini",label:"gpt-5.4-mini",value:"gpt-5.4-mini"},{id:"gpt-5.2",label:"gpt-5.2",value:"gpt-5.2"}],Xf=[{label:"低",value:"low"},{label:"中",value:"medium"},{label:"高",value:"high"},{label:"极高",value:"xhigh"}];var C2;const B3=((C2=nd[0])==null?void 0:C2.value)??"gpt-5.4",lb="gpt-5.4-mini",ob="gpt-5.4-mini",XE=Xf[2].value,Fr=e=>typeof e=="string"?e.trim():"",JE=(e,t)=>{if(!e||typeof e!="object")return null;const a=e,l=Fr(a.value),o=Fr(a.label)||l,u=Fr(a.id)||l||`custom-model-${t+1}`;if(!o||!l)return null;const f=Fr(a.description);return{id:u,label:o,value:l,description:f||null}},eC=e=>{const t=new Set,a=new Set;return e.flatMap(l=>{const o=l.value.toLowerCase();if(a.has(o))return[];a.add(o);let u=l.id,f=2;for(;t.has(u);)u=`${l.id}-${f}`,f+=1;return t.add(u),[{...l,id:u}]})},H3=e=>{if(!Array.isArray(e))return nd;const t=eC(e.flatMap((a,l)=>{const o=JE(a,l);return o?[o]:[]}));return t.length>0?t:nd},ld=e=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}},tC=()=>{typeof window>"u"||window.dispatchEvent(new Event(M0))},od=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}},C_=(e,t=!1)=>{const a=ld(e);return a==="true"?!0:a==="false"?!1:t},T_=(e,t)=>{od(e,t?"true":"false")},cd=(e,t)=>{const a=t==null?void 0:t.trim();return a?`${e}:${a}`:null},xf=e=>{const t=Fr(e==null?void 0:e.value)||"",a=Fr(e==null?void 0:e.label)||t;return{id:Fr(e==null?void 0:e.id)||Fr(e==null?void 0:e.value)||`custom-model-${Date.now()}`,label:a,value:t,description:Fr(e==null?void 0:e.description)||null}},nC=()=>hh().map(({id:e,...t})=>t),hh=()=>{const e=ld(E_);if(!e)return nd;try{return H3(JSON.parse(e))}catch{return nd}},sC=e=>{const t=H3(e);od(E_,JSON.stringify(t)),tC()},aC=e=>Xf.some(t=>t.value===e),R_=()=>{var a;const e=ld(D3),t=hh();return t.some(l=>l.value===e)?e:((a=t[0])==null?void 0:a.value)??B3},qm=()=>{const e=ld(O3),t=hh();if(t.some(l=>l.value===e))return e;const a=t.find(l=>l.value===lb)??t[0];return(a==null?void 0:a.value)??lb},$3=()=>{const e=ld(I3),t=hh();if(t.some(l=>l.value===e))return e;const a=t.find(l=>l.value===ob)??t[0];return(a==null?void 0:a.value)??ob},F3=()=>{const e=ld(L3);return aC(e)?e:XE},zf=e=>{od(D3,e)},jg=e=>{od(O3,e)},wg=e=>{od(I3,e)},q3=e=>{od(L3,e)},cb=e=>{const t=cd(P3,e);return t?C_(t):!1},ub=e=>{const t=cd(U3,e);return t?C_(t):!1},db=e=>{const t=cd(z3,e);return t?C_(t):!1},W3=(e,t)=>{const a=cd(P3,e);a&&T_(a,t)},K3=(e,t)=>{const a=cd(U3,e);a&&T_(a,t)},Q3=(e,t)=>{const a=cd(z3,e);a&&T_(a,t)},iC=(e,t)=>{W3(e,t.isFastModeEnabled),K3(e,t.isPlanModeEnabled),Q3(e,t.isYoloModeEnabled)},wp=(e,t=nC())=>{var a,l;return((a=t.find(o=>o.value===e))==null?void 0:a.label)??(typeof e=="string"&&e.trim()?e.trim():((l=t[0])==null?void 0:l.label)??B3)},rC=e=>{var t;return((t=Xf.find(a=>a.value===e))==null?void 0:t.label)??Xf[2].label},lC=JSON.parse('[{"id":"absolutely","light":{"codeThemeId":"absolutely","theme":{"accent":"#cc7d5e","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#2d2d2b","opaqueWindows":true,"semanticColors":{"diffAdded":"#00c853","diffRemoved":"#ff5f38","skill":"#cc7d5e"},"surface":"#f9f9f7"},"variant":"light"},"dark":{"codeThemeId":"absolutely","theme":{"accent":"#cc7d5e","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#f9f9f7","opaqueWindows":false,"semanticColors":{"diffAdded":"#00c853","diffRemoved":"#ff5f38","skill":"#cc7d5e"},"surface":"#2d2d2b"},"variant":"dark"}},{"id":"ayu","dark":{"codeThemeId":"ayu","theme":{"accent":"#e6b450","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#bfbdb6","opaqueWindows":false,"semanticColors":{"diffAdded":"#7fd962","diffRemoved":"#ea6c73","skill":"#cda1fa"},"surface":"#0b0e14"},"variant":"dark"}},{"id":"catppuccin","light":{"codeThemeId":"catppuccin","theme":{"accent":"#8839ef","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#4c4f69","opaqueWindows":true,"semanticColors":{"diffAdded":"#40a02b","diffRemoved":"#d20f39","skill":"#8839ef"},"surface":"#eff1f5"},"variant":"light"},"dark":{"codeThemeId":"catppuccin","theme":{"accent":"#cba6f7","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#cdd6f4","opaqueWindows":false,"semanticColors":{"diffAdded":"#a6e3a1","diffRemoved":"#f38ba8","skill":"#cba6f7"},"surface":"#1e1e2e"},"variant":"dark"}},{"id":"codex","light":{"codeThemeId":"codex","theme":{"accent":"#0169cc","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#0d0d0d","opaqueWindows":true,"semanticColors":{"diffAdded":"#00a240","diffRemoved":"#e02e2a","skill":"#751ed9"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"codex","theme":{"accent":"#0169cc","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#fcfcfc","opaqueWindows":false,"semanticColors":{"diffAdded":"#00a240","diffRemoved":"#e02e2a","skill":"#b06dff"},"surface":"#111111"},"variant":"dark"}},{"id":"dracula","dark":{"codeThemeId":"dracula","theme":{"accent":"#ff79c6","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#f8f8f2","opaqueWindows":false,"semanticColors":{"diffAdded":"#50fa7b","diffRemoved":"#ff5555","skill":"#ff79c6"},"surface":"#282a36"},"variant":"dark"}},{"id":"everforest","light":{"codeThemeId":"everforest","theme":{"accent":"#93b259","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#5c6a72","opaqueWindows":true,"semanticColors":{"diffAdded":"#8da101","diffRemoved":"#f85552","skill":"#df69ba"},"surface":"#fdf6e3"},"variant":"light"},"dark":{"codeThemeId":"everforest","theme":{"accent":"#a7c080","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#d3c6aa","opaqueWindows":false,"semanticColors":{"diffAdded":"#a7c080","diffRemoved":"#e67e80","skill":"#d699b6"},"surface":"#2d353b"},"variant":"dark"}},{"id":"github","light":{"codeThemeId":"github","theme":{"accent":"#0969da","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#1f2328","opaqueWindows":true,"semanticColors":{"diffAdded":"#1a7f37","diffRemoved":"#cf222e","skill":"#8250df"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"github","theme":{"accent":"#1f6feb","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e6edf3","opaqueWindows":false,"semanticColors":{"diffAdded":"#3fb950","diffRemoved":"#f85149","skill":"#bc8cff"},"surface":"#0d1117"},"variant":"dark"}},{"id":"gruvbox","light":{"codeThemeId":"gruvbox","theme":{"accent":"#458588","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#3c3836","opaqueWindows":true,"semanticColors":{"diffAdded":"#3c3836","diffRemoved":"#cc241d","skill":"#b16286"},"surface":"#fbf1c7"},"variant":"light"},"dark":{"codeThemeId":"gruvbox","theme":{"accent":"#458588","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#ebdbb2","opaqueWindows":false,"semanticColors":{"diffAdded":"#ebdbb2","diffRemoved":"#cc241d","skill":"#b16286"},"surface":"#282828"},"variant":"dark"}},{"id":"linear","light":{"codeThemeId":"linear","theme":{"accent":"#5e6ad2","contrast":45,"fonts":{"code":null,"ui":"Inter"},"ink":"#2a3140","opaqueWindows":true,"semanticColors":{"diffAdded":"#00a240","diffRemoved":"#ba2623","skill":"#8160d8"},"surface":"#f7f8fa"},"variant":"light"},"dark":{"codeThemeId":"linear","theme":{"accent":"#5e6ad2","contrast":60,"fonts":{"code":null,"ui":"Inter"},"ink":"#e6e9ef","opaqueWindows":true,"semanticColors":{"diffAdded":"#7ad9c0","diffRemoved":"#fa423e","skill":"#c2a1ff"},"surface":"#17181d"},"variant":"dark"}},{"id":"lobster","dark":{"codeThemeId":"lobster","theme":{"accent":"#ff5c5c","contrast":60,"fonts":{"code":null,"ui":"Satoshi"},"ink":"#e4e4e7","opaqueWindows":true,"semanticColors":{"diffAdded":"#22c55e","diffRemoved":"#ff5c5c","skill":"#3b82f6"},"surface":"#111827"},"variant":"dark"}},{"id":"material","dark":{"codeThemeId":"material","theme":{"accent":"#80cbc4","contrast":60,"fonts":{"code":null,"ui":"Satoshi"},"ink":"#eeffff","opaqueWindows":true,"semanticColors":{"diffAdded":"#c3e88d","diffRemoved":"#f07178","skill":"#c792ea"},"surface":"#212121"},"variant":"dark"}},{"id":"matrix","dark":{"codeThemeId":"matrix","theme":{"accent":"#1eff5a","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#b8ffca","opaqueWindows":true,"semanticColors":{"diffAdded":"#1eff5a","diffRemoved":"#fa423e","skill":"#1eff5a"},"surface":"#040805"},"variant":"dark"}},{"id":"monokai","dark":{"codeThemeId":"monokai","theme":{"accent":"#99947c","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#f8f8f2","opaqueWindows":true,"semanticColors":{"diffAdded":"#86b42b","diffRemoved":"#c4265e","skill":"#8c6bc8"},"surface":"#272822"},"variant":"dark"}},{"id":"night-owl","dark":{"codeThemeId":"night-owl","theme":{"accent":"#44596b","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#d6deeb","opaqueWindows":true,"semanticColors":{"diffAdded":"#c5e478","diffRemoved":"#ef5350","skill":"#c792ea"},"surface":"#011627"},"variant":"dark"}},{"id":"nord","dark":{"codeThemeId":"nord","theme":{"accent":"#88c0d0","contrast":60,"fonts":{"code":null,"ui":"ui-monospace, \\"SFMono-Regular\\", \\"SF Mono\\", Menlo, Consolas, \\"Liberation Mono\\", monospace"},"ink":"#d8dee9","opaqueWindows":true,"semanticColors":{"diffAdded":"#a3be8c","diffRemoved":"#bf616a","skill":"#b48ead"},"surface":"#2e3440"},"variant":"dark"}},{"id":"notion","light":{"codeThemeId":"notion","theme":{"accent":"#3183d8","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#37352f","opaqueWindows":true,"semanticColors":{"diffAdded":"#008000","diffRemoved":"#a31515","skill":"#0000ff"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"notion","theme":{"accent":"#3183d8","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#d9d9d8","opaqueWindows":true,"semanticColors":{"diffAdded":"#4ec9b0","diffRemoved":"#fa423e","skill":"#3183d8"},"surface":"#191919"},"variant":"dark"}},{"id":"one","light":{"codeThemeId":"one","theme":{"accent":"#526fff","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#383a42","opaqueWindows":true,"semanticColors":{"diffAdded":"#3bba54","diffRemoved":"#e45649","skill":"#526fff"},"surface":"#fafafa"},"variant":"light"},"dark":{"codeThemeId":"one","theme":{"accent":"#4d78cc","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#abb2bf","opaqueWindows":true,"semanticColors":{"diffAdded":"#8cc265","diffRemoved":"#e05561","skill":"#c162de"},"surface":"#282c34"},"variant":"dark"}},{"id":"oscurange","dark":{"codeThemeId":"oscurange","theme":{"accent":"#f9b98c","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e6e6e6","opaqueWindows":true,"semanticColors":{"diffAdded":"#40c977","diffRemoved":"#fa423e","skill":"#479ffa"},"surface":"#0b0b0f"},"variant":"dark"}},{"id":"proof","light":{"codeThemeId":"proof","theme":{"accent":"#3d755d","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#2f312d","opaqueWindows":false,"semanticColors":{"diffAdded":"#3d755d","diffRemoved":"#ba2623","skill":"#5f6ac2"},"surface":"#f5f3ed"},"variant":"light"}},{"id":"rose-pine","light":{"codeThemeId":"rose-pine","theme":{"accent":"#d7827e","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#575279","opaqueWindows":false,"semanticColors":{"diffAdded":"#56949f","diffRemoved":"#797593","skill":"#907aa9"},"surface":"#faf4ed"},"variant":"light"},"dark":{"codeThemeId":"rose-pine","theme":{"accent":"#ea9a97","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e0def4","opaqueWindows":true,"semanticColors":{"diffAdded":"#9ccfd8","diffRemoved":"#908caa","skill":"#c4a7e7"},"surface":"#232136"},"variant":"dark"}},{"id":"sentry","dark":{"codeThemeId":"sentry","theme":{"accent":"#7055f6","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#e6dff9","opaqueWindows":true,"semanticColors":{"diffAdded":"#8ee6d7","diffRemoved":"#fa423e","skill":"#7055f6"},"surface":"#2d2935"},"variant":"dark"}},{"id":"solarized","light":{"codeThemeId":"solarized","theme":{"accent":"#b58900","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#657b83","opaqueWindows":false,"semanticColors":{"diffAdded":"#859900","diffRemoved":"#dc322f","skill":"#d33682"},"surface":"#fdf6e3"},"variant":"light"},"dark":{"codeThemeId":"solarized","theme":{"accent":"#d30102","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#839496","opaqueWindows":true,"semanticColors":{"diffAdded":"#859900","diffRemoved":"#dc322f","skill":"#d33682"},"surface":"#002b36"},"variant":"dark"}},{"id":"temple","dark":{"codeThemeId":"temple","theme":{"accent":"#e4f222","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#c7e6da","opaqueWindows":true,"semanticColors":{"diffAdded":"#40c977","diffRemoved":"#fa423e","skill":"#e4f222"},"surface":"#02120c"},"variant":"dark"}},{"id":"tokyo-night","dark":{"codeThemeId":"tokyo-night","theme":{"accent":"#3d59a1","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#a9b1d6","opaqueWindows":true,"semanticColors":{"diffAdded":"#449dab","diffRemoved":"#914c54","skill":"#9d7cd8"},"surface":"#1a1b26"},"variant":"dark"}},{"id":"vscode-plus","light":{"codeThemeId":"vscode-plus","theme":{"accent":"#007acc","contrast":45,"fonts":{"code":null,"ui":null},"ink":"#000000","opaqueWindows":false,"semanticColors":{"diffAdded":"#008000","diffRemoved":"#ee0000","skill":"#0000ff"},"surface":"#ffffff"},"variant":"light"},"dark":{"codeThemeId":"vscode-plus","theme":{"accent":"#007acc","contrast":60,"fonts":{"code":null,"ui":null},"ink":"#d4d4d4","opaqueWindows":true,"semanticColors":{"diffAdded":"#369432","diffRemoved":"#f44747","skill":"#000080"},"surface":"#1e1e1e"},"variant":"dark"}}]'),oC={themes:lC},G3="panda:theme-settings",cC=13,uC=12,Y3="codex",M_="codex",dC='-apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", sans-serif',fC='ui-monospace, "SFMono-Regular", "SF Mono", "Cascadia Mono", "Cascadia Code", Consolas, monospace',hC=/\b(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|emoji|math|fangsong|ui-serif|ui-sans-serif|ui-monospace|ui-rounded)\b/i,fb=(e,t)=>{const a=e==null?void 0:e.trim();return a?hC.test(a)?a:`${a}, ${t}`:t},mC={absolutely:"Absolutely",ayu:"Ayu",catppuccin:"Catppuccin",codex:"Codex",dracula:"Dracula",everforest:"Everforest",github:"GitHub",gruvbox:"Gruvbox",linear:"Linear",lobster:"Lobster",material:"Material",matrix:"Matrix",monokai:"Monokai","night-owl":"Night Owl",nord:"Nord",notion:"Notion",one:"One",oscurange:"Oscurange",proof:"Proof","rose-pine":"Rose Pine",sentry:"Sentry",solarized:"Solarized",temple:"Temple","tokyo-night":"Tokyo Night","vscode-plus":"VSCode Plus"},ud=(e,t,a)=>Math.min(a,Math.max(t,e)),$o=(e,t)=>{const l=e.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!l)return t;const[,o]=l;return`#${(o.length===3?o.split("").map(f=>`${f}${f}`).join(""):o).toUpperCase()}`},Pr=e=>{const t=$o(e,"#000000").slice(1);return{r:Number.parseInt(t.slice(0,2),16),g:Number.parseInt(t.slice(2,4),16),b:Number.parseInt(t.slice(4,6),16)}},pC=(e,t,a)=>`#${[e,t,a].map(l=>ud(Math.round(l),0,255).toString(16).padStart(2,"0")).join("").toUpperCase()}`,pt=(e,t,a)=>{const l=Pr(e),o=Pr(t),u=ud(a,0,1);return pC(l.r+(o.r-l.r)*u,l.g+(o.g-l.g)*u,l.b+(o.b-l.b)*u)},gC=e=>{const{r:t,g:a,b:l}=Pr(e),o=u=>{const f=u/255;return f<=.03928?f/12.92:((f+.055)/1.055)**2.4};return o(t)*.2126+o(a)*.7152+o(l)*.0722},_C=e=>gC(e)>.5?"#0D1117":"#FFFFFF",Or=(e,t)=>{const a=Math.round(ud(t,0,1)*100);return a>=100?e:`color-mix(in srgb, ${e} ${a}%, transparent)`},V3=oC.themes,Z3=(e,t)=>{var l,o;const a=t==="light"?e.light:e.dark;return a?{id:e.id,label:mC[e.id]??e.id,codeThemeId:a.codeThemeId,variant:t,accent:$o(a.theme.accent,"#0169CC"),background:$o(a.theme.surface,"#FFFFFF"),foreground:$o(a.theme.ink,"#0D0D0D"),contrast:ud(Number(a.theme.contrast),0,100),opaqueWindows:!!a.theme.opaqueWindows,semanticColors:{diffAdded:$o(a.theme.semanticColors.diffAdded,"#00A240"),diffRemoved:$o(a.theme.semanticColors.diffRemoved,"#E02E2A"),skill:$o(a.theme.semanticColors.skill,"#751ED9")},fonts:{ui:((l=a.theme.fonts.ui)==null?void 0:l.trim())||null,code:((o=a.theme.fonts.code)==null?void 0:o.trim())||null}}:null},A0=V3.map(e=>Z3(e,"light")).filter(e=>!!e),Jf=V3.map(e=>Z3(e,"dark")).filter(e=>!!e);Jf.find(e=>e.id===M_)??Jf[0];const lc={mode:"system",lightThemeId:Y3,darkThemeId:M_,uiFontSize:cC,codeFontSize:uC},X3=e=>ud(Number(e),11,18),J3=e=>ud(Number(e),10,18),A_=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Ap=e=>A0.find(t=>t.id===e)??A0[0],Dp=e=>Jf.find(t=>t.id===e)??Jf[0],hb=(e,t=lc,a="light")=>a==="dark"?{...t,darkThemeId:Dp(e).id}:{...t,lightThemeId:Ap(e).id},Fl=e=>({mode:(e==null?void 0:e.mode)==="light"||(e==null?void 0:e.mode)==="dark"||(e==null?void 0:e.mode)==="system"?e.mode:lc.mode,lightThemeId:Ap((e==null?void 0:e.lightThemeId)??Y3).id,darkThemeId:Dp((e==null?void 0:e.darkThemeId)??M_).id,uiFontSize:X3((e==null?void 0:e.uiFontSize)??lc.uiFontSize),codeFontSize:J3((e==null?void 0:e.codeFontSize)??lc.codeFontSize)}),ex=()=>{if(typeof window>"u")return lc;try{const e=window.localStorage.getItem(G3);return e?Fl(JSON.parse(e)):lc}catch{return lc}},Sf=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(G3,JSON.stringify(Fl(e)))}catch{}},yC=(e,t)=>e==="system"?t:e,Lr=(e,t=A_())=>{const a=Fl(e),l=yC(a.mode,t),o=Ap(a.lightThemeId),u=Dp(a.darkThemeId),f=l==="dark"?u:o;return{...a,appearance:l,lightTheme:o,darkTheme:u,activeTheme:f,uiFontFamily:fb(f.fonts.ui,dC),codeFontFamily:fb(f.fonts.code,fC)}},vC=e=>{if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>{e(t.matches?"dark":"light")};return a(),t.addEventListener("change",a),()=>{t.removeEventListener("change",a)}},bC=(e,t)=>{const a=Lr(e,t),l=a.activeTheme,o=t==="dark",u=(l.contrast-(o?60:45))/100,f=l.semanticColors.diffAdded,m=l.semanticColors.diffRemoved,y=l.semanticColors.skill,g=Pr(f),S=Pr(m),p=Pr(y),b=Pr(l.accent),w=Pr(l.background),N=Pr(l.foreground),j=l.background,T=o?pt(l.background,"#FFFFFF",.05+u*.08):pt(l.background,"#FFFFFF",.42+u*.16),D=o?pt(l.background,"#FFFFFF",.07+u*.08):pt(l.background,"#FFFFFF",.78+u*.1),z=o?pt(l.background,"#FFFFFF",.1+u*.08):pt(l.background,"#FFFFFF",.56+u*.14),I=o?pt(l.background,"#FFFFFF",.14+u*.08):pt(l.background,l.foreground,.1+u*.12),k=o?pt(l.background,"#000000",.08-u*.06):pt(l.background,l.foreground,.03+u*.08),P=o?pt(l.background,"#FFFFFF",.08+u*.06):pt(l.background,l.foreground,.06+u*.08),Q=o?pt(l.background,"#FFFFFF",.14+u*.08):pt(l.background,l.foreground,.14+u*.1),se=o?pt(l.background,"#FFFFFF",.22+u*.08):pt(l.background,l.foreground,.22+u*.1),W=o?pt(l.background,"#FFFFFF",.08+u*.04):pt(l.background,l.foreground,.1+u*.08),V=l.foreground,Y=o?pt(l.foreground,l.background,.28-u*.1):pt(l.foreground,l.background,.5-u*.14),ee=o?pt(l.foreground,l.background,.46-u*.1):pt(l.foreground,l.background,.64-u*.14),me=pt(l.foreground,l.background,o?.58:.74),ge=l.accent,te=o?pt(l.accent,"#FFFFFF",.18):pt(l.accent,"#FFFFFF",.24),xe=o?pt(l.accent,l.background,.78):pt(l.accent,l.background,.88),C=o?pt(l.accent,l.background,.84):pt(l.accent,l.background,.92),q=_C(ge),ie=o?pt(l.background,"#FFFFFF",.1):pt(l.background,l.foreground,.08),he=o?pt(l.background,"#000000",.06):pt(l.background,l.foreground,.035),re=o?pt(l.background,"#FFFFFF",.05):pt(l.background,l.foreground,.06),L=o?pt(l.background,"#FFFFFF",.03):pt(l.background,l.foreground,.085),ae=o?pt(l.background,"#FFFFFF",.065):pt(l.background,l.foreground,.05),ke=pt(l.foreground,l.background,o?.42:.68),U=o?pt(l.background,"#FFFFFF",.08):pt(l.foreground,l.background,.18),ve=o?pt(l.background,"#FFFFFF",.08):pt(l.background,l.foreground,.06),Z=o?pt(l.background,"#FFFFFF",.12):pt(l.background,l.foreground,.1),Se=o?pt(l.background,"#FFFFFF",.14+u*.05):pt(l.background,l.foreground,.12+u*.08),je=l.opaqueWindows?1:o?.92:.95,Oe=l.opaqueWindows?1:o?.94:.965,Ie=l.opaqueWindows?1:.94;return{"--theme-id":l.id,"--theme-code-theme-id":l.codeThemeId,"--theme-window-opaque":l.opaqueWindows?"1":"0","--theme-accent":ge,"--theme-accent-rgb":`${b.r} ${b.g} ${b.b}`,"--theme-background":l.background,"--theme-background-rgb":`${w.r} ${w.g} ${w.b}`,"--theme-foreground":l.foreground,"--theme-foreground-rgb":`${N.r} ${N.g} ${N.b}`,"--theme-shadow-rgb":o?"0 0 0":"39 28 17","--theme-ui-font":a.uiFontFamily,"--theme-code-font":a.codeFontFamily,"--theme-ui-font-size":`${a.uiFontSize}px`,"--theme-code-font-size":`${a.codeFontSize}px`,"--color-surface-base":j,"--color-surface-elevated":T,"--color-surface-panel":D,"--color-surface-raised":z,"--color-surface-panel-strong":I,"--color-surface-sidebar":Or(k,Oe),"--color-surface-sidebar-elevated":Or(P,Oe),"--color-surface-border":Q,"--color-surface-border-strong":se,"--color-surface-border-soft":W,"--color-surface-overlay":Or(I,je),"--color-surface-floating":Or(D,je),"--color-surface-tooltip":Or(U,Ie),"--color-surface-code":he,"--color-surface-code-muted":re,"--color-surface-code-gutter":L,"--color-surface-code-meta":ae,"--color-surface-inline-code":ie,"--color-surface-hover":ve,"--color-surface-pressed":Z,"--color-surface-danger-soft":Or(m,o?.14:.08),"--color-surface-success-soft":Or(f,o?.14:.08),"--color-text-primary":V,"--color-text-secondary":Y,"--color-text-muted":ee,"--color-text-tertiary":me,"--color-text-on-accent":q,"--color-text-link":ge,"--color-text-link-hover":te,"--color-text-danger":m,"--color-text-success":f,"--color-accent-primary":ge,"--color-accent-primary-soft":xe,"--color-accent-secondary":te,"--color-accent-secondary-soft":C,"--color-accent-contrast":q,"--color-accent-primary-rgb":`${b.r} ${b.g} ${b.b}`,"--color-success":f,"--color-warning":pt(l.accent,f,.35),"--color-danger":m,"--color-status-online":ge,"--color-status-offline":o?"#76808A":"#A5ACA4","--color-skill":y,"--color-skill-rgb":`${p.r} ${p.g} ${p.b}`,"--color-code-keyword":y,"--color-code-title":ge,"--color-code-string":pt(f,l.foreground,o?.26:.18),"--color-code-number":pt(y,ge,.36),"--color-code-comment":pt(l.foreground,l.background,o?.52:.72),"--color-code-meta-text":ke,"--color-code-add":f,"--color-code-add-rgb":`${g.r} ${g.g} ${g.b}`,"--color-code-add-bg":Or(f,o?.16:.11),"--color-code-remove":m,"--color-code-remove-rgb":`${S.r} ${S.g} ${S.b}`,"--color-code-remove-bg":Or(m,o?.18:.11),"--color-divider":Se,"--color-overlay-scrim":l.opaqueWindows?o?"rgba(8, 10, 12, 0.66)":"rgba(23, 20, 17, 0.14)":o?"rgba(8, 10, 12, 0.54)":"rgba(23, 20, 17, 0.09)","--shadow-soft":o?"0 24px 54px rgba(0, 0, 0, 0.34)":"0 24px 54px rgba(24, 18, 12, 0.08)","--shadow-panel":o?"0 10px 26px rgba(0, 0, 0, 0.24)":"0 10px 26px rgba(37, 23, 10, 0.06)","--shadow-sm":o?"0 2px 12px rgba(0, 0, 0, 0.18)":"0 2px 12px rgba(37, 23, 10, 0.05)","--shadow-overlay":o?"0 20px 44px rgba(0, 0, 0, 0.36)":"0 18px 40px rgba(42, 26, 12, 0.1)","--font-display":a.uiFontFamily,"--font-sans":a.uiFontFamily,"--font-mono":a.codeFontFamily,"--font-size-ui-base":`${a.uiFontSize}px`,"--font-size-code-base":`${a.codeFontSize}px`}},tx=(e,t=A_())=>{if(typeof document>"u")return;const a=Lr(e,t),l=bC(a,a.appearance),o=document.documentElement;o.dataset.theme=a.appearance,o.dataset.uiTheme=a.appearance,o.dataset.themeId=a.activeTheme.id,o.dataset.codeThemeId=a.activeTheme.codeThemeId,o.dataset.windowStyle=a.activeTheme.opaqueWindows?"opaque":"soft",o.style.colorScheme=a.appearance;for(const[u,f]of Object.entries(l))o.style.setProperty(u,f)},xC=async()=>{if(await yp().catch(()=>{}),"serviceWorker"in navigator){const t=await navigator.serviceWorker.getRegistrations();await Promise.all(t.map(a=>a.unregister()))}if("caches"in window){const t=await window.caches.keys();await Promise.all(t.map(a=>window.caches.delete(a)))}const e=window.indexedDB;if(typeof e.databases=="function"){const t=await e.databases();await Promise.all(t.map(a=>a.name).filter(a=>!!a).map(a=>new Promise(l=>{const o=e.deleteDatabase(a);o.onsuccess=()=>l(),o.onerror=()=>l(),o.onblocked=()=>l()})))}window.localStorage.clear(),window.sessionStorage.clear()},D_="panda:pwa-install-log",SC=48,Cs=e=>((e==null?void 0:e.trim())??"")||null,nx=()=>{if(typeof window>"u")return[];try{const e=window.localStorage.getItem(D_);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.map(a=>{if(!a||typeof a!="object")return null;const l=a;return typeof l.id!="string"||typeof l.timestamp!="string"||typeof l.kind!="string"||typeof l.message!="string"?null:{id:l.id,timestamp:l.timestamp,kind:l.kind,message:l.message,detail:Cs(l.detail)}}).filter(a=>!!a).sort((a,l)=>+new Date(l.timestamp)-+new Date(a.timestamp)):[]}catch{return[]}},jC=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(D_,JSON.stringify(e.slice(0,SC)))}catch{}},wC=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(D_)}catch{}},Pl=e=>{const t=nx(),a={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),kind:e.kind,message:e.message.trim(),detail:Cs(e.detail)};return jC([a,...t]),a},mb=(e,t)=>{var a;return((a=e.find(l=>l.kind===t))==null?void 0:a.timestamp)??null},NC=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()},kC=async e=>{try{let t=await fetch(e,{method:"HEAD",cache:"no-store"});return(t.status===405||t.status===501)&&(t=await fetch(e,{method:"GET",cache:"no-store"})),{ok:t.ok,status:t.status,error:null}}catch(t){return{ok:!1,status:null,error:t instanceof Error?t.message:"Unknown fetch failure"}}},EC=async()=>{if(typeof document>"u"||typeof window>"u")return{href:null,present:!1,ok:!1,error:"Document is unavailable.",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]};const e=document.querySelector('link[rel~="manifest"]'),t=Cs(e==null?void 0:e.href);if(!t)return{href:null,present:!1,ok:!1,error:"页面没有 manifest 链接。",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]};try{const a=await NC(t),l=Array.isArray(a.icons)?a.icons:[],o=await Promise.all(l.slice(0,8).map(async u=>{const f=u,m=Cs(typeof f.src=="string"?f.src:null);if(!m)return{src:"(missing)",purpose:Cs(typeof f.purpose=="string"?f.purpose:null),sizes:Cs(typeof f.sizes=="string"?f.sizes:null),type:Cs(typeof f.type=="string"?f.type:null),ok:!1,status:null,error:"Icon src is missing."};const y=new URL(m,t).toString(),g=await kC(y);return{src:y,purpose:Cs(typeof f.purpose=="string"?f.purpose:null),sizes:Cs(typeof f.sizes=="string"?f.sizes:null),type:Cs(typeof f.type=="string"?f.type:null),ok:g.ok,status:g.status,error:g.error}}));return{href:t,present:!0,ok:!0,error:null,id:Cs(typeof a.id=="string"?a.id:null),name:Cs(typeof a.name=="string"?a.name:null),shortName:Cs(typeof a.short_name=="string"?a.short_name:null),startUrl:Cs(typeof a.start_url=="string"?a.start_url:null),scope:Cs(typeof a.scope=="string"?a.scope:null),display:Cs(typeof a.display=="string"?a.display:null),displayOverride:Array.isArray(a.display_override)?a.display_override.filter(u=>typeof u=="string"):[],themeColor:Cs(typeof a.theme_color=="string"?a.theme_color:null),backgroundColor:Cs(typeof a.background_color=="string"?a.background_color:null),icons:o}}catch(a){return{href:t,present:!0,ok:!1,error:a instanceof Error?a.message:"Manifest fetch failed.",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]}}},CC=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return{supported:!1,controller:!1,registrations:[]};try{const e=await navigator.serviceWorker.getRegistrations();return{supported:!0,controller:!!navigator.serviceWorker.controller,registrations:e.map(t=>{var a,l,o;return{scope:t.scope,activeScriptUrl:((a=t.active)==null?void 0:a.scriptURL)??null,waitingScriptUrl:((l=t.waiting)==null?void 0:l.scriptURL)??null,installingScriptUrl:((o=t.installing)==null?void 0:o.scriptURL)??null}})}}catch{return{supported:!0,controller:!!navigator.serviceWorker.controller,registrations:[]}}},TC=e=>{const t=e.standaloneDisplayMode||e.navigatorStandalone;return t&&e.appInstalledSeen?{label:"较像已安装应用",confidence:"medium",detail:"当前页面正以独立窗口打开,并且这个站点记录到过 appinstalled 事件,更像是真正安装后的应用入口。"}:t?{label:"更像主屏幕快捷方式",confidence:"medium",detail:"当前页面虽然已脱离浏览器标签页,但站点本地没有观测到 appinstalled 事件,无法证明系统级安装已经完成,更像是主屏幕快捷方式。"}:e.installPromptAvailable?{label:"可触发安装流程",confidence:"high",detail:"浏览器已经提供 beforeinstallprompt 事件,设置页里的安装按钮可以主动弹出安装流程。"}:e.beforeInstallPromptSeen?{label:"浏览器曾允许安装",confidence:"low",detail:"站点历史上收到过 beforeinstallprompt,但当前页面没有可用的安装事件,可能需要刷新页面、重新访问或等待浏览器重新评估。"}:{label:"当前不像可安装应用",confidence:"medium",detail:"浏览器当前没有给出可用的安装事件,页面更像普通标签页或只能走“添加到主屏幕”的快捷方式链路。"}},RC=e=>{const t=[];if(e.secureContext||t.push("当前页面不是安全上下文,Chrome 不会提供完整的 PWA 安装链路。"),!e.manifest.present)t.push("页面没有 manifest 链接,浏览器无法把当前站点识别为可安装 Web App。");else if(!e.manifest.ok)t.push(`manifest 读取失败:${e.manifest.error??"未知错误"}。`);else{(!e.manifest.display||e.manifest.display==="browser")&&t.push("manifest 没有声明 standalone/minimal-ui 显示模式,浏览器更可能只给快捷方式。"),!e.manifest.name&&!e.manifest.shortName&&t.push("manifest 缺少 name/short_name,安装身份信息不完整。");const l=e.manifest.icons.some(f=>f.ok&&(f.sizes??"").includes("192x192")),o=e.manifest.icons.some(f=>f.ok&&(f.sizes??"").includes("512x512"));(!l||!o)&&t.push("manifest 图标里缺少可访问的 192x192 或 512x512 图标,Android 安装链路可能会退化。");const u=e.manifest.icons.filter(f=>!f.ok);u.length>0&&t.push(`有 ${u.length} 个 manifest 图标资源探测失败,安装时可能因为图标拉取失败而退化或失败。`)}return e.serviceWorker.supported?e.serviceWorker.registrations.length===0&&t.push("当前页面没有检测到 Service Worker 注册,Chrome 往往不会提供完整安装流程。"):t.push("当前浏览器不支持 Service Worker,无法满足完整的 PWA 安装条件。"),!e.installPromptAvailable&&!e.launchedStandalone&&e.secureContext&&e.manifest.ok&&e.serviceWorker.registrations.length>0&&t.push("浏览器当前没有下发 beforeinstallprompt,设置页按钮无法主动触发安装,只能走浏览器菜单的安装/添加到主屏幕入口。"),e.logs.find(l=>{var o;return l.kind==="install-choice"&&((o=l.detail)==null?void 0:o.toLowerCase().includes("accepted"))})&&!e.appInstalledSeen&&t.push("站点记录到用户接受过安装请求,但没有后续 appinstalled 事件,更像是浏览器回退成快捷方式,或系统级安装没有完成。"),e.launchedStandalone&&!e.appInstalledSeen&&t.push("当前虽然是独立窗口形态,但没有观测到 appinstalled,不能把它视为已经完成系统级安装。"),t},MC=async e=>{const t=nx(),[a,l]=await Promise.all([EC(),CC()]),o=navigator,u=typeof window<"u"&&window.matchMedia("(display-mode: standalone)").matches,f=o.standalone===!0,m=t.some(w=>w.kind==="beforeinstallprompt"),y=t.some(w=>w.kind==="appinstalled"),g=(e==null?void 0:e.installPromptAvailable)===!0,S=u||f,p=[];window.isSecureContext&&p.push("当前是安全上下文。"),a.ok&&p.push("manifest 可读取。"),l.registrations.length>0&&p.push(`检测到 ${l.registrations.length} 个 Service Worker 注册。`),g&&p.push("浏览器已提供可调用的安装事件。"),y&&p.push("站点本地记录到过 appinstalled 事件。");const b=["从桌面图标打开后,确认没有浏览器地址栏或标签栏。","到 Android“设置 -> 应用”里搜索 Panda,若能搜到,更像系统级安装。","到应用抽屉里搜索 Panda;若只在桌面可见而应用抽屉里没有,更像快捷方式。","如果日志里只有“添加到主屏幕”链路,没有 appinstalled,通常不能认定为真正安装完成。"];return{capturedAt:new Date().toISOString(),environment:{href:typeof window>"u"?null:window.location.href,origin:typeof window>"u"?null:window.location.origin,secureContext:typeof window<"u"?window.isSecureContext:!1,online:typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:null,userAgent:typeof navigator>"u"?null:navigator.userAgent,isAndroid:typeof navigator<"u"?/Android/i.test(navigator.userAgent):!1,standaloneDisplayMode:u,navigatorStandalone:f},promptState:{installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y,lastBeforeInstallPromptAt:mb(t,"beforeinstallprompt"),lastAppInstalledAt:mb(t,"appinstalled")},manifest:a,serviceWorker:l,assessment:TC({standaloneDisplayMode:u,navigatorStandalone:f,installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y}),failureReasons:RC({secureContext:typeof window<"u"?window.isSecureContext:!1,manifest:a,serviceWorker:l,installPromptAvailable:g,appInstalledSeen:y,launchedStandalone:S,logs:t}),successSignals:p,confirmationChecklist:b,logs:t}},AC=e=>{if(typeof window>"u")return()=>{};const t=l=>{(l.key===null||l.key===E_)&&e()},a=()=>{e()};return window.addEventListener("storage",t),window.addEventListener(M0,a),()=>{window.removeEventListener("storage",t),window.removeEventListener(M0,a)}},DC=()=>hh(),OC=()=>nd,O_=()=>_.useSyncExternalStore(AC,DC,OC);function I_(e){return ls(w3(e))}const sx=e=>{var t,a,l;return["codex-commands",((t=e==null?void 0:e.agentId)==null?void 0:t.trim())??"",((a=e==null?void 0:e.projectId)==null?void 0:a.trim())??"",((l=e==null?void 0:e.sessionId)==null?void 0:l.trim())??""]},ax=e=>{const t=(e==null?void 0:e.enabled)??!0;return ls({queryKey:sx(e==null?void 0:e.scope),enabled:t,queryFn:async()=>(await wn(e==null?void 0:e.scope)).client.getCodexCommands(),staleTime:0,gcTime:30*6e4,refetchOnWindowFocus:!1,retry:1})},pb=e=>{let t;const a=new Set,l=(g,S)=>{const p=typeof g=="function"?g(t):g;if(!Object.is(p,t)){const b=t;t=S??(typeof p!="object"||p===null)?p:Object.assign({},t,p),a.forEach(w=>w(t,b))}},o=()=>t,m={setState:l,getState:o,getInitialState:()=>y,subscribe:g=>(a.add(g),()=>a.delete(g))},y=t=e(l,o,m);return m},IC=(e=>e?pb(e):pb),LC=e=>e;function PC(e,t=LC){const a=qr.useSyncExternalStore(e.subscribe,qr.useCallback(()=>t(e.getState()),[e,t]),qr.useCallback(()=>t(e.getInitialState()),[e,t]));return qr.useDebugValue(a),a}const gb=e=>{const t=IC(e),a=l=>PC(t,l);return Object.assign(a,t),a},UC=(e=>e?gb(e):gb),_b=ex(),yb=A_(),ja=UC(e=>({panelTab:"git",composerText:"",activeSessionId:null,bottomNavVisible:!0,isSettingsOverlayOpen:!1,themeSettings:_b,systemAppearance:yb,resolvedTheme:Lr(_b,yb),setPanelTab:t=>e({panelTab:t}),setComposerText:t=>e({composerText:t}),setActiveSessionId:t=>e({activeSessionId:t}),setBottomNavVisible:t=>e({bottomNavVisible:t}),openSettingsOverlay:()=>e({isSettingsOverlayOpen:!0}),closeSettingsOverlay:()=>e({isSettingsOverlayOpen:!1}),setThemeMode:t=>e(a=>{const l=Fl({...a.themeSettings,mode:t});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setLightThemeId:t=>e(a=>{const l=Fl(hb(Ap(t).id,a.themeSettings,"light"));return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setDarkThemeId:t=>e(a=>{const l=Fl({...hb(Dp(t).id,a.themeSettings,"dark")});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setUiFontSize:t=>e(a=>{const l=Fl({...a.themeSettings,uiFontSize:t});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setCodeFontSize:t=>e(a=>{const l=Fl({...a.themeSettings,codeFontSize:t});return Sf(l),{themeSettings:l,resolvedTheme:Lr(l,a.systemAppearance)}}),setSystemAppearance:t=>e(a=>({systemAppearance:t,resolvedTheme:Lr(a.themeSettings,t)}))})),vb=980,wm=[{id:"theme",title:"主题",description:"调整界面的颜色风格。",icon:"theme"},{id:"models",title:"模型维护",description:"维护可选模型、默认模型和展示顺序。",icon:"models"},{id:"cache",title:"缓存",description:"解决页面没更新的问题。",icon:"cache"},{id:"notifications",title:"移动提醒",description:"安装到桌面,并在对话完成后接收系统通知。",icon:"notifications"},{id:"installation",title:"安装诊断",description:"判断当前是不是安装版,并分析为什么安装失败。",icon:"installation"},{id:"connection",title:"连接状态",description:"查看现在连到哪台设备。",icon:"connection"},{id:"dev-manager",title:"开发版管理",description:"维护开发版、npm 发布、自升级和 APK 编译下载。",icon:"dev-manager"}],zC=[{id:"appearance",label:"外观与模型",sections:["theme","models","cache"]},{id:"notifications",label:"提醒与安装",sections:["notifications","installation"]},{id:"connection",label:"连接与设备",sections:["connection","dev-manager"]}],BC=[{value:"light",label:"浅色",icon:"sun"},{value:"dark",label:"深色",icon:"moon"},{value:"system",label:"系统",icon:"system"}],HC=(e,t,a,l)=>["const pandaTheme = {",` codeThemeId: "${e}",`,` accent: "${t.toLowerCase()}",`,` contrast: ${a},`,` opaqueWindows: ${l},`,"}"],$C=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m15 6-6 6 6 6"})}),FC=({open:e})=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:e?"m6 9 6 6 6-6":"m9 6 6 6-6 6"})}),qC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01"})}),WC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M12 5v14M5 12h14"})}),KC=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m4 20 4.2-1 9.2-9.2a1.8 1.8 0 0 0 0-2.6l-.6-.6a1.8 1.8 0 0 0-2.6 0L5 15.8 4 20Z"}),i.jsx("path",{d:"m13.5 6.5 4 4"})]}),QC=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M4.5 7h15"}),i.jsx("path",{d:"M9.5 4.5h5"}),i.jsx("path",{d:"M7 7l.6 11a1.8 1.8 0 0 0 1.8 1.7h5.2a1.8 1.8 0 0 0 1.8-1.7L17 7"}),i.jsx("path",{d:"M10 10.5v5.2"}),i.jsx("path",{d:"M14 10.5v5.2"})]}),GC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m12 6-5 5M12 6l5 5M12 6v12"})}),YC=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m12 18-5-5M12 18l5-5M12 18V6"})}),bb=({icon:e})=>e==="cache"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M5 8.5C5 6.57 8.13 5 12 5s7 1.57 7 3.5S15.87 12 12 12 5 10.43 5 8.5Z"}),i.jsx("path",{d:"M5 8.5v7c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5v-7"}),i.jsx("path",{d:"M5 12c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5"})]}):e==="models"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M5 7.5h14M5 12h14M5 16.5h14"}),i.jsx("path",{d:"M8 5.5h.01M8 10h.01M8 14.5h.01"})]}):e==="connection"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9.5 14.5a3.5 3.5 0 0 1 0-5l1.5-1.5a3.5 3.5 0 0 1 5 5L15 14"}),i.jsx("path",{d:"M14.5 9.5a3.5 3.5 0 0 1 0 5L13 16a3.5 3.5 0 0 1-5-5L9 10"})]}):e==="dev-manager"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 3.75v4.5"}),i.jsx("path",{d:"M12 15.75v4.5"}),i.jsx("path",{d:"M3.75 12h4.5"}),i.jsx("path",{d:"M15.75 12h4.5"}),i.jsx("path",{d:"m6.7 6.7 3.1 3.1"}),i.jsx("path",{d:"m14.2 14.2 3.1 3.1"}),i.jsx("path",{d:"m17.3 6.7-3.1 3.1"}),i.jsx("path",{d:"m9.8 14.2-3.1 3.1"}),i.jsx("circle",{cx:"12",cy:"12",r:"2.9"})]}):e==="notifications"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6.5 9.5a5.5 5.5 0 0 1 11 0c0 5.25 1.9 6.83 1.9 6.83H4.6S6.5 14.75 6.5 9.5Z"}),i.jsx("path",{d:"M10 18.25a2.1 2.1 0 0 0 4 0"})]}):e==="installation"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 3.75v10.5"}),i.jsx("path",{d:"m8.5 10.75 3.5 3.5 3.5-3.5"}),i.jsx("path",{d:"M5.25 16.75h13.5"}),i.jsx("path",{d:"M6 19.25h12"})]}):i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 4.75v2.1M12 17.15v2.1M4.78 4.78l1.49 1.49M17.73 17.73l1.49 1.49M2.75 12h2.1M19.15 12h2.1M4.78 19.22l1.49-1.49M17.73 6.27l1.49-1.49"}),i.jsx("circle",{cx:"12",cy:"12",r:"3.85"})]}),VC=({icon:e,active:t})=>{const a=t?2:1.8;return e==="sun"?i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"4.1"}),i.jsx("path",{d:"M12 2.75v2.1M12 19.15v2.1M4.78 4.78l1.49 1.49M17.73 17.73l1.49 1.49M2.75 12h2.1M19.15 12h2.1M4.78 19.22l1.49-1.49M17.73 6.27l1.49-1.49"})]}):e==="moon"?i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M20.2 14.1A8.5 8.5 0 1 1 9.9 3.8a6.9 6.9 0 0 0 10.3 10.3Z"})}):i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"3.5",y:"5",width:"17",height:"12",rx:"2.4"}),i.jsx("path",{d:"M8 19h8"})]})},ZC=({title:e,caption:t,accent:a,background:l,foreground:o,lines:u})=>i.jsxs("div",{className:"theme-preview-panel",style:{"--preview-accent":a,"--preview-background":l,"--preview-foreground":o},children:[i.jsxs("div",{className:"theme-preview-panel__meta",children:[i.jsx("span",{children:e}),i.jsx("span",{children:t})]}),i.jsx("pre",{className:"theme-preview-panel__code","aria-label":`${e} 主题预览`,children:u.map(f=>i.jsx("code",{children:f},f))})]}),hu=({label:e,value:t})=>i.jsxs("div",{className:"settings-row settings-row--token",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsxs("div",{className:"theme-token",children:[i.jsx("span",{className:"theme-token__swatch",style:{"--token-color":t}}),i.jsx("span",{children:t})]})]}),Nm=({label:e,value:t})=>i.jsxs("div",{className:"settings-row settings-row--token",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsx("div",{className:"theme-token",children:t})]}),xb=({label:e,value:t,mono:a})=>i.jsxs("div",{className:"settings-row settings-row--token",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsx("div",{className:`theme-token theme-token--font ${a?"is-mono":""}`,children:t})]}),Sb=({label:e,value:t,onChange:a,min:l,max:o})=>i.jsxs("div",{className:"settings-row settings-row--size",children:[i.jsx("div",{className:"settings-row__copy",children:i.jsx("span",{className:"settings-row__label",children:e})}),i.jsxs("div",{className:"theme-stepper",children:[i.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>a(t-1),"aria-label":`${e} 减小 1px`,children:"-"}),i.jsxs("label",{className:"theme-stepper__input-wrap",children:[i.jsx("input",{className:"theme-stepper__input",type:"number",min:l,max:o,step:1,value:t,onChange:u=>a(Number(u.target.value))}),i.jsx("span",{children:"px"})]}),i.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>a(t+1),"aria-label":`${e} 增大 1px`,children:"+"})]})]}),jb=(e,t,a,l)=>{if(t===a)return e;const o=e.findIndex(S=>S.id===t),u=e.findIndex(S=>S.id===a);if(o<0||u<0)return e;const f=[...e],[m]=f.splice(o,1);if(!m)return e;const y=f.findIndex(S=>S.id===a),g=l==="before"?y:y+1;return f.splice(g,0,m),f},mu=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},km=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,Ng=async(e,t)=>{const a=await u0(t);return{label:e,...a}},ix=({mode:e="page",onRequestClose:t}={})=>{var yn,Zn;const a=ki(),l=La(),o=Mp(),{data:u}=I_(),[f,m]=_.useState(!1),[y,g]=_.useState(null),[S,p]=_.useState(null),[b,w]=_.useState("theme"),[N,j]=_.useState(null),[T,D]=_.useState(()=>typeof window<"u"&&window.innerWidth>=vb),[z,I]=_.useState(()=>N0()),[k,P]=_.useState(()=>Cu()),[Q,se]=_.useState(()=>ed()),[W,V]=_.useState(()=>E0()),[Y,ee]=_.useState(!1),[me,ge]=_.useState(!1),[te,xe]=_.useState(null),[C,q]=_.useState(!1),[ie,he]=_.useState(()=>Nu()),[re,L]=_.useState(()=>X4()),[ae,ke]=_.useState(0),U=ja(A=>A.themeSettings),ve=ja(A=>A.resolvedTheme),Z=ja(A=>A.systemAppearance),Se=ja(A=>A.setThemeMode),je=ja(A=>A.setLightThemeId),Oe=ja(A=>A.setDarkThemeId),Ie=ja(A=>A.setUiFontSize),wt=ja(A=>A.setCodeFontSize),qe=O_(),[bt,Ut]=_.useState(()=>R_()),[$t,zt]=_.useState(()=>qm()),[xt,it]=_.useState(()=>$3()),[ot,ln]=_.useState(null),[on,kn]=_.useState(()=>xf()),[En,ht]=_.useState(null),[Ve,Ke]=_.useState(null),[Nt,Bt]=_.useState(null),Jt=typeof window>"u"?null:pc(),Dt=typeof window>"u"?null:mp(),Ze=(u==null?void 0:u.agents.find(A=>A.id===Jt))??(u==null?void 0:u.agents[0]),un=((yn=Ze==null?void 0:Ze.direct_base_url)==null?void 0:yn.trim().replace(/\/+$/,""))??"",ut=o.platform!=="web",_e=b==="cache"||N==="cache",Fe=Ze!=null&&Ze.id?{agentId:Ze.id}:void 0,X=sx(Fe),B=ls({queryKey:["settings-connection",o.hubUrl,(Ze==null?void 0:Ze.id)??"",un],queryFn:async()=>{const A=await wn(),[le,tt,Ht]=await Promise.all([Ng(A.label,A.baseUrl),Ng("Panda Hub",id()),un?Ng((Ze==null?void 0:Ze.name)??"当前节点",un):Promise.resolve(null)]);return{modeLabel:A.mode==="hub"?"通过 Panda Hub":"直接连接",backendLabel:A.label,backendUrl:A.baseUrl,healthOk:le.healthOk,latencyMs:le.latencyMs,checkedAt:le.checkedAt,activeProbe:le,hubProbe:tt,agentProbe:Ht}},enabled:b==="connection"||N==="connection",staleTime:0,refetchOnWindowFocus:!1}),oe=ls({queryKey:["installed-app-info",o.platform],queryFn:()=>QE(),enabled:ut,staleTime:3e4,refetchOnWindowFocus:!1}),ue=ls({queryKey:["android-release-manifest",o.hubUrl],queryFn:()=>GE(o.hubUrl),enabled:o.platform==="android"&&!!o.hubUrl&&(b==="connection"||N==="connection"),staleTime:0,refetchOnWindowFocus:!1}),we=ax({enabled:_e&&!!Fe,scope:Fe}),Re=()=>{ke(A=>A+1)},He=ls({queryKey:["pwa-install-diagnostics",ae,!!te,ie],queryFn:async()=>MC({installPromptAvailable:!!te}),enabled:b==="installation"||N==="installation",staleTime:0,refetchOnWindowFocus:!1}),ze=Vn({mutationFn:async()=>{if(!Fe)throw new Error("当前没有可用节点,无法刷新命令目录。");return(await wn(Fe)).client.refreshCodexCommands()},onMutate:()=>{g(null)},onSuccess:A=>{l.setQueryData(X,A),g(`命令目录已刷新,共 ${A.commands.length} 条,CLI 版本 ${A.cli_version??"未知"}。`)},onError:A=>{g(A instanceof Error?A.message:"刷新命令目录失败。")}});_.useEffect(()=>{if(typeof window>"u")return;const A=()=>{const le=window.innerWidth>=vb;D(le)};return A(),window.addEventListener("resize",A),()=>{window.removeEventListener("resize",A)}},[]),_.useEffect(()=>{g(null)},[(Zn=B.data)==null?void 0:Zn.backendUrl]),_.useEffect(()=>{T&&j(b)},[b,T]),_.useEffect(()=>{ht(null)},[b]),_.useEffect(()=>{if(typeof window>"u")return;const A=Ht=>{Ht.preventDefault(),xe(Ht),Pl({kind:"beforeinstallprompt",message:"浏览器提供了可调用的安装事件。",detail:window.location.href}),Re()},le=()=>{xe(null),he(!0),p("应用已安装到桌面。"),Pl({kind:"appinstalled",message:"站点收到 appinstalled 事件。",detail:"浏览器报告安装流程已经完成或被接受。"}),Re()},tt=()=>{P(Cu()),I(N0()),he(Nu()),L(X4()),Pl({kind:"visibilitychange",message:`页面切换为 ${document.visibilityState}。`,detail:`standalone=${Nu()?"yes":"no"}`}),Re()};return window.addEventListener("beforeinstallprompt",A),window.addEventListener("appinstalled",le),document.addEventListener("visibilitychange",tt),()=>{window.removeEventListener("beforeinstallprompt",A),window.removeEventListener("appinstalled",le),document.removeEventListener("visibilitychange",tt)}},[]),_.useEffect(()=>{if(qe.length===0||qe.some(le=>le.value===bt))return;const A=qe[0].value;zf(A),Ut(A)},[qe,bt]),_.useEffect(()=>{var le;if(qe.length===0||qe.some(tt=>tt.value===$t))return;const A=((le=qe.find(tt=>tt.value==="gpt-5.4-mini"))==null?void 0:le.value)??qe[0].value;jg(A),zt(A)},[$t,qe]),_.useEffect(()=>{var le;if(qe.length===0||qe.some(tt=>tt.value===xt))return;const A=((le=qe.find(tt=>tt.value==="gpt-5.4-mini"))==null?void 0:le.value)??qe[0].value;wg(A),it(A)},[qe,xt]),_.useEffect(()=>{const A=()=>{j_().then(le=>{P(le)}).catch(()=>{P(Cu())}),se(ed()),V(E0())};return A(),window.addEventListener("focus",A),document.addEventListener("visibilitychange",A),()=>{window.removeEventListener("focus",A),document.removeEventListener("visibilitychange",A)}},[]),_.useEffect(()=>{if(k!=="granted"||!z.completionNotificationsEnabled||!Q)return;let A=!1;return ee(!0),Gk(z).then(le=>{A||V(le.synced)}).catch(()=>{A||V(!1)}).finally(()=>{A||ee(!1)}),()=>{A=!0}},[Q,k,z]);const rt=()=>{if(e==="overlay"){t==null||t();return}if(Dt){Ji((Ze==null?void 0:Ze.id)??null),Js(Dt),a({to:"/"});return}a({to:"/nodes"})},It=A=>{e==="overlay"&&(t==null||t()),a({to:A})},Ft=async()=>{g(null),m(!0);try{await xC(),g("缓存已清理,正在重新载入…"),window.setTimeout(()=>{window.location.replace(`/settings?cache-reset=${Date.now()}`)},180)}catch{m(!1),g("清理失败,请在浏览器设置中手动清理站点数据。")}},Le=async()=>{if(p(null),ut){if(k==="granted"){p("当前已经拿到系统通知权限;完成提醒会自动跟随系统权限生效。");return}const A=await k0();if(P(A),A==="granted"){const le={completionNotificationsEnabled:!0};Ho(le),I(le),p("系统通知已开启,后续任务完成会直接走原生通知。");return}if(A==="denied"){p("系统通知已被拒绝,请到系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(k!=="granted"){const A=await k0();if(P(A),A==="granted"){if(!Q){const le={completionNotificationsEnabled:!0};Ho(le),I(le),p(ut?"系统通知已开启,任务完成时会直接走原生通知。":"系统通知已开启,但当前环境不支持后台 Web Push。");return}ee(!0);try{const le={completionNotificationsEnabled:!0};await Z4(le),Ho(le),I(le),V(!0),p("系统通知和后台 Web Push 都已开启。");return}catch(le){V(!1),p(le instanceof Error?le.message:"通知权限已开启,但 Web Push 订阅失败。");return}finally{ee(!1)}}if(A==="denied"){p("系统通知已被拒绝,请到浏览器或系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(z.completionNotificationsEnabled){ee(!0);try{await Yk();const A={completionNotificationsEnabled:!1};Ho(A),I(A),V(!1),p("完成提醒已关闭,后台推送订阅也已移除。")}catch(A){p(A instanceof Error?A.message:"关闭 Web Push 订阅失败。")}finally{ee(!1)}return}if(!Q){const A={completionNotificationsEnabled:!0};Ho(A),I(A),p(ut?"原生通知已开启,后续会沿用当前 App 的在线事件提醒。":"当前环境不支持后台 Web Push,只能在页面在线时提醒。");return}ee(!0);try{const A={completionNotificationsEnabled:!0};await Z4(A),Ho(A),I(A),V(!0),p("完成提醒已开启,Hub 会在会话完成后推送到这台手机。")}catch(A){V(!1),p(A instanceof Error?A.message:"开启 Web Push 失败。")}finally{ee(!1)}},Et=async()=>{p(null),ge(!0);try{if(ut){await m3({sessionId:"settings-test",completedAt:new Date().toISOString(),title:"Panda 测试提醒",body:"这是一条来自 Android 壳的本地通知测试。",url:"/settings"}),p("测试通知已发出,请看当前设备的系统通知栏。");return}await Vk(),p("测试推送已发出,请看手机或当前设备的通知栏。")}catch(A){p(A instanceof Error?A.message:"发送测试推送失败。")}finally{ge(!1)}},Cn=async()=>{if(!te){Pl({kind:"install-unavailable",message:"当前页面没有可用的安装事件。",detail:re?"浏览器没有下发 beforeinstallprompt,只能走菜单里的安装应用或添加到主屏幕。":"当前浏览器没有提供可调用的安装对话框。"}),Re(),p(re?"请在浏览器菜单里选择“安装应用”或“添加到主屏幕”。":"当前浏览器没有提供安装弹窗,请使用浏览器的“添加到主屏幕”。");return}q(!0),p(null),Pl({kind:"install-button-click",message:"用户点击了设置页里的安装按钮。",detail:"准备调用浏览器安装对话框。"}),Re();try{Pl({kind:"install-prompt-shown",message:"已调用浏览器安装对话框。",detail:"等待用户在系统安装弹窗里做出选择。"}),await te.prompt();const A=await te.userChoice;Pl({kind:"install-choice",message:A.outcome==="accepted"?"用户接受了安装请求。":"用户取消了安装请求。",detail:`outcome=${A.outcome}; platform=${A.platform}`}),Re(),A.outcome==="accepted"?p("安装请求已提交,请回到桌面查看。"):p("你取消了这次安装。")}catch(A){Pl({kind:"install-error",message:"调用浏览器安装流程时报错。",detail:A instanceof Error?A.message:"Unknown install error"}),Re(),p("浏览器没有完成安装流程,请查看下方安装诊断。")}finally{xe(null),q(!1),he(Nu()),Re()}},hs=A=>{var le,tt,Ht,cn,mt;if(sC(A),!A.some(St=>St.value===bt)){const St=((le=A[0])==null?void 0:le.value)??"";St&&(zf(St),Ut(St))}if(!A.some(St=>St.value===$t)){const St=((tt=A.find(Rn=>Rn.value==="gpt-5.4-mini"))==null?void 0:tt.value)??((Ht=A[0])==null?void 0:Ht.value)??"";St&&(jg(St),zt(St))}if(!A.some(St=>St.value===xt)){const St=((cn=A.find(Rn=>Rn.value==="gpt-5.4-mini"))==null?void 0:cn.value)??((mt=A[0])==null?void 0:mt.value)??"";St&&(wg(St),it(St))}},na=()=>{ln("new"),kn(xf()),ht(null)},Ws=A=>{ln(A.id),kn({...A}),ht(null)},Ja=()=>{ln(null),kn(xf()),ht(null)},Rs=()=>{var mt;const A=on.label.trim(),le=on.value.trim();if(!A||!le){ht("请填写显示名和模型 ID。");return}if(qe.find(St=>St.value.toLowerCase()===le.toLowerCase()&&St.id!==ot)){ht(`模型 ID ${le} 已存在。`);return}const Ht={...on,label:A,value:le,description:((mt=on.description)==null?void 0:mt.trim())||null},cn=ot==="new"?[...qe,Ht]:qe.map(St=>St.id===ot?Ht:St);hs(cn),ln(null),kn(xf()),ht(ot==="new"?"模型已添加。":"模型已更新。")},Na=A=>{const le=qe.filter(tt=>tt.id!==A);if(le.length===0){ht("至少保留一个模型。");return}hs(le),ot===A&&(ln(null),kn(xf())),ht("模型已删除。")},Pa=A=>{zf(A),Ut(A),ht(`默认模型已切换为 ${A}。`)},ms=A=>{jg(A),zt(A),ht(`命令执行模型已切换为 ${A}。`)},dn=A=>{wg(A),it(A),ht(`标题生成模型已切换为 ${A}。`)},pn=(A,le)=>{const tt=qe.findIndex(mt=>mt.id===A);if(tt<0)return;const Ht=le==="up"?tt-1:tt+1;if(Ht<0||Ht>=qe.length)return;const cn=qe[Ht];cn&&hs(jb(qe,A,cn.id,le==="up"?"before":"after"))},Un=(A,le)=>{Ke(le),Bt(null),A.dataTransfer.effectAllowed="move",A.dataTransfer.setData("text/plain",le)},ps=(A,le)=>{if(!Ve||Ve===le)return;A.preventDefault();const tt=A.currentTarget.getBoundingClientRect(),Ht=A.clientY<tt.top+tt.height/2?"before":"after";Bt(cn=>(cn==null?void 0:cn.modelId)===le&&cn.position===Ht?cn:{modelId:le,position:Ht})},Ps=A=>{!Ve||!Nt||Nt.modelId!==A||(hs(jb(qe,Ve,A,Nt.position)),Ke(null),Bt(null))},Us=()=>{Ke(null),Bt(null)},Ms=ve.appearance,xs=Ms==="light"?A0:Jf,As=Ms==="light"?U.lightThemeId:U.darkThemeId,Rt=xs.find(A=>A.id===As)??xs[0],J=ve.activeTheme,M=HC(Rt.codeThemeId,Rt.accent,Rt.contrast,Rt.opaqueWindows),G=U.mode==="system"?`当前跟随系统:${Z==="dark"?"深色":"浅色"}`:`当前固定为${ve.appearance==="dark"?"深色":"浅色"}模式`,Ee="当前正在显示",De=Rt.opaqueWindows?"不透明窗口":"半透明窗口",Pe=wm.find(A=>A.id===b)??wm[0],$e={"--settings-mobile-sticky-safe-area":ut?"0px":"var(--app-safe-area-top)"},Je=`${Rt.label} · ${De} · 对比度 ${Rt.contrast}`,Ye=qe.find(A=>A.value===bt)??qe[0]??null,en=qe.find(A=>A.value===$t)??qe.find(A=>A.value==="gpt-5.4-mini")??qe[0]??null,jt=qe.find(A=>A.value===xt)??qe.find(A=>A.value==="gpt-5.4-mini")??qe[0]??null,$n=A=>{var le;return A==="theme"?ve.activeTheme.label:A==="models"?(Ye==null?void 0:Ye.label)??`${qe.length} 个模型`:A==="cache"?y||(we.data?`${we.data.commands.length} 条命令`:"站点与命令目录"):A==="notifications"?z.completionNotificationsEnabled?"已开启":"未开启":A==="installation"?ie?"已安装":"检查状态":(le=B.data)!=null&&le.healthOk?B.data.modeLabel:(Ze==null?void 0:Ze.name)??"查看链路"},gn=()=>i.jsx("div",{className:"settings-mobile-layout",children:i.jsx("div",{className:"settings-mobile-sections",role:"list","aria-label":"设置分组",children:zC.map(A=>i.jsx("section",{className:"settings-mobile-group","aria-label":A.label,children:A.sections.map(le=>{const tt=wm.find(mt=>mt.id===le);if(!tt)return null;const Ht=N===tt.id,cn=$n(tt.id);return i.jsxs(_.Fragment,{children:[i.jsxs("button",{type:"button",className:`settings-mobile-row ${Ht?"is-active":""}`,"data-section":tt.id,onClick:()=>{w(tt.id),j(mt=>mt===tt.id?null:tt.id)},"aria-expanded":Ht,"aria-controls":`settings-mobile-detail-${tt.id}`,children:[i.jsx("span",{className:"settings-mobile-row__icon","data-section":tt.id,"aria-hidden":"true",children:i.jsx(bb,{icon:tt.icon})}),i.jsx("span",{className:"settings-mobile-row__copy",children:i.jsx("span",{className:"settings-mobile-row__title",children:tt.title})}),i.jsx("span",{className:"settings-mobile-row__summary",children:cn}),i.jsx("span",{className:"settings-mobile-row__chevron","aria-hidden":"true",children:i.jsx(FC,{open:!1})})]}),Ht?i.jsx("section",{className:"settings-mobile-detail settings-mobile-detail--inline",id:`settings-mobile-detail-${tt.id}`,children:qt(tt.id)}):null]},tt.id)})},A.id))})}),bn=()=>i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsxs("div",{children:[i.jsx("h3",{className:"settings-panel__title",children:"外观"}),i.jsx("p",{className:"settings-panel__subtitle",children:"先选浅色或深色,再挑一个你喜欢的风格。"})]})}),i.jsx("div",{className:"settings-control-grid",children:i.jsxs("div",{className:"settings-control-block settings-control-block--full",children:[i.jsx("span",{className:"settings-control-block__label",children:"显示方式"}),i.jsx("div",{className:"theme-mode-switch",role:"tablist","aria-label":"主题模式",children:BC.map(A=>{const le=A.value===U.mode;return i.jsxs("button",{type:"button",className:`theme-mode-switch__button ${le?"is-active":""}`,onClick:()=>Se(A.value),role:"tab","aria-selected":le,children:[i.jsx(VC,{icon:A.icon,active:le}),i.jsx("span",{children:A.label})]},A.value)})}),i.jsx("p",{className:"settings-control-block__hint",children:G})]})})]}),i.jsxs("div",{className:"settings-theme-layout",children:[i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:Ms==="light"?"浅色风格":"深色风格"})})}),i.jsxs("div",{className:"settings-theme-selector",children:[i.jsx("label",{className:"settings-select settings-select--wide",children:i.jsx("select",{value:Rt.id,onChange:A=>{if(Ms==="light"){je(A.target.value);return}Oe(A.target.value)},"aria-label":Ms==="light"?"选择浅色主题":"选择深色主题",children:xs.map(A=>i.jsx("option",{value:A.id,children:A.label},`${A.variant}-${A.id}`))})}),i.jsxs("div",{className:"settings-theme-selector__summary",children:[i.jsxs("div",{className:"settings-theme-selector__swatches","aria-hidden":"true",children:[i.jsx("span",{style:{"--theme-card-color":Rt.background}}),i.jsx("span",{style:{"--theme-card-color":Rt.foreground}}),i.jsx("span",{style:{"--theme-card-color":Rt.accent}}),i.jsx("span",{style:{"--theme-card-color":Rt.semanticColors.diffAdded}}),i.jsx("span",{style:{"--theme-card-color":Rt.semanticColors.diffRemoved}})]}),i.jsxs("div",{className:"settings-theme-selector__copy",children:[i.jsx("strong",{children:Rt.label}),i.jsx("span",{children:Je})]}),Rt.id===J.id&&Rt.variant===ve.appearance?i.jsx("span",{className:"settings-theme-selector__badge",children:"当前"}):i.jsx("span",{className:"settings-theme-selector__badge is-muted",children:"已选"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"风格细节"})}),i.jsx("div",{className:"theme-status-badge",children:Ee})]}),i.jsx(ZC,{title:Ms==="light"?"浅色预览":"深色预览",caption:Rt.label,accent:Rt.accent,background:Rt.background,foreground:Rt.foreground,lines:M}),i.jsxs("div",{className:"settings-list",children:[i.jsx(Nm,{label:"代码风格",value:Rt.codeThemeId}),i.jsx(Nm,{label:"当前模式",value:Rt.variant}),i.jsx(Nm,{label:"对比度",value:String(Rt.contrast)}),i.jsx(Nm,{label:"面板质感",value:De}),i.jsx(hu,{label:"强调色",value:Rt.accent}),i.jsx(hu,{label:"背景色",value:Rt.background}),i.jsx(hu,{label:"文字色",value:Rt.foreground}),i.jsx(hu,{label:"新增颜色",value:Rt.semanticColors.diffAdded}),i.jsx(hu,{label:"删除颜色",value:Rt.semanticColors.diffRemoved}),i.jsx(hu,{label:"特殊强调",value:Rt.semanticColors.skill}),i.jsx(xb,{label:"界面字体",value:Rt.fonts.ui??"null"}),i.jsx(xb,{label:"代码字体",value:Rt.fonts.code??"null",mono:!0})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"字号"})})}),i.jsxs("div",{className:"settings-list",children:[i.jsx(Sb,{label:"界面字号",value:U.uiFontSize,onChange:A=>Ie(X3(A)),min:11,max:18}),i.jsx(Sb,{label:"代码字号",value:U.codeFontSize,onChange:A=>wt(J3(A)),min:10,max:18})]})]})]}),Tn=()=>{var A;return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"模型列表"})}),i.jsxs("button",{type:"button",className:"settings-inline-action",onClick:na,children:[i.jsx(WC,{}),"新增模型"]})]}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"首位模型"}),i.jsx("strong",{children:((A=qe[0])==null?void 0:A.label)??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前默认"}),i.jsx("strong",{children:(Ye==null?void 0:Ye.label)??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"命令执行模型"}),i.jsx("strong",{children:(en==null?void 0:en.label)??"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"标题生成模型"}),i.jsx("strong",{children:(jt==null?void 0:jt.label)??"未配置"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"模型角色"})})}),i.jsxs("div",{className:"settings-model-editor__grid",children:[i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"默认模型"}),i.jsx("select",{value:bt,onChange:le=>Pa(le.target.value),children:qe.map(le=>i.jsx("option",{value:le.value,children:le.label},le.id))})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"命令执行模型"}),i.jsx("select",{value:$t,onChange:le=>ms(le.target.value),children:qe.map(le=>i.jsx("option",{value:le.value,children:le.label},le.id))})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"标题生成模型"}),i.jsx("select",{value:xt,onChange:le=>dn(le.target.value),children:qe.map(le=>i.jsx("option",{value:le.value,children:le.label},le.id))})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"维护模型"})})}),En?i.jsx("div",{className:"settings-inline-status",role:"alert",children:En}):null,i.jsx("div",{className:"settings-model-list",role:"list","aria-label":"模型列表",children:qe.map((le,tt)=>{const Ht=Ve===le.id,cn=(Nt==null?void 0:Nt.modelId)===le.id&&Nt.position==="before",mt=(Nt==null?void 0:Nt.modelId)===le.id&&Nt.position==="after",St=le.value===bt;return i.jsxs("article",{className:`settings-model-card ${Ht?"is-dragging":""} ${cn?"is-drop-before":""} ${mt?"is-drop-after":""}`,draggable:!0,onDragStart:Rn=>Un(Rn,le.id),onDragOver:Rn=>ps(Rn,le.id),onDrop:Rn=>{Rn.preventDefault(),Ps(le.id)},onDragEnd:Us,role:"listitem",children:[i.jsxs("div",{className:"settings-model-card__main",children:[i.jsx("span",{className:"settings-model-card__grip","aria-hidden":"true",children:i.jsx(qC,{})}),i.jsxs("div",{className:"settings-model-card__copy",children:[i.jsxs("div",{className:"settings-model-card__title-row",children:[i.jsx("strong",{children:le.label}),St?i.jsx("span",{className:"settings-model-card__badge",children:"默认"}):null]}),i.jsx("code",{className:"settings-model-card__value",children:le.value})]})]}),i.jsxs("div",{className:"settings-model-card__actions",children:[i.jsx("button",{type:"button",className:`settings-mini-button settings-model-card__primary-action ${St?"is-active":""}`,onClick:()=>Pa(le.value),children:"设为默认"}),i.jsxs("div",{className:"settings-model-card__icon-actions",children:[i.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>pn(le.id,"up"),disabled:tt===0,"aria-label":`上移 ${le.label}`,children:i.jsx(GC,{})}),i.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>pn(le.id,"down"),disabled:tt===qe.length-1,"aria-label":`下移 ${le.label}`,children:i.jsx(YC,{})}),i.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Ws(le),"aria-label":`编辑 ${le.label}`,children:i.jsx(KC,{})}),i.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>Na(le.id),disabled:qe.length<=1,"aria-label":`删除 ${le.label}`,children:i.jsx(QC,{})})]})]})]},le.id)})}),ot?i.jsxs("div",{className:"settings-model-editor",children:[i.jsx("div",{className:"settings-model-editor__header",children:i.jsx("strong",{children:ot==="new"?"新增模型":"编辑模型"})}),i.jsxs("div",{className:"settings-model-editor__grid",children:[i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"显示名"}),i.jsx("input",{type:"text",value:on.label,onChange:le=>kn(tt=>({...tt,label:le.target.value})),placeholder:"例如:gpt-5.4"})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"模型 ID"}),i.jsx("input",{type:"text",value:on.value,onChange:le=>kn(tt=>({...tt,value:le.target.value})),placeholder:"例如:gpt-5.4"})]})]}),i.jsxs("div",{className:"settings-model-editor__actions",children:[i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:Ja,children:"取消"}),i.jsx("button",{type:"button",className:"settings-inline-action",onClick:Rs,children:"保存"})]})]}):null]})]})},xn=()=>{var A,le;return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"页面缓存"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"适合什么时候用"}),i.jsx("strong",{children:"页面资源或本地缓存异常"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"常见表现"}),i.jsx("strong",{children:"样式没更新、列表卡旧、页面反复异常"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"清理缓存"})})}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Ft(),disabled:f,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:"清理并刷新"}),i.jsx("span",{children:"删除页面资源缓存和本地会话缓存,强制重新加载最新页面。"})]}),i.jsx("span",{className:"settings-action__state",children:f?"处理中…":"→"})]}),y?i.jsx("p",{className:"settings-block__status",children:y}):null]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"移动端诊断"})})}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>It("/diagnostics"),children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:"打开安卓诊断页"}),i.jsx("span",{children:"在手机上检查样式能力、资源加载、Service Worker 和缓存状态,并可上传到后端日志。"})]}),i.jsx("span",{className:"settings-action__state",children:"→"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"命令目录缓存"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 CLI"}),i.jsx("span",{children:((A=we.data)==null?void 0:A.cli_version)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近刷新"}),i.jsx("span",{children:((le=we.data)==null?void 0:le.loaded_at)??"尚未生成"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"命令数量"}),i.jsx("span",{children:we.data?`${we.data.commands.length} 条`:"检测中…"})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void ze.mutateAsync(),disabled:ze.isPending,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:"刷新命令目录"}),i.jsx("span",{children:"重新从当前 Codex CLI 对应版本拉取命令并覆盖本地缓存文件。"})]}),i.jsx("span",{className:"settings-action__state",children:ze.isPending?"刷新中…":"→"})]})]})]})},zn=()=>{var mt,St,Rn,Ks,ei,zs,Qs,ka,ti,nr,ni,Gs,si,ai,sa,aa,ii,sr,ri,Ds,Bs,ar;const A=oe.data,le=ue.data,tt=!!(le!=null&&le.apk_url),Ht=VE(A,le),cn=A3(o.hubUrl);return i.jsxs("div",{className:"settings-content-stack",children:[ut?i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"Hub 连接配置"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前 Hub"}),i.jsx("strong",{children:o.hubUrl||"未配置"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"首启状态"}),i.jsx("strong",{children:o.onboardingCompleted?"已完成":"未完成"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"App 形态"}),i.jsx("strong",{children:"Capacitor Android"})]})]})]}):i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"网页端连接基线"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前网页入口"}),i.jsx("strong",{children:o.hubUrl||"未检测到"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"地址来源"}),i.jsx("strong",{children:"浏览器访问地址"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"缓存策略"}),i.jsx("strong",{children:"同源页面 + 本地查询缓存"})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:ut?"重新设置 Hub":"当前访问方式"})})}),ut?i.jsx(d6,{title:"输入新的 Hub 地址",description:"扫码或手动输入后,保存即可让 APK 用新地址重新建立连接。",currentHubUrl:o.hubUrl,initialHubUrl:o.hubUrl,hint:"保存后会清理旧的查询缓存、会话定位和连接判定缓存,避免继续误连到旧 Hub。",saveLabel:"保存并重连",savingLabel:"正在保存地址",saveDescription:"新的 Hub 地址会持久化到本机,后续重新打开 APK 会继续沿用。",saveSuccessMessage:"Hub 地址已保存,连接缓存和旧会话定位已重置。",onSaveSuccess:async ia=>{await q6({hubUrl:ia.url,onboardingCompleted:!0}),await v3(l),B.refetch(),ue.refetch(),oe.refetch()}}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Hub 地址"}),i.jsx("span",{children:o.hubUrl||"未检测到"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"可修改性"}),i.jsx("span",{children:"网页端跟随浏览器打开的地址,不额外保存本地覆盖配置。"})]})]})]}),o.platform==="android"?i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"App 升级"})}),i.jsx("div",{className:"settings-actions-row",children:i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{oe.refetch(),ue.refetch()},children:"刷新版本"})})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前版本"}),i.jsx("span",{children:(A==null?void 0:A.version)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 build"}),i.jsx("span",{children:(A==null?void 0:A.build)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"应用包名"}),i.jsx("span",{children:(A==null?void 0:A.appId)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"更新清单"}),i.jsx("span",{children:cn||"等待 Hub 地址"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最新发布"}),i.jsx("span",{children:ue.isLoading?"检测中…":le?`${le.version_name} (${le.version_code})`:ue.error instanceof Error?ue.error.message:"未检测到"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"升级状态"}),i.jsx("span",{className:Ht?"is-ok":"is-muted",children:Ht?"发现新版本":tt?"当前已是最新":"等待发布 APK"})]}),le!=null&&le.published_at?i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"发布时间"}),i.jsx("span",{children:mu(le.published_at)})]}):null,i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>{le!=null&&le.apk_url&&ZE(le.apk_url)},disabled:!(le!=null&&le.apk_url),children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:Ht?"下载并覆盖安装新版 APK":"打开最新 APK 下载地址"}),i.jsx("span",{children:"通过同一个 `applicationId` 和固定签名覆盖安装,旧配置和本地数据会保留,不需要卸载重装。"})]}),i.jsx("span",{className:"settings-action__state",children:le!=null&&le.apk_url?"→":"未就绪"})]}),le!=null&&le.release_notes.length?i.jsx("div",{className:"settings-diagnostic-list",children:le.release_notes.map(ia=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsx("strong",{children:"发布说明"}),i.jsx("span",{children:ia})]},ia))}):null]}):null,i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"当前设备"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"设备名称"}),i.jsx("strong",{children:(Ze==null?void 0:Ze.name)??"未选择节点"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"连接方式"}),i.jsx("strong",{children:((mt=B.data)==null?void 0:mt.modeLabel)??"检测中…"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前链路延迟"}),i.jsx("strong",{className:(St=B.data)!=null&&St.healthOk?"is-ok":"is-muted",children:B.isLoading?"检测中…":km((Rn=B.data)==null?void 0:Rn.latencyMs)})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"当前链路"})}),i.jsx("div",{className:"settings-actions-row",children:i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{B.refetch()},children:"刷新延迟"})})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"服务名称"}),i.jsx("span",{children:((Ks=B.data)==null?void 0:Ks.backendLabel)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"服务地址"}),i.jsx("span",{children:((ei=B.data)==null?void 0:ei.backendUrl)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前状态"}),i.jsx("span",{className:(zs=B.data)!=null&&zs.healthOk?"is-ok":"is-muted",children:B.isLoading?"检测中…":(Qs=B.data)!=null&&Qs.healthOk?"在线":((ka=B.data)==null?void 0:ka.activeProbe.error)??"无法连接"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前延迟"}),i.jsx("span",{children:km((ti=B.data)==null?void 0:ti.latencyMs)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近探测"}),i.jsx("span",{children:mu((nr=B.data)==null?void 0:nr.checkedAt)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"设备标识"}),i.jsx("span",{children:(Ze==null?void 0:Ze.id)??"未选择节点"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近会话"}),i.jsx("span",{children:Dt??"未选择会话"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"延迟对比"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Hub 延迟"}),i.jsx("span",{children:km((ni=B.data)==null?void 0:ni.hubProbe.latencyMs)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Hub 状态"}),i.jsx("span",{className:(Gs=B.data)!=null&&Gs.hubProbe.healthOk?"is-ok":"is-muted",children:(si=B.data)!=null&&si.hubProbe.healthOk?"在线":((ai=B.data)==null?void 0:ai.hubProbe.error)??"无法连接"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Hub 地址"}),i.jsx("span",{children:((sa=B.data)==null?void 0:sa.hubProbe.url)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Agent 延迟"}),i.jsx("span",{children:km((ii=(aa=B.data)==null?void 0:aa.agentProbe)==null?void 0:ii.latencyMs)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Agent 状态"}),i.jsx("span",{className:(ri=(sr=B.data)==null?void 0:sr.agentProbe)!=null&&ri.healthOk?"is-ok":"is-muted",children:(Ds=B.data)!=null&&Ds.agentProbe?B.data.agentProbe.healthOk?"在线":B.data.agentProbe.error??"无法连接":"未选择节点"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前 Agent 地址"}),i.jsx("span",{children:((ar=(Bs=B.data)==null?void 0:Bs.agentProbe)==null?void 0:ar.url)||un||"未配置"})]})]})]})},Ss=()=>{const A=ut?"原生 APK":ie?"已安装":"未安装",le=k==="granted"?"已允许":k==="denied"?"已拒绝":k==="default"?"待授权":"不支持",tt=ut?k==="granted"?"原生通知":"等待授权":Q?Y?"同步中":W?"已连接":z.completionNotificationsEnabled&&k==="granted"?"待连接":"未连接":"不支持",Ht=ut?k==="granted"?"已开启":"待授权":k==="granted"&&z.completionNotificationsEnabled?W?"后台可达":Q?"前台兜底":"仅前台":"未开启",cn=ut?"原生系统通知":Q?W?"Hub Web Push + 系统通知":"系统通知,后台通道待建立":"系统通知(仅页面在线)",mt=ut?k==="granted"?"通常可见,细节取决于系统设置":"先授予通知权限":W?ie?"已具备条件":"大多可见,安装后更稳":Q?"先建立后台通道":"当前环境很难稳定锁屏提醒",St=k==="unsupported"||!ut&&Y,Rn=ut?k==="granted"?"系统通知已开启":"申请通知权限":k==="granted"&&z.completionNotificationsEnabled?"关闭完成提醒":Y?"正在建立后台提醒":"开启完成提醒",Ks=k==="unsupported"?"当前环境不支持系统通知,需要 HTTPS、Service Worker 和受支持浏览器。":ut?k==="granted"?"首次连接时也会自动申请;这里主要用于补检查权限状态。":"如果首次连接时错过了授权,这里可以补申请一次。":Q?"开启后会向 Hub 注册这台设备,后台或锁屏时也能收到完成提醒。":"当前环境只能在页面在线时提醒,建议安装到桌面并使用支持 Web Push 的浏览器。",ei=ut?k==="unsupported"?"不可用":k==="granted"?"已开启":"→":k==="unsupported"?"不可用":Y?"同步中…":k==="granted"&&z.completionNotificationsEnabled?W?"已连接":Q?"待连接":"已开启":"→",zs=ut?k==="granted":k==="granted"&&z.completionNotificationsEnabled&&W&&!Y,Qs=ut?"直接在当前 APK 里发一条本地测试通知,确认系统权限和展示链路正常。":W?"立刻让 Hub 给当前这台设备发一条测试通知,用来确认后台链路是否真的可达。":"只有当前设备已经完成 Web Push 注册后,才能发送测试通知。";return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"安卓优先提醒"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"桌面安装"}),i.jsx("strong",{children:A})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"系统通知权限"}),i.jsx("strong",{children:le})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"完成提醒"}),i.jsx("strong",{children:Ht})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"后台 Web Push"}),i.jsx("strong",{children:tt})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:ut?"当前交付形态":"安装到桌面"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"推荐平台"}),i.jsx("span",{children:ut?"当前已经是 Android APK":re?"Android 当前设备":"Android 效果最佳"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前形态"}),i.jsx("span",{children:ut?"本地前端壳 + 局域网后端":ie?"已是桌面应用":"浏览器标签页"})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Cn(),disabled:ut||ie||C,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:ut?"已经是可安装 APK":ie?"已经安装":"安装到桌面"}),i.jsx("span",{children:ut?"当前无需再走 PWA 安装链路,后续升级直接下载新版 APK 覆盖安装即可。":ie?"现在可以直接从桌面图标进入 Panda。":"安装后更像应用,系统通知和锁屏提醒也更稳定。"})]}),i.jsx("span",{className:"settings-action__state",children:ut||ie?"✓":C?"处理中…":"→"})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"对话完成提醒"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"提醒方式"}),i.jsx("span",{children:cn})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"锁屏可见"}),i.jsx("span",{children:mt})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"后台通道"}),i.jsx("span",{children:tt})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"触发时机"}),i.jsx("span",{children:ut?"App 在线时收到完成事件后,直接发原生系统通知":Q?"Hub 收到对话完成后主动推送":"页面在线时收到完成事件后提醒"})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Le(),disabled:St,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:Rn}),i.jsx("span",{children:Ks})]}),i.jsx("span",{className:"settings-action__state",children:ei})]}),i.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Et(),disabled:!zs||me,children:[i.jsxs("div",{className:"settings-action__copy",children:[i.jsx("strong",{children:ut?me?"正在发送测试通知":"发送测试通知":me?"正在发送测试推送":"发送测试推送"}),i.jsx("span",{children:Qs})]}),i.jsx("span",{className:"settings-action__state",children:me?"发送中…":zs?"→":"未就绪"})]}),S?i.jsx("p",{className:"settings-block__status",children:S}):null]})]})},_n=()=>{const A=He.data,le=A!=null&&A.promptState.installPromptAvailable?"可主动触发":A!=null&&A.promptState.beforeInstallPromptSeen?"本地曾出现":"未出现",tt=A!=null&&A.promptState.appInstalledSeen?"记录到过":"未记录到",Ht=A!=null&&A.manifest.ok?"正常":A!=null&&A.manifest.present?"读取失败":"缺失",cn=A!=null&&A.serviceWorker.registrations.length?`${A.serviceWorker.registrations.length} 个注册`:A!=null&&A.serviceWorker.supported?"未注册":"不支持";return i.jsxs("div",{className:"settings-content-stack",children:[i.jsxs("section",{className:"settings-panel settings-panel--hero",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"安装结果判断"})})}),i.jsxs("div",{className:"settings-summary-strip",children:[i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"当前研判"}),i.jsx("strong",{children:(A==null?void 0:A.assessment.label)??"检测中…"})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"安装事件"}),i.jsx("strong",{children:le})]}),i.jsxs("div",{className:"settings-summary-strip__item",children:[i.jsx("span",{children:"appinstalled"}),i.jsx("strong",{children:tt})]})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsxs("div",{className:"settings-panel__header",children:[i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"当前状态"})}),i.jsxs("div",{className:"settings-actions-row",children:[i.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{He.refetch()},children:"刷新诊断"}),i.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{wC(),Re()},children:"清空日志"})]})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前窗口形态"}),i.jsx("span",{children:A?A.environment.standaloneDisplayMode||A.environment.navigatorStandalone?"独立窗口 / 主屏幕入口":"浏览器标签页":"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"系统级安装研判"}),i.jsx("span",{children:(A==null?void 0:A.assessment.label)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"研判置信度"}),i.jsx("span",{children:(A==null?void 0:A.assessment.confidence)??"检测中…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前说明"}),i.jsx("span",{children:(A==null?void 0:A.assessment.detail)??"正在分析…"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近抓取时间"}),i.jsx("span",{children:mu(A==null?void 0:A.capturedAt)})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"PWA 条件与安装信号"})})}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"安全上下文"}),i.jsx("span",{children:A!=null&&A.environment.secureContext?"是":"否"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"manifest"}),i.jsx("span",{children:Ht})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"manifest display"}),i.jsx("span",{children:(A==null?void 0:A.manifest.display)??"未声明"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"Service Worker"}),i.jsx("span",{children:cn})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"当前可主动触发安装"}),i.jsx("span",{children:A!=null&&A.promptState.installPromptAvailable?"可以":"不可以"})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近 beforeinstallprompt"}),i.jsx("span",{children:mu(A==null?void 0:A.promptState.lastBeforeInstallPromptAt)})]}),i.jsxs("div",{className:"settings-meta",children:[i.jsx("span",{children:"最近 appinstalled"}),i.jsx("span",{children:mu(A==null?void 0:A.promptState.lastAppInstalledAt)})]})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"为什么当前可能安装失败"})})}),He.isLoading?i.jsx("p",{className:"settings-block__status",children:"正在收集安装诊断…"}):A!=null&&A.failureReasons.length?i.jsx("div",{className:"settings-diagnostic-list",children:A.failureReasons.map((mt,St)=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsxs("strong",{children:["原因 ",St+1]}),i.jsx("span",{children:mt})]},`${St}-${mt}`))}):i.jsx("p",{className:"settings-block__status",children:"当前没有发现明显的前端侧阻断条件;如果仍无法完成系统级安装,更像是浏览器策略、安装链路回退或平台侧判断导致。"})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"成功信号与人工确认"})})}),A!=null&&A.successSignals.length?i.jsx("div",{className:"settings-diagnostic-list",children:A.successSignals.map((mt,St)=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsxs("strong",{children:["信号 ",St+1]}),i.jsx("span",{children:mt})]},`${St}-${mt}`))}):null,i.jsx("div",{className:"settings-diagnostic-list",children:(A==null?void 0:A.confirmationChecklist.map((mt,St)=>i.jsxs("div",{className:"settings-diagnostic-list__item",children:[i.jsxs("strong",{children:["确认 ",St+1]}),i.jsx("span",{children:mt})]},`${St}-${mt}`)))??null})]}),i.jsxs("section",{className:"settings-panel",children:[i.jsx("div",{className:"settings-panel__header",children:i.jsx("div",{children:i.jsx("h3",{className:"settings-panel__title",children:"浏览器安装事件日志"})})}),He.isLoading?i.jsx("p",{className:"settings-block__status",children:"正在读取日志…"}):A!=null&&A.logs.length?i.jsx("div",{className:"settings-log-list",children:A.logs.map(mt=>i.jsxs("article",{className:"settings-log-item",children:[i.jsxs("div",{className:"settings-log-item__meta",children:[i.jsx("strong",{children:mt.message}),i.jsx("span",{children:mu(mt.timestamp)})]}),i.jsx("div",{className:"settings-log-item__kind",children:mt.kind}),mt.detail?i.jsx("pre",{className:"settings-log-item__detail",children:mt.detail}):null]},mt.id))}):i.jsx("p",{className:"settings-block__status",children:"还没有本地安装日志。后续在这个页面触发安装、刷新页面、出现 beforeinstallprompt 或 appinstalled 后,这里会自动积累证据。"})]})]})},qt=A=>A==="models"?Tn():A==="cache"?xn():A==="notifications"?Ss():A==="installation"?_n():A==="connection"?zn():A==="dev-manager"?i.jsx(qE,{isActive:b==="dev-manager"||N==="dev-manager",agentId:(Ze==null?void 0:Ze.id)??null}):bn();return i.jsx("div",{className:"conversation-page settings-screen settings-screen--workspace",style:$e,children:i.jsx("div",{className:"conversation-main settings-screen__main settings-screen__workspace-main",children:i.jsx("div",{className:"settings-screen__body",children:i.jsxs("div",{className:"settings-shell",children:[i.jsxs("header",{className:"settings-page-header",children:[i.jsx("button",{type:"button",className:"settings-card__back",onClick:rt,"aria-label":"返回会话",children:i.jsx($C,{})}),i.jsx("div",{className:"settings-page-header__copy",children:i.jsx("h1",{className:"settings-page-header__title",children:"设置"})})]}),T?i.jsxs("div",{className:"settings-workspace",children:[i.jsxs("aside",{className:"settings-sidebar",children:[i.jsx("div",{className:"settings-sidebar__title",children:"设置"}),i.jsx("nav",{className:"settings-sidebar__nav","aria-label":"设置导航",children:wm.map(A=>{const le=A.id===b;return i.jsxs("button",{type:"button",className:`settings-sidebar__item ${le?"is-active":""}`,onClick:()=>w(A.id),children:[i.jsx(bb,{icon:A.icon}),i.jsx("span",{children:A.title})]},A.id)})})]}),i.jsxs("main",{className:"settings-stage",children:[i.jsx("header",{className:"settings-stage__header",children:i.jsxs("div",{children:[i.jsx("h2",{className:"settings-stage__title",children:Pe.title}),i.jsx("p",{className:"settings-stage__description",children:Pe.description})]})}),qt(b)]})]}):gn()]})})})})},XC=({onClose:e})=>{const t=_.useRef(null);return _.useEffect(()=>{var u;if(typeof document>"u")return;const a=document.documentElement.style.overflow,l=document.body.style.overflow;document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",(u=t.current)==null||u.focus();const o=f=>{f.key==="Escape"&&(f.preventDefault(),e())};return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o),document.documentElement.style.overflow=a,document.body.style.overflow=l}},[e]),i.jsx("div",{ref:t,className:"settings-overlay",role:"dialog","aria-modal":"true","aria-label":"设置",tabIndex:-1,children:i.jsx(ix,{mode:"overlay",onRequestClose:e})})},JC=()=>{const e=ki();Mp();const t=ja(p=>p.themeSettings),a=ja(p=>p.systemAppearance),l=ja(p=>p.setSystemAppearance),o=ja(p=>p.isSettingsOverlayOpen),u=ja(p=>p.closeSettingsOverlay),f=Ia({select:p=>p.location.pathname}),m=_.useRef(null),y=pc(),g=ch(y),S=!!(y&&g);return _.useEffect(()=>{tx(t,a)},[a,t]),_.useEffect(()=>vC(l),[l]),_.useEffect(()=>{j_().catch(()=>{})},[]),_.useEffect(()=>{let p;return Jk(b=>{e({to:b}).catch(()=>{typeof window<"u"&&window.location.assign(b)})}).then(b=>{p=b}),()=>{p==null||p()}},[e]),_.useEffect(()=>{if(!o){m.current=null;return}if(m.current===null){m.current=f;return}f!==m.current&&u()},[u,o,f]),Tk()?i.jsx(oE,{}):i.jsxs("div",{className:"app-shell",children:[S?null:i.jsx(mE,{}),i.jsx(AE,{}),i.jsx("div",{className:"app-shell__content","aria-hidden":o,children:i.jsx(l6,{})}),o?i.jsx(XC,{onClose:u}):null]})};/**
|
|
69
69
|
* @license lucide-react v0.577.0 - ISC
|
|
70
70
|
*
|
|
71
71
|
* This source code is licensed under the ISC license.
|
|
@@ -138,11 +138,11 @@ Error generating stack: `+c.message+`
|
|
|
138
138
|
\r
|
|
139
139
|
\r
|
|
140
140
|
`,gR=()=>i.jsx("span",{"aria-hidden":"true",className:"new-thread-hero__logo",dangerouslySetInnerHTML:{__html:pR}}),_R=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m15 18-6-6 6-6"})}),yR=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m9 18 6-6-6-6"})}),Ob=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),i.jsx("path",{d:"M12 10.4v4.2"}),i.jsx("path",{d:"M12 7.9h.01"})]}),vR=(e,t)=>{var a;return((a=e[t])==null?void 0:a.trim())??""},Ib=()=>typeof window<"u"&&!window.matchMedia("(max-width: 768px)").matches,bR=_.memo(function({requests:t,hasStripBelow:a,pendingRequestId:l,onRespond:o}){const u=t[0]??null,[f,m]=_.useState(null),[y,g]=_.useState(""),[S,p]=_.useState({}),[b,w]=_.useState(0),[N,j]=_.useState(null),[T,D]=_.useState(null);_.useEffect(()=>{m(null),g(""),p({}),w(0),j(null),D(null)},[u==null?void 0:u.id]);const z=u?l===u.id:!1,I=(u==null?void 0:u.kind)==="user_input",k=I&&u.questions.length>0?u.questions[Math.max(0,Math.min(b,u.questions.length-1))]??null:null,P=k?vR(S,k.id):"",Q=k?k.options.some(te=>te.label===P):!1,se=!!(k&&P&&(!Q||N===k.id));_.useEffect(()=>{if(!k){j(null);return}if(Q){j(null);return}P&&j(k.id)},[Q,k,P]);const W=_.useMemo(()=>!u||z?!1:u.kind==="user_input"?k?!!P:!1:f?!0:u.allow_freeform?!!y.trim():!1,[k,P,u,y,z,f]);if(!u)return null;const V=u.questions.reduce((te,xe)=>te+xe.options.length,u.options.length),Y=te=>{z||o({requestId:u.id,optionId:(te==null?void 0:te.optionId)??f,text:(te==null?void 0:te.text)??y,answers:(te==null?void 0:te.answers)??S})},ee=()=>{if(!(!u||u.kind!=="user_input"||!k)){if(b<u.questions.length-1){w(te=>Math.min(te+1,u.questions.length-1));return}Y()}},me=()=>{if(!u||u.kind!=="user_input"||!k)return;const te={...S,[k.id]:"忽略"};if(p(te),j(null),b<u.questions.length-1){w(xe=>Math.min(xe+1,u.questions.length-1));return}Y({answers:te})},ge=te=>{if(!(!u||u.kind!=="user_input"||!k||z)){if(P===te){ee();return}p(xe=>({...xe,[k.id]:te})),j(null)}};return i.jsx("section",{className:`session-interaction-strip ${a?"has-strip-below":""} ${I?"is-user-input-flow":""}`,children:u.kind==="user_input"&&k?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"session-interaction-flow__header",children:[i.jsx("div",{className:"session-interaction-flow__prompt",children:k.question}),i.jsxs("div",{className:"session-interaction-flow__progress",children:[i.jsx("button",{type:"button",className:"session-interaction-flow__nav","aria-label":"上一题",disabled:b===0||z,onClick:()=>w(te=>Math.max(0,te-1)),children:i.jsx(_R,{})}),i.jsxs("span",{className:"session-interaction-flow__counter",children:[b+1," / ",u.questions.length]}),i.jsx("button",{type:"button",className:"session-interaction-flow__nav","aria-label":b===u.questions.length-1?"提交回复":"下一题",disabled:z||!W,onClick:ee,children:i.jsx(yR,{})})]})]}),i.jsx("div",{className:"session-interaction-flow__body",children:i.jsxs("div",{className:"session-interaction-flow__list",children:[k.options.map((te,xe)=>i.jsxs("div",{className:`session-interaction-flow__item is-${te.emphasis} ${P===te.label?"is-active":""}`,role:"button",tabIndex:z?-1:0,"aria-pressed":P===te.label,onClick:()=>ge(te.label),onKeyDown:C=>{C.key==="Enter"&&Ib()&&(C.preventDefault(),ge(te.label))},children:[i.jsxs("span",{className:"session-interaction-flow__item-index",children:[xe+1,"."]}),i.jsxs("span",{className:"session-interaction-flow__item-choice",children:[i.jsx("span",{className:"session-interaction-flow__item-label",children:te.label}),te.description?i.jsxs("span",{className:"session-interaction-flow__tooltip-wrap",children:[i.jsx("button",{type:"button",className:"session-interaction-flow__tooltip-trigger","aria-label":`查看 ${te.label} 的说明`,"aria-expanded":T===te.id,onMouseEnter:()=>D(te.id),onMouseLeave:()=>D(C=>C===te.id?null:C),onBlur:()=>D(C=>C===te.id?null:C),onClick:C=>{C.stopPropagation(),D(q=>q===te.id?null:te.id)},children:i.jsx(Ob,{})}),i.jsx("div",{className:`session-interaction-flow__tooltip ${T===te.id?"is-visible":""}`,role:"tooltip",children:te.description})]}):null]})]},te.id)),i.jsx("div",{className:`session-interaction-flow__item is-custom ${se?"is-active":""}`,children:i.jsxs("div",{className:"session-interaction-flow__custom-input-wrap",children:[i.jsx("input",{type:"text",className:"session-interaction-flow__custom-input",value:Q?"":P,disabled:z,placeholder:k.is_secret?"输入敏感信息":"否,请告知如何调整",onFocus:()=>{j(k.id),Q&&p(te=>({...te,[k.id]:""}))},onKeyDown:te=>{te.key==="Enter"&&W&&!z&&Ib()&&(te.preventDefault(),ee())},onChange:te=>{j(k.id),p(xe=>({...xe,[k.id]:te.target.value}))}}),i.jsxs("div",{className:"session-interaction-flow__inline-actions",children:[i.jsx("button",{type:"button",className:"session-interaction-flow__ghost",disabled:z,onClick:me,children:"忽略"}),i.jsx("button",{type:"button",className:"session-interaction-flow__primary",disabled:!W,onClick:ee,children:z?"提交中...":b===u.questions.length-1?u.submit_label??"提交回复":"继续"})]})]})})]})})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"session-interaction-strip__header",children:[i.jsx("span",{className:"session-interaction-strip__icon","aria-hidden":"true",children:i.jsx(Ob,{})}),i.jsxs("div",{className:"session-interaction-strip__copy",children:[i.jsxs("div",{className:"session-interaction-strip__title",children:[u.title,t.length>1?i.jsxs("span",{className:"session-interaction-strip__count",children:["还有 ",t.length-1," 个待处理"]}):null]}),u.description?i.jsx("div",{className:"session-interaction-strip__description",children:u.description}):null]})]}),u.options.length>0?i.jsx("div",{className:"session-interaction-strip__options",children:u.options.map(te=>i.jsxs("button",{type:"button",className:`session-interaction-option is-${te.emphasis} ${f===te.id?"is-active":""}`,disabled:z,onClick:()=>{m(te.id),!u.allow_freeform&&V<=3&&Y({optionId:te.id})},children:[i.jsx("span",{className:"session-interaction-option__label",children:te.label}),te.description?i.jsx("span",{className:"session-interaction-option__description",children:te.description}):null]},te.id))}):null,u.allow_freeform?i.jsxs("label",{className:"session-interaction-strip__freeform",children:[i.jsx("span",{className:"session-interaction-strip__freeform-label",children:"自定义回复"}),i.jsx("textarea",{value:y,disabled:z,placeholder:u.freeform_placeholder??"输入回复内容",onChange:te=>g(te.target.value)})]}):null,u.allow_freeform||u.options.length>3?i.jsx("div",{className:"session-interaction-strip__footer",children:i.jsx("button",{type:"button",className:"session-interaction-strip__submit",disabled:!W,onClick:()=>Y(),children:z?"提交中...":u.submit_label??"继续"})}):null]})})}),xR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6l12 12"}),i.jsx("path",{d:"M18 6 6 18"})]}),SR=({panel:e,isPending:t,onDismiss:a,onSelectOption:l,onSubmitText:o})=>{const[u,f]=_.useState("");return _.useEffect(()=>{f("")},[e.panel_id,e.status]),i.jsxs("section",{className:`session-command-panel is-${e.status}`,children:[i.jsxs("div",{className:"session-command-panel__header",children:[i.jsxs("div",{className:"session-command-panel__command",children:["/",e.command_name]}),i.jsx("button",{type:"button",className:"session-command-panel__close","aria-label":"关闭命令面板",onClick:a,children:i.jsx(xR,{})})]}),i.jsx("div",{className:"session-command-panel__title",children:e.title}),e.description?i.jsx("div",{className:"session-command-panel__description",children:e.description}):null,i.jsx("pre",{className:"session-command-panel__body",children:e.body}),e.input_type==="choice"&&e.options.length>0?i.jsx("div",{className:"session-command-panel__options",children:e.options.map(m=>i.jsxs("button",{type:"button",className:"session-command-panel__option",disabled:t,onClick:()=>l(m.id),children:[i.jsx("span",{className:"session-command-panel__option-label",children:m.label}),m.description?i.jsx("span",{className:"session-command-panel__option-description",children:m.description}):null]},m.id))}):null,e.input_type==="text"?i.jsxs("form",{className:"session-command-panel__form",onSubmit:m=>{m.preventDefault(),!(!u.trim()||t)&&o(u.trim())},children:[i.jsx("input",{className:"session-command-panel__input",value:u,disabled:t,placeholder:e.input_placeholder??"继续输入",onChange:m=>f(m.target.value)}),i.jsx("button",{type:"submit",className:"session-command-panel__submit",disabled:t||!u.trim(),children:e.submit_label??"提交"})]}):null]})},jR=_.memo(function({planSnapshot:t,hasStripAbove:a,hasStripBelow:l}){const[o,u]=_.useState(!0);return t.steps.length?i.jsxs("section",{className:`session-plan-strip ${o?"is-collapsed":""} ${a?"has-strip-above":""} ${l?"has-strip-below":""}`,children:[i.jsxs("button",{type:"button",className:"session-plan-strip__toggle",onClick:()=>u(f=>!f),"aria-expanded":!o,children:[i.jsxs("div",{className:"session-plan-strip__summary",children:[i.jsx("span",{className:"session-plan-strip__summary-mark","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"4.5",y:"5",width:"15",height:"14",rx:"2.5"}),i.jsx("path",{d:"M8 9h8"}),i.jsx("path",{d:"M8 13h5.5"}),i.jsx("path",{d:"m15.5 14.5 1.5 1.5 2.5-3"})]})}),i.jsx("span",{className:"session-plan-strip__summary-text",children:i.jsxs("span",{children:["共 ",t.total_count," 个任务,已完成 ",t.completed_count," 个"]})})]}),i.jsx("span",{className:"session-plan-strip__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m8 10 4 4 4-4"})})})]}),o?null:i.jsx(i.Fragment,{children:i.jsx("div",{className:"session-plan-strip__steps",children:t.steps.map((f,m)=>i.jsxs("div",{className:`session-plan-step is-${f.status}`,children:[i.jsx("span",{className:"session-plan-step__dot","aria-hidden":"true",children:f.status==="in_progress"?i.jsx("span",{className:"session-plan-step__spinner"}):null}),i.jsxs("span",{className:"session-plan-step__index",children:[m+1,"."]}),i.jsx("span",{className:"session-plan-step__label",children:f.step})]},f.id))})})]}):null}),wR=(e,t,a)=>{const l=((a==null?void 0:a.enabled)??!0)&&!!e;return ls({queryKey:["project-skills",t??"",e],enabled:l,queryFn:async()=>e?(await wn({projectId:e,agentId:t??null})).client.getProjectSkills(e):[],staleTime:6e4,gcTime:10*6e4,refetchOnWindowFocus:!1,retry:1})},Lb=24,NR=e=>{const t=yx(e);return t.length===0?i.jsx("span",{children:" "}):t.map((a,l)=>{const o=`skill-aware-token-${l}`;return a.kind==="skill"?i.jsx("span",{className:"skill-aware-textarea__token is-skill",children:a.raw},o):a.kind==="command"?i.jsx("span",{className:"skill-aware-textarea__token is-command",children:a.raw},o):a.kind==="code"?i.jsx("span",{className:"skill-aware-textarea__token is-code",children:a.value},o):a.kind==="path-link"?i.jsx("span",{className:"skill-aware-textarea__token is-link",children:a.label},o):i.jsx("span",{children:a.value},o)})},Pb=({value:e,onChange:t,onKeyDown:a,placeholder:l,disabled:o=!1,className:u,projectId:f,agentId:m,autoFocus:y=!1})=>{var ie;const g=u.includes("composer-fullscreen-sheet__input"),S=_.useRef(null),p=_.useRef(null),[b,w]=_.useState({start:0,end:0}),[N,j]=_.useState(!1),[T,D]=_.useState(!1),[z,I]=_.useState(0),k=_.useMemo(()=>vx(e,b.start,b.end),[b.end,b.start,e]),P=_.useMemo(()=>bx(e,b.start,b.end),[b.end,b.start,e]),Q=N&&!o&&!!k&&!T,se=N&&!o&&!!P&&!T,W=se?"command":Q?"skill":null,V=wR(f,m,{enabled:Q}),Y=ax({enabled:se,scope:m?{agentId:m,projectId:f}:void 0}),ee=_.useMemo(()=>uR(V.data??[],(k==null?void 0:k.query)??"").slice(0,Lb),[k==null?void 0:k.query,V.data]),me=_.useMemo(()=>{var he;return dR(((he=Y.data)==null?void 0:he.commands)??[],(P==null?void 0:P.query)??"").slice(0,Lb)},[P==null?void 0:P.query,(ie=Y.data)==null?void 0:ie.commands]);_.useEffect(()=>{I(0)},[k==null?void 0:k.query,k==null?void 0:k.start,P==null?void 0:P.query,e,f]),_.useEffect(()=>{D(!1)},[k==null?void 0:k.query,k==null?void 0:k.start,k==null?void 0:k.end,P==null?void 0:P.query,P==null?void 0:P.start,P==null?void 0:P.end]);const ge=()=>{if(!S.current||!p.current)return;const he=S.current,re=p.current;re.scrollTop=he.scrollTop,re.scrollLeft=he.scrollLeft;const L=Math.max(0,he.offsetWidth-he.clientWidth);re.style.setProperty("--skill-aware-textarea-scrollbar-width",`${L}px`),re.style.setProperty("--skill-aware-textarea-padding-inline-end",window.getComputedStyle(he).paddingInlineEnd)};_.useEffect(()=>{ge()},[e]),_.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const he=S.current;if(!he)return;const re=new ResizeObserver(()=>{ge()});return re.observe(he),ge(),()=>{re.disconnect()}},[]);const te=()=>{S.current&&w({start:S.current.selectionStart??0,end:S.current.selectionEnd??0})},xe=he=>{if(!S.current)return;const re=oR(e,S.current.selectionStart??b.start,S.current.selectionEnd??b.end,he.name);re&&(t(re.value),typeof window<"u"&&window.requestAnimationFrame(()=>{S.current&&(S.current.focus(),S.current.setSelectionRange(re.selectionStart,re.selectionEnd),w({start:re.selectionStart,end:re.selectionEnd}))}))},C=he=>{if(!S.current)return;const re=cR(e,S.current.selectionStart??b.start,S.current.selectionEnd??b.end,he.name);re&&(t(re.value),typeof window<"u"&&window.requestAnimationFrame(()=>{S.current&&(S.current.focus(),S.current.setSelectionRange(re.selectionStart,re.selectionEnd),w({start:re.selectionStart,end:re.selectionEnd}))}))},q=he=>{const re=W==="skill"&&ee.length>0||W==="command"&&me.length>0;if(W&&re){if(he.key==="ArrowDown"){he.preventDefault();const L=W==="command"?me.length:ee.length;I(ae=>(ae+1)%L);return}if(he.key==="ArrowUp"){he.preventDefault();const L=W==="command"?me.length:ee.length;I(ae=>ae-1<0?L-1:ae-1);return}if((he.key==="Enter"||he.key==="Tab")&&!he.shiftKey&&!he.altKey&&!he.ctrlKey&&!he.metaKey){if(he.preventDefault(),W==="command"){const ae=me[z]??me[0];if(!ae)return;C(ae);return}const L=ee[z]??ee[0];if(!L)return;xe(L);return}}if(W&&he.key==="Escape"){he.preventDefault(),D(!0);return}a==null||a(he)};return i.jsxs("div",{className:`skill-aware-textarea ${W?"is-picker-open":""} ${g?"is-fullscreen":""}`,children:[se?i.jsx("div",{className:"skill-mention-picker",role:"listbox","aria-label":"命令建议",children:Y.isLoading?i.jsx("div",{className:"skill-mention-picker__empty",children:"正在加载命令…"}):Y.isError?i.jsx("div",{className:"skill-mention-picker__empty",children:"命令列表加载失败"}):me.length===0?i.jsx("div",{className:"skill-mention-picker__empty",children:"未找到匹配命令"}):me.map((he,re)=>{const L=re===z;return i.jsx("button",{type:"button",className:`skill-mention-picker__item ${L?"is-active":""}`,role:"option","aria-selected":L,onMouseDown:ae=>{ae.preventDefault(),C(he)},onMouseEnter:()=>I(re),children:i.jsxs("span",{className:"skill-mention-picker__main",children:[i.jsxs("span",{className:"skill-mention-picker__name",children:["/",he.name]}),i.jsx("span",{className:"skill-mention-picker__description",children:he.description})]})},he.name)})}):Q?i.jsx("div",{className:"skill-mention-picker",role:"listbox","aria-label":"技能建议",children:V.isLoading?i.jsx("div",{className:"skill-mention-picker__empty",children:"正在加载技能…"}):V.isError?i.jsx("div",{className:"skill-mention-picker__empty",children:"技能列表加载失败"}):ee.length===0?i.jsx("div",{className:"skill-mention-picker__empty",children:"未找到匹配技能"}):ee.map((he,re)=>{const L=re===z;return i.jsx("button",{type:"button",className:`skill-mention-picker__item ${L?"is-active":""}`,role:"option","aria-selected":L,onMouseDown:ae=>{ae.preventDefault(),xe(he)},onMouseEnter:()=>I(re),children:i.jsxs("span",{className:"skill-mention-picker__main",children:[i.jsxs("span",{className:"skill-mention-picker__name",children:["$",he.name]}),i.jsx("span",{className:"skill-mention-picker__description",children:he.description}),i.jsx("span",{className:"skill-mention-picker__scope",children:lR(he.scope)})]})},`${he.scope}:${he.name}:${he.path}`)})}):null,i.jsxs("div",{className:"skill-aware-textarea__surface",children:[i.jsx("div",{ref:p,className:`${u} skill-aware-textarea__overlay`,"aria-hidden":"true",children:e?NR(e):i.jsx("span",{children:" "})}),i.jsx("textarea",{ref:S,className:`${u} skill-aware-textarea__input`,value:e,disabled:o,placeholder:l,autoFocus:y,onChange:he=>{t(he.target.value),D(!1),w({start:he.target.selectionStart??0,end:he.target.selectionEnd??0})},onKeyDown:q,onClick:te,onSelect:te,onKeyUp:te,onFocus:()=>{j(!0),D(!1),te()},onBlur:()=>{j(!1)},onScroll:ge})]})]})},Mg=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6l12 12"}),i.jsx("path",{d:"M18 6 6 18"})]}),kR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 5v14"}),i.jsx("path",{d:"m7 14 5 5 5-5"})]}),ER=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M8 3H4v4"}),i.jsx("path",{d:"M16 3h4v4"}),i.jsx("path",{d:"M8 21H4v-4"}),i.jsx("path",{d:"M16 21h4v-4"}),i.jsx("path",{d:"M9 9 4 4"}),i.jsx("path",{d:"m15 9 5-5"}),i.jsx("path",{d:"m9 15-5 5"}),i.jsx("path",{d:"m15 15 5 5"})]}),CR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 5v14"}),i.jsx("path",{d:"M5 12h14"})]}),Ub=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M13 2 5.5 13h5L9 22l9.5-13h-5L13 2Z"})}),zb=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9 6h10"}),i.jsx("path",{d:"M9 12h10"}),i.jsx("path",{d:"M9 18h10"}),i.jsx("path",{d:"m4 6 1.5 1.5L7.5 5"}),i.jsx("path",{d:"m4 12 1.5 1.5L7.5 11"}),i.jsx("path",{d:"m4 18 1.5 1.5L7.5 17"})]}),Bb=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 10V7.8A5 5 0 0 1 12 3a5 5 0 0 1 5 4.8V10"}),i.jsx("path",{d:"M5.5 10h13a1.5 1.5 0 0 1 1.5 1.5v7A2.5 2.5 0 0 1 17.5 21h-11A2.5 2.5 0 0 1 4 18.5v-7A1.5 1.5 0 0 1 5.5 10Z"}),i.jsx("path",{d:"M12 14v2.6"})]}),TR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 16V5"}),i.jsx("path",{d:"m8 9 4-4 4 4"}),i.jsx("path",{d:"M20 16.5v1A2.5 2.5 0 0 1 17.5 20h-11A2.5 2.5 0 0 1 4 17.5v-1"})]}),xx=_.memo(function({isDesktopSidebar:t,sidebarShift:a,isSidebarDragging:l,composerError:o,onDismissComposerError:u,interactionRequests:f,pendingInteractionRequestId:m,onRespondInteraction:y,parentSession:g,backgroundAgentSessions:S,isBackgroundAgentsOpen:p,planSnapshot:b,onToggleBackgroundAgents:w,onOpenSession:N,getBackgroundAgentStatusLabel:j,getBackgroundAgentAccent:T,formatBackgroundAgentsLabel:D,hasBackgroundAgentStrip:z,commandPanel:I,isCommandPanelPending:k,onDismissCommandPanel:P,onCommandPanelOptionSelect:Q,onCommandPanelTextSubmit:se,projectId:W=null,agentId:V=null,draft:Y,pendingAttachments:ee,canSendInput:me,canSubmitInput:ge=!0,isInputLocked:te=!1,inputPlaceholder:xe,readOnlyPlaceholder:C,onDraftChange:q,onUploadFiles:ie,onRemoveAttachment:he,onSubmit:re,showStopIcon:L,isSendPending:ae,onInterrupt:ke,isFastModeEnabled:U,isPlanModeEnabled:ve,isYoloModeEnabled:Z,onToggleFastMode:Se,onTogglePlanMode:je,onToggleYoloMode:Oe,showModeBadges:Ie=!1,selectedModel:wt,modelOptions:qe=[],selectedReasoning:bt,onSelectModel:Ut,onSelectReasoning:$t,contextUsage:zt,isContextUsageOpen:xt,onToggleContextUsage:it,contextUsageRingStyle:ot,usedPercent:ln,remainingPercent:on,usedTokensLabel:kn,totalTokensLabel:En,showJumpToBottom:ht,onJumpToBottom:Ve}){const Ke=_.useId(),[Nt,Bt]=_.useState(!1),[Jt,Dt]=_.useState(null),Ze=_.useRef(null),un=_.useRef(null),ut=f[0]??null,_e=(ut==null?void 0:ut.kind)==="user_input",Fe=f.length>0,X=!!b&&!_e,B=!_e&&z,oe=X||B,ue=Fe||X||B,we={transform:`translateX(${a}px)`,transition:l?"none":void 0},Re=(!!Y.trim()||ee.length>0)&&me&&ge&&!te&&!ae&&!L,He=me&&!te,ze=Ie&&(U||ve||Z),rt=()=>{Re&&(Dt(null),re())},It=Le=>{Le.key!=="Enter"||Le.shiftKey||Le.altKey||Le.ctrlKey||Le.metaKey||Le.nativeEvent.isComposing||typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches||(Le.preventDefault(),rt())};_.useEffect(()=>{if(!Nt)return;const Le=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=Le}},[Nt]),_.useEffect(()=>{if(!Nt||typeof window>"u")return;const Le=window.matchMedia("(min-width: 769px)"),Et=()=>{Le.matches&&Bt(!1)};return Et(),typeof Le.addEventListener=="function"?(Le.addEventListener("change",Et),()=>{Le.removeEventListener("change",Et)}):(Le.addListener(Et),()=>{Le.removeListener(Et)})},[Nt]),_.useEffect(()=>{if(!Jt)return;const Le=Cn=>{const hs=Cn.target;Ze.current&&hs instanceof Node&&Ze.current.contains(hs)||Dt(null)},Et=Cn=>{Cn.key==="Escape"&&Dt(null)};return window.addEventListener("pointerdown",Le),window.addEventListener("keydown",Et),()=>{window.removeEventListener("pointerdown",Le),window.removeEventListener("keydown",Et)}},[Jt]);const Ft=Le=>ze?i.jsxs("div",{className:Le,"aria-label":"当前已启用的会话模式",children:[U?i.jsxs("button",{type:"button",className:"composer-mode-badge is-fast",onClick:()=>{Dt(null),Se()},"aria-label":"关闭 Fast 模式",children:[i.jsx("span",{className:"composer-mode-badge__icon","aria-hidden":"true",children:i.jsx(Ub,{})}),i.jsx("span",{className:"composer-mode-badge__label",children:"Fast"})]}):null,ve?i.jsxs("button",{type:"button",className:"composer-mode-badge is-plan",onClick:()=>{Dt(null),je()},"aria-label":"关闭计划模式",children:[i.jsx("span",{className:"composer-mode-badge__icon","aria-hidden":"true",children:i.jsx(zb,{})}),i.jsx("span",{className:"composer-mode-badge__label",children:"计划"})]}):null,Z?i.jsxs("button",{type:"button",className:"composer-mode-badge is-yolo",onClick:()=>{Dt(null),Oe()},"aria-label":"关闭 Yolo 模式",children:[i.jsx("span",{className:"composer-mode-badge__icon","aria-hidden":"true",children:i.jsx(Bb,{})}),i.jsx("span",{className:"composer-mode-badge__label",children:"Yolo"})]}):null]}):null;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`composer-wrap ${t?"has-desktop-sidebar":""}`,style:we,children:[o?i.jsxs("div",{className:"composer-alert",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"composer-alert__text",children:o}),i.jsx("button",{type:"button",className:"composer-alert__close",onClick:u,"aria-label":"关闭错误提示",children:i.jsx(Mg,{})})]}):null,Fe?i.jsx(bR,{requests:f,hasStripBelow:oe,pendingRequestId:m,onRespond:y}):null,X&&b?i.jsx(jR,{planSnapshot:b,hasStripAbove:Fe,hasStripBelow:B}):null,B&&g?i.jsxs("button",{type:"button",className:`background-agents-exit ${Fe||X?"has-strip-above":""}`,onClick:()=>{N(g.id)},children:[i.jsx("span",{className:"background-agents-exit__icon","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M6 12h12"}),i.jsx("path",{d:"m13 7 5 5-5 5"})]})}),i.jsx("span",{children:"返回主会话"})]}):B&&S.length>0?i.jsxs("section",{className:`background-agents-card ${p?"is-open":""} ${Fe||X?"has-strip-above":""}`,children:[i.jsxs("button",{type:"button",className:"background-agents-card__toggle",onClick:w,"aria-expanded":p,children:[i.jsx("span",{className:"background-agents-card__icon","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"7",y:"4",width:"10",height:"7",rx:"2.5"}),i.jsx("path",{d:"M12 11v3"}),i.jsx("circle",{cx:"10",cy:"7.5",r:"0.8",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"14",cy:"7.5",r:"0.8",fill:"currentColor",stroke:"none"}),i.jsx("path",{d:"M4.5 18a4.5 4.5 0 0 1 4.5-4.5h6A4.5 4.5 0 0 1 19.5 18"})]})}),i.jsxs("span",{className:"background-agents-card__summary",children:[i.jsx("span",{className:"background-agents-card__title",children:D(S.length)}),p?i.jsx("span",{className:"background-agents-card__hint",children:"(@ to tag agents)"}):null]}),i.jsx("span",{className:"background-agents-card__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m8 10 4 4 4-4"})})})]}),p?i.jsx("div",{className:"background-agents-card__list",children:S.map(Le=>{var Et,Cn;return i.jsxs("button",{type:"button",className:`background-agent-row ${Le.run_state==="running"?"is-running":"is-idle"}`,style:{"--agent-accent":T(Le)},onClick:()=>{N(Le.id)},children:[i.jsx("span",{className:"background-agent-row__accent","aria-hidden":"true"}),i.jsxs("span",{className:"background-agent-row__meta",children:[i.jsxs("span",{className:"background-agent-row__title",children:[i.jsx("span",{className:"background-agent-row__name",children:((Et=Le.subagent)==null?void 0:Et.nickname)??Le.title}),i.jsxs("span",{className:"background-agent-row__role",children:["(",((Cn=Le.subagent)==null?void 0:Cn.role)??"agent",")"]})]}),i.jsx("span",{className:"background-agent-row__status",children:j(Le)})]}),i.jsx("span",{className:"background-agent-row__open",children:"Open"})]},Le.id)})}):null]}):null,I?i.jsx(SR,{panel:I,isPending:k,onDismiss:P,onSelectOption:Q,onSubmitText:se}):null,_e?null:i.jsxs("form",{className:`chat-composer ${ue?"is-attached-to-agent-strip":""}`,onSubmit:Le=>{Le.preventDefault(),rt()},children:[i.jsxs("div",{className:"chat-composer__editor",children:[ee.length>0?i.jsx("div",{className:"chat-composer__attachments",children:ee.map(Le=>{const Et=L0(Le.size_bytes);return i.jsxs("div",{className:"chat-composer__attachment-chip",children:[i.jsxs("div",{className:"chat-composer__attachment-copy",children:[i.jsx("span",{className:"chat-composer__attachment-name",children:Le.name}),i.jsxs("span",{className:"chat-composer__attachment-meta",children:[Le.kind==="image"?"图片":"文件",Et?` · ${Et}`:""]})]}),i.jsx("button",{type:"button",className:"chat-composer__attachment-remove","aria-label":`移除 ${Le.name}`,onClick:()=>he(Le.id),children:i.jsx(Mg,{})})]},Le.id)})}):null,i.jsx(Pb,{className:"chat-composer__input",value:Y,disabled:!He,projectId:W,agentId:V,placeholder:He?xe??"要求后续变更":C??"当前会话为只读模式",onChange:q,onKeyDown:It}),i.jsx("button",{type:"button",className:"composer-fullscreen-toggle","aria-label":"全屏编辑",onClick:()=>Bt(!0),children:i.jsx(ER,{})}),i.jsx("input",{id:Ke,ref:un,type:"file",className:"chat-composer__file-input",multiple:!0,onChange:Le=>{Le.target.files&&Le.target.files.length>0&&ie(Le.target.files),Le.target.value=""}})]}),Ft("composer-mode-badges composer-mode-badges--mobile"),i.jsxs("div",{className:"chat-composer__toolbar",children:[i.jsxs("div",{ref:Ze,className:"chat-composer__controls",children:[i.jsxs("div",{className:`composer-utility-menu ${Jt==="utility"?"is-open":""}`,children:[i.jsx("button",{type:"button",className:"composer-utility-menu__trigger","aria-label":"打开额外功能","aria-expanded":Jt==="utility",onClick:()=>Dt(Le=>Le==="utility"?null:"utility"),children:i.jsx(CR,{})}),Jt==="utility"?i.jsxs("div",{className:"composer-utility-menu__popover",role:"menu",children:[i.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitem",onClick:()=>{var Le;Dt(null),(Le=un.current)==null||Le.click()},children:[i.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:i.jsx(TR,{})}),i.jsx("span",{className:"composer-utility-menu__item-label",children:"上传文件"})]}),i.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitemcheckbox","aria-checked":U,onClick:Se,children:[i.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:i.jsx(Ub,{})}),i.jsx("span",{className:"composer-utility-menu__item-label",children:"Fast 模式"}),i.jsx("span",{className:`composer-utility-menu__switch ${U?"is-on":""}`,"aria-hidden":"true",children:i.jsx("span",{className:"composer-utility-menu__switch-thumb"})})]}),i.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitemcheckbox","aria-checked":ve,onClick:je,children:[i.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:i.jsx(zb,{})}),i.jsx("span",{className:"composer-utility-menu__item-label",children:"计划模式"}),i.jsx("span",{className:`composer-utility-menu__switch ${ve?"is-on":""}`,"aria-hidden":"true",children:i.jsx("span",{className:"composer-utility-menu__switch-thumb"})})]}),i.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitemcheckbox","aria-checked":Z,onClick:Oe,children:[i.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:i.jsx(Bb,{})}),i.jsx("span",{className:"composer-utility-menu__item-label",children:"Yolo 模式"}),i.jsx("span",{className:`composer-utility-menu__switch ${Z?"is-on":""}`,"aria-hidden":"true",children:i.jsx("span",{className:"composer-utility-menu__switch-thumb"})})]})]}):null]}),i.jsxs("div",{className:`composer-choice ${Jt==="model"?"is-open":""}`,children:[i.jsxs("button",{type:"button",className:"composer-control","aria-label":"选择模型","aria-expanded":Jt==="model",onClick:()=>Dt(Le=>Le==="model"?null:"model"),children:[i.jsx("span",{className:"composer-icon",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M12 3 4 7v10l8 4 8-4V7z"}),i.jsx("path",{d:"m4 7 8 4 8-4"}),i.jsx("path",{d:"M12 11v10"})]})}),i.jsx("span",{className:"composer-control__value",children:wp(wt,qe)})]}),Jt==="model"?i.jsx("div",{className:"composer-choice-menu",role:"menu","aria-label":"选择模型",children:qe.map(Le=>i.jsxs("button",{type:"button",className:`composer-choice-menu__item ${wt===Le.value?"is-active":""}`,role:"menuitemradio","aria-checked":wt===Le.value,onClick:()=>{Ut(Le.value),Dt(null)},children:[i.jsx("span",{className:"composer-choice-menu__text",children:i.jsx("span",{className:"composer-choice-menu__label",children:Le.label})}),wt===Le.value?i.jsx("span",{className:"composer-choice-menu__check",children:"✓"}):null]},Le.value))}):null]}),i.jsxs("div",{className:`composer-choice ${Jt==="reasoning"?"is-open":""}`,children:[i.jsxs("button",{type:"button",className:"composer-control","aria-label":"选择推理强度","aria-expanded":Jt==="reasoning",onClick:()=>Dt(Le=>Le==="reasoning"?null:"reasoning"),children:[i.jsx("span",{className:"composer-icon",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M9.5 3a6.5 6.5 0 0 0-3.7 11.84c.53.38.92.95 1.1 1.57l.1.34c.13.44.54.75 1 .75h7c.46 0 .87-.31 1-.75l.1-.34c.18-.62.57-1.2 1.1-1.57A6.5 6.5 0 0 0 14.5 3z"}),i.jsx("path",{d:"M10 21h4"}),i.jsx("path",{d:"M9 18h6"})]})}),i.jsx("span",{className:"composer-control__value",children:rC(bt)})]}),Jt==="reasoning"?i.jsx("div",{className:"composer-choice-menu",role:"menu","aria-label":"选择推理强度",children:Xf.map(Le=>i.jsxs("button",{type:"button",className:`composer-choice-menu__item ${bt===Le.value?"is-active":""}`,role:"menuitemradio","aria-checked":bt===Le.value,onClick:()=>{$t(Le.value),Dt(null)},children:[i.jsx("span",{className:"composer-choice-menu__label",children:Le.label}),bt===Le.value?i.jsx("span",{className:"composer-choice-menu__check",children:"✓"}):null]},Le.value))}):null]}),Ft("composer-mode-badges composer-mode-badges--inline")]}),i.jsxs("div",{className:"chat-composer__actions",children:[zt?i.jsxs("div",{className:`composer-context ${xt?"is-open":""}`,children:[i.jsx("button",{type:"button",className:"composer-context__trigger","aria-label":"查看背景信息窗口使用情况",onClick:Le=>{Le.stopPropagation(),it()},children:i.jsx("span",{className:"composer-context__ring",style:ot,children:i.jsx("span",{className:"composer-context__ring-core"})})}),xt?i.jsxs("div",{className:"composer-context__popover",role:"tooltip",children:[i.jsx("div",{className:"composer-context__title",children:"背景信息窗口:"}),i.jsxs("div",{children:[ln,"% 已用(剩余 ",on,"%)"]}),i.jsxs("div",{children:["已用 ",kn,",共 ",En]})]}):null]}):null,i.jsx("button",{type:L?"button":"submit",className:"composer-send",disabled:L?!me:!Re,"aria-label":L?"中断":"发送",onClick:()=>{L&&ke()},children:L?i.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:i.jsx("rect",{x:"7",y:"7",width:"10",height:"10",rx:"2.5"})}):i.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:i.jsx("path",{d:"M12 17V7m0 0-4 4m4-4 4 4",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})]}),Nt?i.jsx("div",{className:"composer-fullscreen-sheet",role:"dialog","aria-modal":"true","aria-label":"全屏编辑",children:i.jsxs("div",{className:"composer-fullscreen-sheet__panel",children:[i.jsxs("div",{className:"composer-fullscreen-sheet__header",children:[i.jsx("div",{className:"composer-fullscreen-sheet__title",children:"全屏编辑"}),i.jsx("button",{type:"button",className:"composer-fullscreen-sheet__close","aria-label":"退出全屏编辑",onClick:()=>Bt(!1),children:i.jsx(Mg,{})})]}),i.jsx(Pb,{className:"composer-fullscreen-sheet__input",value:Y,disabled:!He,projectId:W,agentId:V,placeholder:He?xe??"要求后续变更":C??"当前会话为只读模式",onChange:q,onKeyDown:It,autoFocus:!0}),i.jsxs("div",{className:"composer-fullscreen-sheet__footer",children:[i.jsxs("div",{className:"composer-fullscreen-sheet__meta",children:[i.jsx("span",{children:wt}),i.jsx("span",{children:bt}),Z?i.jsx("span",{children:"Yolo"}):null,ee.length>0?i.jsxs("span",{children:[ee.length," 个附件"]}):null]}),i.jsxs("div",{className:"composer-fullscreen-sheet__actions",children:[i.jsx("button",{type:"button",className:"composer-fullscreen-sheet__button",onClick:()=>Bt(!1),children:"关闭"}),L?i.jsx("button",{type:"button",className:"composer-fullscreen-sheet__button is-primary",disabled:!me,onClick:ke,children:"中断"}):i.jsx("button",{type:"button",className:"composer-fullscreen-sheet__button is-primary",disabled:!Re,onClick:()=>{rt(),Bt(!1)},children:"发送"})]})]})]})}):null,ht?i.jsx("button",{type:"button",className:`conversation-jump-bottom ${t?"has-desktop-sidebar":""}`,style:we,onClick:Ve,"aria-label":"滚动到最下面",children:i.jsx(kR,{})}):null]})}),Hb=10,RR=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=Hb?t:t.slice(0,Hb).trimEnd()},MR=(e,t)=>{var l,o;const a=RR(e);return a||((o=(l=t[0])==null?void 0:l.name)==null?void 0:o.trim())||"附件"},AR=e=>{var a;const t=/^\/([A-Za-z][A-Za-z0-9._-]*)/.exec(e.trim());return((a=t==null?void 0:t[1])==null?void 0:a.toLowerCase())??""},DR=({currentAgent:e,projects:t,sessions:a,initialProjectId:l=null,entryView:o,isDesktopSidebar:u,sidebarOffset:f,isSidebarDragging:m,onOpenSidebar:y,onProjectSelected:g,onSessionCreated:S})=>{const p=La(),[b,w]=_.useState(""),[N,j]=_.useState(l),[T,D]=_.useState(null),[z,I]=_.useState(null),[k,P]=_.useState(()=>R_()),[Q,se]=_.useState(()=>F3()),[W,V]=_.useState([]),[Y,ee]=_.useState(!1),[me,ge]=_.useState(!1),[te,xe]=_.useState(!1),[C,q]=_.useState(o),ie=O_(),he=_.useMemo(()=>ie.map(({id:Z,...Se})=>Se),[ie]),re=_.useMemo(()=>t.find(Z=>Z.id===N)??t[0]??null,[t,N]);_.useEffect(()=>{zf(k)},[k]),_.useEffect(()=>{q3(Q)},[Q]),_.useEffect(()=>{he.length!==0&&(he.some(Z=>Z.value===k)||P(he[0].value))},[he,k]),_.useEffect(()=>{q(o)},[o]),_.useEffect(()=>{I(null)},[N]),_.useEffect(()=>{var Se,je;if(N&&t.some(Oe=>Oe.id===N))return;const Z=(l&&t.some(Oe=>Oe.id===l)?l:null)??((Se=a.find(Oe=>!Oe.archived))==null?void 0:Se.project_id)??((je=t[0])==null?void 0:je.id)??null;j(Z)},[l,t,N,a]);const L=Vn({mutationFn:async Z=>{if(!re||!Z.input.trim()&&Z.attachments.length===0)throw new Error("请先选择线程,再输入第一条消息");return(await(await wn({projectId:Z.projectId,agentId:e.id})).client.createSession({agentId:e.id,projectId:Z.projectId,title:Z.title,input:Z.input,attachments:Z.attachments,model:Z.model,titleGenerationModel:Z.titleGenerationModel,reasoningEffort:Z.reasoningEffort,serviceTier:Z.serviceTier,planMode:Z.planMode,yoloMode:Z.yoloMode})).session},onMutate:()=>D(null),onSuccess:async(Z,Se)=>{const je=new Date().toISOString(),Oe={id:`optimistic-user:${Z.id}:create`,kind:"user",title:"你",body:Se.input,body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:Z.last_event_at||je,accent:"primary",attachments:_x(Se.attachments)};Ji(e.id),Js(Z.id),iC(Z.id,{isFastModeEnabled:Se.serviceTier==="fast",isPlanModeEnabled:Se.planMode,isYoloModeEnabled:Se.yoloMode}),Kr(Z.id),ku(null),fk({sessionId:Z.id,agentId:Z.agent_id,projectId:Z.project_id,createdAt:je,session:Z,project:re?{id:re.id,agent_id:re.agent_id,name:re.name,display_name:re.display_name,pinned:re.pinned,path:re.path}:null,optimisticEntry:Oe}),p.setQueriesData({queryKey:os},Ie=>j3(Ie,Z)),p.setQueryData(Fo(Z.id),Ie=>O0(Ie,Oe)),ee(!1),ge(!1),xe(!1),S(Z.id),p.invalidateQueries({queryKey:["plan",Z.id]}),p.invalidateQueries({queryKey:["change-sets",Z.id]})},onError:Z=>{D(Z instanceof Error?Z.message:"创建会话失败")}}),ae=(re==null?void 0:re.path)??null,ke=C==="directory-picker",U={transform:`translateX(${f}px)`,transition:m?"none":void 0},ve=()=>{const Z=b.trim();if(!(!Z&&W.length===0||L.isPending||!re)){if(z_(Z)){if(W.length>0){D("命令暂不支持附件,请先移除附件后再执行。");return}const Se=AR(Z);if(Se==="model"){if(w(""),he.length>0){I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${re.id}`,command_name:Se,command_text:Z,title:"为新会话选择模型",description:"选择后会更新新会话的默认模型,再继续输入真正的首条消息。",status:"awaiting_input",body:"在下面选择一个模型。",submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"choice",options:he.map(je=>({id:je.value,label:je.label,description:je.description??null})),input_placeholder:null,submit_label:null,effect:null});return}I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${re.id}`,command_name:Se,command_text:Z,title:"为新会话选择模型",description:"选择后会更新新会话的默认模型,再继续输入真正的首条消息。",status:"completed",body:"当前没有可选模型,请先去设置页维护模型列表。",submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}if(Se==="status"){w(""),I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${re.id}`,command_name:Se,command_text:Z,title:"新会话当前设置",description:"这里展示的是创建下一条会话时会使用的本地设置。",status:"completed",body:[`线程:${re.display_name??re.name}`,`模型:${k}`,`推理强度:${Q}`,`Fast 模式:${Y?"开启":"关闭"}`,`计划模式:${me?"开启":"关闭"}`,`Yolo 模式:${te?"开启":"关闭"}`].join(`
|
|
141
|
-
`),submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}w(""),I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${re.id}`,command_name:Se||"unknown",command_text:Z,title:`/${Se||"unknown"} 暂不可用`,description:"新建线程阶段目前只接入了少量本地命令。",status:"completed",body:"请先进入已有会话后再执行这个命令,或者先使用 /model 调整新会话默认模型。",submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}L.mutate({projectId:re.id,input:Z,title:MR(Z,W),attachments:W,model:k,titleGenerationModel:$3(),reasoningEffort:Q,serviceTier:Y?"fast":void 0,planMode:me,yoloMode:te})}};return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`conversation-main conversation-main--new-thread ${u?"has-desktop-sidebar":""}`,style:U,children:[i.jsxs("div",{className:"conversation-topbar",children:[u?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:y,"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]}),i.jsx("div",{className:"conversation-topbar__meta",children:i.jsx("div",{className:"conversation-topbar__title-row",children:i.jsx("h1",{"aria-label":"未命名会话",children:" "})})})]}),i.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:i.jsx("div",{className:"conversation-thread conversation-thread--empty",children:ke?i.jsx(mR,{agentId:e.id,projects:t,title:"选择目录",subtitle:"",onProjectCreated:Z=>{p.setQueriesData({queryKey:os},Se=>_E(Se,Z)),j(Z.id),g(Z.id),q("composer")}}):i.jsx("section",{className:"new-thread-hero",children:i.jsxs("div",{className:"new-thread-hero__stack",children:[i.jsx(gR,{}),i.jsxs("label",{className:"new-thread-hero__selector",children:[i.jsx("span",{className:"new-thread-hero__selector-label",children:"在线程中发起会话"}),i.jsx("select",{className:"new-thread-hero__select",value:N??"",onChange:Z=>{const Se=Z.target.value||null;j(Se),Se&&g(Se)},children:t.map(Z=>i.jsx("option",{value:Z.id,children:Z.display_name??Z.name},Z.id))})]}),ae?i.jsx("div",{className:"new-thread-hero__path",children:ae}):i.jsx("div",{className:"new-thread-hero__hint",children:"选择一个线程后,直接输入第一条消息即可开始。"}),u?null:i.jsx("button",{type:"button",className:"new-thread-hero__directory-trigger",onClick:()=>q("directory-picker"),children:"新增目录线程"})]})})})})]}),ke?null:i.jsx(xx,{isDesktopSidebar:u,sidebarShift:f,isSidebarDragging:m,composerError:T,onDismissComposerError:()=>D(null),interactionRequests:[],pendingInteractionRequestId:null,onRespondInteraction:()=>{},parentSession:null,backgroundAgentSessions:[],isBackgroundAgentsOpen:!1,planSnapshot:null,onToggleBackgroundAgents:()=>{},onOpenSession:()=>{},getBackgroundAgentStatusLabel:()=>"",getBackgroundAgentAccent:()=>"var(--color-accent-primary)",formatBackgroundAgentsLabel:Z=>`${Z} background agents`,hasBackgroundAgentStrip:!1,commandPanel:z,isCommandPanelPending:!1,onDismissCommandPanel:()=>I(null),onCommandPanelOptionSelect:Z=>{P(Z),I(Se=>Se&&{...Se,status:"completed",body:`新会话默认模型已切换为 ${wp(Z,he)}。现在可以继续输入真正的首条消息。`,updated_at:new Date().toISOString(),input_type:"none",options:[]})},onCommandPanelTextSubmit:()=>{},projectId:(re==null?void 0:re.id)??null,agentId:e.id,draft:b,pendingAttachments:W,canSendInput:!!re,inputPlaceholder:re?`向 ${re.display_name??re.name} 发起第一条任务…`:"先选择线程,再输入第一条任务",readOnlyPlaceholder:"先选择线程,再输入第一条任务",onDraftChange:w,onUploadFiles:Z=>{const Se=[...Z];Se.length!==0&&(D(null),Promise.all(Se.map(je=>gx(je))).then(je=>{V(Oe=>[...Oe,...je])}).catch(je=>{D(je instanceof Error?je.message:"无法读取附件")}))},onRemoveAttachment:Z=>{V(Se=>Se.filter(je=>je.id!==Z))},onSubmit:ve,showStopIcon:!1,isSendPending:L.isPending,onInterrupt:()=>{},isFastModeEnabled:Y,isPlanModeEnabled:me,isYoloModeEnabled:te,onToggleFastMode:()=>ee(Z=>!Z),onTogglePlanMode:()=>ge(Z=>!Z),onToggleYoloMode:()=>xe(Z=>!Z),showModeBadges:!0,selectedModel:k,modelOptions:he,selectedReasoning:Q,onSelectModel:P,onSelectReasoning:Z=>se(Z),contextUsage:null,isContextUsageOpen:!1,onToggleContextUsage:()=>{},usedPercent:0,remainingPercent:0,usedTokensLabel:"0",totalTokensLabel:"0",showJumpToBottom:!1,onJumpToBottom:()=>{}})]})},Sx="panda:session-timeline-snapshots",Wm=1,OR=1440*60*1e3,jx=12,IR=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},LR=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}},wx=()=>{const e=IR(Sx);if(!e||e.version!==Wm||!Array.isArray(e.items))return{version:Wm,items:[]};const t=Date.now(),a=e.items.filter(l=>!!(l&&typeof l.sessionId=="string"&&typeof l.storedAt=="number"&&l.snapshot&&typeof l.snapshot=="object")).filter(l=>t-l.storedAt<=OR).sort((l,o)=>o.storedAt-l.storedAt).slice(0,jx);return{version:Wm,items:a}},PR=e=>{const a=wx().items.find(l=>l.sessionId===e);return a?a.snapshot:null},UR=e=>{if(!e||e.view!=="full_compact")return;const t=Date.now(),a=wx(),l=[{sessionId:e.session_id,storedAt:t,snapshot:e},...a.items.filter(o=>o.sessionId!==e.session_id)].slice(0,jx);LR(Sx,{version:Wm,items:l})},zR=e=>{var t,a,l;return["session-tool-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(a=e==null?void 0:e.scope)!=null&&a.sessionId?"":((l=e==null?void 0:e.scope)==null?void 0:l.agentId)??"",(e==null?void 0:e.sessionId)??"",(e==null?void 0:e.entryId)??""]};function BR(e){return ls({queryKey:zR(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId)&&!!(e!=null&&e.entryId),queryFn:async()=>!(e!=null&&e.sessionId)||!(e!=null&&e.entryId)?null:(await wn(e.scope)).client.getSessionToolCallDetail(e.sessionId,e.entryId),refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const Nx=e=>{var t,a,l;return["workspace-session-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(a=e==null?void 0:e.scope)!=null&&a.sessionId?"":((l=e==null?void 0:e.scope)==null?void 0:l.agentId)??"",(e==null?void 0:e.sessionId)??""]};function HR(e){return ls({queryKey:Nx(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId),queryFn:async()=>e!=null&&e.sessionId?(await wn(e.scope)).client.getWorkspaceSessionDetail(e.sessionId):null,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const $R={can_stream_live:!1,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!1,can_show_terminal:!1},FR=e=>({id:e.id,agent_id:e.agent_id,project_id:e.project_id,archived:e.archived,title:e.title,last_event_at:e.last_event_at,pinned:e.pinned,run_state:e.run_state,run_state_changed_at:e.run_state_changed_at,subagent:e.subagent,provider:"codex",mode:"managed",health:"active",branch:"",worktree:"",summary:"",latest_assistant_message:null,context_usage:null,capability:$R}),qR=(e,t)=>e?!t||t.id!==e.id?FR(e):{...t,id:e.id,agent_id:e.agent_id,project_id:e.project_id,archived:e.archived,title:e.title,last_event_at:e.last_event_at,pinned:e.pinned,run_state:e.run_state,run_state_changed_at:e.run_state_changed_at,subagent:e.subagent}:t??null,$b=e=>{if(!e)return null;const t={};return typeof e.title=="string"&&(t.title=e.title),typeof e.archived=="boolean"&&(t.archived=e.archived),typeof e.pinned=="boolean"&&(t.pinned=e.pinned),typeof e.last_event_at=="string"&&(t.last_event_at=e.last_event_at),(e.run_state==="idle"||e.run_state==="running"||e.run_state==="completed")&&(t.run_state=e.run_state),(e.run_state_changed_at===null||typeof e.run_state_changed_at=="string")&&(t.run_state_changed_at=e.run_state_changed_at),typeof e.summary=="string"&&(t.summary=e.summary),(e.latest_assistant_message===null||typeof e.latest_assistant_message=="string")&&(t.latest_assistant_message=e.latest_assistant_message),typeof e.provider=="string"&&(t.provider=e.provider),typeof e.mode=="string"&&(t.mode=e.mode),typeof e.health=="string"&&(t.health=e.health),typeof e.branch=="string"&&(t.branch=e.branch),typeof e.worktree=="string"&&(t.worktree=e.worktree),(e.context_usage===null||typeof e.context_usage=="object"&&e.context_usage!==null)&&(t.context_usage=e.context_usage),(e.subagent===null||typeof e.subagent=="object"&&e.subagent!==null)&&(t.subagent=e.subagent),typeof e.capability=="object"&&e.capability!==null&&(t.capability=e.capability),Object.keys(t).length>0?t:null},WR=(e,t,a)=>{if(!e||e.session.id!==t)return e;const{last_event_at:l,...o}=a;let u={...e.session,...o};if(typeof l=="string"&&l.trim()){const f=new Date(l).getTime(),m=new Date(e.session.last_event_at).getTime();Number.isFinite(f)&&(!Number.isFinite(m)||f>m)&&(u={...u,last_event_at:l})}return{...e,session:u}},Fb=_.lazy(async()=>({default:(await Zr(()=>import("./session-diff-preview-DwKy91Si.js"),__vite__mapDeps([0,1]))).SessionDiffPreview})),Ag=["var(--session-git-graph-1)","var(--session-git-graph-2)","var(--session-git-graph-3)","var(--session-git-graph-4)","var(--session-git-graph-5)","var(--session-git-graph-6)"],kx=14,Ex=10,Ul=24,gu=48,Dg=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m9 6 6 6-6 6"})}),KR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M20 11a8 8 0 1 0 2.2 5.5"}),i.jsx("path",{d:"M20 4v7h-7"})]}),QR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M3 12a9 9 0 1 0 2.64-6.36"}),i.jsx("path",{d:"M3 4v5h5"}),i.jsx("path",{d:"M12 7v5l3 2"})]}),qb=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9 14 4 9l5-5"}),i.jsx("path",{d:"M4 9h8a8 8 0 1 1 0 16h-1"})]}),Wb=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7.5 12.5 10.5 15.5 16.5 8.5"}),i.jsx("circle",{cx:"12",cy:"12",r:"8.5"})]}),GR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 16V5"}),i.jsx("path",{d:"m7.5 9.5 4.5-4.5 4.5 4.5"}),i.jsx("path",{d:"M5 19h14"})]}),YR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6 18 18"}),i.jsx("path",{d:"M18 6 6 18"})]}),VR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 4v10"}),i.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),i.jsx("path",{d:"M17 6a4 4 0 0 0-4 4H7"}),i.jsx("circle",{cx:"7",cy:"4",r:"2"}),i.jsx("circle",{cx:"17",cy:"6",r:"2"}),i.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),ZR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"4",y:"5",width:"16",height:"11",rx:"2"}),i.jsx("path",{d:"M8 19h8"}),i.jsx("path",{d:"M10 16v3"}),i.jsx("path",{d:"M14 16v3"})]}),XR=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M7.5 18a4.5 4.5 0 1 1 .9-8.91A5.5 5.5 0 0 1 19 11a3.5 3.5 0 0 1-.5 7Z"})}),JR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 4v10"}),i.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),i.jsx("path",{d:"M7 10a4 4 0 0 1 4-4h6"}),i.jsx("circle",{cx:"7",cy:"4",r:"2"}),i.jsx("circle",{cx:"17",cy:"6",r:"2"}),i.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),zl=({label:e,icon:t,onClick:a,disabled:l=!1,variant:o="default",pending:u=!1,className:f})=>i.jsx("button",{type:"button",className:`session-git-panel__icon-button is-${o} ${u?"is-pending":""} ${f??""}`.trim(),onClick:a,disabled:l,"aria-label":e,title:e,children:i.jsx("span",{className:"session-git-panel__icon-button-glyph","aria-hidden":"true",children:t})}),Kb=e=>{switch(e){case"added":return"A";case"deleted":return"D";case"renamed":return"R";case"untracked":return"U";default:return"M"}},eM=e=>e.status==="renamed"&&e.previous_path?`该变更仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件已删除,没有可展示的补丁内容。":e.status==="untracked"?"该文件还没有可展示的补丁内容。":"此变更没有可展示的补丁内容。",tM=(e,t)=>t&&t.diff.trim()?"此变更没有可展示的补丁内容。":e.status==="renamed"&&e.previous_path?`该提交仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件在这次提交中已删除,没有可展示的补丁内容。":"该文件在这次提交中没有可展示的补丁内容。",jf=e=>Ag[e%Ag.length]??Ag[0],zo=e=>Ex+e*kx,Tm=(e,t)=>`${e}\0${t}`,B_=e=>Array.isArray(e.parent_oids)?e.parent_oids.filter(Boolean):[],nM=e=>Array.isArray(e.refs)?e.refs.filter(Boolean):[],sM=e=>{var u;const t={};let a=[],l=0;const o=()=>{const f=l;return l+=1,f};for(const f of e){let m=a.findIndex(w=>w.oid===f.oid);m<0&&(a=[...a,{oid:f.oid,colorIndex:o()}],m=a.length-1);const y=a.map(w=>({...w})),g=((u=y[m])==null?void 0:u.colorIndex)??o(),S=[...new Set(B_(f))],p=y.map(w=>({...w}));S.length>0?p[m]={oid:S[0],colorIndex:g}:p.splice(m,1);const b=[];if(S.length>0){const w=p.findIndex(N=>N.oid===S[0]);b.push(w>=0?w:m)}S.slice(1).forEach((w,N)=>{let j=p.findIndex(T=>T.oid===w);j<0&&(j=Math.min(p.length,m+1+N),p.splice(j,0,{oid:w,colorIndex:o()})),b.push(j)}),t[f.oid]={beforeLanes:y,afterLanes:p,laneIndex:m,nodeColorIndex:g,parentLaneIndexes:b},a=p.filter((w,N,j)=>j.findIndex(T=>T.oid===w.oid)===N)}return t},aM=({commit:e,row:t,isLocalHead:a,isRemoteHead:l,isFirstRow:o,maxLaneCount:u})=>{const f=B_(e).length,m=Math.max(u,t.beforeLanes.length,t.afterLanes.length,1),y=Math.max(40,Ex*2+(m-1)*kx),g=zo(t.laneIndex),S=f>1?4.7:3.9,p=Math.max(0,Ul-S-1.1),b={"--session-git-graph-width":`${Math.max(48,Math.ceil(y*(56/gu)))}px`};return i.jsx("span",{className:"session-git-history__graph",style:b,children:i.jsxs("svg",{className:`session-git-history__graph-svg ${f>1?"is-merge":""}`,viewBox:`0 0 ${y} ${gu}`,preserveAspectRatio:"xMinYMid meet","aria-hidden":"true",children:[t.beforeLanes.map((w,N)=>i.jsx("path",{d:`M ${zo(N)} ${o?p:0} L ${zo(N)} ${p}`,stroke:jf(w.colorIndex),strokeWidth:"2",strokeLinecap:"round",fill:"none",opacity:o?0:1},`before:${w.oid}:${N}`)),t.afterLanes.map((w,N)=>{const j=t.beforeLanes.findIndex(I=>I.oid===w.oid),T=j>=0?zo(j):zo(N),D=zo(N),z=T===D?`M ${D} ${Ul} L ${D} ${gu}`:`M ${T} ${Ul} C ${T} 27 ${D} 31 ${D} ${gu}`;return i.jsx("path",{d:z,stroke:jf(w.colorIndex),strokeWidth:"2",strokeLinecap:"round",fill:"none"},`after:${w.oid}:${N}`)}),t.parentLaneIndexes.map((w,N)=>{var z;const j=zo(w),T=jf(((z=t.afterLanes[w])==null?void 0:z.colorIndex)??t.nodeColorIndex),D=j===g?`M ${g} ${Ul} L ${j} ${gu}`:`M ${g} ${Ul} C ${g} 27 ${j} 31 ${j} ${gu}`;return i.jsx("path",{d:D,stroke:T,strokeWidth:N>0||f>1?"2.2":"2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",opacity:N>0||f>1?.96:.88},`parent:${e.oid}:${N}`)}),i.jsx("circle",{cx:g,cy:Ul,r:S,fill:"var(--color-surface-panel)",stroke:jf(t.nodeColorIndex),strokeWidth:f>1?"1.8":"1.55"}),i.jsx("circle",{cx:g,cy:Ul,r:a||l?1.6:1.05,fill:jf(t.nodeColorIndex)}),a&&l?i.jsx("circle",{cx:g,cy:Ul,r:"6.4",fill:"none",stroke:"color-mix(in oklab, var(--color-accent-primary) 22%, transparent)",strokeWidth:"1",strokeDasharray:"1.5 3"}):null]})})},iM=({workspace:e,history:t,isLoading:a,isHistoryLoading:l,error:o,historyError:u,onRefresh:f,onRefreshHistory:m,onRequestHistory:y,onDiscardFile:g,onDiscardAll:S,onCommitAll:p,onSwitchBranch:b,onPush:w,onLoadWorkspaceFileDiff:N,onLoadHistoryFileDiff:j,pendingAction:T,compact:D=!1})=>{const[z,I]=_.useState("changes"),[k,P]=_.useState({}),[Q,se]=_.useState({}),[W,V]=_.useState({}),[Y,ee]=_.useState({}),[me,ge]=_.useState({}),[te,xe]=_.useState({}),[C,q]=_.useState({}),[ie,he]=_.useState({}),[re,L]=_.useState({}),[ae,ke]=_.useState(!1),[U,ve]=_.useState(null),[Z,Se]=_.useState(""),[je,Oe]=_.useState(null),Ie=_.useRef(null);_.useEffect(()=>{P(Fe=>{if(!(e!=null&&e.files.length))return{};const X=new Set(e.files.map(ue=>ue.path));let B=!1;const oe={};for(const[ue,we]of Object.entries(Fe)){if(!X.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:Fe});const _e=new Set((e==null?void 0:e.files.map(Fe=>Fe.path))??[]);se(Fe=>{let X=!1;const B={};for(const[oe,ue]of Object.entries(Fe)){if(!_e.has(oe)){X=!0;continue}B[oe]=ue}return X?B:Fe}),V(Fe=>{let X=!1;const B={};for(const[oe,ue]of Object.entries(Fe)){if(!_e.has(oe)){X=!0;continue}B[oe]=ue}return X?B:Fe}),ee(Fe=>{let X=!1;const B={};for(const[oe,ue]of Object.entries(Fe)){if(!_e.has(oe)){X=!0;continue}B[oe]=ue}return X?B:Fe})},[e==null?void 0:e.files]),_.useEffect(()=>{const _e=new Set((t==null?void 0:t.commits.map(X=>X.oid))??[]),Fe=new Set((t==null?void 0:t.commits.flatMap(X=>X.files.map(B=>Tm(X.oid,B.path))))??[]);ge(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!_e.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X}),xe(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!_e.has(ue)){B=!0;continue}if(we&&!Fe.has(Tm(ue,we))){B=!0,oe[ue]=null;continue}oe[ue]=we}return B?oe:X}),q(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!Fe.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X}),he(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!Fe.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X}),L(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!Fe.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X})},[t==null?void 0:t.commits]),_.useEffect(()=>{if(!ae)return;const _e=Fe=>{var X;(X=Ie.current)!=null&&X.contains(Fe.target)||ke(!1)};return window.addEventListener("pointerdown",_e),()=>{window.removeEventListener("pointerdown",_e)}},[ae]),_.useEffect(()=>{e&&(U==="commit"&&(T==null?void 0:T.action)!=="commit-all"&&e.files.length===0&&(ve(null),Se("")),je&&e.branch===je&&(Oe(null),ve(null),Se(""),ke(!1)))},[U,T==null?void 0:T.action,je,e]),_.useEffect(()=>{e!=null&&e.branches.length||ke(!1)},[e==null?void 0:e.branches]),_.useEffect(()=>{se({}),V({}),ee({})},[e==null?void 0:e.updated_at]);const wt=(e==null?void 0:e.files)??[],qe=(t==null?void 0:t.commits)??[],bt=wt.length>0,Ut=qe.length>0,$t=(T==null?void 0:T.action)==="discard-all",zt=(T==null?void 0:T.action)==="commit-all",xt=(T==null?void 0:T.action)==="switch-branch",it=(T==null?void 0:T.action)==="push",ot=z==="changes",ln=U==="switch-branch"&&je?`提交后切换到 ${je}`:"提交全部改动",on=_.useMemo(()=>{if(!e)return null;const _e=[];return e.upstream_branch&&_e.push(e.upstream_branch),e.ahead_count>0&&_e.push(`ahead ${e.ahead_count}`),e.behind_count>0&&_e.push(`behind ${e.behind_count}`),_e.join(" · ")},[e]),kn=_.useMemo(()=>{if(!t)return null;const _e=[t.branch];return t.upstream_branch&&_e.push(t.upstream_branch),_e.join(" · ")},[t]),En=_.useMemo(()=>z==="history"?sM(qe):{},[z,qe]),ht=_.useMemo(()=>z!=="history"?1:Math.max(1,...Object.values(En).map(_e=>Math.max(_e.beforeLanes.length,_e.afterLanes.length,_e.laneIndex+1))),[z,En]),Ve=(_e,Fe)=>{Q[_e]||W[_e]||(V(X=>({...X,[_e]:!0})),ee(X=>{const B={...X};return delete B[_e],B}),N(_e,Fe).then(X=>{se(B=>({...B,[_e]:X}))}).catch(X=>{ee(B=>({...B,[_e]:X instanceof Error?X.message:"无法读取该文件的差异。"}))}).finally(()=>{V(X=>{const B={...X};return delete B[_e],B})}))};_.useEffect(()=>{if(!(z!=="changes"||wt.length===0))for(const _e of wt)k[_e.path]&&Ve(_e.path,_e.previous_path)},[z,k,wt,N,Q,W]);const Ke=()=>{ve(null),Se(""),Oe(null)},Nt=()=>{Oe(null),ve(_e=>_e==="commit"?(Se(""),null):"commit")},Bt=()=>{const _e=Z.trim();if(_e){if(U==="switch-branch"&&je){Promise.resolve(b(je,_e)).catch(()=>{});return}p(_e)}},Jt=_e=>{if(!(!e||_e===e.branch||T)){if(ke(!1),e.files.length>0){Oe(_e),ve("switch-branch");return}Promise.resolve(b(_e)).catch(()=>{})}},Dt=()=>{if(ot){f();return}m()},Ze=()=>{I(_e=>{const Fe=_e==="changes"?"history":"changes";return Fe==="history"&&y(),Fe})},un=(_e,Fe)=>{const X=Tm(_e.oid,Fe.path),B=te[_e.oid]===Fe.path;xe(oe=>({...oe,[_e.oid]:B?null:Fe.path})),!(B||C[X]||ie[X])&&(he(oe=>({...oe,[X]:!0})),L(oe=>{const ue={...oe};return delete ue[X],ue}),j(_e.oid,Fe.path,Fe.previous_path).then(oe=>{q(ue=>({...ue,[X]:oe}))}).catch(oe=>{L(ue=>({...ue,[X]:oe instanceof Error?oe.message:"无法读取该文件的提交差异。"}))}).finally(()=>{he(oe=>{const ue={...oe};return delete ue[X],ue})}))},ut=_e=>{const Fe=new Date(_e);return Number.isNaN(Fe.getTime())?_e:new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(Fe)};return i.jsxs("section",{className:`session-git-panel ${D?"is-compact":""}`,children:[i.jsxs("div",{className:"session-git-panel__header",children:[i.jsxs("div",{className:"session-git-panel__heading",ref:Ie,children:[i.jsxs("button",{type:"button",className:"session-git-panel__branch-button",onClick:()=>ke(_e=>!_e),disabled:!e||!!T,"aria-haspopup":"menu","aria-expanded":ae,title:e?`切换分支:${e.branch}`:"分支加载中",children:[i.jsx("span",{className:"session-git-panel__branch-icon","aria-hidden":"true",children:i.jsx(VR,{})}),i.jsx("span",{className:"session-git-panel__branch",children:(e==null?void 0:e.branch)??"加载中"}),i.jsx("span",{className:`session-git-panel__branch-chevron ${ae?"is-open":""}`,"aria-hidden":"true",children:i.jsx(Dg,{})})]}),ae&&e?i.jsx("div",{className:"session-git-panel__branch-menu",role:"menu","aria-label":"分支列表",children:e.branches.map(_e=>{const Fe=_e===e.branch,X=(T==null?void 0:T.action)==="switch-branch"&&T.branch===_e;return i.jsxs("button",{type:"button",className:`session-git-panel__branch-option ${Fe?"is-current":""}`,onClick:()=>Jt(_e),disabled:Fe||!!T,role:"menuitemradio","aria-checked":Fe,title:Fe?`${_e}(当前)`:`切换到 ${_e}`,children:[i.jsx("span",{className:"session-git-panel__branch-option-name",children:_e}),Fe?i.jsx("span",{className:"session-git-panel__branch-option-meta",children:"当前"}):null,X?i.jsx("span",{className:"session-git-panel__branch-option-meta",children:"切换中"}):null]},_e)})}):null]}),i.jsxs("div",{className:"session-git-panel__toolbar",children:[i.jsx(zl,{label:ot?"切换到提交历史":"返回修改列表",icon:i.jsx(QR,{}),onClick:Ze,disabled:!!T,variant:ot?"default":"primary",className:ot?void 0:"is-active"}),i.jsx(zl,{label:ot?a?"正在刷新":"刷新":l?"正在刷新历史":"刷新历史",icon:i.jsx(KR,{}),onClick:Dt,disabled:ot?a||!!T:l,pending:ot?a:l}),ot&&bt?i.jsxs(i.Fragment,{children:[i.jsx(zl,{label:$t?"正在撤回全部修改":"撤回全部修改",icon:i.jsx(qb,{}),onClick:S,disabled:!!T,variant:"danger",pending:$t}),i.jsx(zl,{label:zt?"正在提交全部修改":U==="commit"?"收起提交编辑器":"提交全部修改",icon:i.jsx(Wb,{}),onClick:Nt,disabled:!!T,variant:"primary",pending:zt})]}):null,ot&&!bt?i.jsx(zl,{label:it?"正在推送当前分支":"推送当前分支",icon:i.jsx(GR,{}),onClick:w,disabled:!!T,variant:"primary",pending:it}):null]})]}),ot&&e?i.jsxs("div",{className:"session-git-panel__summary",children:[i.jsx("span",{className:"session-git-panel__summary-text",children:bt?`${wt.length} 个文件待处理`:"当前工作区没有待提交改动"}),on?i.jsx("span",{className:"session-git-panel__summary-meta",children:on}):null]}):null,!ot&&t?i.jsxs("div",{className:"session-git-panel__summary",children:[i.jsx("span",{className:"session-git-panel__summary-text",children:Ut?`${qe.length} 条最近提交`:"当前分支还没有提交历史"}),kn?i.jsx("span",{className:"session-git-panel__summary-meta",children:kn}):null]}):null,ot&&U&&bt?i.jsxs("div",{className:"session-git-panel__composer",children:[i.jsx("div",{className:"session-git-panel__composer-title",children:ln}),i.jsxs("div",{className:"session-git-panel__composer-row",children:[i.jsx("input",{value:Z,onChange:_e=>Se(_e.target.value),placeholder:"输入 commit message",className:"session-git-panel__input",disabled:!!T}),i.jsx(zl,{label:U==="switch-branch"?"提交并切换分支":"确认提交",icon:i.jsx(Wb,{}),onClick:Bt,disabled:!Z.trim()||!!T,variant:"primary",pending:zt||xt}),i.jsx(zl,{label:"取消提交",icon:i.jsx(YR,{}),onClick:Ke,disabled:!!T})]})]}):null,ot&&o?i.jsx("div",{className:"session-git-panel__notice is-error",children:o}):null,!ot&&u?i.jsx("div",{className:"session-git-panel__notice is-error",children:u}):null,ot&&a&&!e?i.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前工作区改动…"}):null,!ot&&l&&!t?i.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前分支提交历史…"}):null,ot&&!a&&e&&!bt?i.jsx("div",{className:"session-git-panel__empty",children:"当前分支没有待提交改动。你现在可以直接推送当前分支。"}):null,!ot&&!l&&t&&!Ut?i.jsx("div",{className:"session-git-panel__empty",children:"当前分支还没有提交历史。"}):null,ot&&bt?i.jsx("div",{className:"session-git-panel__list",children:wt.map(_e=>{const Fe=!!k[_e.path],X=(T==null?void 0:T.action)==="discard-file"&&T.path===_e.path,B=Q[_e.path],oe=!!W[_e.path],ue=Y[_e.path]??null;return i.jsxs("article",{className:`session-git-file ${Fe?"is-expanded":""}`,children:[i.jsxs("div",{className:"session-git-file__head",children:[i.jsxs("button",{type:"button",className:"session-git-file__toggle",onClick:()=>{const we=!Fe;P(Re=>({...Re,[_e.path]:we})),we&&Ve(_e.path,_e.previous_path)},"aria-expanded":Fe,children:[i.jsxs("span",{className:"session-git-file__main",children:[i.jsx("span",{className:"session-git-file__path",children:_e.path}),_e.previous_path?i.jsxs("span",{className:"session-git-file__rename",children:["来自 ",_e.previous_path]}):null]}),i.jsxs("span",{className:"session-git-file__meta",children:[i.jsx("span",{className:`session-git-file__status is-${_e.status}`,children:Kb(_e.status)}),i.jsxs("span",{className:"session-git-file__counts",children:[i.jsxs("span",{className:"is-add",children:["+",_e.additions]}),i.jsxs("span",{className:"is-remove",children:["-",_e.deletions]})]}),i.jsx("span",{className:"session-git-file__chevron","aria-hidden":"true",children:i.jsx(Dg,{})})]})]}),i.jsx(zl,{label:X?`正在撤回 ${_e.path}`:`撤回 ${_e.path}`,icon:i.jsx(qb,{}),onClick:()=>g(_e.path),disabled:!!T,variant:"danger",pending:X,className:"session-git-file__action"})]}),Fe?i.jsx("div",{className:"session-git-file__detail",children:ue?i.jsx("div",{className:"session-git-panel__notice is-error",children:ue}):oe?i.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的差异…"}):i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:i.jsx(Fb,{diffText:(B==null?void 0:B.diff)??"",filePath:_e.path,emptyMessage:eM(_e)})})}):null]},_e.path)})}):null,!ot&&Ut?i.jsx("div",{className:"session-git-history",children:qe.map((_e,Fe)=>{const X=!!me[_e.oid],B=B_(_e),oe=te[_e.oid]??null,ue=En[_e.oid],we=(t==null?void 0:t.head_oid)===_e.oid,Re=(t==null?void 0:t.upstream_head_oid)===_e.oid,He=nM(_e).filter(ze=>!ze||ze===(t==null?void 0:t.branch)||ze===(t==null?void 0:t.upstream_branch)||ze===`HEAD -> ${t==null?void 0:t.branch}`?!1:ze!=="HEAD");return i.jsxs("article",{className:`session-git-history__item ${X?"is-expanded":""} ${B.length>1?"is-merge":""} ${we?"is-local-head":""} ${Re?"is-remote-head":""}`.trim(),children:[i.jsxs("button",{type:"button",className:"session-git-history__toggle",onClick:()=>ge(ze=>({...ze,[_e.oid]:!ze[_e.oid]})),"aria-expanded":X,children:[ue?i.jsx(aM,{commit:_e,row:ue,isLocalHead:we,isRemoteHead:Re,isFirstRow:Fe===0,maxLaneCount:ht}):null,i.jsxs("span",{className:"session-git-history__content",children:[i.jsx("span",{className:"session-git-history__subject",children:_e.subject}),i.jsxs("span",{className:"session-git-history__meta",children:[i.jsx("span",{children:_e.short_oid}),i.jsx("span",{children:_e.author_name}),i.jsx("span",{children:ut(_e.committed_at)})]})]}),i.jsxs("span",{className:"session-git-history__refs",children:[we?i.jsx("span",{className:"session-git-history__ref is-local",title:"本地当前 HEAD",children:i.jsx(ZR,{})}):null,Re?i.jsx("span",{className:"session-git-history__ref is-remote",title:t!=null&&t.upstream_branch?`云端位置:${t.upstream_branch}`:"云端位置",children:i.jsx(XR,{})}):null,B.length>1?i.jsx("span",{className:"session-git-history__ref is-merge",title:"合并提交",children:i.jsx(JR,{})}):null,He.slice(0,2).map(ze=>i.jsx("span",{className:"session-git-history__ref is-label",title:ze,children:ze},`${_e.oid}:${ze}`))]}),i.jsx("span",{className:"session-git-history__chevron","aria-hidden":"true",children:i.jsx(Dg,{})})]}),X?i.jsx("div",{className:"session-git-history__files",children:i.jsx("div",{className:"session-git-history__files-list",children:_e.files.map(ze=>{const rt=oe===ze.path,It=Tm(_e.oid,ze.path),Ft=C[It],Le=!!ie[It],Et=re[It]??null;return i.jsxs("div",{className:`session-git-history-file-row ${rt?"is-selected":""}`,children:[i.jsxs("button",{type:"button",className:`session-git-history-file ${rt?"is-selected":""}`,onClick:()=>un(_e,ze),"aria-pressed":rt,children:[i.jsx("span",{className:`session-git-file__status is-${ze.status}`,children:Kb(ze.status)}),i.jsx("span",{className:"session-git-history-file__path",children:ze.path}),ze.previous_path?i.jsxs("span",{className:"session-git-history-file__rename",children:["来自 ",ze.previous_path]}):null,i.jsx("span",{className:"session-git-history-file__meta",children:Ft?i.jsxs("span",{className:"session-git-history-file__counts",children:[i.jsxs("span",{className:"is-add",children:["+",Ft.additions]}),i.jsxs("span",{className:"is-remove",children:["-",Ft.deletions]})]}):Le?i.jsx("span",{className:"session-git-history-file__loading",children:"读取中…"}):i.jsx("span",{className:"session-git-history-file__hint",children:"点击查看"})})]}),rt?i.jsxs("div",{className:"session-git-history__diff is-inline",children:[i.jsxs("div",{className:"session-git-history__diff-header",children:[i.jsx("span",{className:"session-git-history__diff-path",children:ze.path}),ze.previous_path?i.jsxs("span",{className:"session-git-history__diff-rename",children:["来自 ",ze.previous_path]}):null]}),Et?i.jsx("div",{className:"session-git-panel__notice is-error",children:Et}):Le?i.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的提交差异…"}):i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:i.jsx(Fb,{diffText:(Ft==null?void 0:Ft.diff)??"",filePath:ze.path,emptyMessage:tM(ze,Ft??null)})})]}):null]},`${_e.oid}:${ze.path}`)})})}):null]},_e.oid)})}):null]})},Qb={name:"",description:null,command:"",kill_command:null,cwd:null,shell:"auto",node_version:null,port:null},Gb=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m8 6 9 6-9 6z"})}),Yb=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("rect",{x:"6.5",y:"6.5",width:"11",height:"11",rx:"1.8"})}),rM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),i.jsx("path",{d:"M18 15.2 18.8 18 21.6 18.8 18.8 19.6 18 22.4 17.2 19.6 14.4 18.8 17.2 18Z"})]}),lM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m4 20 4.2-1 9.2-9.2a1.8 1.8 0 0 0 0-2.6l-.6-.6a1.8 1.8 0 0 0-2.6 0L5 15.8 4 20Z"}),i.jsx("path",{d:"m13.5 6.5 4 4"})]}),oM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M4.5 7h15"}),i.jsx("path",{d:"M9.5 4.5h5"}),i.jsx("path",{d:"M7 7l.6 11a1.8 1.8 0 0 0 1.8 1.7h5.2a1.8 1.8 0 0 0 1.8-1.7L17 7"}),i.jsx("path",{d:"M10 10.5v5.2"}),i.jsx("path",{d:"M14 10.5v5.2"})]}),cM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 5v14"}),i.jsx("path",{d:"M5 12h14"})]}),Vb={auto:"自动",powershell:"PowerShell",cmd:"CMD",bash:"Bash"},uM=({commands:e,nodeRuntime:t,error:a,pendingRunCommandId:l,pendingKillCommandId:o,pendingDeleteCommandId:u,isSaving:f,isGenerating:m,isStartingAll:y,isStoppingAll:g,generationReason:S,executionModelLabel:p,onRun:b,onRunAll:w,onRunAllKill:N,onRunKill:j,onSave:T,onDelete:D,onGenerate:z})=>{var xe;const[I,k]=_.useState("list"),[P,Q]=_.useState(null),[se,W]=_.useState(Qb),V=_.useMemo(()=>e.find(C=>C.id===P)??null,[e,P]),Y=_.useMemo(()=>{const C=[...(t==null?void 0:t.versions)??[]];return se.node_version&&!C.includes(se.node_version)&&C.unshift(se.node_version),C},[se.node_version,t==null?void 0:t.versions]),ee=_.useMemo(()=>e.filter(C=>!!C.kill_command).length,[e]),me=()=>{W(Qb),Q(null),k("edit")},ge=C=>{W({name:C.name,description:C.description,command:C.command,kill_command:C.kill_command,cwd:C.cwd,shell:C.shell,node_version:C.node_version,port:C.port}),Q(C.id),k("edit")},te=()=>{T({commandId:V==null?void 0:V.id,draft:se}),f||(k("list"),Q(null))};return i.jsxs("div",{className:"session-run-panel",children:[i.jsxs("div",{className:"session-run-panel__header",children:[i.jsxs("div",{className:"session-run-panel__header-copy",children:[i.jsxs("div",{className:"session-run-panel__title-row",children:[i.jsx("h2",{className:"session-run-panel__title",children:"项目命令"}),i.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),i.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",p]})]}),i.jsxs("div",{className:"session-run-panel__header-actions",children:[i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-primary","aria-label":y?"正在一键启动项目命令":"一键启动项目命令",title:y?"正在一键启动项目命令":"一键启动项目命令",disabled:e.length===0||y||g,onClick:w,children:i.jsx(Gb,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":g?"正在一键停止项目命令":"一键停止项目命令",title:g?"正在一键停止项目命令":"一键停止项目命令",disabled:ee===0||y||g,onClick:N,children:i.jsx(Yb,{})}),i.jsx("button",{type:"button",className:`session-run-panel__icon-button ${m?"is-loading":""}`,"aria-label":m?"正在一键生成项目命令":"一键生成项目命令",title:m?"正在一键生成项目命令":"一键生成项目命令","aria-busy":m,disabled:m||y||g,onClick:z,children:i.jsx(rM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目命令",title:"新增项目命令",onClick:me,children:i.jsx(cM,{})})]})]}),a?i.jsx("div",{className:"session-run-panel__notice is-error",children:a}):null,m?i.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐命令…"}):null,S?i.jsx("div",{className:"session-run-panel__hint",children:S}):null,I==="edit"?i.jsxs("div",{className:"session-run-panel__card",children:[i.jsx("h3",{className:"session-run-panel__section-title",children:V?"编辑命令":"新增命令"}),i.jsxs("div",{className:"session-run-panel__form-grid",children:[i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"名称"}),i.jsx("input",{value:se.name,onChange:C=>W(q=>({...q,name:C.target.value})),className:"session-run-panel__input",placeholder:"例如:启动前端"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"说明"}),i.jsx("input",{value:se.description??"",onChange:C=>W(q=>({...q,description:C.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),i.jsxs("label",{className:"session-run-panel__field is-full",children:[i.jsx("span",{children:"命令"}),i.jsx("textarea",{value:se.command,onChange:C=>W(q=>({...q,command:C.target.value})),className:"session-run-panel__textarea",placeholder:"pnpm dev",rows:4})]}),i.jsxs("label",{className:"session-run-panel__field is-full",children:[i.jsx("span",{children:"停止命令"}),i.jsx("textarea",{value:se.kill_command??"",onChange:C=>W(q=>({...q,kill_command:C.target.value||null})),className:"session-run-panel__textarea",placeholder:"留空表示不需要单独停止",rows:3})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"工作目录"}),i.jsx("input",{value:se.cwd??"",onChange:C=>W(q=>({...q,cwd:C.target.value||null})),className:"session-run-panel__input",placeholder:"留空表示项目根目录"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"端口"}),i.jsx("input",{value:se.port??"",onChange:C=>{const q=Number.parseInt(C.target.value,10);W(ie=>({...ie,port:Number.isFinite(q)&&q>0?q:null}))},className:"session-run-panel__input",placeholder:"例如:5173",inputMode:"numeric"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"Shell"}),i.jsx("select",{value:se.shell,onChange:C=>W(q=>({...q,shell:C.target.value})),className:"session-run-panel__select",children:Object.entries(Vb).map(([C,q])=>i.jsx("option",{value:C,children:q},C))})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"Node 环境"}),i.jsxs("select",{value:se.node_version??"",onChange:C=>W(q=>({...q,node_version:C.target.value||null})),className:"session-run-panel__select",children:[i.jsx("option",{value:"",children:"默认环境"}),Y.map(C=>i.jsxs("option",{value:C,children:["Node ",C,t!=null&&t.versions.includes(C)?"":"(未检测到)"]},C))]})]})]}),i.jsx("div",{className:"session-run-panel__hint",children:t!=null&&t.versions.length?"Node 版本只会临时注入当前命令,不会修改系统全局环境。":((xe=t==null?void 0:t.error)==null?void 0:xe.trim())||"未检测到可用的 nvm Node 版本,将按默认环境运行。"}),i.jsxs("div",{className:"session-run-panel__form-actions",children:[i.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>k("list"),children:"取消"}),i.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!se.name.trim()||!se.command.trim()||f,onClick:te,children:f?"保存中...":V?"保存修改":"保存命令"})]})]}):null,i.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(C=>i.jsxs("article",{className:"session-run-panel__command-card",children:[i.jsxs("div",{className:"session-run-panel__command-head",children:[i.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>ge(C),children:[i.jsxs("div",{className:"session-run-panel__command-heading",children:[i.jsx("span",{className:"session-run-panel__command-name",children:C.name}),C.description?i.jsx("span",{className:"session-run-panel__command-description",children:C.description}):null]}),i.jsx("div",{className:"session-run-panel__command-line",children:C.command})]}),i.jsxs("div",{className:"session-run-panel__command-actions",children:[C.kill_command?i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":`执行 ${C.name} 的停止命令`,title:`执行 ${C.name} 的停止命令`,disabled:o===C.id,onClick:()=>j(C.id),children:i.jsx(Yb,{})}):null,i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${C.name}`,title:`编辑 ${C.name}`,onClick:()=>ge(C),children:i.jsx(lM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${C.name}`,title:`删除 ${C.name}`,disabled:u===C.id,onClick:()=>D(C.id),children:i.jsx(oM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-primary","aria-label":`运行 ${C.name}`,title:`运行 ${C.name}`,disabled:l===C.id,onClick:()=>b(C.id),children:i.jsx(Gb,{})})]})]}),i.jsx("div",{className:"session-run-panel__command-footer",children:i.jsxs("div",{className:"session-run-panel__command-meta",children:[i.jsx("span",{className:"session-run-panel__command-pill",children:Vb[C.shell]}),C.node_version?i.jsxs("span",{className:"session-run-panel__command-pill is-node",children:["Node ",C.node_version]}):null,C.port?i.jsxs("span",{className:"session-run-panel__command-pill",children:[":",C.port]}):null,C.kill_command?i.jsx("span",{className:"session-run-panel__command-pill is-kill",children:"可停止"}):null,i.jsx("span",{className:"session-run-panel__command-pill",children:C.cwd?C.cwd:"项目根目录"})]})})]},C.id)):i.jsxs("div",{className:"session-run-panel__empty",children:[i.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目命令"}),i.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},Zb={name:"",description:null,url:""},dM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),i.jsx("path",{d:"M18 15.2 18.8 18 21.6 18.8 18.8 19.6 18 22.4 17.2 19.6 14.4 18.8 17.2 18Z"})]}),fM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),i.jsx("path",{d:"M3.8 12h16.4"}),i.jsx("path",{d:"M12 3.7c2.3 2.4 3.6 5.3 3.6 8.3S14.3 17.9 12 20.3c-2.3-2.4-3.6-5.3-3.6-8.3S9.7 6.1 12 3.7Z"})]}),hM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m4 20 4.2-1 9.2-9.2a1.8 1.8 0 0 0 0-2.6l-.6-.6a1.8 1.8 0 0 0-2.6 0L5 15.8 4 20Z"}),i.jsx("path",{d:"m13.5 6.5 4 4"})]}),mM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M4.5 7h15"}),i.jsx("path",{d:"M9.5 4.5h5"}),i.jsx("path",{d:"M7 7l.6 11a1.8 1.8 0 0 0 1.8 1.7h5.2a1.8 1.8 0 0 0 1.8-1.7L17 7"}),i.jsx("path",{d:"M10 10.5v5.2"}),i.jsx("path",{d:"M14 10.5v5.2"})]}),pM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 5v14"}),i.jsx("path",{d:"M5 12h14"})]}),gM=({websites:e,error:t,pendingDeleteWebsiteId:a,isSaving:l,isGenerating:o,generationReason:u,executionModelLabel:f,onOpen:m,onSave:y,onDelete:g,onGenerate:S})=>{const[p,b]=_.useState("list"),[w,N]=_.useState(null),[j,T]=_.useState(Zb),D=_.useMemo(()=>e.find(P=>P.id===w)??null,[w,e]),z=()=>{T(Zb),N(null),b("edit")},I=P=>{T({name:P.name,description:P.description,url:P.url}),N(P.id),b("edit")},k=()=>{y({websiteId:D==null?void 0:D.id,draft:j}),l||(b("list"),N(null))};return i.jsxs("div",{className:"session-run-panel",children:[i.jsxs("div",{className:"session-run-panel__header",children:[i.jsxs("div",{className:"session-run-panel__header-copy",children:[i.jsxs("div",{className:"session-run-panel__title-row",children:[i.jsx("h2",{className:"session-run-panel__title",children:"项目网页"}),i.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),i.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",f]})]}),i.jsxs("div",{className:"session-run-panel__header-actions",children:[i.jsx("button",{type:"button",className:`session-run-panel__icon-button ${o?"is-loading":""}`,"aria-label":o?"正在一键生成项目网页":"一键生成项目网页",title:o?"正在一键生成项目网页":"一键生成项目网页","aria-busy":o,disabled:o,onClick:S,children:i.jsx(dM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目网页",title:"新增项目网页",onClick:z,children:i.jsx(pM,{})})]})]}),t?i.jsx("div",{className:"session-run-panel__notice is-error",children:t}):null,o?i.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐网页…"}):null,u?i.jsx("div",{className:"session-run-panel__hint",children:u}):null,p==="edit"?i.jsxs("div",{className:"session-run-panel__card",children:[i.jsx("h3",{className:"session-run-panel__section-title",children:D?"编辑网页":"新增网页"}),i.jsxs("div",{className:"session-run-panel__form-grid",children:[i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"名称"}),i.jsx("input",{value:j.name,onChange:P=>T(Q=>({...Q,name:P.target.value})),className:"session-run-panel__input",placeholder:"例如:前端首页"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"说明"}),i.jsx("input",{value:j.description??"",onChange:P=>T(Q=>({...Q,description:P.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),i.jsxs("label",{className:"session-run-panel__field is-full",children:[i.jsx("span",{children:"地址"}),i.jsx("input",{value:j.url,onChange:P=>T(Q=>({...Q,url:P.target.value})),className:"session-run-panel__input",placeholder:"http://localhost:5173"})]})]}),i.jsxs("div",{className:"session-run-panel__form-actions",children:[i.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>b("list"),children:"取消"}),i.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!j.name.trim()||!j.url.trim()||l,onClick:k,children:l?"保存中...":D?"保存修改":"保存网页"})]})]}):null,i.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(P=>i.jsxs("article",{className:"session-run-panel__command-card",children:[i.jsxs("div",{className:"session-run-panel__command-head",children:[i.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>I(P),children:[i.jsxs("div",{className:"session-run-panel__command-heading",children:[i.jsx("span",{className:"session-run-panel__command-name",children:P.name}),P.description?i.jsx("span",{className:"session-run-panel__command-description",children:P.description}):null]}),i.jsx("div",{className:"session-run-panel__command-line",children:P.url})]}),i.jsxs("div",{className:"session-run-panel__command-actions",children:[i.jsx("a",{className:"session-run-panel__icon-button is-primary","aria-label":`打开 ${P.name}`,title:`打开 ${P.name}`,href:P.url,target:"_blank",rel:"noreferrer",onClick:()=>m(P),children:i.jsx(fM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${P.name}`,title:`编辑 ${P.name}`,onClick:()=>I(P),children:i.jsx(hM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${P.name}`,title:`删除 ${P.name}`,disabled:a===P.id,onClick:()=>g(P.id),children:i.jsx(mM,{})})]})]}),i.jsx("div",{className:"session-run-panel__command-footer",children:i.jsx("div",{className:"session-run-panel__command-meta",children:i.jsx("span",{className:"session-run-panel__command-pill",children:"网页"})})})]},P.id)):i.jsxs("div",{className:"session-run-panel__empty",children:[i.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目网页"}),i.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},_M=/\u001b\[([0-9;]*)m/g,yM={stdout:"",stderr:"stderr",system:"system"},Xb={30:"black",31:"red",32:"green",33:"yellow",34:"blue",35:"magenta",36:"cyan",37:"white",90:"bright-black",91:"bright-red",92:"bright-green",93:"bright-yellow",94:"bright-blue",95:"bright-magenta",96:"bright-cyan",97:"bright-white"},U0={fg:null,bg:null,bold:!1,dim:!1,underline:!1},vM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6 18 18"}),i.jsx("path",{d:"M18 6 6 18"})]}),bM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M8 4H4v4"}),i.jsx("path",{d:"M16 4h4v4"}),i.jsx("path",{d:"M8 20H4v-4"}),i.jsx("path",{d:"M16 20h4v-4"}),i.jsx("path",{d:"M9 9 4 4"}),i.jsx("path",{d:"m15 9 5-5"}),i.jsx("path",{d:"m9 15-5 5"}),i.jsx("path",{d:"m15 15 5 5"})]}),xM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9 4H4v5"}),i.jsx("path",{d:"M15 4h5v5"}),i.jsx("path",{d:"M9 20H4v-5"}),i.jsx("path",{d:"M15 20h5v-5"}),i.jsx("path",{d:"m4 9 5-5"}),i.jsx("path",{d:"m20 9-5-5"}),i.jsx("path",{d:"m4 15 5 5"}),i.jsx("path",{d:"m20 15-5 5"})]}),SM=e=>{if(!e)return"刚刚";const t=new Date(e);return Number.isNaN(t.getTime())?"刚刚":new Intl.DateTimeFormat("zh-CN",{hour:"2-digit",minute:"2-digit"}).format(t)},Jb=(e,t)=>{const a=[e];return t.bold&&a.push("is-bold"),t.dim&&a.push("is-dim"),t.underline&&a.push("is-underline"),t.fg&&a.push(`is-fg-${t.fg}`),t.bg&&a.push(`is-bg-${t.bg}`),a.join(" ")},jM=(e,t)=>{if(t===0)return{...U0};if(t===1)return{...e,bold:!0,dim:!1};if(t===2)return{...e,dim:!0,bold:!1};if(t===4)return{...e,underline:!0};if(t===22)return{...e,bold:!1,dim:!1};if(t===24)return{...e,underline:!1};if(t===39)return{...e,fg:null};if(t===49)return{...e,bg:null};const a=Xb[t];if(a)return{...e,fg:a};const l=Xb[t-10];return l&&t>=40?{...e,bg:l}:e},wM=(e,t)=>{const a=[];let l=0,o={...U0};for(const u of e.matchAll(_M)){const f=u.index??0;f>l&&a.push({text:e.slice(l,f),className:Jb(t,o)});const m=(u[1]??"").split(";").map(y=>Number.parseInt(y||"0",10)).filter(y=>Number.isFinite(y));m.length===0?o={...U0}:o=m.reduce(jM,o),l=f+u[0].length}return l<e.length&&a.push({text:e.slice(l),className:Jb(t,o)}),a.length===0&&a.push({text:e,className:t}),a},Cx=_.memo(({chunks:e})=>{const t=_.useMemo(()=>e.map(a=>{const l=yM[a.stream],o=["session-terminal-output__segment",`is-${a.stream}`].join(" ");return{cursor:a.cursor,label:l,segments:wM(a.text,o)}}),[e]);return i.jsx(i.Fragment,{children:t.map(a=>i.jsxs("span",{className:"session-terminal-output__chunk",children:[a.label?i.jsx("span",{className:"session-terminal-output__label",children:a.label}):null,a.segments.map((l,o)=>i.jsx("span",{className:l.className,children:l.text},`${a.cursor}:${o}`))]},a.cursor))})});Cx.displayName="TerminalOutput";const NM=({terminals:e,activeTerminalId:t,outputs:a,error:l,compact:o=!1,canToggleFullscreen:u=!1,isFullscreen:f=!1,onSelectTerminal:m,onCloseTerminal:y,onToggleFullscreen:g})=>{const S=_.useRef(null),p=e.find(w=>w.id===t)??e[0]??null,b=p?a[p.id]:null;return _.useEffect(()=>{const w=S.current;w&&(w.scrollTop=w.scrollHeight)},[b==null?void 0:b.chunks,p==null?void 0:p.id]),e.length===0?i.jsx("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:i.jsxs("div",{className:"session-terminal-panel__empty",children:[i.jsx("div",{className:"session-terminal-panel__empty-title",children:"还没有运行中的命令"}),i.jsx("p",{className:"session-terminal-panel__empty-copy",children:"从右上角的运行按钮启动一个项目命令后,这里会实时显示终端输出。"})]})}):i.jsxs("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:[i.jsxs("div",{className:"session-terminal-panel__tabs",children:[i.jsx("div",{className:"session-terminal-panel__tab-list",role:"tablist","aria-label":"终端列表",children:e.map(w=>{const N=w.id===(p==null?void 0:p.id);return i.jsxs("div",{className:`session-terminal-panel__tab ${N?"is-active":""}`,children:[i.jsxs("button",{type:"button",className:"session-terminal-panel__tab-button",role:"tab","aria-selected":N,onClick:()=>m(w.id),children:[i.jsx("span",{className:`session-terminal-panel__tab-dot is-${w.status}`,"aria-hidden":"true"}),i.jsx("span",{className:"session-terminal-panel__tab-title",children:w.title}),i.jsx("span",{className:"session-terminal-panel__tab-time",children:SM(w.last_output_at??w.updated_at)})]}),i.jsx("button",{type:"button",className:"session-terminal-panel__tab-close","aria-label":`关闭 ${w.title}`,onClick:j=>{j.stopPropagation(),y(w.id)},children:i.jsx(vM,{})})]},w.id)})}),u&&g?i.jsx("button",{type:"button",className:"session-terminal-panel__fullscreen-button",onClick:g,"aria-label":f?"退出终端全屏":"终端全屏",title:f?"退出终端全屏":"终端全屏",children:f?i.jsx(xM,{}):i.jsx(bM,{})}):null]}),p?i.jsxs(i.Fragment,{children:[l?i.jsx("div",{className:"session-terminal-panel__notice is-error",children:l}):null,b!=null&&b.error?i.jsx("div",{className:"session-terminal-panel__notice is-error",children:b.error}):null,b!=null&&b.truncated?i.jsx("div",{className:"session-terminal-panel__notice",children:"终端输出过长,已自动显示服务端仍保留的最近内容。"}):null,i.jsx("div",{ref:S,className:"session-terminal-panel__output-wrap",children:i.jsx("pre",{className:"session-terminal-output",children:b&&b.chunks.length>0?i.jsx(Cx,{chunks:b.chunks}):b!=null&&b.isLoading?i.jsx("span",{className:"session-terminal-output__placeholder",children:"正在读取终端输出..."}):i.jsx("span",{className:"session-terminal-output__placeholder",children:"这个终端暂时还没有输出。"})})})]}):null]})},kM=_.memo(function({conversationMainRef:t,conversationScrollRef:a,isDesktopSidebar:l,sidebarShift:o,isSidebarDragging:u,title:f,titleActions:m,topbarActions:y,onOpenSidebar:g,threadContent:S,connectionStatus:p,sessionRecoveryStatus:b,isConnectionDetailOpen:w,onToggleConnectionDetail:N,showThinkingStatus:j}){const T={transform:`translateX(${o}px)`,transition:u?"none":void 0};return i.jsxs("div",{ref:t,className:`conversation-main ${l?"has-desktop-sidebar":""}`,style:T,children:[i.jsxs("div",{className:"conversation-topbar",children:[l?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:g,"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]}),i.jsx("div",{className:"conversation-topbar__meta",children:i.jsxs("div",{className:"conversation-topbar__title-row",children:[i.jsx("h1",{children:f}),m]})}),y]}),i.jsx("div",{ref:a,className:"conversation-scroll",children:i.jsxs("div",{className:"conversation-thread",children:[S,p.state!=="connected"?i.jsx("section",{className:"conversation-entry is-connection-status",children:i.jsxs("div",{className:"connection-status",children:[i.jsx("button",{type:"button",className:"connection-status__pill",onClick:D=>{D.stopPropagation(),N()},children:i.jsx("span",{children:p.state==="failed"?"连接异常":`Reconnecting... ${p.attempt}/${p.maxAttempts}`})}),w&&p.error?i.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:p.error}):null]})}):null,p.state==="connected"&&b.state!=="idle"?i.jsx("section",{className:"conversation-entry is-connection-status",children:i.jsxs("div",{className:"connection-status",children:[i.jsx("div",{className:"connection-status__pill",children:i.jsx("span",{children:b.state==="recovering"?"恢复会话中...":"会话恢复失败"})}),b.state==="failed"&&b.error?i.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:b.error}):null]})}):null,j?i.jsx("section",{className:"conversation-entry is-thinking-status",children:i.jsx("div",{className:"thinking-status-pill",children:i.jsx("span",{children:"正在思考"})})}):null]})})]})}),EM="panda:last-session-id",CM=.4,TM=104,RM=1800*1e3,MM=15e3,AM=120*1e3,e2=1100,Tx="panda:desktop-sidebar-width",Mf="panda:desktop-sidebar-width-version",Af="2026-03-24-narrow",DM=300,Rx=232,_u=Rx,OM=460,t2=72,Og=72,n2=120,z0=54,s2=300,IM=640,LM=4200,Ig="local-model-panel:",PM=160,UM={id:"",agent_id:"",name:"",display_name:null,pinned:!1,path:""},zM={id:"",agent_id:"",project_id:"",archived:!1,title:"",last_event_at:"",pinned:!1,run_state:"idle",run_state_changed_at:null,subagent:null},BM={...zM,provider:"codex",mode:"managed",health:"active",branch:"",worktree:"",summary:"",latest_assistant_message:null,context_usage:null,capability:{can_stream_live:!1,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!1,can_show_terminal:!1}},HM=(e,t)=>{if(!t)return e??null;if(e!=null&&e.sessions.some(o=>o.id===t.sessionId))return e;const a=t.project?[t.project,...((e==null?void 0:e.projects)??[]).filter(o=>{var u;return o.id!==((u=t.project)==null?void 0:u.id)})]:[...(e==null?void 0:e.projects)??[]],l=[t.session,...((e==null?void 0:e.sessions)??[]).filter(o=>o.id!==t.sessionId)];return{generated_at:(e==null?void 0:e.generated_at)??t.createdAt,agent:(e==null?void 0:e.agent)??null,projects:a,project_stats:a.map(o=>{const u=l.filter(m=>m.project_id===o.id),f=e==null?void 0:e.project_stats.find(m=>m.project_id===o.id);return{project_id:o.id,visible_session_count:u.filter(m=>!m.archived).length,archived_session_count:(f==null?void 0:f.archived_session_count)??0,hidden_history_count:(f==null?void 0:f.hidden_history_count)??0}}),sessions:l,active_session_id:t.sessionId}},$M={session_id:"",generated_at:"",view:"tail",anchor_entry_id:null,has_earlier_entries:!1,entries:[]},FM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"6",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"18",cy:"12",r:"1",fill:"currentColor",stroke:"none"})]}),a2=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"9",y:"9",width:"10",height:"10",rx:"2"}),i.jsx("path",{d:"M7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1"})]}),i2=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m7.5 12.5 3 3 6-7"})}),qM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6l12 12"}),i.jsx("path",{d:"M18 6 6 18"})]}),WM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m9 18-6-6 6-6"}),i.jsx("path",{d:"m15 6 6 6-6 6"})]}),KM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"6",cy:"6",r:"2.2"}),i.jsx("circle",{cx:"18",cy:"6",r:"2.2"}),i.jsx("circle",{cx:"12",cy:"18",r:"2.2"}),i.jsx("path",{d:"M8 7.6 10.5 16"}),i.jsx("path",{d:"M16 7.6 13.5 16"}),i.jsx("path",{d:"M8.2 6h7.6"})]}),QM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),i.jsx("path",{d:"m7.5 9 2.8 3-2.8 3"}),i.jsx("path",{d:"M12.8 15H16.5"})]}),GM=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.1",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M7 5.5 18 12 7 18.5Z"})}),YM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"8.4"}),i.jsx("path",{d:"M3.8 12h16.4"}),i.jsx("path",{d:"M12 3.7c2.3 2.3 3.6 5.2 3.6 8.3s-1.3 6-3.6 8.3c-2.3-2.3-3.6-5.2-3.6-8.3s1.3-6 3.6-8.3Z"})]}),VM=()=>i.jsx(uT,{"aria-hidden":"true",strokeWidth:1.9}),r2=()=>i.jsx(hT,{"aria-hidden":"true",strokeWidth:1.9}),Bo=12,ZM=_.memo(function({isActive:t,label:a,path:l,tokenKey:o,onToggle:u}){const f=_.useRef(null),m=_.useRef(null),[y,g]=_.useState(void 0);return _.useEffect(()=>{if(!t){g(void 0);return}const S=()=>{const b=f.current,w=m.current;if(!b||!w)return;const N=b.getBoundingClientRect(),j=typeof window<"u"?window.innerWidth:document.documentElement.clientWidth,T=typeof window<"u"?window.innerHeight:document.documentElement.clientHeight,D=Math.max(220,Math.min(520,j-Bo*2));w.style.width=`${D}px`,w.style.maxWidth=`${D}px`;const z=w.getBoundingClientRect(),I=Math.min(Math.max(N.left,Bo),Math.max(Bo,j-Bo-D)),k=N.top-z.height-8,P=k>=Bo?k:Math.min(N.bottom+8,T-Bo-z.height);g({left:`${I}px`,top:`${Math.max(Bo,P)}px`,width:`${D}px`,maxWidth:`${D}px`})},p=window.requestAnimationFrame(S);return window.addEventListener("resize",S),document.addEventListener("scroll",S,!0),()=>{window.cancelAnimationFrame(p),window.removeEventListener("resize",S),document.removeEventListener("scroll",S,!0)}},[t,l]),i.jsxs("span",{ref:f,className:`conversation-inline-link ${t?"is-active":""}`,children:[i.jsx("span",{role:"button",tabIndex:0,className:"conversation-inline-link__button",onClick:S=>{S.stopPropagation(),u()},onKeyDown:S=>{S.key!=="Enter"&&S.key!==" "||(S.preventDefault(),S.stopPropagation(),u())},children:a}),t&&typeof document<"u"?Ya.createPortal(i.jsx("span",{ref:m,className:"conversation-inline-link__tooltip",role:"tooltip",style:y,children:l}),document.body):null]},o)}),l2=(e,t)=>{const a=new Map;for(const l of e)a.set(l.cursor,l);for(const l of t)a.set(l.cursor,l);return[...a.values()].sort((l,o)=>l.cursor-o.cursor)},XM=800,H_=(e,t,a)=>{const l=e.get(t);if(l!==void 0)return e.delete(t),e.set(t,l),l;const o=a();if(e.set(t,o),e.size>XM){const u=e.keys().next().value;u&&e.delete(u)}return o},JM=new Map,eA=new Map,tA=new Map,B0=()=>Zr(()=>import("./session-diff-preview-DwKy91Si.js"),__vite__mapDeps([0,1])),nA=_.lazy(async()=>({default:(await B0()).SessionDiffPreview})),H0=(e,t,a)=>i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}),children:i.jsx(nA,{diffText:e,filePath:t,emptyMessage:a})}),sA=e=>i.jsx("span",{className:"conversation-inline-link",children:i.jsx("span",{className:"conversation-inline-link__button",title:e,children:Mx(e)})}),aA=/<proposed_plan>([\s\S]*?)<\/proposed_plan>/g,iA=e=>H_(JM,e,()=>yx(e)),eh=e=>e.replace(/\\/g,"/"),rA=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lA=e=>{var l,o;const t=/^\s*(\d+)\.\s+(.+)$/.exec(e);if(t)return{ordered:!0,ordinal:Number.parseInt(t[1]??"",10),text:((l=t[2])==null?void 0:l.trim())??""};const a=/^\s*[-*]\s+(.+)$/.exec(e);return a?{ordered:!1,ordinal:null,text:((o=a[1])==null?void 0:o.trim())??""}:null},oA=e=>{var a;const t=/^\/([A-Za-z][A-Za-z0-9._-]*)/.exec(e.trim());return((a=t==null?void 0:t[1])==null?void 0:a.toLowerCase())??""},cA=e=>e.kind==="system"&&e.title==="context_compacted",o2=e=>e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e)),uA=e=>H_(eA,e,()=>{var m;const t=e.replace(/\r\n/g,`
|
|
141
|
+
`),submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}w(""),I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${re.id}`,command_name:Se||"unknown",command_text:Z,title:`/${Se||"unknown"} 暂不可用`,description:"新建线程阶段目前只接入了少量本地命令。",status:"completed",body:"请先进入已有会话后再执行这个命令,或者先使用 /model 调整新会话默认模型。",submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}L.mutate({projectId:re.id,input:Z,title:MR(Z,W),attachments:W,model:k,titleGenerationModel:$3(),reasoningEffort:Q,serviceTier:Y?"fast":void 0,planMode:me,yoloMode:te})}};return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`conversation-main conversation-main--new-thread ${u?"has-desktop-sidebar":""}`,style:U,children:[i.jsxs("div",{className:"conversation-topbar",children:[u?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:y,"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]}),i.jsx("div",{className:"conversation-topbar__meta",children:i.jsx("div",{className:"conversation-topbar__title-row",children:i.jsx("h1",{"aria-label":"未命名会话",children:" "})})})]}),i.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:i.jsx("div",{className:"conversation-thread conversation-thread--empty",children:ke?i.jsx(mR,{agentId:e.id,projects:t,title:"选择目录",subtitle:"",onProjectCreated:Z=>{p.setQueriesData({queryKey:os},Se=>_E(Se,Z)),j(Z.id),g(Z.id),q("composer")}}):i.jsx("section",{className:"new-thread-hero",children:i.jsxs("div",{className:"new-thread-hero__stack",children:[i.jsx(gR,{}),i.jsxs("label",{className:"new-thread-hero__selector",children:[i.jsx("span",{className:"new-thread-hero__selector-label",children:"在线程中发起会话"}),i.jsx("select",{className:"new-thread-hero__select",value:N??"",onChange:Z=>{const Se=Z.target.value||null;j(Se),Se&&g(Se)},children:t.map(Z=>i.jsx("option",{value:Z.id,children:Z.display_name??Z.name},Z.id))})]}),ae?i.jsx("div",{className:"new-thread-hero__path",children:ae}):i.jsx("div",{className:"new-thread-hero__hint",children:"选择一个线程后,直接输入第一条消息即可开始。"}),u?null:i.jsx("button",{type:"button",className:"new-thread-hero__directory-trigger",onClick:()=>q("directory-picker"),children:"新增目录线程"})]})})})})]}),ke?null:i.jsx(xx,{isDesktopSidebar:u,sidebarShift:f,isSidebarDragging:m,composerError:T,onDismissComposerError:()=>D(null),interactionRequests:[],pendingInteractionRequestId:null,onRespondInteraction:()=>{},parentSession:null,backgroundAgentSessions:[],isBackgroundAgentsOpen:!1,planSnapshot:null,onToggleBackgroundAgents:()=>{},onOpenSession:()=>{},getBackgroundAgentStatusLabel:()=>"",getBackgroundAgentAccent:()=>"var(--color-accent-primary)",formatBackgroundAgentsLabel:Z=>`${Z} background agents`,hasBackgroundAgentStrip:!1,commandPanel:z,isCommandPanelPending:!1,onDismissCommandPanel:()=>I(null),onCommandPanelOptionSelect:Z=>{P(Z),I(Se=>Se&&{...Se,status:"completed",body:`新会话默认模型已切换为 ${wp(Z,he)}。现在可以继续输入真正的首条消息。`,updated_at:new Date().toISOString(),input_type:"none",options:[]})},onCommandPanelTextSubmit:()=>{},projectId:(re==null?void 0:re.id)??null,agentId:e.id,draft:b,pendingAttachments:W,canSendInput:!!re,inputPlaceholder:re?`向 ${re.display_name??re.name} 发起第一条任务…`:"先选择线程,再输入第一条任务",readOnlyPlaceholder:"先选择线程,再输入第一条任务",onDraftChange:w,onUploadFiles:Z=>{const Se=[...Z];Se.length!==0&&(D(null),Promise.all(Se.map(je=>gx(je))).then(je=>{V(Oe=>[...Oe,...je])}).catch(je=>{D(je instanceof Error?je.message:"无法读取附件")}))},onRemoveAttachment:Z=>{V(Se=>Se.filter(je=>je.id!==Z))},onSubmit:ve,showStopIcon:!1,isSendPending:L.isPending,onInterrupt:()=>{},isFastModeEnabled:Y,isPlanModeEnabled:me,isYoloModeEnabled:te,onToggleFastMode:()=>ee(Z=>!Z),onTogglePlanMode:()=>ge(Z=>!Z),onToggleYoloMode:()=>xe(Z=>!Z),showModeBadges:!0,selectedModel:k,modelOptions:he,selectedReasoning:Q,onSelectModel:P,onSelectReasoning:Z=>se(Z),contextUsage:null,isContextUsageOpen:!1,onToggleContextUsage:()=>{},usedPercent:0,remainingPercent:0,usedTokensLabel:"0",totalTokensLabel:"0",showJumpToBottom:!1,onJumpToBottom:()=>{}})]})},Sx="panda:session-timeline-snapshots",Wm=1,OR=1440*60*1e3,jx=12,IR=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},LR=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}},wx=()=>{const e=IR(Sx);if(!e||e.version!==Wm||!Array.isArray(e.items))return{version:Wm,items:[]};const t=Date.now(),a=e.items.filter(l=>!!(l&&typeof l.sessionId=="string"&&typeof l.storedAt=="number"&&l.snapshot&&typeof l.snapshot=="object")).filter(l=>t-l.storedAt<=OR).sort((l,o)=>o.storedAt-l.storedAt).slice(0,jx);return{version:Wm,items:a}},PR=e=>{const a=wx().items.find(l=>l.sessionId===e);return a?a.snapshot:null},UR=e=>{if(!e||e.view!=="full_compact")return;const t=Date.now(),a=wx(),l=[{sessionId:e.session_id,storedAt:t,snapshot:e},...a.items.filter(o=>o.sessionId!==e.session_id)].slice(0,jx);LR(Sx,{version:Wm,items:l})},zR=e=>{var t,a,l;return["session-tool-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(a=e==null?void 0:e.scope)!=null&&a.sessionId?"":((l=e==null?void 0:e.scope)==null?void 0:l.agentId)??"",(e==null?void 0:e.sessionId)??"",(e==null?void 0:e.entryId)??""]};function BR(e){return ls({queryKey:zR(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId)&&!!(e!=null&&e.entryId),queryFn:async()=>!(e!=null&&e.sessionId)||!(e!=null&&e.entryId)?null:(await wn(e.scope)).client.getSessionToolCallDetail(e.sessionId,e.entryId),refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const Nx=e=>{var t,a,l;return["workspace-session-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(a=e==null?void 0:e.scope)!=null&&a.sessionId?"":((l=e==null?void 0:e.scope)==null?void 0:l.agentId)??"",(e==null?void 0:e.sessionId)??""]};function HR(e){return ls({queryKey:Nx(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId),queryFn:async()=>e!=null&&e.sessionId?(await wn(e.scope)).client.getWorkspaceSessionDetail(e.sessionId):null,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const $R={can_stream_live:!1,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!1,can_show_terminal:!1},FR=e=>({id:e.id,agent_id:e.agent_id,project_id:e.project_id,archived:e.archived,title:e.title,last_event_at:e.last_event_at,pinned:e.pinned,run_state:e.run_state,run_state_changed_at:e.run_state_changed_at,subagent:e.subagent,provider:"codex",mode:"managed",health:"active",branch:"",worktree:"",summary:"",latest_assistant_message:null,context_usage:null,capability:$R}),qR=(e,t)=>e?!t||t.id!==e.id?FR(e):{...t,id:e.id,agent_id:e.agent_id,project_id:e.project_id,archived:e.archived,title:e.title,last_event_at:e.last_event_at,pinned:e.pinned,run_state:e.run_state,run_state_changed_at:e.run_state_changed_at,subagent:e.subagent}:t??null,$b=e=>{if(!e)return null;const t={};return typeof e.title=="string"&&(t.title=e.title),typeof e.archived=="boolean"&&(t.archived=e.archived),typeof e.pinned=="boolean"&&(t.pinned=e.pinned),typeof e.last_event_at=="string"&&(t.last_event_at=e.last_event_at),(e.run_state==="idle"||e.run_state==="running"||e.run_state==="completed")&&(t.run_state=e.run_state),(e.run_state_changed_at===null||typeof e.run_state_changed_at=="string")&&(t.run_state_changed_at=e.run_state_changed_at),typeof e.summary=="string"&&(t.summary=e.summary),(e.latest_assistant_message===null||typeof e.latest_assistant_message=="string")&&(t.latest_assistant_message=e.latest_assistant_message),typeof e.provider=="string"&&(t.provider=e.provider),typeof e.mode=="string"&&(t.mode=e.mode),typeof e.health=="string"&&(t.health=e.health),typeof e.branch=="string"&&(t.branch=e.branch),typeof e.worktree=="string"&&(t.worktree=e.worktree),(e.context_usage===null||typeof e.context_usage=="object"&&e.context_usage!==null)&&(t.context_usage=e.context_usage),(e.subagent===null||typeof e.subagent=="object"&&e.subagent!==null)&&(t.subagent=e.subagent),typeof e.capability=="object"&&e.capability!==null&&(t.capability=e.capability),Object.keys(t).length>0?t:null},WR=(e,t,a)=>{if(!e||e.session.id!==t)return e;const{last_event_at:l,...o}=a;let u={...e.session,...o};if(typeof l=="string"&&l.trim()){const f=new Date(l).getTime(),m=new Date(e.session.last_event_at).getTime();Number.isFinite(f)&&(!Number.isFinite(m)||f>m)&&(u={...u,last_event_at:l})}return{...e,session:u}},Fb=_.lazy(async()=>({default:(await Zr(()=>import("./session-diff-preview-CCCZmf4G.js"),__vite__mapDeps([0,1]))).SessionDiffPreview})),Ag=["var(--session-git-graph-1)","var(--session-git-graph-2)","var(--session-git-graph-3)","var(--session-git-graph-4)","var(--session-git-graph-5)","var(--session-git-graph-6)"],kx=14,Ex=10,Ul=24,gu=48,Dg=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m9 6 6 6-6 6"})}),KR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M20 11a8 8 0 1 0 2.2 5.5"}),i.jsx("path",{d:"M20 4v7h-7"})]}),QR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M3 12a9 9 0 1 0 2.64-6.36"}),i.jsx("path",{d:"M3 4v5h5"}),i.jsx("path",{d:"M12 7v5l3 2"})]}),qb=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9 14 4 9l5-5"}),i.jsx("path",{d:"M4 9h8a8 8 0 1 1 0 16h-1"})]}),Wb=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7.5 12.5 10.5 15.5 16.5 8.5"}),i.jsx("circle",{cx:"12",cy:"12",r:"8.5"})]}),GR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 16V5"}),i.jsx("path",{d:"m7.5 9.5 4.5-4.5 4.5 4.5"}),i.jsx("path",{d:"M5 19h14"})]}),YR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6 18 18"}),i.jsx("path",{d:"M18 6 6 18"})]}),VR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 4v10"}),i.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),i.jsx("path",{d:"M17 6a4 4 0 0 0-4 4H7"}),i.jsx("circle",{cx:"7",cy:"4",r:"2"}),i.jsx("circle",{cx:"17",cy:"6",r:"2"}),i.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),ZR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"4",y:"5",width:"16",height:"11",rx:"2"}),i.jsx("path",{d:"M8 19h8"}),i.jsx("path",{d:"M10 16v3"}),i.jsx("path",{d:"M14 16v3"})]}),XR=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M7.5 18a4.5 4.5 0 1 1 .9-8.91A5.5 5.5 0 0 1 19 11a3.5 3.5 0 0 1-.5 7Z"})}),JR=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M7 4v10"}),i.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),i.jsx("path",{d:"M7 10a4 4 0 0 1 4-4h6"}),i.jsx("circle",{cx:"7",cy:"4",r:"2"}),i.jsx("circle",{cx:"17",cy:"6",r:"2"}),i.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),zl=({label:e,icon:t,onClick:a,disabled:l=!1,variant:o="default",pending:u=!1,className:f})=>i.jsx("button",{type:"button",className:`session-git-panel__icon-button is-${o} ${u?"is-pending":""} ${f??""}`.trim(),onClick:a,disabled:l,"aria-label":e,title:e,children:i.jsx("span",{className:"session-git-panel__icon-button-glyph","aria-hidden":"true",children:t})}),Kb=e=>{switch(e){case"added":return"A";case"deleted":return"D";case"renamed":return"R";case"untracked":return"U";default:return"M"}},eM=e=>e.status==="renamed"&&e.previous_path?`该变更仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件已删除,没有可展示的补丁内容。":e.status==="untracked"?"该文件还没有可展示的补丁内容。":"此变更没有可展示的补丁内容。",tM=(e,t)=>t&&t.diff.trim()?"此变更没有可展示的补丁内容。":e.status==="renamed"&&e.previous_path?`该提交仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件在这次提交中已删除,没有可展示的补丁内容。":"该文件在这次提交中没有可展示的补丁内容。",jf=e=>Ag[e%Ag.length]??Ag[0],zo=e=>Ex+e*kx,Tm=(e,t)=>`${e}\0${t}`,B_=e=>Array.isArray(e.parent_oids)?e.parent_oids.filter(Boolean):[],nM=e=>Array.isArray(e.refs)?e.refs.filter(Boolean):[],sM=e=>{var u;const t={};let a=[],l=0;const o=()=>{const f=l;return l+=1,f};for(const f of e){let m=a.findIndex(w=>w.oid===f.oid);m<0&&(a=[...a,{oid:f.oid,colorIndex:o()}],m=a.length-1);const y=a.map(w=>({...w})),g=((u=y[m])==null?void 0:u.colorIndex)??o(),S=[...new Set(B_(f))],p=y.map(w=>({...w}));S.length>0?p[m]={oid:S[0],colorIndex:g}:p.splice(m,1);const b=[];if(S.length>0){const w=p.findIndex(N=>N.oid===S[0]);b.push(w>=0?w:m)}S.slice(1).forEach((w,N)=>{let j=p.findIndex(T=>T.oid===w);j<0&&(j=Math.min(p.length,m+1+N),p.splice(j,0,{oid:w,colorIndex:o()})),b.push(j)}),t[f.oid]={beforeLanes:y,afterLanes:p,laneIndex:m,nodeColorIndex:g,parentLaneIndexes:b},a=p.filter((w,N,j)=>j.findIndex(T=>T.oid===w.oid)===N)}return t},aM=({commit:e,row:t,isLocalHead:a,isRemoteHead:l,isFirstRow:o,maxLaneCount:u})=>{const f=B_(e).length,m=Math.max(u,t.beforeLanes.length,t.afterLanes.length,1),y=Math.max(40,Ex*2+(m-1)*kx),g=zo(t.laneIndex),S=f>1?4.7:3.9,p=Math.max(0,Ul-S-1.1),b={"--session-git-graph-width":`${Math.max(48,Math.ceil(y*(56/gu)))}px`};return i.jsx("span",{className:"session-git-history__graph",style:b,children:i.jsxs("svg",{className:`session-git-history__graph-svg ${f>1?"is-merge":""}`,viewBox:`0 0 ${y} ${gu}`,preserveAspectRatio:"xMinYMid meet","aria-hidden":"true",children:[t.beforeLanes.map((w,N)=>i.jsx("path",{d:`M ${zo(N)} ${o?p:0} L ${zo(N)} ${p}`,stroke:jf(w.colorIndex),strokeWidth:"2",strokeLinecap:"round",fill:"none",opacity:o?0:1},`before:${w.oid}:${N}`)),t.afterLanes.map((w,N)=>{const j=t.beforeLanes.findIndex(I=>I.oid===w.oid),T=j>=0?zo(j):zo(N),D=zo(N),z=T===D?`M ${D} ${Ul} L ${D} ${gu}`:`M ${T} ${Ul} C ${T} 27 ${D} 31 ${D} ${gu}`;return i.jsx("path",{d:z,stroke:jf(w.colorIndex),strokeWidth:"2",strokeLinecap:"round",fill:"none"},`after:${w.oid}:${N}`)}),t.parentLaneIndexes.map((w,N)=>{var z;const j=zo(w),T=jf(((z=t.afterLanes[w])==null?void 0:z.colorIndex)??t.nodeColorIndex),D=j===g?`M ${g} ${Ul} L ${j} ${gu}`:`M ${g} ${Ul} C ${g} 27 ${j} 31 ${j} ${gu}`;return i.jsx("path",{d:D,stroke:T,strokeWidth:N>0||f>1?"2.2":"2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",opacity:N>0||f>1?.96:.88},`parent:${e.oid}:${N}`)}),i.jsx("circle",{cx:g,cy:Ul,r:S,fill:"var(--color-surface-panel)",stroke:jf(t.nodeColorIndex),strokeWidth:f>1?"1.8":"1.55"}),i.jsx("circle",{cx:g,cy:Ul,r:a||l?1.6:1.05,fill:jf(t.nodeColorIndex)}),a&&l?i.jsx("circle",{cx:g,cy:Ul,r:"6.4",fill:"none",stroke:"color-mix(in oklab, var(--color-accent-primary) 22%, transparent)",strokeWidth:"1",strokeDasharray:"1.5 3"}):null]})})},iM=({workspace:e,history:t,isLoading:a,isHistoryLoading:l,error:o,historyError:u,onRefresh:f,onRefreshHistory:m,onRequestHistory:y,onDiscardFile:g,onDiscardAll:S,onCommitAll:p,onSwitchBranch:b,onPush:w,onLoadWorkspaceFileDiff:N,onLoadHistoryFileDiff:j,pendingAction:T,compact:D=!1})=>{const[z,I]=_.useState("changes"),[k,P]=_.useState({}),[Q,se]=_.useState({}),[W,V]=_.useState({}),[Y,ee]=_.useState({}),[me,ge]=_.useState({}),[te,xe]=_.useState({}),[C,q]=_.useState({}),[ie,he]=_.useState({}),[re,L]=_.useState({}),[ae,ke]=_.useState(!1),[U,ve]=_.useState(null),[Z,Se]=_.useState(""),[je,Oe]=_.useState(null),Ie=_.useRef(null);_.useEffect(()=>{P(Fe=>{if(!(e!=null&&e.files.length))return{};const X=new Set(e.files.map(ue=>ue.path));let B=!1;const oe={};for(const[ue,we]of Object.entries(Fe)){if(!X.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:Fe});const _e=new Set((e==null?void 0:e.files.map(Fe=>Fe.path))??[]);se(Fe=>{let X=!1;const B={};for(const[oe,ue]of Object.entries(Fe)){if(!_e.has(oe)){X=!0;continue}B[oe]=ue}return X?B:Fe}),V(Fe=>{let X=!1;const B={};for(const[oe,ue]of Object.entries(Fe)){if(!_e.has(oe)){X=!0;continue}B[oe]=ue}return X?B:Fe}),ee(Fe=>{let X=!1;const B={};for(const[oe,ue]of Object.entries(Fe)){if(!_e.has(oe)){X=!0;continue}B[oe]=ue}return X?B:Fe})},[e==null?void 0:e.files]),_.useEffect(()=>{const _e=new Set((t==null?void 0:t.commits.map(X=>X.oid))??[]),Fe=new Set((t==null?void 0:t.commits.flatMap(X=>X.files.map(B=>Tm(X.oid,B.path))))??[]);ge(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!_e.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X}),xe(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!_e.has(ue)){B=!0;continue}if(we&&!Fe.has(Tm(ue,we))){B=!0,oe[ue]=null;continue}oe[ue]=we}return B?oe:X}),q(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!Fe.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X}),he(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!Fe.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X}),L(X=>{let B=!1;const oe={};for(const[ue,we]of Object.entries(X)){if(!Fe.has(ue)){B=!0;continue}oe[ue]=we}return B?oe:X})},[t==null?void 0:t.commits]),_.useEffect(()=>{if(!ae)return;const _e=Fe=>{var X;(X=Ie.current)!=null&&X.contains(Fe.target)||ke(!1)};return window.addEventListener("pointerdown",_e),()=>{window.removeEventListener("pointerdown",_e)}},[ae]),_.useEffect(()=>{e&&(U==="commit"&&(T==null?void 0:T.action)!=="commit-all"&&e.files.length===0&&(ve(null),Se("")),je&&e.branch===je&&(Oe(null),ve(null),Se(""),ke(!1)))},[U,T==null?void 0:T.action,je,e]),_.useEffect(()=>{e!=null&&e.branches.length||ke(!1)},[e==null?void 0:e.branches]),_.useEffect(()=>{se({}),V({}),ee({})},[e==null?void 0:e.updated_at]);const wt=(e==null?void 0:e.files)??[],qe=(t==null?void 0:t.commits)??[],bt=wt.length>0,Ut=qe.length>0,$t=(T==null?void 0:T.action)==="discard-all",zt=(T==null?void 0:T.action)==="commit-all",xt=(T==null?void 0:T.action)==="switch-branch",it=(T==null?void 0:T.action)==="push",ot=z==="changes",ln=U==="switch-branch"&&je?`提交后切换到 ${je}`:"提交全部改动",on=_.useMemo(()=>{if(!e)return null;const _e=[];return e.upstream_branch&&_e.push(e.upstream_branch),e.ahead_count>0&&_e.push(`ahead ${e.ahead_count}`),e.behind_count>0&&_e.push(`behind ${e.behind_count}`),_e.join(" · ")},[e]),kn=_.useMemo(()=>{if(!t)return null;const _e=[t.branch];return t.upstream_branch&&_e.push(t.upstream_branch),_e.join(" · ")},[t]),En=_.useMemo(()=>z==="history"?sM(qe):{},[z,qe]),ht=_.useMemo(()=>z!=="history"?1:Math.max(1,...Object.values(En).map(_e=>Math.max(_e.beforeLanes.length,_e.afterLanes.length,_e.laneIndex+1))),[z,En]),Ve=(_e,Fe)=>{Q[_e]||W[_e]||(V(X=>({...X,[_e]:!0})),ee(X=>{const B={...X};return delete B[_e],B}),N(_e,Fe).then(X=>{se(B=>({...B,[_e]:X}))}).catch(X=>{ee(B=>({...B,[_e]:X instanceof Error?X.message:"无法读取该文件的差异。"}))}).finally(()=>{V(X=>{const B={...X};return delete B[_e],B})}))};_.useEffect(()=>{if(!(z!=="changes"||wt.length===0))for(const _e of wt)k[_e.path]&&Ve(_e.path,_e.previous_path)},[z,k,wt,N,Q,W]);const Ke=()=>{ve(null),Se(""),Oe(null)},Nt=()=>{Oe(null),ve(_e=>_e==="commit"?(Se(""),null):"commit")},Bt=()=>{const _e=Z.trim();if(_e){if(U==="switch-branch"&&je){Promise.resolve(b(je,_e)).catch(()=>{});return}p(_e)}},Jt=_e=>{if(!(!e||_e===e.branch||T)){if(ke(!1),e.files.length>0){Oe(_e),ve("switch-branch");return}Promise.resolve(b(_e)).catch(()=>{})}},Dt=()=>{if(ot){f();return}m()},Ze=()=>{I(_e=>{const Fe=_e==="changes"?"history":"changes";return Fe==="history"&&y(),Fe})},un=(_e,Fe)=>{const X=Tm(_e.oid,Fe.path),B=te[_e.oid]===Fe.path;xe(oe=>({...oe,[_e.oid]:B?null:Fe.path})),!(B||C[X]||ie[X])&&(he(oe=>({...oe,[X]:!0})),L(oe=>{const ue={...oe};return delete ue[X],ue}),j(_e.oid,Fe.path,Fe.previous_path).then(oe=>{q(ue=>({...ue,[X]:oe}))}).catch(oe=>{L(ue=>({...ue,[X]:oe instanceof Error?oe.message:"无法读取该文件的提交差异。"}))}).finally(()=>{he(oe=>{const ue={...oe};return delete ue[X],ue})}))},ut=_e=>{const Fe=new Date(_e);return Number.isNaN(Fe.getTime())?_e:new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(Fe)};return i.jsxs("section",{className:`session-git-panel ${D?"is-compact":""}`,children:[i.jsxs("div",{className:"session-git-panel__header",children:[i.jsxs("div",{className:"session-git-panel__heading",ref:Ie,children:[i.jsxs("button",{type:"button",className:"session-git-panel__branch-button",onClick:()=>ke(_e=>!_e),disabled:!e||!!T,"aria-haspopup":"menu","aria-expanded":ae,title:e?`切换分支:${e.branch}`:"分支加载中",children:[i.jsx("span",{className:"session-git-panel__branch-icon","aria-hidden":"true",children:i.jsx(VR,{})}),i.jsx("span",{className:"session-git-panel__branch",children:(e==null?void 0:e.branch)??"加载中"}),i.jsx("span",{className:`session-git-panel__branch-chevron ${ae?"is-open":""}`,"aria-hidden":"true",children:i.jsx(Dg,{})})]}),ae&&e?i.jsx("div",{className:"session-git-panel__branch-menu",role:"menu","aria-label":"分支列表",children:e.branches.map(_e=>{const Fe=_e===e.branch,X=(T==null?void 0:T.action)==="switch-branch"&&T.branch===_e;return i.jsxs("button",{type:"button",className:`session-git-panel__branch-option ${Fe?"is-current":""}`,onClick:()=>Jt(_e),disabled:Fe||!!T,role:"menuitemradio","aria-checked":Fe,title:Fe?`${_e}(当前)`:`切换到 ${_e}`,children:[i.jsx("span",{className:"session-git-panel__branch-option-name",children:_e}),Fe?i.jsx("span",{className:"session-git-panel__branch-option-meta",children:"当前"}):null,X?i.jsx("span",{className:"session-git-panel__branch-option-meta",children:"切换中"}):null]},_e)})}):null]}),i.jsxs("div",{className:"session-git-panel__toolbar",children:[i.jsx(zl,{label:ot?"切换到提交历史":"返回修改列表",icon:i.jsx(QR,{}),onClick:Ze,disabled:!!T,variant:ot?"default":"primary",className:ot?void 0:"is-active"}),i.jsx(zl,{label:ot?a?"正在刷新":"刷新":l?"正在刷新历史":"刷新历史",icon:i.jsx(KR,{}),onClick:Dt,disabled:ot?a||!!T:l,pending:ot?a:l}),ot&&bt?i.jsxs(i.Fragment,{children:[i.jsx(zl,{label:$t?"正在撤回全部修改":"撤回全部修改",icon:i.jsx(qb,{}),onClick:S,disabled:!!T,variant:"danger",pending:$t}),i.jsx(zl,{label:zt?"正在提交全部修改":U==="commit"?"收起提交编辑器":"提交全部修改",icon:i.jsx(Wb,{}),onClick:Nt,disabled:!!T,variant:"primary",pending:zt})]}):null,ot&&!bt?i.jsx(zl,{label:it?"正在推送当前分支":"推送当前分支",icon:i.jsx(GR,{}),onClick:w,disabled:!!T,variant:"primary",pending:it}):null]})]}),ot&&e?i.jsxs("div",{className:"session-git-panel__summary",children:[i.jsx("span",{className:"session-git-panel__summary-text",children:bt?`${wt.length} 个文件待处理`:"当前工作区没有待提交改动"}),on?i.jsx("span",{className:"session-git-panel__summary-meta",children:on}):null]}):null,!ot&&t?i.jsxs("div",{className:"session-git-panel__summary",children:[i.jsx("span",{className:"session-git-panel__summary-text",children:Ut?`${qe.length} 条最近提交`:"当前分支还没有提交历史"}),kn?i.jsx("span",{className:"session-git-panel__summary-meta",children:kn}):null]}):null,ot&&U&&bt?i.jsxs("div",{className:"session-git-panel__composer",children:[i.jsx("div",{className:"session-git-panel__composer-title",children:ln}),i.jsxs("div",{className:"session-git-panel__composer-row",children:[i.jsx("input",{value:Z,onChange:_e=>Se(_e.target.value),placeholder:"输入 commit message",className:"session-git-panel__input",disabled:!!T}),i.jsx(zl,{label:U==="switch-branch"?"提交并切换分支":"确认提交",icon:i.jsx(Wb,{}),onClick:Bt,disabled:!Z.trim()||!!T,variant:"primary",pending:zt||xt}),i.jsx(zl,{label:"取消提交",icon:i.jsx(YR,{}),onClick:Ke,disabled:!!T})]})]}):null,ot&&o?i.jsx("div",{className:"session-git-panel__notice is-error",children:o}):null,!ot&&u?i.jsx("div",{className:"session-git-panel__notice is-error",children:u}):null,ot&&a&&!e?i.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前工作区改动…"}):null,!ot&&l&&!t?i.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前分支提交历史…"}):null,ot&&!a&&e&&!bt?i.jsx("div",{className:"session-git-panel__empty",children:"当前分支没有待提交改动。你现在可以直接推送当前分支。"}):null,!ot&&!l&&t&&!Ut?i.jsx("div",{className:"session-git-panel__empty",children:"当前分支还没有提交历史。"}):null,ot&&bt?i.jsx("div",{className:"session-git-panel__list",children:wt.map(_e=>{const Fe=!!k[_e.path],X=(T==null?void 0:T.action)==="discard-file"&&T.path===_e.path,B=Q[_e.path],oe=!!W[_e.path],ue=Y[_e.path]??null;return i.jsxs("article",{className:`session-git-file ${Fe?"is-expanded":""}`,children:[i.jsxs("div",{className:"session-git-file__head",children:[i.jsxs("button",{type:"button",className:"session-git-file__toggle",onClick:()=>{const we=!Fe;P(Re=>({...Re,[_e.path]:we})),we&&Ve(_e.path,_e.previous_path)},"aria-expanded":Fe,children:[i.jsxs("span",{className:"session-git-file__main",children:[i.jsx("span",{className:"session-git-file__path",children:_e.path}),_e.previous_path?i.jsxs("span",{className:"session-git-file__rename",children:["来自 ",_e.previous_path]}):null]}),i.jsxs("span",{className:"session-git-file__meta",children:[i.jsx("span",{className:`session-git-file__status is-${_e.status}`,children:Kb(_e.status)}),i.jsxs("span",{className:"session-git-file__counts",children:[i.jsxs("span",{className:"is-add",children:["+",_e.additions]}),i.jsxs("span",{className:"is-remove",children:["-",_e.deletions]})]}),i.jsx("span",{className:"session-git-file__chevron","aria-hidden":"true",children:i.jsx(Dg,{})})]})]}),i.jsx(zl,{label:X?`正在撤回 ${_e.path}`:`撤回 ${_e.path}`,icon:i.jsx(qb,{}),onClick:()=>g(_e.path),disabled:!!T,variant:"danger",pending:X,className:"session-git-file__action"})]}),Fe?i.jsx("div",{className:"session-git-file__detail",children:ue?i.jsx("div",{className:"session-git-panel__notice is-error",children:ue}):oe?i.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的差异…"}):i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:i.jsx(Fb,{diffText:(B==null?void 0:B.diff)??"",filePath:_e.path,emptyMessage:eM(_e)})})}):null]},_e.path)})}):null,!ot&&Ut?i.jsx("div",{className:"session-git-history",children:qe.map((_e,Fe)=>{const X=!!me[_e.oid],B=B_(_e),oe=te[_e.oid]??null,ue=En[_e.oid],we=(t==null?void 0:t.head_oid)===_e.oid,Re=(t==null?void 0:t.upstream_head_oid)===_e.oid,He=nM(_e).filter(ze=>!ze||ze===(t==null?void 0:t.branch)||ze===(t==null?void 0:t.upstream_branch)||ze===`HEAD -> ${t==null?void 0:t.branch}`?!1:ze!=="HEAD");return i.jsxs("article",{className:`session-git-history__item ${X?"is-expanded":""} ${B.length>1?"is-merge":""} ${we?"is-local-head":""} ${Re?"is-remote-head":""}`.trim(),children:[i.jsxs("button",{type:"button",className:"session-git-history__toggle",onClick:()=>ge(ze=>({...ze,[_e.oid]:!ze[_e.oid]})),"aria-expanded":X,children:[ue?i.jsx(aM,{commit:_e,row:ue,isLocalHead:we,isRemoteHead:Re,isFirstRow:Fe===0,maxLaneCount:ht}):null,i.jsxs("span",{className:"session-git-history__content",children:[i.jsx("span",{className:"session-git-history__subject",children:_e.subject}),i.jsxs("span",{className:"session-git-history__meta",children:[i.jsx("span",{children:_e.short_oid}),i.jsx("span",{children:_e.author_name}),i.jsx("span",{children:ut(_e.committed_at)})]})]}),i.jsxs("span",{className:"session-git-history__refs",children:[we?i.jsx("span",{className:"session-git-history__ref is-local",title:"本地当前 HEAD",children:i.jsx(ZR,{})}):null,Re?i.jsx("span",{className:"session-git-history__ref is-remote",title:t!=null&&t.upstream_branch?`云端位置:${t.upstream_branch}`:"云端位置",children:i.jsx(XR,{})}):null,B.length>1?i.jsx("span",{className:"session-git-history__ref is-merge",title:"合并提交",children:i.jsx(JR,{})}):null,He.slice(0,2).map(ze=>i.jsx("span",{className:"session-git-history__ref is-label",title:ze,children:ze},`${_e.oid}:${ze}`))]}),i.jsx("span",{className:"session-git-history__chevron","aria-hidden":"true",children:i.jsx(Dg,{})})]}),X?i.jsx("div",{className:"session-git-history__files",children:i.jsx("div",{className:"session-git-history__files-list",children:_e.files.map(ze=>{const rt=oe===ze.path,It=Tm(_e.oid,ze.path),Ft=C[It],Le=!!ie[It],Et=re[It]??null;return i.jsxs("div",{className:`session-git-history-file-row ${rt?"is-selected":""}`,children:[i.jsxs("button",{type:"button",className:`session-git-history-file ${rt?"is-selected":""}`,onClick:()=>un(_e,ze),"aria-pressed":rt,children:[i.jsx("span",{className:`session-git-file__status is-${ze.status}`,children:Kb(ze.status)}),i.jsx("span",{className:"session-git-history-file__path",children:ze.path}),ze.previous_path?i.jsxs("span",{className:"session-git-history-file__rename",children:["来自 ",ze.previous_path]}):null,i.jsx("span",{className:"session-git-history-file__meta",children:Ft?i.jsxs("span",{className:"session-git-history-file__counts",children:[i.jsxs("span",{className:"is-add",children:["+",Ft.additions]}),i.jsxs("span",{className:"is-remove",children:["-",Ft.deletions]})]}):Le?i.jsx("span",{className:"session-git-history-file__loading",children:"读取中…"}):i.jsx("span",{className:"session-git-history-file__hint",children:"点击查看"})})]}),rt?i.jsxs("div",{className:"session-git-history__diff is-inline",children:[i.jsxs("div",{className:"session-git-history__diff-header",children:[i.jsx("span",{className:"session-git-history__diff-path",children:ze.path}),ze.previous_path?i.jsxs("span",{className:"session-git-history__diff-rename",children:["来自 ",ze.previous_path]}):null]}),Et?i.jsx("div",{className:"session-git-panel__notice is-error",children:Et}):Le?i.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的提交差异…"}):i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:i.jsx(Fb,{diffText:(Ft==null?void 0:Ft.diff)??"",filePath:ze.path,emptyMessage:tM(ze,Ft??null)})})]}):null]},`${_e.oid}:${ze.path}`)})})}):null]},_e.oid)})}):null]})},Qb={name:"",description:null,command:"",kill_command:null,cwd:null,shell:"auto",node_version:null,port:null},Gb=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m8 6 9 6-9 6z"})}),Yb=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("rect",{x:"6.5",y:"6.5",width:"11",height:"11",rx:"1.8"})}),rM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),i.jsx("path",{d:"M18 15.2 18.8 18 21.6 18.8 18.8 19.6 18 22.4 17.2 19.6 14.4 18.8 17.2 18Z"})]}),lM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m4 20 4.2-1 9.2-9.2a1.8 1.8 0 0 0 0-2.6l-.6-.6a1.8 1.8 0 0 0-2.6 0L5 15.8 4 20Z"}),i.jsx("path",{d:"m13.5 6.5 4 4"})]}),oM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M4.5 7h15"}),i.jsx("path",{d:"M9.5 4.5h5"}),i.jsx("path",{d:"M7 7l.6 11a1.8 1.8 0 0 0 1.8 1.7h5.2a1.8 1.8 0 0 0 1.8-1.7L17 7"}),i.jsx("path",{d:"M10 10.5v5.2"}),i.jsx("path",{d:"M14 10.5v5.2"})]}),cM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 5v14"}),i.jsx("path",{d:"M5 12h14"})]}),Vb={auto:"自动",powershell:"PowerShell",cmd:"CMD",bash:"Bash"},uM=({commands:e,nodeRuntime:t,error:a,pendingRunCommandId:l,pendingKillCommandId:o,pendingDeleteCommandId:u,isSaving:f,isGenerating:m,isStartingAll:y,isStoppingAll:g,generationReason:S,executionModelLabel:p,onRun:b,onRunAll:w,onRunAllKill:N,onRunKill:j,onSave:T,onDelete:D,onGenerate:z})=>{var xe;const[I,k]=_.useState("list"),[P,Q]=_.useState(null),[se,W]=_.useState(Qb),V=_.useMemo(()=>e.find(C=>C.id===P)??null,[e,P]),Y=_.useMemo(()=>{const C=[...(t==null?void 0:t.versions)??[]];return se.node_version&&!C.includes(se.node_version)&&C.unshift(se.node_version),C},[se.node_version,t==null?void 0:t.versions]),ee=_.useMemo(()=>e.filter(C=>!!C.kill_command).length,[e]),me=()=>{W(Qb),Q(null),k("edit")},ge=C=>{W({name:C.name,description:C.description,command:C.command,kill_command:C.kill_command,cwd:C.cwd,shell:C.shell,node_version:C.node_version,port:C.port}),Q(C.id),k("edit")},te=()=>{T({commandId:V==null?void 0:V.id,draft:se}),f||(k("list"),Q(null))};return i.jsxs("div",{className:"session-run-panel",children:[i.jsxs("div",{className:"session-run-panel__header",children:[i.jsxs("div",{className:"session-run-panel__header-copy",children:[i.jsxs("div",{className:"session-run-panel__title-row",children:[i.jsx("h2",{className:"session-run-panel__title",children:"项目命令"}),i.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),i.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",p]})]}),i.jsxs("div",{className:"session-run-panel__header-actions",children:[i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-primary","aria-label":y?"正在一键启动项目命令":"一键启动项目命令",title:y?"正在一键启动项目命令":"一键启动项目命令",disabled:e.length===0||y||g,onClick:w,children:i.jsx(Gb,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":g?"正在一键停止项目命令":"一键停止项目命令",title:g?"正在一键停止项目命令":"一键停止项目命令",disabled:ee===0||y||g,onClick:N,children:i.jsx(Yb,{})}),i.jsx("button",{type:"button",className:`session-run-panel__icon-button ${m?"is-loading":""}`,"aria-label":m?"正在一键生成项目命令":"一键生成项目命令",title:m?"正在一键生成项目命令":"一键生成项目命令","aria-busy":m,disabled:m||y||g,onClick:z,children:i.jsx(rM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目命令",title:"新增项目命令",onClick:me,children:i.jsx(cM,{})})]})]}),a?i.jsx("div",{className:"session-run-panel__notice is-error",children:a}):null,m?i.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐命令…"}):null,S?i.jsx("div",{className:"session-run-panel__hint",children:S}):null,I==="edit"?i.jsxs("div",{className:"session-run-panel__card",children:[i.jsx("h3",{className:"session-run-panel__section-title",children:V?"编辑命令":"新增命令"}),i.jsxs("div",{className:"session-run-panel__form-grid",children:[i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"名称"}),i.jsx("input",{value:se.name,onChange:C=>W(q=>({...q,name:C.target.value})),className:"session-run-panel__input",placeholder:"例如:启动前端"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"说明"}),i.jsx("input",{value:se.description??"",onChange:C=>W(q=>({...q,description:C.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),i.jsxs("label",{className:"session-run-panel__field is-full",children:[i.jsx("span",{children:"命令"}),i.jsx("textarea",{value:se.command,onChange:C=>W(q=>({...q,command:C.target.value})),className:"session-run-panel__textarea",placeholder:"pnpm dev",rows:4})]}),i.jsxs("label",{className:"session-run-panel__field is-full",children:[i.jsx("span",{children:"停止命令"}),i.jsx("textarea",{value:se.kill_command??"",onChange:C=>W(q=>({...q,kill_command:C.target.value||null})),className:"session-run-panel__textarea",placeholder:"留空表示不需要单独停止",rows:3})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"工作目录"}),i.jsx("input",{value:se.cwd??"",onChange:C=>W(q=>({...q,cwd:C.target.value||null})),className:"session-run-panel__input",placeholder:"留空表示项目根目录"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"端口"}),i.jsx("input",{value:se.port??"",onChange:C=>{const q=Number.parseInt(C.target.value,10);W(ie=>({...ie,port:Number.isFinite(q)&&q>0?q:null}))},className:"session-run-panel__input",placeholder:"例如:5173",inputMode:"numeric"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"Shell"}),i.jsx("select",{value:se.shell,onChange:C=>W(q=>({...q,shell:C.target.value})),className:"session-run-panel__select",children:Object.entries(Vb).map(([C,q])=>i.jsx("option",{value:C,children:q},C))})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"Node 环境"}),i.jsxs("select",{value:se.node_version??"",onChange:C=>W(q=>({...q,node_version:C.target.value||null})),className:"session-run-panel__select",children:[i.jsx("option",{value:"",children:"默认环境"}),Y.map(C=>i.jsxs("option",{value:C,children:["Node ",C,t!=null&&t.versions.includes(C)?"":"(未检测到)"]},C))]})]})]}),i.jsx("div",{className:"session-run-panel__hint",children:t!=null&&t.versions.length?"Node 版本只会临时注入当前命令,不会修改系统全局环境。":((xe=t==null?void 0:t.error)==null?void 0:xe.trim())||"未检测到可用的 nvm Node 版本,将按默认环境运行。"}),i.jsxs("div",{className:"session-run-panel__form-actions",children:[i.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>k("list"),children:"取消"}),i.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!se.name.trim()||!se.command.trim()||f,onClick:te,children:f?"保存中...":V?"保存修改":"保存命令"})]})]}):null,i.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(C=>i.jsxs("article",{className:"session-run-panel__command-card",children:[i.jsxs("div",{className:"session-run-panel__command-head",children:[i.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>ge(C),children:[i.jsxs("div",{className:"session-run-panel__command-heading",children:[i.jsx("span",{className:"session-run-panel__command-name",children:C.name}),C.description?i.jsx("span",{className:"session-run-panel__command-description",children:C.description}):null]}),i.jsx("div",{className:"session-run-panel__command-line",children:C.command})]}),i.jsxs("div",{className:"session-run-panel__command-actions",children:[C.kill_command?i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":`执行 ${C.name} 的停止命令`,title:`执行 ${C.name} 的停止命令`,disabled:o===C.id,onClick:()=>j(C.id),children:i.jsx(Yb,{})}):null,i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${C.name}`,title:`编辑 ${C.name}`,onClick:()=>ge(C),children:i.jsx(lM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${C.name}`,title:`删除 ${C.name}`,disabled:u===C.id,onClick:()=>D(C.id),children:i.jsx(oM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-primary","aria-label":`运行 ${C.name}`,title:`运行 ${C.name}`,disabled:l===C.id,onClick:()=>b(C.id),children:i.jsx(Gb,{})})]})]}),i.jsx("div",{className:"session-run-panel__command-footer",children:i.jsxs("div",{className:"session-run-panel__command-meta",children:[i.jsx("span",{className:"session-run-panel__command-pill",children:Vb[C.shell]}),C.node_version?i.jsxs("span",{className:"session-run-panel__command-pill is-node",children:["Node ",C.node_version]}):null,C.port?i.jsxs("span",{className:"session-run-panel__command-pill",children:[":",C.port]}):null,C.kill_command?i.jsx("span",{className:"session-run-panel__command-pill is-kill",children:"可停止"}):null,i.jsx("span",{className:"session-run-panel__command-pill",children:C.cwd?C.cwd:"项目根目录"})]})})]},C.id)):i.jsxs("div",{className:"session-run-panel__empty",children:[i.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目命令"}),i.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},Zb={name:"",description:null,url:""},dM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),i.jsx("path",{d:"M18 15.2 18.8 18 21.6 18.8 18.8 19.6 18 22.4 17.2 19.6 14.4 18.8 17.2 18Z"})]}),fM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),i.jsx("path",{d:"M3.8 12h16.4"}),i.jsx("path",{d:"M12 3.7c2.3 2.4 3.6 5.3 3.6 8.3S14.3 17.9 12 20.3c-2.3-2.4-3.6-5.3-3.6-8.3S9.7 6.1 12 3.7Z"})]}),hM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m4 20 4.2-1 9.2-9.2a1.8 1.8 0 0 0 0-2.6l-.6-.6a1.8 1.8 0 0 0-2.6 0L5 15.8 4 20Z"}),i.jsx("path",{d:"m13.5 6.5 4 4"})]}),mM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M4.5 7h15"}),i.jsx("path",{d:"M9.5 4.5h5"}),i.jsx("path",{d:"M7 7l.6 11a1.8 1.8 0 0 0 1.8 1.7h5.2a1.8 1.8 0 0 0 1.8-1.7L17 7"}),i.jsx("path",{d:"M10 10.5v5.2"}),i.jsx("path",{d:"M14 10.5v5.2"})]}),pM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M12 5v14"}),i.jsx("path",{d:"M5 12h14"})]}),gM=({websites:e,error:t,pendingDeleteWebsiteId:a,isSaving:l,isGenerating:o,generationReason:u,executionModelLabel:f,onOpen:m,onSave:y,onDelete:g,onGenerate:S})=>{const[p,b]=_.useState("list"),[w,N]=_.useState(null),[j,T]=_.useState(Zb),D=_.useMemo(()=>e.find(P=>P.id===w)??null,[w,e]),z=()=>{T(Zb),N(null),b("edit")},I=P=>{T({name:P.name,description:P.description,url:P.url}),N(P.id),b("edit")},k=()=>{y({websiteId:D==null?void 0:D.id,draft:j}),l||(b("list"),N(null))};return i.jsxs("div",{className:"session-run-panel",children:[i.jsxs("div",{className:"session-run-panel__header",children:[i.jsxs("div",{className:"session-run-panel__header-copy",children:[i.jsxs("div",{className:"session-run-panel__title-row",children:[i.jsx("h2",{className:"session-run-panel__title",children:"项目网页"}),i.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),i.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",f]})]}),i.jsxs("div",{className:"session-run-panel__header-actions",children:[i.jsx("button",{type:"button",className:`session-run-panel__icon-button ${o?"is-loading":""}`,"aria-label":o?"正在一键生成项目网页":"一键生成项目网页",title:o?"正在一键生成项目网页":"一键生成项目网页","aria-busy":o,disabled:o,onClick:S,children:i.jsx(dM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目网页",title:"新增项目网页",onClick:z,children:i.jsx(pM,{})})]})]}),t?i.jsx("div",{className:"session-run-panel__notice is-error",children:t}):null,o?i.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐网页…"}):null,u?i.jsx("div",{className:"session-run-panel__hint",children:u}):null,p==="edit"?i.jsxs("div",{className:"session-run-panel__card",children:[i.jsx("h3",{className:"session-run-panel__section-title",children:D?"编辑网页":"新增网页"}),i.jsxs("div",{className:"session-run-panel__form-grid",children:[i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"名称"}),i.jsx("input",{value:j.name,onChange:P=>T(Q=>({...Q,name:P.target.value})),className:"session-run-panel__input",placeholder:"例如:前端首页"})]}),i.jsxs("label",{className:"session-run-panel__field",children:[i.jsx("span",{children:"说明"}),i.jsx("input",{value:j.description??"",onChange:P=>T(Q=>({...Q,description:P.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),i.jsxs("label",{className:"session-run-panel__field is-full",children:[i.jsx("span",{children:"地址"}),i.jsx("input",{value:j.url,onChange:P=>T(Q=>({...Q,url:P.target.value})),className:"session-run-panel__input",placeholder:"http://localhost:5173"})]})]}),i.jsxs("div",{className:"session-run-panel__form-actions",children:[i.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>b("list"),children:"取消"}),i.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!j.name.trim()||!j.url.trim()||l,onClick:k,children:l?"保存中...":D?"保存修改":"保存网页"})]})]}):null,i.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(P=>i.jsxs("article",{className:"session-run-panel__command-card",children:[i.jsxs("div",{className:"session-run-panel__command-head",children:[i.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>I(P),children:[i.jsxs("div",{className:"session-run-panel__command-heading",children:[i.jsx("span",{className:"session-run-panel__command-name",children:P.name}),P.description?i.jsx("span",{className:"session-run-panel__command-description",children:P.description}):null]}),i.jsx("div",{className:"session-run-panel__command-line",children:P.url})]}),i.jsxs("div",{className:"session-run-panel__command-actions",children:[i.jsx("a",{className:"session-run-panel__icon-button is-primary","aria-label":`打开 ${P.name}`,title:`打开 ${P.name}`,href:P.url,target:"_blank",rel:"noreferrer",onClick:()=>m(P),children:i.jsx(fM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${P.name}`,title:`编辑 ${P.name}`,onClick:()=>I(P),children:i.jsx(hM,{})}),i.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${P.name}`,title:`删除 ${P.name}`,disabled:a===P.id,onClick:()=>g(P.id),children:i.jsx(mM,{})})]})]}),i.jsx("div",{className:"session-run-panel__command-footer",children:i.jsx("div",{className:"session-run-panel__command-meta",children:i.jsx("span",{className:"session-run-panel__command-pill",children:"网页"})})})]},P.id)):i.jsxs("div",{className:"session-run-panel__empty",children:[i.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目网页"}),i.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},_M=/\u001b\[([0-9;]*)m/g,yM={stdout:"",stderr:"stderr",system:"system"},Xb={30:"black",31:"red",32:"green",33:"yellow",34:"blue",35:"magenta",36:"cyan",37:"white",90:"bright-black",91:"bright-red",92:"bright-green",93:"bright-yellow",94:"bright-blue",95:"bright-magenta",96:"bright-cyan",97:"bright-white"},U0={fg:null,bg:null,bold:!1,dim:!1,underline:!1},vM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6 18 18"}),i.jsx("path",{d:"M18 6 6 18"})]}),bM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M8 4H4v4"}),i.jsx("path",{d:"M16 4h4v4"}),i.jsx("path",{d:"M8 20H4v-4"}),i.jsx("path",{d:"M16 20h4v-4"}),i.jsx("path",{d:"M9 9 4 4"}),i.jsx("path",{d:"m15 9 5-5"}),i.jsx("path",{d:"m9 15-5 5"}),i.jsx("path",{d:"m15 15 5 5"})]}),xM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M9 4H4v5"}),i.jsx("path",{d:"M15 4h5v5"}),i.jsx("path",{d:"M9 20H4v-5"}),i.jsx("path",{d:"M15 20h5v-5"}),i.jsx("path",{d:"m4 9 5-5"}),i.jsx("path",{d:"m20 9-5-5"}),i.jsx("path",{d:"m4 15 5 5"}),i.jsx("path",{d:"m20 15-5 5"})]}),SM=e=>{if(!e)return"刚刚";const t=new Date(e);return Number.isNaN(t.getTime())?"刚刚":new Intl.DateTimeFormat("zh-CN",{hour:"2-digit",minute:"2-digit"}).format(t)},Jb=(e,t)=>{const a=[e];return t.bold&&a.push("is-bold"),t.dim&&a.push("is-dim"),t.underline&&a.push("is-underline"),t.fg&&a.push(`is-fg-${t.fg}`),t.bg&&a.push(`is-bg-${t.bg}`),a.join(" ")},jM=(e,t)=>{if(t===0)return{...U0};if(t===1)return{...e,bold:!0,dim:!1};if(t===2)return{...e,dim:!0,bold:!1};if(t===4)return{...e,underline:!0};if(t===22)return{...e,bold:!1,dim:!1};if(t===24)return{...e,underline:!1};if(t===39)return{...e,fg:null};if(t===49)return{...e,bg:null};const a=Xb[t];if(a)return{...e,fg:a};const l=Xb[t-10];return l&&t>=40?{...e,bg:l}:e},wM=(e,t)=>{const a=[];let l=0,o={...U0};for(const u of e.matchAll(_M)){const f=u.index??0;f>l&&a.push({text:e.slice(l,f),className:Jb(t,o)});const m=(u[1]??"").split(";").map(y=>Number.parseInt(y||"0",10)).filter(y=>Number.isFinite(y));m.length===0?o={...U0}:o=m.reduce(jM,o),l=f+u[0].length}return l<e.length&&a.push({text:e.slice(l),className:Jb(t,o)}),a.length===0&&a.push({text:e,className:t}),a},Cx=_.memo(({chunks:e})=>{const t=_.useMemo(()=>e.map(a=>{const l=yM[a.stream],o=["session-terminal-output__segment",`is-${a.stream}`].join(" ");return{cursor:a.cursor,label:l,segments:wM(a.text,o)}}),[e]);return i.jsx(i.Fragment,{children:t.map(a=>i.jsxs("span",{className:"session-terminal-output__chunk",children:[a.label?i.jsx("span",{className:"session-terminal-output__label",children:a.label}):null,a.segments.map((l,o)=>i.jsx("span",{className:l.className,children:l.text},`${a.cursor}:${o}`))]},a.cursor))})});Cx.displayName="TerminalOutput";const NM=({terminals:e,activeTerminalId:t,outputs:a,error:l,compact:o=!1,canToggleFullscreen:u=!1,isFullscreen:f=!1,onSelectTerminal:m,onCloseTerminal:y,onToggleFullscreen:g})=>{const S=_.useRef(null),p=e.find(w=>w.id===t)??e[0]??null,b=p?a[p.id]:null;return _.useEffect(()=>{const w=S.current;w&&(w.scrollTop=w.scrollHeight)},[b==null?void 0:b.chunks,p==null?void 0:p.id]),e.length===0?i.jsx("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:i.jsxs("div",{className:"session-terminal-panel__empty",children:[i.jsx("div",{className:"session-terminal-panel__empty-title",children:"还没有运行中的命令"}),i.jsx("p",{className:"session-terminal-panel__empty-copy",children:"从右上角的运行按钮启动一个项目命令后,这里会实时显示终端输出。"})]})}):i.jsxs("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:[i.jsxs("div",{className:"session-terminal-panel__tabs",children:[i.jsx("div",{className:"session-terminal-panel__tab-list",role:"tablist","aria-label":"终端列表",children:e.map(w=>{const N=w.id===(p==null?void 0:p.id);return i.jsxs("div",{className:`session-terminal-panel__tab ${N?"is-active":""}`,children:[i.jsxs("button",{type:"button",className:"session-terminal-panel__tab-button",role:"tab","aria-selected":N,onClick:()=>m(w.id),children:[i.jsx("span",{className:`session-terminal-panel__tab-dot is-${w.status}`,"aria-hidden":"true"}),i.jsx("span",{className:"session-terminal-panel__tab-title",children:w.title}),i.jsx("span",{className:"session-terminal-panel__tab-time",children:SM(w.last_output_at??w.updated_at)})]}),i.jsx("button",{type:"button",className:"session-terminal-panel__tab-close","aria-label":`关闭 ${w.title}`,onClick:j=>{j.stopPropagation(),y(w.id)},children:i.jsx(vM,{})})]},w.id)})}),u&&g?i.jsx("button",{type:"button",className:"session-terminal-panel__fullscreen-button",onClick:g,"aria-label":f?"退出终端全屏":"终端全屏",title:f?"退出终端全屏":"终端全屏",children:f?i.jsx(xM,{}):i.jsx(bM,{})}):null]}),p?i.jsxs(i.Fragment,{children:[l?i.jsx("div",{className:"session-terminal-panel__notice is-error",children:l}):null,b!=null&&b.error?i.jsx("div",{className:"session-terminal-panel__notice is-error",children:b.error}):null,b!=null&&b.truncated?i.jsx("div",{className:"session-terminal-panel__notice",children:"终端输出过长,已自动显示服务端仍保留的最近内容。"}):null,i.jsx("div",{ref:S,className:"session-terminal-panel__output-wrap",children:i.jsx("pre",{className:"session-terminal-output",children:b&&b.chunks.length>0?i.jsx(Cx,{chunks:b.chunks}):b!=null&&b.isLoading?i.jsx("span",{className:"session-terminal-output__placeholder",children:"正在读取终端输出..."}):i.jsx("span",{className:"session-terminal-output__placeholder",children:"这个终端暂时还没有输出。"})})})]}):null]})},kM=_.memo(function({conversationMainRef:t,conversationScrollRef:a,isDesktopSidebar:l,sidebarShift:o,isSidebarDragging:u,title:f,titleActions:m,topbarActions:y,onOpenSidebar:g,threadContent:S,connectionStatus:p,sessionRecoveryStatus:b,isConnectionDetailOpen:w,onToggleConnectionDetail:N,showThinkingStatus:j}){const T={transform:`translateX(${o}px)`,transition:u?"none":void 0};return i.jsxs("div",{ref:t,className:`conversation-main ${l?"has-desktop-sidebar":""}`,style:T,children:[i.jsxs("div",{className:"conversation-topbar",children:[l?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:g,"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]}),i.jsx("div",{className:"conversation-topbar__meta",children:i.jsxs("div",{className:"conversation-topbar__title-row",children:[i.jsx("h1",{children:f}),m]})}),y]}),i.jsx("div",{ref:a,className:"conversation-scroll",children:i.jsxs("div",{className:"conversation-thread",children:[S,p.state!=="connected"?i.jsx("section",{className:"conversation-entry is-connection-status",children:i.jsxs("div",{className:"connection-status",children:[i.jsx("button",{type:"button",className:"connection-status__pill",onClick:D=>{D.stopPropagation(),N()},children:i.jsx("span",{children:p.state==="failed"?"连接异常":`Reconnecting... ${p.attempt}/${p.maxAttempts}`})}),w&&p.error?i.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:p.error}):null]})}):null,p.state==="connected"&&b.state!=="idle"?i.jsx("section",{className:"conversation-entry is-connection-status",children:i.jsxs("div",{className:"connection-status",children:[i.jsx("div",{className:"connection-status__pill",children:i.jsx("span",{children:b.state==="recovering"?"恢复会话中...":"会话恢复失败"})}),b.state==="failed"&&b.error?i.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:b.error}):null]})}):null,j?i.jsx("section",{className:"conversation-entry is-thinking-status",children:i.jsx("div",{className:"thinking-status-pill",children:i.jsx("span",{children:"正在思考"})})}):null]})})]})}),EM="panda:last-session-id",CM=.4,TM=104,RM=1800*1e3,MM=15e3,AM=120*1e3,e2=1100,Tx="panda:desktop-sidebar-width",Mf="panda:desktop-sidebar-width-version",Af="2026-03-24-narrow",DM=300,Rx=232,_u=Rx,OM=460,t2=72,Og=72,n2=120,z0=54,s2=300,IM=640,LM=4200,Ig="local-model-panel:",PM=160,UM={id:"",agent_id:"",name:"",display_name:null,pinned:!1,path:""},zM={id:"",agent_id:"",project_id:"",archived:!1,title:"",last_event_at:"",pinned:!1,run_state:"idle",run_state_changed_at:null,subagent:null},BM={...zM,provider:"codex",mode:"managed",health:"active",branch:"",worktree:"",summary:"",latest_assistant_message:null,context_usage:null,capability:{can_stream_live:!1,can_send_input:!1,can_interrupt:!1,can_approve:!1,can_reject:!1,can_show_git:!1,can_show_terminal:!1}},HM=(e,t)=>{if(!t)return e??null;if(e!=null&&e.sessions.some(o=>o.id===t.sessionId))return e;const a=t.project?[t.project,...((e==null?void 0:e.projects)??[]).filter(o=>{var u;return o.id!==((u=t.project)==null?void 0:u.id)})]:[...(e==null?void 0:e.projects)??[]],l=[t.session,...((e==null?void 0:e.sessions)??[]).filter(o=>o.id!==t.sessionId)];return{generated_at:(e==null?void 0:e.generated_at)??t.createdAt,agent:(e==null?void 0:e.agent)??null,projects:a,project_stats:a.map(o=>{const u=l.filter(m=>m.project_id===o.id),f=e==null?void 0:e.project_stats.find(m=>m.project_id===o.id);return{project_id:o.id,visible_session_count:u.filter(m=>!m.archived).length,archived_session_count:(f==null?void 0:f.archived_session_count)??0,hidden_history_count:(f==null?void 0:f.hidden_history_count)??0}}),sessions:l,active_session_id:t.sessionId}},$M={session_id:"",generated_at:"",view:"tail",anchor_entry_id:null,has_earlier_entries:!1,entries:[]},FM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"6",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"18",cy:"12",r:"1",fill:"currentColor",stroke:"none"})]}),a2=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"9",y:"9",width:"10",height:"10",rx:"2"}),i.jsx("path",{d:"M7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1"})]}),i2=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"m7.5 12.5 3 3 6-7"})}),qM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M6 6l12 12"}),i.jsx("path",{d:"M18 6 6 18"})]}),WM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"m9 18-6-6 6-6"}),i.jsx("path",{d:"m15 6 6 6-6 6"})]}),KM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"6",cy:"6",r:"2.2"}),i.jsx("circle",{cx:"18",cy:"6",r:"2.2"}),i.jsx("circle",{cx:"12",cy:"18",r:"2.2"}),i.jsx("path",{d:"M8 7.6 10.5 16"}),i.jsx("path",{d:"M16 7.6 13.5 16"}),i.jsx("path",{d:"M8.2 6h7.6"})]}),QM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),i.jsx("path",{d:"m7.5 9 2.8 3-2.8 3"}),i.jsx("path",{d:"M12.8 15H16.5"})]}),GM=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.1",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i.jsx("path",{d:"M7 5.5 18 12 7 18.5Z"})}),YM=()=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("circle",{cx:"12",cy:"12",r:"8.4"}),i.jsx("path",{d:"M3.8 12h16.4"}),i.jsx("path",{d:"M12 3.7c2.3 2.3 3.6 5.2 3.6 8.3s-1.3 6-3.6 8.3c-2.3-2.3-3.6-5.2-3.6-8.3s1.3-6 3.6-8.3Z"})]}),VM=()=>i.jsx(uT,{"aria-hidden":"true",strokeWidth:1.9}),r2=()=>i.jsx(hT,{"aria-hidden":"true",strokeWidth:1.9}),Bo=12,ZM=_.memo(function({isActive:t,label:a,path:l,tokenKey:o,onToggle:u}){const f=_.useRef(null),m=_.useRef(null),[y,g]=_.useState(void 0);return _.useEffect(()=>{if(!t){g(void 0);return}const S=()=>{const b=f.current,w=m.current;if(!b||!w)return;const N=b.getBoundingClientRect(),j=typeof window<"u"?window.innerWidth:document.documentElement.clientWidth,T=typeof window<"u"?window.innerHeight:document.documentElement.clientHeight,D=Math.max(220,Math.min(520,j-Bo*2));w.style.width=`${D}px`,w.style.maxWidth=`${D}px`;const z=w.getBoundingClientRect(),I=Math.min(Math.max(N.left,Bo),Math.max(Bo,j-Bo-D)),k=N.top-z.height-8,P=k>=Bo?k:Math.min(N.bottom+8,T-Bo-z.height);g({left:`${I}px`,top:`${Math.max(Bo,P)}px`,width:`${D}px`,maxWidth:`${D}px`})},p=window.requestAnimationFrame(S);return window.addEventListener("resize",S),document.addEventListener("scroll",S,!0),()=>{window.cancelAnimationFrame(p),window.removeEventListener("resize",S),document.removeEventListener("scroll",S,!0)}},[t,l]),i.jsxs("span",{ref:f,className:`conversation-inline-link ${t?"is-active":""}`,children:[i.jsx("span",{role:"button",tabIndex:0,className:"conversation-inline-link__button",onClick:S=>{S.stopPropagation(),u()},onKeyDown:S=>{S.key!=="Enter"&&S.key!==" "||(S.preventDefault(),S.stopPropagation(),u())},children:a}),t&&typeof document<"u"?Ya.createPortal(i.jsx("span",{ref:m,className:"conversation-inline-link__tooltip",role:"tooltip",style:y,children:l}),document.body):null]},o)}),l2=(e,t)=>{const a=new Map;for(const l of e)a.set(l.cursor,l);for(const l of t)a.set(l.cursor,l);return[...a.values()].sort((l,o)=>l.cursor-o.cursor)},XM=800,H_=(e,t,a)=>{const l=e.get(t);if(l!==void 0)return e.delete(t),e.set(t,l),l;const o=a();if(e.set(t,o),e.size>XM){const u=e.keys().next().value;u&&e.delete(u)}return o},JM=new Map,eA=new Map,tA=new Map,B0=()=>Zr(()=>import("./session-diff-preview-CCCZmf4G.js"),__vite__mapDeps([0,1])),nA=_.lazy(async()=>({default:(await B0()).SessionDiffPreview})),H0=(e,t,a)=>i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}),children:i.jsx(nA,{diffText:e,filePath:t,emptyMessage:a})}),sA=e=>i.jsx("span",{className:"conversation-inline-link",children:i.jsx("span",{className:"conversation-inline-link__button",title:e,children:Mx(e)})}),aA=/<proposed_plan>([\s\S]*?)<\/proposed_plan>/g,iA=e=>H_(JM,e,()=>yx(e)),eh=e=>e.replace(/\\/g,"/"),rA=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lA=e=>{var l,o;const t=/^\s*(\d+)\.\s+(.+)$/.exec(e);if(t)return{ordered:!0,ordinal:Number.parseInt(t[1]??"",10),text:((l=t[2])==null?void 0:l.trim())??""};const a=/^\s*[-*]\s+(.+)$/.exec(e);return a?{ordered:!1,ordinal:null,text:((o=a[1])==null?void 0:o.trim())??""}:null},oA=e=>{var a;const t=/^\/([A-Za-z][A-Za-z0-9._-]*)/.exec(e.trim());return((a=t==null?void 0:t[1])==null?void 0:a.toLowerCase())??""},cA=e=>e.kind==="system"&&e.title==="context_compacted",o2=e=>e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e)),uA=e=>H_(eA,e,()=>{var m;const t=e.replace(/\r\n/g,`
|
|
142
142
|
`).split(`
|
|
143
143
|
`),a=[];let l=[],o=null;const u=()=>{l.length!==0&&(a.push({kind:"paragraph",lines:[...l]}),l=[])},f=()=>{if(!o||o.items.length===0){o=null;return}a.push({kind:"list",ordered:o.ordered,items:[...o.items]}),o=null};for(let y=0;y<t.length;y+=1){const g=t[y],S=/^\s{0,3}(```+|~~~+)[ \t]*([^`]*)$/.exec(g);if(S){u(),f();const w=S[1]??"```",N=(S[2]??"").trim(),j=N?((m=N.split(/\s+/,1)[0])==null?void 0:m.toLowerCase())??null:null,T=new RegExp(`^\\s{0,3}${rA(w)}\\s*$`),D=[];for(y+=1;y<t.length&&!T.test(t[y]??"");)D.push(t[y]??""),y+=1;a.push({kind:"code",rawInfo:N,language:j,content:D.join(`
|
|
144
144
|
`)});continue}const p=/^\s{0,3}(#{1,6})\s+(.+?)\s*$/.exec(g),b=lA(g);if(p){u(),f(),a.push({kind:"heading",level:p[1].length,text:p[2].replace(/\s+#+\s*$/,"").trim()});continue}if(b){u(),(!o||o.ordered!==b.ordered)&&(f(),o={ordered:b.ordered,items:[]}),o.items.push({text:b.text,ordinal:b.ordinal});continue}if(!g.trim()){u();continue}f(),l.push(g)}return u(),f(),a}),dA=e=>H_(tA,e,()=>{const t=[];let a=0;e.replace(aA,(o,u,f)=>{const m=e.slice(a,f);return m.trim()&&t.push({kind:"markdown",content:m.trim()}),typeof u=="string"&&u.trim()?t.push({kind:"proposed-plan",content:u.trim()}):o.trim()&&t.push({kind:"markdown",content:o.trim()}),a=f+o.length,o});const l=e.slice(a);return l.trim()&&t.push({kind:"markdown",content:l.trim()}),t.length===0&&e.trim()&&t.push({kind:"markdown",content:e.trim()}),t}),fA=e=>{const t=e.files.filter(a=>!!a.item_id);return t.length>0?t:e.files.filter(a=>!a.item_id)},c2=(e,t,a)=>{const l=new Map(((a==null?void 0:a.files)??[]).map(f=>[f.path,f])),o=e.files.filter(f=>!f.item_id);if(o.length>0)return o.map(f=>{var m;return{changeSetId:e.id,path:f.path,pathLabel:Gr(f.path,t),additions:f.additions,deletions:f.deletions,itemId:f.item_id,diffAvailable:f.diff_available,diffText:(m=l.get(f.path))==null?void 0:m.diffText,emptyMessage:"此变更没有可展示的补丁内容"}});const u=new Map;for(const f of e.files)u.set(f.path,f);return[...u.values()].map(f=>{var m;return{changeSetId:e.id,path:f.path,pathLabel:Gr(f.path,t),additions:f.additions,deletions:f.deletions,itemId:f.item_id,diffAvailable:f.diff_available,diffText:(m=l.get(f.path))==null?void 0:m.diffText,emptyMessage:"此变更没有可展示的补丁内容"}})},Km=(e,t,a)=>`${e}:${a??"summary"}:${t}`,Lg=e=>`turn-summary:${e}`,u2=(e,t)=>`${e}:${t}`,hA=e=>{var t,a;for(let l=e.length-1;l>=0;l-=1)if(((t=e[l])==null?void 0:t.kind)==="user")return((a=e[l])==null?void 0:a.id)??null;return null},d2=(e,t,a)=>({session_id:e,generated_at:new Date().toISOString(),view:"tail",anchor_entry_id:hA(t),has_earlier_entries:a,entries:t}),$_=e=>Array.isArray(e),Rm=e=>$_(e)?e:Array.isArray(e==null?void 0:e.entries)?e.entries:[],Mm=e=>$_(e)?!1:(e==null?void 0:e.has_earlier_entries)??!1,Pg=e=>$_(e)?"tail":(e==null?void 0:e.view)??"tail",mA=(e,t)=>{const a=new Map((e??[]).map(l=>[l.id,l]));for(const l of t)a.set(l.id,l);return[...a.values()].sort((l,o)=>+new Date(l.started_at)-+new Date(o.started_at))},pA=e=>`${e} background agent${e===1?"":"s"}`,gA=e=>e.startsWith("Reconnecting...")?"retrying":"error",_A=e=>e.startsWith("Reconnecting...")?"Codex 重连中":"Codex 运行异常",Mx=e=>{const t=eh(e).replace(/\/+$/,""),a=t.split("/");return a[a.length-1]||t},f2=e=>`${e.kind}\0${e.title}\0${e.body}\0${e.accent}`,yA=(e,t)=>{if(!t||t.length===0||e.length===0)return e;let a=0;for(;a<e.length&&a<t.length&&f2(e[a])===f2(t[a]);)a+=1;return a<=0||a>=e.length?e:e.slice(a)},vA=e=>{const t=e.trim();if(!t.startsWith("<subagent_notification>"))return null;const a=t.indexOf("{");if(a<0)return null;const l=t.lastIndexOf("}");if(l<=a)return null;try{const o=JSON.parse(t.slice(a,l+1)),u=p=>typeof p=="string"?p.trim():"";if(typeof o.status=="string"){const p=o.status.trim();if(p==="shutdown")return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:"子代理已关闭",state:"shutdown"};if(p==="completed")return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:"子代理已完成",state:"completed"};if(p==="errored")return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:"子代理异常结束",state:"errored"};if(p==="working")return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:"子代理处理中",state:"working"}}const f=o.status&&typeof o.status=="object"?o.status:null,m=u(f==null?void 0:f.completed),y=u(f==null?void 0:f.errored),g=u(f==null?void 0:f.working),S=u(f==null?void 0:f.shutdown);if(m)return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:m,state:"completed"};if(y)return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:y,state:"errored"};if(g)return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:g,state:"working"};if(S)return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:S||"子代理已关闭",state:"shutdown"}}catch{return null}return null},Ug=["#2f72d8","#d06a3b","#2d9b7f","#8c62d9","#bf5b7f","#b78b2d"],Ax=e=>{const t=(e??"").trim();if(!t)return Ug[0];let a=0;for(let l=0;l<t.length;l+=1)a=a*31+t.charCodeAt(l)>>>0;return Ug[a%Ug.length]},bA=e=>{var t;return Ax(((t=e.subagent)==null?void 0:t.nickname)??e.title??e.id)},Dx=e=>{let t=-1,a=-1;return e.forEach((l,o)=>{if(!(l.kind!=="system"||l.title!=="status")){if(l.body==="开始处理请求"){t=o;return}l.body==="处理完成"&&(a=o)}}),t>a?t:-1},xA=e=>{var a;const t=Dx(e);return t<0?null:((a=e[t])==null?void 0:a.timestamp)??null},SA=e=>{const t=Dx(e);if(t<0)return new Set;const a=[],l=new Set;for(const o of e.slice(t)){if(o.kind!=="tool")continue;if(o.title!=="tool-output"){if(a.push({name:o.title}),o.title==="close_agent"){const f=o.session_ids[0]??null;f&&l.delete(f)}continue}const u=a.shift()??null;if((u==null?void 0:u.name)==="spawn_agent"){const f=o.session_ids[0]??null;f&&l.add(f)}}return l},jA=e=>e.run_state==="running"?"is working":e.run_state==="completed"?"completed":"is awaiting instruction",Ox=1e4,wf=1200,Ix=e=>new Set(((e==null?void 0:e.files)??[]).map(t=>eh(t.path))),Lx=(e,t)=>{if(t.size===0)return 0;let a=0;for(const l of e.files)t.has(eh(l.path))&&(a+=1);return a},wA=(e,t,a)=>{const l=+new Date(t);if(!Number.isFinite(l))return!1;const o=Ix(a);return e.some(u=>{if(u.source!=="app-server")return!1;const f=+new Date(u.updated_at);return!Number.isFinite(f)||Math.abs(f-l)>Ox?!1:o.size===0?!0:Lx(u,o)>0})},NA=(e,t)=>{if(!e)return"已处理";const a=Math.max(0,new Date(t).getTime()-new Date(e).getTime()),l=Math.max(0,Math.round(a/1e3)),o=Math.floor(l/60),u=l%60;return o<=0?`已处理 ${u}s`:`已处理 ${o}m ${u}s`},Gr=(e,t)=>{const a=eh(e),l=t?eh(t).replace(/\/+$/,""):"";return l&&a.toLowerCase().startsWith(`${l.toLowerCase()}/`)?a.slice(l.length+1):a},Px=(e,t)=>!e||e.files.length===0?null:{files:e.files.map(a=>({path:a.path,displayPath:Gr(a.path,t),operation:"update",additions:a.additions,deletions:a.deletions,diffText:""})),additions:e.additions,deletions:e.deletions},Ux=(e,t)=>{const a=e.split(/\r?\n/),l=[];let o=null,u=[];const f=()=>{o&&(l.push({...o,diffText:u.join(`
|
|
145
145
|
`).trim()}),o=null,u=[])};for(const m of a){const y=m.replace(/\r$/,""),g=y.trimStart();if(y.startsWith("*** Add File: ")){f();const S=y.slice(14).trim();o={path:S,displayPath:Gr(S,t),operation:"add",additions:0,deletions:0,diffText:""};continue}if(y.startsWith("*** Update File: ")){f();const S=y.slice(17).trim();o={path:S,displayPath:Gr(S,t),operation:"update",additions:0,deletions:0,diffText:""};continue}if(y.startsWith("*** Delete File: ")){f();const S=y.slice(17).trim();o={path:S,displayPath:Gr(S,t),operation:"delete",additions:0,deletions:0,diffText:""};continue}if(o){if(y.startsWith("*** End Patch")){f();continue}if(y.startsWith("*** ")){f();continue}y.startsWith("+")?o.additions+=1:y.startsWith("-")&&(o.deletions+=1),(g.startsWith("@@")||y.startsWith("+")||y.startsWith("-")||y.startsWith(" "))&&u.push(g.startsWith("@@")?g:y)}}return f(),l.length===0?null:{files:l,additions:l.reduce((m,y)=>m+y.additions,0),deletions:l.reduce((m,y)=>m+y.deletions,0)}},kA=e=>{if(e.length===0)return null;const t=new Map;for(const l of e)for(const o of l.files){const u=t.get(o.path);if(!u){t.set(o.path,{...o});continue}u.additions+=o.additions,u.deletions+=o.deletions,u.diffText=[u.diffText,o.diffText].filter(Boolean).join(`
|
|
146
146
|
`),u.operation=o.operation}const a=[...t.values()];return{files:a,additions:a.reduce((l,o)=>l+o.additions,0),deletions:a.reduce((l,o)=>l+o.deletions,0)}},Am=(e,t=TM)=>{const a=e.replace(/\s+/g," ").trim();return a.length<=t?a:`${a.slice(0,t-1).trimEnd()}…`},F_=e=>{try{return JSON.parse(e)}catch{return null}},EA=e=>{const t=F_(e.body);if(t){const a=["command","cmd","path","pattern","q","input"];for(const l of a){const o=t[l];if(typeof o=="string"&&o.trim())return Am(o)}}return e.title&&e.title!=="tool-output"?e.body.trim().startsWith("{")||e.body.trim().startsWith("[")?Am(e.title.replace(/-/g," ")):Am(e.body||e.title):Am(e.body||"工具执行")},CA=e=>{if(e.title==="apply_patch")return e.body.trim();const t=F_(e.body);return t&&typeof t.command=="string"&&t.command.trim()?t.command.trim():e.body.trim()||e.title},TA=e=>e.map(t=>{const a=F_(t.body);return a&&typeof a.output=="string"?a.output.trim():t.body.trim()}).filter(Boolean).join(`
|
|
147
147
|
|
|
148
|
-
`),RA=e=>e.kind==="entry"&&e.entry.kind==="user",zx=e=>e.kind==="entry"&&e.entry.kind==="assistant",MA=e=>RA(e)||zx(e),AA=e=>e.kind==="tool-group"?!0:e.entry.kind==="assistant"||e.entry.kind==="thinking"||e.entry.kind==="tool",DA=e=>{if(e.length<=1)return e;const t=[];for(const a of e){const l=t[t.length-1];if(l&&l.kind==="entry"&&a.kind==="entry"&&l.entry.kind==="assistant"&&a.entry.kind==="assistant"&&l.entry.body.trim()===a.entry.body.trim()){t[t.length-1]=a;continue}t.push(a)}return t},OA=e=>`展开 ${e.length} 条过程消息`,IA=e=>`收起 ${e.length} 条过程消息`,LA=(e,t)=>{const a=DA(e.items),{completion:l}=e,o=a.findLastIndex(m=>zx(m));if(o===-1||!l||!t)return{id:e.id,startedAt:e.startedAt,visibleStartItems:o===-1?a:a.slice(0,o),hiddenItems:[],visibleEndItems:o===-1?[]:a.slice(o),completion:l};const u=[],f=[];return a.forEach((m,y)=>{if(y!==o){if(MA(m)){u.push(m);return}f.push(m)}}),{id:e.id,startedAt:e.startedAt,visibleStartItems:u,hiddenItems:f,visibleEndItems:[a[o]],completion:l}},PA=(e,t)=>{const a=[];let l=[],o=null;const u=()=>{for(const m of l)a.push({kind:"item",id:m.kind==="entry"?m.entry.id:m.group.id,item:m});l=[]},f=()=>{o&&((o.items.length>0||o.completion)&&a.push({kind:"turn",turn:LA(o,t)}),o=null)};for(const m of e){if(m.kind==="turn-start"){f(),o={id:m.id,startedAt:m.startedAt,items:l,completion:null},l=[];continue}if(m.kind==="turn-complete"){if(o){o.completion=m;continue}o={id:m.id,startedAt:null,items:l,completion:m},l=[];continue}if(o){if(o.completion&&!AA(m)){f(),l.push(m);continue}o.items.push(m);continue}l.push(m)}return f(),u(),a},UA=e=>e.run_state!=="running"&&Date.now()-new Date(e.last_event_at).getTime()>=RM,zA=(e,t)=>{var g,S;const a=t==null?void 0:t.projectPath,l=(t==null?void 0:t.compactCompletedTurns)??!1,o=[];let u=null,f=!1,m=null,y=[];for(let p=0;p<e.length;p+=1){const b=e[p];if(b.kind==="system"&&b.body==="开始处理请求"){o.push({kind:"turn-start",id:b.id,startedAt:b.timestamp}),m=b.timestamp,y=[];continue}if(b.kind==="system"&&b.body==="处理完成"){o.push({kind:"turn-complete",id:b.id,durationLabel:NA(m,b.timestamp),patchSummary:kA(y),completedAt:b.timestamp}),m=null,y=[];continue}if(b.kind==="tool"&&b.title!=="tool-output"){const w=[];let N=p+1;for(;N<e.length&&((g=e[N])==null?void 0:g.kind)==="tool"&&((S=e[N])==null?void 0:S.title)==="tool-output";)w.push(e[N]),N+=1;u=b.id;const j=b.title==="apply_patch"?Px(b.patch_summary,a)??Ux(b.body,a):null;j&&y.push(j),w.length===0&&(f=!0),o.push({kind:"tool-group",group:{id:b.id,commandEntry:b,outputEntries:w,patchSummary:j}}),p=N-1;continue}if(b.kind==="tool"&&b.title==="tool-output"){o.push({kind:"tool-group",group:{id:b.id,commandEntry:b,outputEntries:[],patchSummary:null}}),u=b.id;continue}o.push({kind:"entry",entry:b})}return{blocks:PA(o,l),lastToolGroupId:u,hasRunningToolGroup:f}},BA=e=>e.kind==="entry"?e.entry.timestamp:e.group.commandEntry.timestamp,HA=(e,t)=>{var f,m;const a=[...e.visibleStartItems,...e.hiddenItems,...e.visibleEndItems].map(BA).filter(y=>!!y),l=a.length>0?a[a.length-1]:null,o=e.startedAt??a[0]??((f=e.completion)==null?void 0:f.completedAt)??null,u=((m=e.completion)==null?void 0:m.completedAt)??l??o;return{startMs:o?+new Date(o):null,endMs:u?+new Date(u):null,nextStartMs:t!=null&&t.startedAt?+new Date(t.startedAt):null}},$A=(e,t)=>{const a=+new Date(e.started_at),l=e.completed_at?+new Date(e.completed_at):null,o=t.startMs??(t.endMs!==null?t.endMs-wf:null),u=t.nextStartMs??(t.endMs!==null?t.endMs+wf:Number.POSITIVE_INFINITY);return o!==null&&a<o-wf?!1:a<=u+wf?!0:l!==null&&l<=u+wf},FA=(e,t)=>{if(t===null)return Number.POSITIVE_INFINITY;const a=+new Date(e.updated_at);return Number.isFinite(a)?Math.abs(a-t):Number.POSITIVE_INFINITY},qA=(e,t)=>{const a=[...t].sort((f,m)=>+new Date(f.started_at)-+new Date(m.started_at)),l=new Set,o=e.filter(f=>f.kind==="turn"),u=new Map(o.map((f,m)=>[f.turn.id,m]));return e.map(f=>{var j,T,D;if(f.kind!=="turn")return f;const m=u.get(f.turn.id)??-1,y=m>=0?((j=o[m+1])==null?void 0:j.turn)??null:null,g=HA(f.turn,y),S=((T=f.turn.completion)==null?void 0:T.patchSummary)??null,p=Ix(S),w=((D=a.filter(z=>!l.has(z.id)).map(z=>({changeSet:z,overlapCount:Lx(z,p),updatedAtDistance:FA(z,g.endMs)})).filter(z=>z.overlapCount>0&&z.updatedAtDistance<=Ox).sort((z,I)=>I.overlapCount!==z.overlapCount?I.overlapCount-z.overlapCount:z.changeSet.source!==I.changeSet.source?z.changeSet.source==="app-server"?-1:1:z.updatedAtDistance!==I.updatedAtDistance?z.updatedAtDistance-I.updatedAtDistance:+new Date(z.changeSet.started_at)-+new Date(I.changeSet.started_at))[0])==null?void 0:D.changeSet)??a.find(z=>l.has(z.id)?!1:$A(z,g))??null;return w&&l.add(w.id),{kind:"turn",turn:f.turn,changeSet:w}})},WA=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),$0=e=>Math.max(Rx,Math.min(OM,e)),KA=()=>{if(typeof window>"u")return _u;try{const e=window.localStorage.getItem(Tx),t=window.localStorage.getItem(Mf);if(!e)return window.localStorage.setItem(Mf,Af),_u;const a=Number(e);if(!Number.isFinite(a))return window.localStorage.setItem(Mf,Af),_u;const o=t!==Af||a===DM||a>_u?_u:a;return window.localStorage.setItem(Mf,Af),$0(o)}catch{return _u}};function Dm({active:e,render:t,fallback:a=null}){const[l,o]=_.useState(!e);return _.useEffect(()=>{if(!e){o(!1);return}o(!1);const u=window.requestAnimationFrame(()=>{o(!0)});return()=>{window.cancelAnimationFrame(u)}},[e]),e?l?i.jsx(i.Fragment,{children:t()}):i.jsx(i.Fragment,{children:a}):null}const QA=_.memo(function({sessionId:t,group:a,projectPath:l}){const[o,u]=_.useState({}),f=a.commandEntry.detail_available||a.outputEntries.some(j=>j.detail_available),m=BR({sessionId:t,entryId:a.commandEntry.id,scope:{sessionId:t},enabled:f}),y=m.data,g=(y==null?void 0:y.command_entry)??a.commandEntry,S=y!=null&&y.output_entries&&y.output_entries.length>0?y.output_entries:a.outputEntries,p=g.title==="apply_patch"?Ux(g.body,l)??Px(g.patch_summary,l)??a.patchSummary:a.patchSummary,b=CA(g),w=TA(S),N=j=>{u(T=>({...T,[j]:!T[j]}))};return m.isPending&&f&&!y?i.jsx("div",{className:"patch-file-card__empty",children:"正在加载工具详情…"}):g.title==="apply_patch"&&p?p.files.length>1?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"tool-entry__patch-list",children:p.files.map(j=>{const T=`${a.id}:${j.path}`,D=!!o[T];return i.jsxs("div",{className:`tool-entry tool-entry--patch-file ${D?"is-expanded":""}`,children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>N(T),"aria-expanded":D,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:"已编辑"}),i.jsx("span",{className:"tool-entry__command",children:sA(j.displayPath)}),i.jsxs("span",{className:"tool-entry__counts",children:[i.jsxs("span",{className:"is-add",children:["+",j.additions]}),i.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),D?i.jsx("div",{className:"tool-entry__details",children:j.diffText.trim()?i.jsxs("div",{className:"patch-file-card",children:[i.jsxs("div",{className:"patch-file-card__header",children:[i.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),i.jsxs("div",{className:"patch-file-card__counts",children:[i.jsxs("span",{className:"is-add",children:["+",j.additions]}),i.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),i.jsx("div",{className:"patch-file-card__diff",children:H0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]}):i.jsx("div",{className:"patch-file-card__empty",children:"此变更没有可展示的补丁内容"})}):null]},T)})}),m.isError?i.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):i.jsxs("div",{className:"tool-entry__patch-list",children:[p.files.map(j=>i.jsxs("div",{className:"patch-file-card",children:[i.jsxs("div",{className:"patch-file-card__header",children:[i.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),i.jsxs("div",{className:"patch-file-card__counts",children:[i.jsxs("span",{className:"is-add",children:["+",j.additions]}),i.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),i.jsx("div",{className:"patch-file-card__diff",children:H0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]},`${a.id}-${j.path}`)),m.isError?i.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"tool-entry__section",children:[i.jsx("div",{className:"tool-entry__label",children:"命令"}),i.jsx("pre",{className:"tool-entry__pre",children:b})]}),w?i.jsxs("div",{className:"tool-entry__section",children:[i.jsx("div",{className:"tool-entry__label",children:"输出"}),i.jsx("pre",{className:"tool-entry__pre",children:w})]}):null,m.isError?i.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]})}),GA=_.memo(function({sessionId:t,sessions:a,sessionRunState:l,isDesktopSidebar:o,projectPath:u,renderedBlocks:f,lastToolGroupId:m,sessionChangeSets:y,isSubagentTimelinePending:g,isInitialTimelinePending:S,hasTimeline:p,proposedPlanReplyDrafts:b,pendingProposedPlanReplyEntryId:w,canRespondToProposedPlan:N,onProposedPlanReplyDraftChange:j,onSubmitProposedPlanReply:T,onPreviewImage:D,changeSetDiffs:z,changeSetDiffErrors:I,loadingChangeSetDiffKeys:k,onLoadSessionChangeSets:P,onLoadChangeSetFileDiff:Q,onLoadFullTimeline:se,timelineLoadState:W,canRollbackChangeSets:V,pendingRollbackTurnId:Y,rollbackTurnError:ee,rolledBackTurnIds:me,onRollbackTurn:ge}){const[te,xe]=_.useState({}),[C,q]=_.useState({}),[ie,he]=_.useState({}),[re,L]=_.useState(null),[ae,ke]=_.useState(null),[U,ve]=_.useState(null),Z=_.useRef(null),Se=_.useRef(null),je=_.useMemo(()=>{var X;return((X=[...f].reverse().find(B=>B.kind==="turn"&&!!B.turn.completion))==null?void 0:X.turn.id)??null},[f]);_.useEffect(()=>{const X=B=>{const oe=B.target;oe instanceof Element&&oe.closest(".conversation-inline-link")||L(null)};return window.addEventListener("pointerdown",X),()=>{window.removeEventListener("pointerdown",X)}},[]),_.useEffect(()=>()=>{Z.current!==null&&window.clearTimeout(Z.current),Se.current!==null&&window.clearTimeout(Se.current)},[]);const Oe=X=>{xe(B=>({...B,[X]:!B[X]}))},Ie=X=>{q(B=>({...B,[X]:!B[X]}))},wt=X=>{he(B=>({...B,[X]:!B[X]}))};_.useEffect(()=>{var B;const X=new Map;for(const oe of f){if(oe.kind!=="turn")continue;const ue=oe.changeSet;if(!ue||ue.status!=="completed"||ue.files.length===0)continue;const we=Lg(oe.turn.id),Re=c2(ue,u,((B=oe.turn.completion)==null?void 0:B.patchSummary)??null);for(const He of Re){if(!He.changeSetId||!He.diffAvailable)continue;const ze=u2(we,He.path);if(!ie[ze])continue;const rt=Km(He.changeSetId,He.path,He.itemId);z[rt]||k[rt]||X.set(rt,{changeSetId:He.changeSetId,path:He.path,itemId:He.itemId??null})}}for(const oe of X.values())Q(oe)},[z,ie,k,Q,u,f]);const qe=async X=>{var ue;const B=X.trim();if(!B)return!1;const oe=()=>{const we=document.createElement("textarea");we.value=B,we.setAttribute("readonly","true"),we.style.position="fixed",we.style.opacity="0",we.style.pointerEvents="none",document.body.appendChild(we),we.select(),document.execCommand("copy"),document.body.removeChild(we)};try{return(ue=navigator.clipboard)!=null&&ue.writeText?await navigator.clipboard.writeText(B):oe(),!0}catch{return!1}},bt=async(X,B)=>{await qe(B)&&(ke(X),Z.current!==null&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{ke(ue=>ue===X?null:ue),Z.current=null},1400))},Ut=async(X,B)=>{await qe(B)&&(ve(X),Se.current!==null&&window.clearTimeout(Se.current),Se.current=window.setTimeout(()=>{ve(ue=>ue===X?null:ue),Se.current=null},1400))};function $t(X,B,oe){return H0(X,B,oe)}function zt(X,B,oe){const ue=re===oe,we=()=>{L(Re=>Re===oe?null:oe)};return i.jsx(ZM,{isActive:ue,label:X,path:B,tokenKey:oe,onToggle:we},oe)}function xt(X,B,oe=Gr(X,u)){return zt(Mx(oe),oe,B)}function it(X,B){return iA(X).map((ue,we)=>{const Re=`${B}-${we}`;return ue.kind==="text"?i.jsx("span",{children:ue.value},Re):ue.kind==="code"?i.jsx("code",{className:"conversation-inline-code",children:ue.value},Re):ue.kind==="strong"?i.jsx("strong",{children:it(ue.value,`${Re}-strong`)},Re):ue.kind==="emphasis"?i.jsx("em",{children:it(ue.value,`${Re}-emphasis`)},Re):ue.kind==="skill"?i.jsx("span",{className:"conversation-skill-token",children:ue.raw},Re):ue.kind==="command"?i.jsx("span",{className:"conversation-command-token",children:ue.raw},Re):zt(ue.label,ue.path,Re)})}function ot(X,B){return uA(X).map((ue,we)=>{const Re=`${B}-block-${we}`;if(ue.kind==="heading"){const He=Math.min(ue.level,3),ze=He===1?"h1":He===2?"h2":"h3";return i.jsx(ze,{className:`conversation-markdown-heading is-level-${He}`,children:it(ue.text,`${Re}-heading`)},Re)}if(ue.kind==="list"){const He=ue.ordered?"ol":"ul";return i.jsx(He,{className:"conversation-markdown-list",children:ue.items.map((ze,rt)=>i.jsx("li",{value:ue.ordered?ze.ordinal??void 0:void 0,children:it(ze.text,`${Re}-item-${rt}`)},`${Re}-item-${rt}`))},Re)}if(ue.kind==="code"){const He=`${Re}-meta`;return i.jsxs("div",{className:"conversation-markdown-code-block",children:[ue.rawInfo?i.jsxs("div",{className:"conversation-markdown-code-block__meta",children:[i.jsx("span",{className:"conversation-markdown-code-block__meta-label",children:ue.rawInfo}),i.jsxs("button",{type:"button",className:`conversation-markdown-code-block__copy ${U===He?"is-copied":""}`,onClick:()=>{Ut(He,ue.content)},"aria-label":U===He?"已复制代码块内容":"复制代码块内容",children:[i.jsx("span",{className:"conversation-markdown-code-block__copy-icon","aria-hidden":"true",children:U===He?i.jsx(i2,{}):i.jsx(a2,{})}),i.jsx("span",{className:"sr-only",children:U===He?"已复制":"复制"})]})]}):null,i.jsx("pre",{className:"conversation-markdown-code-block__pre",children:i.jsx("code",{children:ue.content})})]},Re)}return i.jsx("p",{className:"conversation-markdown-paragraph",children:ue.lines.map((He,ze)=>i.jsxs("span",{children:[ze>0?i.jsx("br",{}):null,it(He,`${Re}-line-${ze}`)]},`${Re}-line-${ze}`))},Re)})}function ln(X,B,oe){const ue=`${X.id}:proposed-plan:${oe}`,we=b[ue]??"",Re=w===ue,He=!N||Re;return i.jsxs("div",{className:"proposed-plan-card",children:[i.jsx("div",{className:"proposed-plan-card__content",children:ot(B,`${ue}:content`)}),i.jsxs("div",{className:"proposed-plan-card__footer",children:[i.jsx("div",{className:"proposed-plan-card__title",children:"实施此计划?"}),i.jsxs("div",{className:"proposed-plan-card__actions",children:[i.jsx("button",{type:"button",className:"proposed-plan-card__confirm",disabled:He,onClick:()=>{T(ue,"是,实施此计划")},children:Re?"回复中…":"是,实施此计划"}),i.jsxs("div",{className:"proposed-plan-card__custom",children:[i.jsx("input",{type:"text",className:"proposed-plan-card__input",value:we,disabled:He,placeholder:"否,请告知如何调整",onChange:ze=>{j(ue,ze.target.value)},onKeyDown:ze=>{ze.key!=="Enter"||!we.trim()||He||(ze.preventDefault(),T(ue,we))}}),i.jsx("button",{type:"button",className:"proposed-plan-card__submit",disabled:He||!we.trim(),onClick:()=>{T(ue,we)},children:Re?"回复中…":"回复"})]})]})]})]},ue)}function on(X){const B=dA(X.body);return B.some(ue=>ue.kind==="proposed-plan")?B.map((ue,we)=>{const Re=`${X.id}-content-${we}`;return ue.kind==="markdown"?i.jsx("div",{className:"conversation-entry__rich-block",children:ot(ue.content,Re)},Re):ln(X,ue.content,we)}):ot(X.body,X.id)}function kn(X){const B=I6([],X.attachments);if(B.length===0)return null;const oe=B.filter(Tb),ue=B.filter(we=>!Tb(we));return i.jsxs("div",{className:"conversation-entry__attachments",children:[oe.length>0?i.jsx("div",{className:"conversation-entry__attachment-grid",children:oe.map(we=>{const Re=L0(we.size_bytes),He=we.name??"图片",ze=`图片${Re?` · ${Re}`:""}`,rt=i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"conversation-entry__attachment-media",children:we.content_url?i.jsxs(i.Fragment,{children:[i.jsx("img",{src:we.content_url,alt:He,loading:"lazy"}),i.jsx("span",{className:"conversation-entry__attachment-badge",children:"预览"})]}):i.jsx("div",{className:"conversation-entry__attachment-fallback",children:"无法预览"})}),i.jsxs("div",{className:"conversation-entry__attachment-caption",children:[i.jsx("span",{className:"conversation-entry__attachment-title",children:He}),i.jsx("span",{className:"conversation-entry__attachment-meta",children:ze})]})]});return we.content_url?i.jsx("button",{type:"button",className:"conversation-entry__attachment-card is-image",onClick:()=>D({src:we.content_url,label:He,meta:ze}),"aria-label":`预览 ${He}`,children:rt},`${X.id}:${we.id}`):i.jsx("div",{className:"conversation-entry__attachment-card is-image",children:rt},`${X.id}:${we.id}`)})}):null,ue.length>0?i.jsx("div",{className:"conversation-entry__file-list",children:ue.map(we=>{const Re=L0(we.size_bytes),He=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"conversation-entry__file-icon","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z"}),i.jsx("path",{d:"M14 3v5h5"}),i.jsx("path",{d:"M9 13h6"}),i.jsx("path",{d:"M9 17h4"})]})}),i.jsxs("span",{className:"conversation-entry__file-copy",children:[i.jsx("span",{className:"conversation-entry__file-title",children:we.name??"附件"}),i.jsxs("span",{className:"conversation-entry__file-meta",children:["文件",Re?` · ${Re}`:""]})]})]});return we.content_url?i.jsx("a",{className:"conversation-entry__file-card",href:we.content_url,download:we.name??void 0,target:"_blank",rel:"noreferrer",children:He},`${X.id}:${we.id}`):i.jsx("div",{className:"conversation-entry__file-card",children:He},`${X.id}:${we.id}`)})}):null]})}function En(X,B){return i.jsx("div",{className:"turn-patch-summary__files",children:B.map(oe=>{const ue=u2(X,oe.path),we=!!ie[ue],Re=oe.changeSetId?Km(oe.changeSetId,oe.path,oe.itemId):null,He=Re?z[Re]:void 0,ze=Re?k[Re]===!0:!1,rt=Re?I[Re]??null:null,It=(He==null?void 0:He.file.diff)??oe.diffText??"",Ft=(He==null?void 0:He.empty_message)??oe.emptyMessage;return i.jsxs("div",{className:`turn-patch-file ${we?"is-expanded":""}`,children:[i.jsxs("button",{type:"button",className:"turn-patch-file__toggle",onClick:()=>{wt(ue),oe.changeSetId||P(),Re&&oe.changeSetId&&oe.diffAvailable&&!He&&!ze&&Q({changeSetId:oe.changeSetId,path:oe.path,itemId:oe.itemId??null})},"aria-expanded":we,children:[i.jsx("div",{className:"turn-patch-file__path",children:oe.pathLabel}),i.jsxs("div",{className:"turn-patch-file__meta",children:[i.jsxs("span",{className:"turn-patch-summary__counts",children:[i.jsxs("span",{className:"is-add",children:["+",oe.additions]}),i.jsxs("span",{className:"is-remove",children:["-",oe.deletions]})]}),i.jsx("span",{className:"turn-patch-file__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]})]}),we?i.jsx("div",{className:"turn-patch-file__detail",children:ze?i.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}):rt?i.jsx("div",{className:"patch-file-card__empty",children:rt}):oe.diffAvailable===!1&&!It.trim()?i.jsx("div",{className:"patch-file-card__empty",children:Ft}):i.jsx(Dm,{active:we,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),render:()=>$t(It,oe.path,Ft)})}):null]},ue)})})}function ht(X){return fA(X).map(B=>{const oe=`live:${X.id}:${B.item_id??"summary"}:${B.path}`,ue=!!ie[oe],we=X.status==="running",Re=Km(X.id,B.path,B.item_id),He=z[Re],ze=k[Re]===!0,rt=I[Re]??null,It=(He==null?void 0:He.file.diff)??"",Ft=(He==null?void 0:He.empty_message)??"此变更还没有可展示的补丁内容";return i.jsx("section",{className:"conversation-entry is-tool-group",children:i.jsxs("div",{className:`tool-entry ${we?"is-running":"is-complete"} ${ue?"is-expanded":""} is-patch`,children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>{wt(oe),B.diff_available&&!He&&!ze&&Q({changeSetId:X.id,path:B.path,itemId:B.item_id??null})},"aria-expanded":ue,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:"已编辑"}),i.jsx("span",{className:"tool-entry__command",children:xt(B.path,`${oe}:live-link`,Gr(B.path,u))}),i.jsxs("span",{className:"tool-entry__counts",children:[i.jsxs("span",{className:"is-add",children:["+",B.additions]}),i.jsxs("span",{className:"is-remove",children:["-",B.deletions]})]})]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),ue?i.jsx("div",{className:"tool-entry__details",children:ze?i.jsx("div",{className:"patch-file-card__empty",children:"正在载入详情…"}):rt?i.jsx("div",{className:"patch-file-card__empty",children:rt}):!B.diff_available&&!It.trim()?i.jsx("div",{className:"patch-file-card__empty",children:Ft}):i.jsx(Dm,{active:ue,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>i.jsx("div",{className:"tool-entry__patch-list",children:i.jsxs("div",{className:"patch-file-card",children:[i.jsxs("div",{className:"patch-file-card__header",children:[i.jsx("div",{className:"patch-file-card__path",children:Gr(B.path,u)}),i.jsxs("div",{className:"patch-file-card__counts",children:[i.jsxs("span",{className:"is-add",children:["+",B.additions]}),i.jsxs("span",{className:"is-remove",children:["-",B.deletions]})]})]}),i.jsx("div",{className:"patch-file-card__diff",children:$t(It,B.path,Ft)})]})})})}):null]})},oe)})}const Ve=X=>{const B=V&&je===X&&!me[X],oe=(ee==null?void 0:ee.turnId)===X?ee.message:null;return{isEligible:B,isPending:Y===X,error:oe}};function Ke(X,B,oe,ue){const we=c2(X,u,ue),Re=we.reduce((rt,It)=>rt+It.additions,0),He=we.reduce((rt,It)=>rt+It.deletions,0),ze=Ve(B);return i.jsxs("div",{className:"turn-patch-summary",children:[i.jsxs("div",{className:"turn-patch-summary__header",children:[i.jsxs("div",{className:"turn-patch-summary__title",children:[i.jsxs("span",{children:[we.length," 个文件已更改"]}),i.jsxs("span",{className:"turn-patch-summary__counts",children:[i.jsxs("span",{className:"is-add",children:["+",Re]}),i.jsxs("span",{className:"is-remove",children:["-",He]})]})]}),ze.isEligible?i.jsx("div",{className:"turn-patch-summary__actions",children:i.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>ge(B),disabled:ze.isPending,"aria-label":ze.isPending?"正在回滚这轮改动":"回滚这轮改动",title:ze.isPending?"正在回滚这轮改动":"回滚这轮改动",children:i.jsx(r2,{})})}):null]}),ze.error?i.jsx("div",{className:"turn-patch-summary__notice is-error",children:ze.error}):null,En(oe,we)]})}function Nt(X,B,oe){const ue=Ve(X);return i.jsxs("div",{className:"turn-patch-summary",children:[i.jsxs("div",{className:"turn-patch-summary__header",children:[i.jsxs("div",{className:"turn-patch-summary__title",children:[i.jsxs("span",{children:[oe.files.length," 个文件已更改"]}),i.jsxs("span",{className:"turn-patch-summary__counts",children:[i.jsxs("span",{className:"is-add",children:["+",oe.additions]}),i.jsxs("span",{className:"is-remove",children:["-",oe.deletions]})]})]}),ue.isEligible?i.jsx("div",{className:"turn-patch-summary__actions",children:i.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>ge(X),disabled:ue.isPending,"aria-label":ue.isPending?"正在回滚这轮改动":"回滚这轮改动",title:ue.isPending?"正在回滚这轮改动":"回滚这轮改动",children:i.jsx(r2,{})})}):null]}),ue.error?i.jsx("div",{className:"turn-patch-summary__notice is-error",children:ue.error}):null,En(B,oe.files.map(we=>({path:we.path,pathLabel:we.displayPath,additions:we.additions,deletions:we.deletions,diffText:we.diffText,emptyMessage:"此变更没有可展示的补丁内容"})))]})}function Bt(X,B){var It,Ft;const oe=B.agentId?a.find(Le=>Le.id===B.agentId)??null:null,ue=Ax(((It=oe==null?void 0:oe.subagent)==null?void 0:It.nickname)??(oe==null?void 0:oe.title)??B.agentId),we=`subagent:${X.id}`,Re=!!te[we],He=B.state==="working",ze=B.state==="completed"?"子代理返回":B.state==="shutdown"?"子代理已关闭":B.state==="errored"?"子代理异常":"子代理处理中",rt=((Ft=oe==null?void 0:oe.subagent)==null?void 0:Ft.nickname)??(oe==null?void 0:oe.title)??"子代理";return i.jsx("section",{className:"conversation-entry is-tool-group",children:i.jsxs("div",{className:`tool-entry is-subagent ${He?"is-running":"is-complete"} ${Re?"is-expanded":""}`,style:{"--subagent-accent":ue},children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>Oe(we),"aria-expanded":Re,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:ze}),i.jsx("span",{className:"tool-entry__command tool-entry__command--agent",children:rt})]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Re?i.jsx("div",{className:"tool-entry__details",children:i.jsx(Dm,{active:Re,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>i.jsxs("div",{className:"tool-entry__section",children:[i.jsx("div",{className:"tool-entry__label",children:rt}),i.jsx("div",{className:"tool-entry__markdown",children:ot(B.body,`${X.id}-subagent`)})]})})}):null]})},X.id)}function Jt(X){var ue,we;if(X.kind==="tool-group"){const{group:Re}=X;if(Re.commandEntry.title==="apply_patch"&&wA(y,Re.commandEntry.timestamp,Re.patchSummary))return null;const He=!!te[Re.id],ze=l==="running"&&m===Re.id&&Re.outputEntries.length===0,rt=Re.commandEntry.title==="apply_patch"&&!!Re.patchSummary,It=rt&&(((ue=Re.patchSummary)==null?void 0:ue.files.length)??0)>1,Ft=rt?Re.patchSummary.files.length===1?Re.patchSummary.files[0].displayPath:`${Re.patchSummary.files.length} 个文件`:EA(Re.commandEntry);return i.jsx("section",{className:"conversation-entry is-tool-group",children:i.jsxs("div",{className:`tool-entry ${ze?"is-running":"is-complete"} ${He?"is-expanded":""} ${rt?"is-patch":""} ${It?"has-flat-patch-list":""}`,children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>Oe(Re.id),"aria-expanded":He,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:rt?"已编辑":ze?"正在执行":"已执行"}),i.jsx("span",{className:"tool-entry__command",children:rt&&((we=Re.patchSummary)==null?void 0:we.files.length)===1?xt(Re.patchSummary.files[0].path,`${Re.id}:patch-link`,Re.patchSummary.files[0].displayPath):Ft}),rt&&Re.patchSummary?i.jsxs("span",{className:"tool-entry__counts",children:[i.jsxs("span",{className:"is-add",children:["+",Re.patchSummary.additions]}),i.jsxs("span",{className:"is-remove",children:["-",Re.patchSummary.deletions]})]}):null]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),He?i.jsx("div",{className:"tool-entry__details",children:i.jsx(Dm,{active:He,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>i.jsx(QA,{sessionId:t,group:Re,projectPath:u})})}):null]})},Re.id)}const B=X.entry,oe=B.kind==="user"?vA(B.body):null;if(oe)return Bt(B,oe);if(B.kind==="thinking")return l!=="running"?null:i.jsx("section",{className:"conversation-entry is-thinking-status",children:i.jsx("div",{className:"thinking-status-pill",children:i.jsx("span",{children:"正在思考"})})},B.id);if(cA(B))return i.jsx("section",{className:"conversation-context-compact",children:i.jsx("div",{className:"context-compact-divider",children:i.jsx("span",{children:"背景信息已自动压缩"})})},B.id);if(B.kind==="system"&&B.title==="system_prompt")return null;if(B.kind==="system"&&B.title==="runtime-status"){const Re=gA(B.body);return i.jsx("section",{className:"conversation-entry is-runtime-status",children:i.jsxs("div",{className:`runtime-status-entry is-${Re}`,children:[i.jsx("div",{className:"runtime-status-entry__label",children:_A(B.body)}),i.jsx("pre",{className:"runtime-status-entry__body",children:B.body})]})},B.id)}return i.jsx("section",{className:`conversation-entry ${B.kind==="user"?"is-user":"is-system"} is-${B.kind}`,children:B.kind==="user"?i.jsxs("div",{className:"conversation-entry__stack",children:[i.jsxs("div",{className:"conversation-entry__body",children:[B.body.trim()?ot(B.body,B.id):null,B.attachments.length>0?kn(B):null]}),B.body.trim()?i.jsxs("button",{type:"button",className:`conversation-entry__copy ${ae===B.id?"is-copied":""}`,onClick:()=>{bt(B.id,B.body)},"aria-label":ae===B.id?"已复制消息":"复制消息",children:[i.jsx("span",{className:"conversation-entry__copy-icon","aria-hidden":"true",children:ae===B.id?i.jsx(i2,{}):i.jsx(a2,{})}),i.jsx("span",{className:"sr-only",children:ae===B.id?"已复制":"复制"})]}):null]}):i.jsxs("div",{className:"conversation-entry__body",children:[B.body.trim()?B.kind==="assistant"?on(B):ot(B.body,B.id):null,B.attachments.length>0?kn(B):null]})},B.id)}if(g)return i.jsx("div",{className:"empty-panel",children:"正在载入子代理会话…"});if(S)return i.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[i.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"})]}),i.jsx("span",{className:"sr-only",children:"正在加载会话记录"})]});if(!p)return i.jsx("div",{className:"empty-panel",children:"这个会话还没有历史记录。"});const Dt=W.canLoadEarlierEntries||W.isPulling||W.isLoadingFull,Ze=W.isPulling||W.isLoadingFull||W.triggerSource==="click",un=W.isLoadingFull?"正在加载全部对话…":W.isPulling?W.isReadyToLoad?"松开加载全部":"下拉加载更多":o?"加载全部对话":"点击加载全部",ut=W.isLoadingFull||W.triggerSource==="click"?z0:W.indicatorOffset,_e={opacity:Ze?1:0,transform:`translate3d(-50%, calc(-100% + ${ut}px), 0) scale(${Ze?1:.92})`},Fe={transform:`rotate(${W.indicatorRotation}deg)`};return i.jsxs(i.Fragment,{children:[Dt?i.jsx("section",{className:`conversation-entry is-history-loader ${W.isReadyToLoad?"is-ready":""}`,children:i.jsxs("div",{className:`timeline-history-loader ${W.isLoadingFull?"is-loading":""} ${W.triggerSource==="click"?"is-click-loading":""}`,children:[i.jsx("span",{className:"timeline-history-loader__indicator",style:_e,"aria-hidden":"true",children:i.jsx("span",{className:"timeline-history-loader__indicator-surface",children:i.jsx("span",{className:"timeline-history-loader__indicator-track",style:Fe,children:i.jsx("span",{className:`timeline-history-loader__indicator-spin ${W.isLoadingFull?"is-loading":""}`,children:i.jsx("span",{className:"timeline-history-loader__indicator-icon",children:i.jsx(VM,{})})})})})}),i.jsx("div",{className:"turn-complete-divider timeline-history-loader__divider",children:W.isLoadingFull?i.jsx("span",{className:"timeline-history-loader__content is-loading",children:i.jsx("span",{children:un})}):i.jsx("button",{type:"button",className:`timeline-history-loader__button ${W.isPulling?"is-pulling":""}`,onClick:()=>se("click"),children:un})})]})}):null,f.map(X=>{var ze;if(X.kind==="item")return Jt(X.item);const{turn:B}=X,oe=X.changeSet,ue=((ze=B.completion)==null?void 0:ze.patchSummary)??null,we=!!C[B.id],Re=B.hiddenItems.length>0&&!we,He=we?IA(B.hiddenItems):OA(B.hiddenItems);return i.jsxs("section",{className:"conversation-turn",children:[B.visibleStartItems.map(rt=>Jt(rt)),B.hiddenItems.length>0?i.jsxs("div",{className:"conversation-turn__history",children:[i.jsxs("button",{type:"button",className:`turn-history-toggle ${we?"is-expanded":""}`,onClick:()=>Ie(B.id),"aria-expanded":we,children:[i.jsx("span",{className:"turn-history-toggle__label",children:He}),i.jsx("span",{className:"turn-history-toggle__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Re?null:B.hiddenItems.map(rt=>Jt(rt))]}):null,B.completion&&B.visibleEndItems.length>0?i.jsx("section",{className:"conversation-turn-complete",children:i.jsx("div",{className:"turn-complete-divider",children:i.jsx("span",{children:B.completion.durationLabel})})}):null,B.visibleEndItems.map(rt=>Jt(rt)),oe&&oe.source==="app-server"&&oe.files.length>0?ht(oe):null,B.completion&&B.visibleEndItems.length===0?i.jsx("section",{className:"conversation-turn-complete",children:i.jsx("div",{className:"turn-complete-divider",children:i.jsx("span",{children:B.completion.durationLabel})})}):null,oe&&oe.status==="completed"&&oe.files.length>0?Ke(oe,B.id,Lg(B.id),ue):ue?Nt(B.id,Lg(B.id),ue):null]},B.id)})]})}),YA=({sessionId:e,workspaceDirectorySnapshot:t=null,workspaceAgentIndicatorState:a,embedded:l=!1,isDesktopSidebar:o,sidebarOffset:u=0,isSidebarDragging:f=!1,onOpenSidebar:m,onSelectSession:y,onExitToNodes:g}={})=>{var ko,Bd,$i,Hd,vi,Bc,Hc,bi,xi,yl,$c,Fc,vl,bl,$d,Fd,jr,Eo,qd;const{sessionId:S}=ad({strict:!1}),p=e??S??"",b=v_(p),w=(b==null?void 0:b.agentId)??pc(),N=ki(),j=La(),{data:T}=ox({scope:{sessionId:p,agentId:w??void 0},selectedSessionId:p,enabled:!l&&!t}),D=_.useMemo(()=>HM(t??T,b),[T,b,t]),z=(D==null?void 0:D.sessions.find(v=>v.id===p))??null,I=!!(z||b!=null&&b.session),k=HR({sessionId:p,scope:{sessionId:p,agentId:w??void 0},enabled:!!p}),{historyState:P,archivedState:Q,loadMoreHistory:se,loadMoreArchived:W,reset:V}=ux({scope:{sessionId:p},selectedSessionId:p}),Y=_.useRef(null),ee=_.useRef(null),me=_.useRef(null),ge=_.useRef(null),te=_.useRef(null),[xe,C]=_.useState(!1),[q,ie]=_.useState(()=>typeof window<"u"&&window.innerWidth>=e2),[he,re]=_.useState(()=>KA()),[L,ae]=_.useState(!1),[ke,U]=_.useState(""),[ve,Z]=_.useState([]),[Se,je]=_.useState(null),[Oe,Ie]=_.useState(null),[wt,qe]=_.useState(null),[bt,Ut]=_.useState(()=>R_()),[$t,zt]=_.useState(()=>F3()),[xt,it]=_.useState(()=>cb(p)),[ot,ln]=_.useState(()=>ub(p)),[on,kn]=_.useState(()=>db(p)),En=O_(),ht=_.useMemo(()=>En.map(({id:v,...O})=>O),[En]),[Ve,Ke]=_.useState({}),[Nt,Bt]=_.useState(null),[Jt,Dt]=_.useState(!1),[Ze,un]=_.useState(!1),[ut,_e]=_.useState(""),[Fe,X]=_.useState(!1),[B,oe]=_.useState(!1),[ue,we]=_.useState(null),[Re,He]=_.useState(null),[ze,rt]=_.useState(!1),[It,Ft]=_.useState(!1),[Le,Et]=_.useState("code"),[Cn,hs]=_.useState(!1),[na,Ws]=_.useState(null),[Ja,Rs]=_.useState(null),[Na,Pa]=_.useState({}),[ms,dn]=_.useState(null),[pn,Un]=_.useState(!1),[ps,Ps]=_.useState(!1),[Us,Ms]=_.useState(!1),[xs,As]=_.useState(!1),[Rt,J]=_.useState(null),[M,G]=_.useState(null),[Ee,De]=_.useState({}),[Pe,$e]=_.useState(!1),[Je,Ye]=_.useState({state:"connected",attempt:0,maxAttempts:5}),[en,jt]=_.useState({sessionId:p??null,pending:!!p,error:null}),[$n,gn]=_.useState({state:"idle"}),bn=_.useRef({}),Tn=_.useRef(D),xn=_.useRef(null);_.useEffect(()=>{zf(bt)},[bt]),_.useEffect(()=>{q3($t)},[$t]),_.useEffect(()=>{ht.length!==0&&(ht.some(v=>v.value===bt)||Ut(ht[0].value))},[ht,bt]),_.useEffect(()=>{it(cb(p)),ln(ub(p)),kn(db(p)),qe(null),Et("code"),hs(!1),Ws(null),Rs(null),Pa({}),dn(null),Un(!1),Ps(!1),Ms(!1),As(!1),J(null),G(null),De({}),ni({}),si({}),sa({}),ii(0),ri(!1),Bs(!1),ia(null),Ea.current=null,ir.current=null,_c.current=null,Xr.current=null,rr.current=!1,Jr.current=!!p},[p]),_.useEffect(()=>{bn.current=Ee},[Ee]),_.useEffect(()=>{Tn.current=D},[D]),_.useEffect(()=>{W3(p,xt)},[xt,p]),_.useEffect(()=>{K3(p,ot)},[ot,p]),_.useEffect(()=>{Q3(p,on)},[on,p]),_.useEffect(()=>{Ke({}),Bt(null)},[p]),_.useEffect(()=>{A.current=null},[p]),_.useEffect(()=>{if(!Se)return;const v=F=>{F.key==="Escape"&&je(null)},O=document.body.style.overflow;return document.body.style.overflow="hidden",window.addEventListener("keydown",v),()=>{document.body.style.overflow=O,window.removeEventListener("keydown",v)}},[Se]);const[zn,Ss]=_.useState(!1),_n=_.useRef(null),qt=_.useRef(null),yn=_.useRef(null),Zn=_.useRef(0),A=_.useRef(null),le=_.useRef(0),tt=_.useRef(0),Ht=_.useRef(0),cn=_.useRef(null),mt=_.useRef(null),St=_.useRef(0),Rn=_.useRef(null),Ks=_.useRef(!1),ei=_.useRef(!1),zs=_.useRef(!1),Qs=_.useRef(0),ka=_.useRef(p??null),ti=_.useRef({sessionId:p??null,agentId:null,embedded:l}),[nr,ni]=_.useState({}),[Gs,si]=_.useState({}),[ai,sa]=_.useState({}),[aa,ii]=_.useState(0),[sr,ri]=_.useState(!1),[Ds,Bs]=_.useState(!1),[ar,ia]=_.useState(null),Ea=_.useRef(null),ir=_.useRef(null),_c=_.useRef(null),Xr=_.useRef(null),rr=_.useRef(!1),Jr=_.useRef(!1),el=_.useRef(new Set),ss=_.useCallback(v=>{if(v.length===0)return;const O=v.map(be=>`${be}:`),F=be=>O.some(Ue=>be.startsWith(Ue));ni(be=>Object.fromEntries(Object.entries(be).filter(([Ue])=>!F(Ue)))),si(be=>Object.fromEntries(Object.entries(be).filter(([Ue])=>!F(Ue)))),sa(be=>Object.fromEntries(Object.entries(be).filter(([Ue])=>!F(Ue))))},[]),Ca=_.useCallback(v=>{el.current.add(v)},[]),Ei=_.useCallback(v=>{el.current.delete(v)},[]),tl=_.useRef(null),uo=_.useRef(null),js=_.useRef(null),fo=_.useRef(null),li=_.useRef(he),Ci=_.useRef(null),oi=_.useRef(null);let pe=qR(z,(ko=k.data)==null?void 0:ko.session)??(b==null?void 0:b.session)??null;const Sn=(D==null?void 0:D.agent)??null;let ra=(D==null?void 0:D.projects.find(v=>v.id===(pe==null?void 0:pe.project_id)))??(b==null?void 0:b.project);const la=(pe==null?void 0:pe.capability.can_show_git)??!1,oa=(pe==null?void 0:pe.capability.can_show_terminal)??!1;ti.current={sessionId:p??null,agentId:(pe==null?void 0:pe.agent_id)??(Sn==null?void 0:Sn.id)??w,embedded:l};const tn=_.useCallback(()=>{var O;const v=(pe==null?void 0:pe.agent_id)??(Sn==null?void 0:Sn.id)??w;return v&&((O=mt.current)==null?void 0:O.agentId)===v?Promise.resolve(mt.current.target):wn({sessionId:p,agentId:v})},[Sn==null?void 0:Sn.id,w,pe==null?void 0:pe.agent_id,p]),nl=_.useCallback(async v=>{if(l){y==null||y(v);return}Js(v),Kr(v),Sn!=null&&Sn.id&&Ji(Sn.id),await N({to:"/",replace:!0})},[Sn==null?void 0:Sn.id,l,N,y]),yc=_.useCallback(async()=>{if(l){g==null||g();return}await N({to:"/nodes"})},[l,N,g]),ph=v=>v instanceof Element&&!!v.closest('button, textarea, input, a, [role="button"], [role="dialog"]'),dd=v=>ph(v),vc=()=>{const v=me.current;if(!v)return;const O=()=>{v.scrollTo({top:v.scrollHeight,behavior:"auto"})};O(),window.requestAnimationFrame(()=>{O(),window.requestAnimationFrame(O)})},gh=_.useCallback(()=>{const v=me.current;return v?v.scrollHeight-v.scrollTop-v.clientHeight<=t2:!0},[]),Lp=_.useCallback(v=>{(v!=null&&v.force||gh())&&vc()},[gh]),fd=()=>{const v=me.current;if(!v){$e(!1);return}const O=v.scrollHeight-v.scrollTop-v.clientHeight;$e(O>t2)},as=_.useCallback(v=>{j.setQueriesData({queryKey:os},v)},[j]),hd=_.useCallback((v,O)=>{j.setQueryData(Nx({sessionId:v,scope:{sessionId:v}}),F=>WR(F??void 0,v,O)??F)},[j]),Pp=(D==null?void 0:D.projects)??[],lr=(D==null?void 0:D.sessions)??[],_h=(D==null?void 0:D.project_stats)??[],jn=_.useMemo(()=>{var v;return(v=pe==null?void 0:pe.subagent)!=null&&v.parent_session_id?lr.find(O=>{var F;return O.id===((F=pe==null?void 0:pe.subagent)==null?void 0:F.parent_session_id)})??null:null},[(Bd=pe==null?void 0:pe.subagent)==null?void 0:Bd.parent_session_id,lr]),sl=_.useCallback(v=>{const O=v.session_id;O&&(j.setQueryData(Fo(O),F=>mx(F,v.entries)),j.setQueryData(["timeline",O],F=>{const be=XT(F,v);return be.view==="full_compact"&&UR(be),be}))},[j]),yh=_.useCallback(v=>{var Kt,In;const O=v.session_id;if(!O)return;const F=ti.current.sessionId===O;sl(v.timeline),j.setQueryData(["interactions",O],v.interactions),F&&we(yt=>yt&&v.interactions.some(rs=>rs.id===yt)?yt:null),j.setQueryData(["plan",O],v.plan_snapshot),v.change_sets.length>0?(ss(v.change_sets.map(yt=>yt.id)),j.setQueryData(["change-sets",O],v.change_sets),Ca(O)):el.current.has(O)||(j.setQueryData(["change-sets",O],[]),Ei(O)),j.setQueryData(["session-run-workbench",O],v.run_workbench);const be=(Kt=v.timeline.entries.at(-1))==null?void 0:Kt.timestamp,Ue=be&&(!v.session_patch.last_event_at||+new Date(be)>+new Date(v.session_patch.last_event_at))?{...v.session_patch,last_event_at:be}:v.session_patch,gt=$b(Ue);gt&&hd(O,gt);const Xe=C0(Ue);Xe&&vp(Tn.current??void 0,O)&&as(yt=>Tf(yt,O,Xe)),F&&(v.session_patch.run_state==="running"||v.session_patch.run_state==="completed"||v.session_patch.run_state==="idle")&&(X(v.session_patch.run_state==="running"),v.session_patch.run_state!=="running"&&oe(!1)),F&&((In=v.run_workbench)!=null&&In.terminal_snapshot)&&De(yt=>{var Ce;const rs=new Set((Ce=v.run_workbench)==null?void 0:Ce.terminal_snapshot.terminals.map(Ct=>Ct.id)),es={};for(const[Ct,nn]of Object.entries(yt))rs.has(Ct)&&(es[Ct]=nn);return es}),jn!=null&&jn.id&&j.invalidateQueries({queryKey:["timeline",jn.id,"prefix-source"],exact:!0})},[sl,ss,hd,Ca,jn==null?void 0:jn.id,j,Ei]),bc=_.useCallback(async v=>{var be;if(!p)return null;const O=p;if(((be=cn.current)==null?void 0:be.sessionId)===O)return cn.current.promise;const F=(async()=>{var gt;const Ue=++Zn.current;gn({state:"recovering"});try{const Kt=await(await tn()).client.getSessionBootstrap(p);return Zn.current!==Ue?null:(yh(Kt),tt.current=Date.now(),gn({state:"idle"}),Kt)}catch(Xe){return Zn.current!==Ue||gn({state:"failed",error:Xe instanceof Error?Xe.message:v==="initial"?"会话加载失败。":"会话同步失败。"}),null}finally{((gt=cn.current)==null?void 0:gt.sessionId)===O&&(cn.current=null)}})();return cn.current={sessionId:O,promise:F},F},[yh,tn,p]),md=_.useCallback(v=>{p&&(Ht.current>0||(Ht.current=Date.now(),bc(v).then(O=>{jt({sessionId:p,pending:!1,error:O?null:"Unable to load session bootstrap."})}).catch(O=>{jt({sessionId:p,pending:!1,error:O instanceof Error?O.message:"Unable to load session bootstrap."})})))},[bc,p]),vh=_.useCallback(async()=>{if(!p||el.current.has(p))return;const O=await(await tn()).client.getSessionChangeSets(p);ss(O.map(F=>F.id)),j.setQueryData(["change-sets",p],O),Ca(p)},[ss,Ca,j,tn,p]),xc=_.useCallback(async(v="click")=>{if(!p||Ds)return;const O=me.current;O&&(Xr.current=O.scrollHeight,rr.current=!0),ia(v),Bs(!0);const F=Date.now();try{const Ue=await(await tn()).client.getSessionTimeline(p,{view:"full_compact"});sl(Ue)}finally{if(v==="click"){const be=IM-(Date.now()-F);be>0&&await new Promise(Ue=>{window.setTimeout(Ue,be)})}Bs(!1),ii(0),ri(!1),ia(null)}},[sl,Ds,tn,p]),bh=_.useCallback(async v=>{if(!p)return;const O=Km(v.changeSetId,v.path,v.itemId);if(!(nr[O]||ai[O])){sa(F=>({...F,[O]:!0})),si(F=>({...F,[O]:void 0}));try{const be=await(await tn()).client.getSessionChangeSetFileDiff(p,v);ni(Ue=>({...Ue,[O]:be}))}catch(F){si(be=>({...be,[O]:F instanceof Error?F.message:"无法读取这个文件的差异详情。"}))}finally{sa(F=>({...F,[O]:!1}))}}},[nr,ai,tn,p]),ca=ls({queryKey:["timeline",p],enabled:!1,queryFn:async()=>$M,initialData:p?PR(p)??j.getQueryData(["timeline",p]):void 0,refetchInterval:!1}),or=ls({queryKey:Fo(p),enabled:!1,queryFn:async()=>[],initialData:[]});_.useEffect(()=>{const v=b==null?void 0:b.optimisticEntry;!p||(b==null?void 0:b.sessionId)!==p||!v||j.setQueryData(Fo(p),O=>O!=null&&O.some(F=>F.id===v.id)?O:O0(O,v))},[b,j,p]),_.useEffect(()=>{var O;(b==null?void 0:b.sessionId)!==p||!(((O=k.data)==null?void 0:O.session.id)===p||T!=null&&T.sessions.some(F=>F.id===p))||hk(p)},[T,b==null?void 0:b.sessionId,($i=k.data)==null?void 0:$i.session.id,p]);const ho=Rm(ca.data),Up=or.data??[],mo=ho.length>0||Up.length>0||!!(b!=null&&b.optimisticEntry),Ti=ls({queryKey:["timeline",jn==null?void 0:jn.id,"prefix-source"],enabled:!!(jn!=null&&jn.id),queryFn:async()=>(await(await wn({sessionId:jn.id,projectId:jn.project_id,agentId:jn.agent_id})).client.getSessionTimeline(jn.id,{view:"tail"})).entries,refetchInterval:!1}),pd=_.useMemo(()=>{const v=Rm(ca.data);return pe!=null&&pe.subagent?new Set:SA(v)},[pe==null?void 0:pe.subagent,ca.data]),Sc=_.useMemo(()=>xA(Rm(ca.data)),[ca.data]),gd=_.useMemo(()=>pe!=null&&pe.subagent?[]:lr.filter(v=>{var O;return v.id!==p&&((O=v.subagent)==null?void 0:O.parent_session_id)===p&&!v.archived}).filter(v=>{if(v.run_state==="running")return!0;if(!((pe==null?void 0:pe.run_state)==="running"||Fe))return!1;if(pd.has(v.id))return!0;if(!Sc)return!1;const O=new Date(Sc).getTime(),F=new Date(v.last_event_at).getTime();return Number.isFinite(O)&&Number.isFinite(F)&&F>=O-AM}).sort((v,O)=>+new Date(O.last_event_at)-+new Date(v.last_event_at)),[Sc,Fe,pd,pe==null?void 0:pe.run_state,pe==null?void 0:pe.subagent,p,lr]);_.useEffect(()=>{if(!p){xn.current=null,zs.current=!1,Qs.current=0,ka.current=null,jt({sessionId:null,pending:!1,error:null}),Ye({state:"connected",attempt:0,maxAttempts:5});return}const v=!mo;jt({sessionId:p,pending:v,error:null}),tt.current=v?0:Date.now(),Ht.current=0},[mo,p]),_.useEffect(()=>{if(!p||!en.pending)return;if(Je.state==="failed"){md("initial");return}if(Je.state!=="connected")return;const v=le.current;if(v<=0)return;const O=window.setTimeout(()=>{tt.current>=v||md("initial")},1200);return()=>{window.clearTimeout(O)}},[Je.state,en.pending,md,p]),_.useEffect(()=>{if(!p||Je.state!=="connected"||en.pending||mo||!zs.current||ka.current!==p)return;const v=Qs.current;if(v<=0)return;const O=window.setTimeout(()=>{if(zs.current&&Qs.current===v){if(tt.current>=v){zs.current=!1,Qs.current=0,ka.current=null;return}zs.current=!1,Qs.current=0,ka.current=null,bc("connected")}},1200);return()=>{window.clearTimeout(O)}},[Je.state,bc,mo,en.pending,p]);const al=ls({queryKey:["change-sets",p],enabled:!1,queryFn:async()=>p?(await tn()).client.getSessionChangeSets(p):[],initialData:p?j.getQueryData(["change-sets",p])??[]:[],refetchInterval:!1}),il=ls({queryKey:["session-git-workspace",p],enabled:!!(p&&la&&Le==="git"),queryFn:async()=>(await tn()).client.getSessionGitWorkspace(p),refetchInterval:!1}),Ua=ls({queryKey:["session-git-history",p],enabled:!1,queryFn:async()=>(await tn()).client.getSessionGitHistory(p),refetchInterval:!1}),rl=ls({queryKey:["session-run-workbench",p],enabled:!!p&&oa&&(pn||ps||Le==="terminal"),queryFn:async()=>p?(await tn()).client.getSessionRunWorkbench(p):null,initialData:p?j.getQueryData(["session-run-workbench",p])??null:null,refetchInterval:!1}),po=_.useCallback(async v=>{if(!p)return;const O=["session-run-workbench",p],F=j.getQueryData(O);if(F){j.setQueryData(O,v(F));return}const Ue=await(await tn()).client.getSessionRunWorkbench(p);j.setQueryData(O,v(Ue))},[j,tn,p]),Ri=ls({queryKey:["plan",p],enabled:!1,queryFn:async()=>null,initialData:p?j.getQueryData(["plan",p])??null:null,refetchInterval:!1}),cr=ls({queryKey:["interactions",p],enabled:!1,queryFn:async()=>[],initialData:p?j.getQueryData(["interactions",p])??[]:[],refetchInterval:!1}),Mi=_.useCallback(async(v,O)=>{if(p){De(F=>{var be,Ue,gt;return{...F,[v]:{chunks:((be=F[v])==null?void 0:be.chunks)??[],nextCursor:((Ue=F[v])==null?void 0:Ue.nextCursor)??0,truncated:((gt=F[v])==null?void 0:gt.truncated)??!1,isLoading:!0,error:null}}});try{const F=await tn(),be=bn.current[v],Ue=await F.client.getSessionTerminalOutput({sessionId:p,terminalId:v,cursor:O!=null&&O.force||be!=null&&be.truncated||be==null?void 0:be.nextCursor});De(gt=>{const Xe=gt[v],Kt=O!=null&&O.force||Ue.truncated||!Xe?Ue.chunks:l2(Xe.chunks,Ue.chunks);return{...gt,[v]:{chunks:Kt,nextCursor:Ue.next_cursor,truncated:Ue.truncated,isLoading:!1,error:null}}})}catch(F){De(be=>{var Ue,gt,Xe;return{...be,[v]:{chunks:((Ue=be[v])==null?void 0:Ue.chunks)??[],nextCursor:((gt=be[v])==null?void 0:gt.nextCursor)??0,truncated:((Xe=be[v])==null?void 0:Xe.truncated)??!1,isLoading:!1,error:F instanceof Error?F.message:"无法读取终端输出。"}}})}}},[p]);_.useEffect(()=>{var be,Ue;const v=(be=rl.data)==null?void 0:be.terminal_snapshot.active_terminal_id,O=(Ue=rl.data)==null?void 0:Ue.terminal_snapshot.terminals.find(gt=>gt.id===v);if(!v||!O)return;const F=Ee[v];(!F||F.truncated||F.nextCursor<O.output_cursor)&&Mi(v)},[Mi,rl.data,Ee]);const xh=!!(pe!=null&&pe.subagent&&(jn!=null&&jn.id)&&Ti.isPending&&!Ti.data),Ai=_.useMemo(()=>{const v=Rm(ca.data);return pe!=null&&pe.subagent?jn!=null&&jn.id&&Ti.isPending&&!Ti.data?[]:yA(v,Ti.data):v},[jn==null?void 0:jn.id,Ti.data,Ti.isPending,pe==null?void 0:pe.subagent,ca.data]),ll=_.useMemo(()=>ZT(Ai,or.data),[Ai,or.data]);_.useEffect(()=>{p&&window.localStorage.setItem(EM,p)},[p]),_.useEffect(()=>{const v=yn.current;v&&((or.data??[]).some(O=>O.id===v.optimisticEntryId)||(yn.current=null))},[or.data]),_.useEffect(()=>{Ft(!1)},[p]),_.useEffect(()=>{_e((pe==null?void 0:pe.title)??""),un(!1)},[pe==null?void 0:pe.title,p]),_.useEffect(()=>{oe(!1)},[p]),_.useEffect(()=>()=>{_n.current&&window.clearTimeout(_n.current),qt.current&&window.clearTimeout(qt.current),oi.current&&window.cancelAnimationFrame(oi.current)},[]),_.useEffect(()=>{if(qt.current&&(window.clearTimeout(qt.current),qt.current=null),!!Oe)return qt.current=window.setTimeout(()=>{Ie(null),qt.current=null},LM),()=>{qt.current&&(window.clearTimeout(qt.current),qt.current=null)}},[Oe]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Tx,String($0(he))),window.localStorage.setItem(Mf,Af)}catch{}},[he]),_.useEffect(()=>{li.current=he},[he]),_.useEffect(()=>{if(typeof window>"u")return;const v=()=>{const O=window.innerWidth>=e2;ie(O),O&&C(!1)};return v(),window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v)}},[]),_.useEffect(()=>{if(!L)return;const v=F=>{const be=fo.current;if(!be)return;const Ue=F.clientX-be.startX,gt=$0(be.startWidth+Ue);Ci.current=gt,oi.current===null&&(oi.current=window.requestAnimationFrame(()=>{oi.current=null;const Xe=Ci.current,Kt=Y.current;Xe===null||!Kt||Kt.style.setProperty("--desktop-sidebar-width",`${Xe}px`)}))},O=()=>{oi.current!==null&&(window.cancelAnimationFrame(oi.current),oi.current=null);const F=Ci.current??li.current;Ci.current=null,fo.current=null,ae(!1),li.current=F,re(F)};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",O),window.addEventListener("pointercancel",O),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",O),window.removeEventListener("pointercancel",O)}},[L]),_.useEffect(()=>{const v=O=>{const F=O.target;rt(!1),Ss(!1),!(F instanceof Element&&(F.closest(".conversation-topbar__actions")||F.closest(".conversation-topbar__title-actions")||F.closest(".picker-sheet")||F.closest(".picker-sheet-wrap")))&&(Dt(!1),Un(!1),Ps(!1))};return window.addEventListener("pointerdown",v),()=>{window.removeEventListener("pointerdown",v)}},[]),_.useEffect(()=>{const v=Y.current;if(!v||q)return;const O=gt=>{const Xe=gt.touches[0];gt.touches.length!==1||!Xe||dd(gt.target)||(uo.current={startX:Xe.clientX,startY:Xe.clientY})},F=gt=>{if(gt.touches.length!==1)return;const Xe=gt.touches[0];if(!js.current){const In=uo.current;if(!In)return;const yt=Xe.clientX-In.startX,rs=Xe.clientY-In.startY;if(Math.abs(yt)<8&&Math.abs(rs)<8)return;if(Math.abs(yt)<=Math.abs(rs)){uo.current=null;return}pi(In.startX,In.startY)}Cd(Xe.clientX,Xe.clientY)&>.preventDefault()},be=gt=>{if(uo.current=null,!js.current)return;const Xe=gt.changedTouches[0];if(!Xe){js.current=null,$a(null);return}Td(Xe.clientX,Xe.clientY)},Ue=()=>{uo.current=null,js.current=null,$a(null)};return v.addEventListener("touchstart",O,{passive:!0,capture:!0}),v.addEventListener("touchmove",F,{passive:!1,capture:!0}),v.addEventListener("touchend",be,{capture:!0}),v.addEventListener("touchcancel",Ue,{capture:!0}),()=>{v.removeEventListener("touchstart",O,{capture:!0}),v.removeEventListener("touchmove",F,{capture:!0}),v.removeEventListener("touchend",be,{capture:!0}),v.removeEventListener("touchcancel",Ue,{capture:!0})}},[q,xe]),_.useEffect(()=>{const v=me.current;if(!v)return;if(rr.current&&Xr.current!==null){const F=Xr.current,be=v.scrollHeight;v.scrollTop+=Math.max(0,be-F),rr.current=!1,Xr.current=null;return}if(!p||!Jr.current||Ai.length===0)return;vc();const O=window.setTimeout(()=>{vc(),Jr.current=!1},120);return()=>{window.clearTimeout(O)}},[Ai.length,p]),_.useEffect(()=>{const v=me.current;if(!v)return;const O=()=>{fd()};return O(),v.addEventListener("scroll",O,{passive:!0}),window.addEventListener("resize",O),()=>{v.removeEventListener("scroll",O),window.removeEventListener("resize",O)}},[Ai.length,p]),_.useEffect(()=>{const v=me.current;if(!v)return;const O=ca.data,F=(Mm(O)||Pg(O)!=="full_compact")&&!Ds,be=()=>{Ea.current=null,ir.current=null,ii(0),ri(!1)},Ue=()=>{const yt=F&&ir.current!==null&&aa>=Og;be(),yt&&xc("pull")},gt=yt=>{var rs,es;!F||yt.touches.length!==1||v.scrollTop>0||ph(yt.target)||(Ea.current=((rs=yt.touches[0])==null?void 0:rs.clientX)??null,ir.current=((es=yt.touches[0])==null?void 0:es.clientY)??null)},Xe=yt=>{if(yt.defaultPrevented)return;const rs=Ea.current,es=ir.current;if(rs===null||es===null||yt.touches.length!==1)return;const Ce=yt.touches[0],Ct=((Ce==null?void 0:Ce.clientX)??rs)-rs,nn=((Ce==null?void 0:Ce.clientY)??es)-es;if(Math.abs(Ct)>Math.abs(nn)){be();return}if(nn<=0){ii(0),ri(!1);return}if(v.scrollTop>0){be();return}yt.cancelable&&yt.preventDefault(),ri(!0),ii(Math.min(n2,nn))},Kt=()=>{Ue()},In=()=>{be()};return v.addEventListener("touchstart",gt,{passive:!0}),v.addEventListener("touchmove",Xe,{passive:!1}),v.addEventListener("touchend",Kt),v.addEventListener("touchcancel",In),()=>{v.removeEventListener("touchstart",gt),v.removeEventListener("touchmove",Xe),v.removeEventListener("touchend",Kt),v.removeEventListener("touchcancel",In)}},[Ds,xc,aa,ca.data]),_.useEffect(()=>{var gt,Xe;if(!p){Rn.current!==null&&(clearTimeout(Rn.current),Rn.current=null),(gt=mt.current)==null||gt.stream.setSessionId(null);return}let v=!1;const O=++St.current,F=ti.current.agentId,be=()=>{Rn.current!==null&&(clearTimeout(Rn.current),Rn.current=null)},Ue=()=>{l||(be(),Rn.current=setTimeout(()=>{Rn.current=null;const Kt=ti.current;Rf(j,{scope:{sessionId:Kt.sessionId,agentId:Kt.agentId},selectedSessionId:Kt.sessionId})},PM))};return F&&((Xe=mt.current)==null?void 0:Xe.agentId)===F?(mt.current.stream.setSessionId(p),()=>{v=!0}):(tn().then(Kt=>{var rs,es;if(v||St.current!==O)return;const In=Kt.client.getConnectionKey();if(((rs=mt.current)==null?void 0:rs.key)===In){mt.current.stream.setSessionId(p);return}(es=mt.current)==null||es.stream.close(),Ks.current=!1,ei.current=!1;const yt=Kt.client.createEventStream(Ce=>{var qi,Co,xl,wr,Dh,Fn,qc,Wc,Wd,Kd,Oh,Kc,Qc,Gc,ks,Wn,To,Sl,Ro,Yc,Fa,Mo;const Ct=typeof((qi=Ce.payload)==null?void 0:qi.sessionId)=="string"?Ce.payload.sessionId:null,nn=ti.current.sessionId,Qt=Ct===nn?nn:null,Fi=typeof((Co=Ce.payload)==null?void 0:Co.projectId)=="string"?Ce.payload.projectId:null;if(Ce.type==="agent.online"){if(ei.current){ei.current=!1;return}V(),Ue();return}if(Ce.type==="timeline.reset"&&Qt){tt.current=Date.now(),zs.current=!1,Qs.current=0,ka.current=null,jt({sessionId:Qt,pending:!1,error:null});const st=Array.isArray((xl=Ce.payload)==null?void 0:xl.entries)?Ce.payload.entries:[],Vt=Mm(j.getQueryData(["timeline",Qt]));sl(d2(Qt,st,Vt));const Mn=(wr=st[st.length-1])==null?void 0:wr.timestamp;Mn&&as(sn=>T0(sn,Qt,Mn)),window.requestAnimationFrame(fd);return}if(Ce.type==="interaction.reset"&&Qt){const st=Array.isArray((Dh=Ce.payload)==null?void 0:Dh.requests)?Ce.payload.requests:[];j.setQueryData(["interactions",Qt],st),we(Vt=>Vt&&st.some(Mn=>Mn.id===Vt)?Vt:null);return}if(Ce.type==="plan.reset"&&Qt){const st=(Fn=Ce.payload)!=null&&Fn.planSnapshot&&typeof Ce.payload.planSnapshot=="object"?Ce.payload.planSnapshot:null;j.setQueryData(["plan",Qt],st);return}if(Ce.type==="timeline.delta"&&Qt){const st=Array.isArray((qc=Ce.payload)==null?void 0:qc.entries)?Ce.payload.entries:[],Vt=Mm(j.getQueryData(["timeline",Qt]));sl(d2(Qt,hx(void 0,st),Vt));const Mn=(Wc=st[st.length-1])==null?void 0:Wc.timestamp;Mn&&as(sn=>T0(sn,Qt,Mn)),Lp(),window.requestAnimationFrame(fd);return}if(Ce.type==="interaction.delta"&&Qt){const st=Array.isArray((Wd=Ce.payload)==null?void 0:Wd.requests)?Ce.payload.requests:[],Vt=Array.isArray((Kd=Ce.payload)==null?void 0:Kd.resolvedRequestIds)?Ce.payload.resolvedRequestIds.filter(Mn=>typeof Mn=="string"&&Mn.trim().length>0):[];j.setQueryData(["interactions",Qt],Mn=>{const sn=new Map((Mn??[]).map(Hn=>[Hn.id,Hn]));for(const Hn of st)sn.set(Hn.id,Hn);for(const Hn of Vt)sn.delete(Hn);return[...sn.values()].sort((Hn,qa)=>+new Date(qa.updated_at)-+new Date(Hn.updated_at))}),Vt.length>0&&we(Mn=>Mn&&Vt.includes(Mn)?null:Mn);return}if(Ce.type==="plan.delta"&&Qt){const st=(Oh=Ce.payload)!=null&&Oh.planSnapshot&&typeof Ce.payload.planSnapshot=="object"?Ce.payload.planSnapshot:null;j.setQueryData(["plan",Qt],st);return}if(Ce.type==="changeset.reset"&&Qt){const st=Array.isArray((Kc=Ce.payload)==null?void 0:Kc.changeSets)?Ce.payload.changeSets:[];st.length>0?(ss(st.map(Vt=>Vt.id)),j.setQueryData(["change-sets",Qt],st),Ca(Qt)):el.current.has(Qt)||(j.setQueryData(["change-sets",Qt],[]),Ei(Qt));return}if(Ce.type==="changeset.delta"&&Qt){const st=Array.isArray((Qc=Ce.payload)==null?void 0:Qc.changeSets)?Ce.payload.changeSets:[];ss(st.map(Vt=>Vt.id)),j.setQueryData(["change-sets",Qt],Vt=>mA(Vt,st));return}if(Ce.type==="terminal.snapshot"&&Qt){const st=(Gc=Ce.payload)!=null&&Gc.snapshot&&typeof Ce.payload.snapshot=="object"?Ce.payload.snapshot:null;if(!st)return;j.setQueryData(["session-run-workbench",Qt],Vt=>Vt&&{...Vt,terminal_snapshot:st}),De(Vt=>{const Mn=new Set(st.terminals.map(Hn=>Hn.id)),sn={};for(const[Hn,qa]of Object.entries(Vt))Mn.has(Hn)&&(sn[Hn]=qa);return sn});return}if(Ce.type==="terminal.delta"&&Qt){const st=(ks=Ce.payload)!=null&&ks.terminal&&typeof Ce.payload.terminal=="object"?Ce.payload.terminal:null,Vt=Array.isArray((Wn=Ce.payload)==null?void 0:Wn.chunks)?Ce.payload.chunks:[],Mn=typeof((To=Ce.payload)==null?void 0:To.activeTerminalId)=="string"?Ce.payload.activeTerminalId:null;if(!st)return;j.setQueryData(["session-run-workbench",Qt],sn=>{if(!sn)return sn;const Hn=sn.terminal_snapshot.terminals.filter(Zc=>Zc.id!==st.id),qa=sn.terminal_snapshot.terminals.findIndex(Zc=>Zc.id===st.id),Vc=[...Hn];return qa<=0?Vc.unshift(st):Vc.splice(qa,0,st),{...sn,terminal_snapshot:{...sn.terminal_snapshot,active_terminal_id:Mn,updated_at:st.updated_at,terminals:Vc}}}),De(sn=>{var qa;if(Vt.length===0)return sn;const Hn=sn[st.id];return{...sn,[st.id]:{chunks:l2((Hn==null?void 0:Hn.chunks)??[],Vt),nextCursor:typeof((qa=Ce.payload)==null?void 0:qa.nextCursor)=="number"?Ce.payload.nextCursor:st.output_cursor,truncated:(Hn==null?void 0:Hn.truncated)??!1,isLoading:!1,error:null}}});return}if(Ce.type==="thread.updated"&&Fi){const st=typeof((Sl=Ce.payload)==null?void 0:Sl.action)=="string"?Ce.payload.action:"",Vt=(Ro=Ce.payload)!=null&&Ro.projectPatch&&typeof Ce.payload.projectPatch=="object"?Ce.payload.projectPatch:null,Mn=Array.isArray((Yc=Ce.payload)==null?void 0:Yc.orderedProjectIds)?Ce.payload.orderedProjectIds.filter(sn=>typeof sn=="string"&&sn.trim().length>0):[];if((st==="pin"||st==="unpin"||st==="rename")&&Vt){as(sn=>Tu(sn,Fi,Vt));return}if(st==="reorder"&&Mn.length>0){as(sn=>xp(sn,Mn));return}if(st==="remove"||st==="archive"){V(),as(sn=>Sp(sn,Fi));return}if(st==="unarchive"){V(),Ue();return}}if(Ce.type==="session.updated"&&Ct){const st=(Fa=Ce.payload)!=null&&Fa.sessionPatch&&typeof Ce.payload.sessionPatch=="object"?C0(Ce.payload.sessionPatch):null,Vt=(Mo=Ce.payload)!=null&&Mo.sessionPatch&&typeof Ce.payload.sessionPatch=="object"?$b(Ce.payload.sessionPatch):null;Vt&&hd(Ct,Vt);const Mn=vp(Tn.current??void 0,Ct);if(st&&Mn)as(sn=>Tf(sn,Ct,st));else{if(ti.current.embedded&&Ct===nn&&!Tn.current)return;if(Mn)return;Ue()}Qt&&((st==null?void 0:st.run_state)==="running"||(st==null?void 0:st.run_state)==="completed"||(st==null?void 0:st.run_state)==="idle")&&(X(st.run_state==="running"),st.run_state!=="running"&&oe(!1));return}Ce.type==="turn.completed"&&Qt&&(X(!1),oe(!1),j.setQueryData(["plan",Qt],null))},{sessionId:p,reconnectWhenHidden:!0,onStatus:Ce=>{if(Ye(Ce),Ce.state==="connected"){const Ct=Date.now(),nn=Ks.current;le.current=Ct,zs.current=nn,Qs.current=nn?Ct:0,ka.current=nn?p:null,ei.current=!0,nn&&(V(),Ue()),Ks.current=!0,Ss(!1);return}Zn.current+=1,gn({state:"idle"})}});mt.current={key:In,agentId:F,target:Kt,stream:yt},yt.setSessionId(p)}).catch(Kt=>{v||St.current!==O||Ye({state:"failed",attempt:0,maxAttempts:5,error:Kt instanceof Error?Kt.message:"Unable to connect to live session."})}),()=>{v=!0})},[l,tn,p]),_.useEffect(()=>()=>{var v;St.current+=1,Rn.current!==null&&(clearTimeout(Rn.current),Rn.current=null),(v=mt.current)==null||v.stream.close(),mt.current=null},[]),_.useEffect(()=>{if(!p||(pe==null?void 0:pe.run_state)!=="running"||pe.context_usage)return;if(A.current!==p){A.current=p;return}let v=!1;const O=window.setTimeout(()=>{v||k.refetch()},1200);return()=>{v=!0,window.clearTimeout(O)}},[p,pe==null?void 0:pe.context_usage,pe==null?void 0:pe.run_state,k.refetch]),_.useEffect(()=>{var Ue,gt;if(!p||!I||!pe||!ra||((Ue=k.data)==null?void 0:Ue.session.id)===p||k.isFetching||xn.current===p||typeof window>"u")return;xn.current=p;const v=window,O=()=>{k.refetch()},F=(gt=v.requestIdleCallback)==null?void 0:gt.call(v,O,{timeout:1500}),be=F===void 0?window.setTimeout(O,320):null;return()=>{var Xe;F!==void 0&&((Xe=v.cancelIdleCallback)==null||Xe.call(v,F)),be!==null&&window.clearTimeout(be)}},[ra,pe,(Hd=k.data)==null?void 0:Hd.session.id,k.isFetching,k.refetch,I,p]),_.useEffect(()=>{Dt(!1)},[q,p]);const _d=_.useCallback(v=>{var O;qe(v),((O=v.effect)==null?void 0:O.type)==="set_session_model"&&(Ut(v.effect.model),v.effect.reasoning_effort&&zt(v.effect.reasoning_effort))},[]),za=Vn({mutationFn:async v=>(await tn()).client.sendSessionInput(v),onMutate:async v=>{await j.cancelQueries({queryKey:["timeline",v.sessionId]}),Ie(null),oe(!1),X(!0),Bt(v.proposedPlanEntryId??null);const O=v.clearComposer!==!1;O&&(U(""),Z([])),_n.current&&window.clearTimeout(_n.current);const F=new Date().toISOString(),be=`${L_}${v.sessionId}:${Date.now()}`;yn.current=O?{optimisticEntryId:be,draft:v.input,attachments:v.attachments}:null,j.setQueryData(Fo(v.sessionId),Ue=>O0(Ue,{id:be,kind:"user",title:"你",body:v.input,body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:F,accent:"primary",attachments:_x(v.attachments)})),as(Ue=>Tf(Ue,v.sessionId,{run_state:"running",run_state_changed_at:F,last_event_at:F}))},onSuccess:async(v,O)=>{Bt(null),O.proposedPlanEntryId&&Ke(F=>{const be={...F};return delete be[O.proposedPlanEntryId],be}),await j.invalidateQueries({queryKey:os}),await j.invalidateQueries({queryKey:["plan",O.sessionId]}),await j.invalidateQueries({queryKey:["change-sets",O.sessionId]}),_n.current=null},onError:(v,O)=>{Bt(null),X(!1);const F=yn.current;F&&(j.setQueryData(Fo(O.sessionId),be=>JT(be,F.optimisticEntryId)),U(be=>be||F.draft),Z(be=>be.length>0?be:F.attachments),yn.current=null),Ie(v instanceof Error?v.message:"无法发送消息")}}),ol=Vn({mutationFn:async v=>(await tn()).client.executeSessionCommand(v),onMutate:v=>{Ie(null),U(""),Z([]);const O=v.input.slice(1).trim().split(/\s+/)[0]??"",F=new Date().toISOString();qe({panel_id:`command-panel-pending-${Date.now()}`,session_id:v.sessionId,command_name:O,command_text:v.input,title:`正在执行 /${O}`,description:null,status:"running",body:"命令执行中…",submitted_at:F,updated_at:F,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null})},onSuccess:async v=>{_d(v.panel),await j.invalidateQueries({queryKey:os})},onError:(v,O)=>{qe(null),U(F=>F||O.input),Ie(v instanceof Error?v.message:"无法执行命令")}}),ur=Vn({mutationFn:async v=>(await tn()).client.respondToSessionCommand(v),onMutate:()=>{Ie(null)},onSuccess:async v=>{_d(v.panel),await j.invalidateQueries({queryKey:os})},onError:v=>{Ie(v instanceof Error?v.message:"无法继续执行命令")}}),yd=Vn({mutationFn:async v=>(await tn()).client.respondToSessionInteraction(v),onMutate:async v=>{Ie(null),we(v.requestId),j.setQueryData(["interactions",v.sessionId],O=>(O??[]).map(F=>F.id===v.requestId?{...F,status:"submitting",updated_at:new Date().toISOString()}:F))},onSuccess:async(v,O)=>{await j.invalidateQueries({queryKey:["interactions",O.sessionId]})},onError:(v,O)=>{j.setQueryData(["interactions",O.sessionId],F=>(F??[]).map(be=>be.id===O.requestId?{...be,status:"pending"}:be)),we(null),Ie(v instanceof Error?v.message:"无法提交确认回复")}}),Ba=Vn({mutationFn:async v=>(await tn()).client.interruptSession(v),onMutate:async v=>{Ie(null),oe(!0),X(!1),_n.current&&(window.clearTimeout(_n.current),_n.current=null);const O=new Date().toISOString();as(F=>Tf(F,v,{run_state:"completed",run_state_changed_at:O,last_event_at:O})),j.setQueryData(["plan",v],null)},onSuccess:(v,O)=>{oe(!1),j.invalidateQueries({queryKey:os}),j.invalidateQueries({queryKey:["timeline",O]}),j.invalidateQueries({queryKey:["change-sets",O]})},onError:(v,O)=>{oe(!1),X(!0),j.invalidateQueries({queryKey:os}),j.invalidateQueries({queryKey:["plan",O]}),Ie(v instanceof Error?v.message:"无法中断会话")}});_.useEffect(()=>{!p||!pe||B||Ba.isPending||X(pe.run_state==="running")},[Ba.isPending,B,pe,pe==null?void 0:pe.run_state,p]);const Xn=Vn({mutationFn:async v=>(await wn({sessionId:v.sessionId})).client.updateSession(v)}),jc=Vn({mutationFn:async v=>(await wn({projectId:v.projectId,agentId:v.agentId})).client.updateThread(v)}),Ys=Vn({mutationFn:async v=>(await tn()).client.executeSessionGitAction({sessionId:p,action:v.action,path:v.path,branch:v.branch,message:v.message}),onMutate:async()=>{Ws(null)},onSuccess:(v,O)=>{j.setQueryData(["session-git-workspace",p],v.workspace),(O.action==="commit-all"||O.action==="switch-branch")&&j.invalidateQueries({queryKey:["session-git-history",p]})},onError:v=>{Ws(v instanceof Error?v.message:"无法执行 git 操作")}}),wc=Vn({mutationFn:async v=>(await tn()).client.executeSessionTurnAction({sessionId:p,turnId:v.turnId,action:"rollback"}),onMutate:()=>{Rs(null)},onSuccess:v=>{Rs(null),Pa(O=>({...O,[v.turn_id]:!0})),j.setQueryData(["session-git-workspace",p],v.workspace)},onError:(v,O)=>{Rs({turnId:O.turnId,message:v instanceof Error?v.message:"无法回滚这轮改动"})}}),ci=Vn({mutationFn:async v=>(await tn()).client.saveSessionRunCommand({sessionId:p,action:v.action,commandId:v.commandId,command:v.command}),onMutate:()=>{dn(null)},onSuccess:async({catalog:v})=>{await po(O=>({...O,command_catalog:v}))},onError:v=>{dn(v instanceof Error?v.message:"无法保存项目命令。")}}),Gn=Vn({mutationFn:async v=>(await tn()).client.saveSessionRunWebsite({sessionId:p,action:v.action,websiteId:v.websiteId,website:v.website}),onMutate:()=>{dn(null)},onSuccess:async({catalog:v})=>{await po(O=>({...O,website_catalog:v}))},onError:v=>{dn(v instanceof Error?v.message:"无法保存项目网页。")}}),Di=Vn({mutationFn:async()=>(await tn()).client.generateSessionRunCommand({sessionId:p,prompt:"",model:qm()}),onMutate:()=>{dn(null),J(null)},onSuccess:async({generation:v,catalog:O})=>{await po(F=>({...F,command_catalog:O})),J(v.reason)},onError:v=>{dn(v instanceof Error?v.message:"无法一键生成项目命令。")}}),go=Vn({mutationFn:async()=>(await tn()).client.generateSessionRunWebsite({sessionId:p,prompt:"",model:qm()}),onMutate:()=>{dn(null),G(null)},onSuccess:async({generation:v,catalog:O})=>{await po(F=>({...F,website_catalog:O})),G(v.reason)},onError:v=>{dn(v instanceof Error?v.message:"无法一键生成项目网页。")}}),is=Vn({mutationFn:async v=>(await tn()).client.executeSessionTerminalAction({sessionId:p,action:v.action,commandId:v.commandId,terminalId:v.terminalId}),onMutate:()=>{dn(null)},onSuccess:async(v,O)=>{j.setQueryData(["session-run-workbench",p],F=>F&&{...F,terminal_snapshot:v.snapshot}),(O.action==="run-command"||O.action==="run-kill-command")&&v.terminal&&(Un(!1),Et("terminal"),await Mi(v.terminal.id,{force:!0})),O.action==="focus"&&O.terminalId&&await Mi(O.terminalId),O.action==="close"&&O.terminalId&&De(F=>{const be={...F};return delete be[O.terminalId],be})},onError:v=>{dn(v instanceof Error?v.message:"无法执行终端操作。")}}),_o=al.data??[],vd=pe&&Pg(ca.data)!=="tail"?UA(pe):!1,cl=_.useMemo(()=>zA(ll,{projectPath:ra==null?void 0:ra.path,compactCompletedTurns:vd}),[vd,ra==null?void 0:ra.path,ll]),bd=_.useMemo(()=>qA(cl.blocks,_o),[cl.blocks,_o]),dr=_.useMemo(()=>{const v=ca.data,O=Mm(v),F=Pg(v),be=Math.max(0,Math.min(n2,aa)),Ue=Math.max(0,Math.min(1,be/Og));return{hasEarlierEntries:O,canLoadEarlierEntries:O||F!=="full_compact",isPulling:sr,pullDistance:be,isReadyToLoad:be>=Og,isLoadingFull:Ds,indicatorOffset:Ds?z0:Math.min(z0,be*.75),indicatorRotation:Ds?s2:Math.round(Ue*s2),triggerSource:ar}},[Ds,sr,ar,aa,ca.data]),fr=[...bd].reverse().find(v=>v.kind==="turn"&&!v.turn.completion)??null;_.useEffect(()=>{var be;if(typeof window>"u")return;const v=window,O=(be=v.requestIdleCallback)==null?void 0:be.call(v,()=>{B0()},{timeout:1500}),F=O===void 0?window.setTimeout(()=>{B0()},320):null;return()=>{var Ue;O!==void 0&&((Ue=v.cancelIdleCallback)==null||Ue.call(v,O)),F!==null&&window.clearTimeout(F)}},[]);const Oi=!!(pe&&ra),xd=!!p&&k.isPending&&!pe;pe??(pe=BM),ra??(ra=UM);const Sd=!!p&&en.sessionId!==p,Ii=!!p&&!Oi&&(en.pending||Sd||xd),ul=Ii?"正在载入会话…":k.error instanceof Error?k.error.message:en.error?en.error:"没有找到这个会话。",yo=pe.capability.can_send_input&&!B,Nc=yo&&(a===void 0||a==="online"),Ha=(cr.data??[]).filter(v=>v.status==="pending"||v.status==="submitting"),jd=(pe.run_state==="running"||Fe)&&!B||Ba.isPending,vo=yo&&Ha.length===0&&!jd&&!za.isPending,kc=(Sn==null?void 0:Sn.id)??pe.agent_id,Sh=_.useCallback((v,O)=>{Ke(F=>{if(!O.trim()){if(!(v in F))return F;const be={...F};return delete be[v],be}return{...F,[v]:O}})},[]),jh=_.useCallback((v,O)=>{const F=O.trim();!F||!vo||za.mutate({sessionId:pe.id,input:F,attachments:[],model:bt,reasoningEffort:$t,serviceTier:xt?"fast":void 0,planMode:ot,yoloMode:on,clearComposer:!1,proposedPlanEntryId:v})},[vo,xt,ot,on,bt,$t,za,pe.id]),wh=_.useCallback(v=>{wc.mutate({turnId:v})},[wc]),wd=wc.isPending?((vi=wc.variables)==null?void 0:vi.turnId)??null:null,Nh=_.useMemo(()=>i.jsx(GA,{sessionId:pe.id,sessions:lr,sessionRunState:pe.run_state,isDesktopSidebar:l?!!o:q,projectPath:ra.path,renderedBlocks:bd,lastToolGroupId:cl.lastToolGroupId,sessionChangeSets:_o,isSubagentTimelinePending:xh,isInitialTimelinePending:!!p&&ll.length===0&&(en.pending||Sd),hasTimeline:ll.length>0,proposedPlanReplyDrafts:Ve,pendingProposedPlanReplyEntryId:Nt,canRespondToProposedPlan:vo,onProposedPlanReplyDraftChange:Sh,onSubmitProposedPlanReply:jh,onPreviewImage:je,changeSetDiffs:nr,changeSetDiffErrors:Gs,loadingChangeSetDiffKeys:ai,onLoadSessionChangeSets:vh,onLoadChangeSetFileDiff:bh,onLoadFullTimeline:()=>{xc()},timelineLoadState:dr,canRollbackChangeSets:la,pendingRollbackTurnId:wd,rollbackTurnError:Ja,rolledBackTurnIds:Na,onRollbackTurn:wh},pe.id),[la,vo,Gs,nr,Sh,jh,l,q,o,xh,vh,bh,xc,ai,wh,Nt,ra.path,Ve,bd,cl.lastToolGroupId,wd,Ja,Na,pe.id,pe.run_state,_o,lr,ll.length,dr]),ui=_.useCallback(async(v,O,F)=>{var be;Ie(null),Dt(!1),O==="pin"||O==="unpin"?Ya.flushSync(()=>{as(Ue=>bp(Ue,v,{pinned:O==="pin"}))}):O==="rename"&&(F!=null&&F.trim())&&as(Ue=>bp(Ue,v,{title:F.trim()}));try{const Ue=await Xn.mutateAsync({sessionId:v,action:O,name:F}),gt=(be=Ue.affectedSessionIds)!=null&&be.length?Ue.affectedSessionIds:[v];if(O==="delete"){as(Xe=>S3(Xe,gt)),V();for(const Xe of gt)j.removeQueries({queryKey:["timeline",Xe],exact:!0}),j.removeQueries({queryKey:Fo(Xe),exact:!0}),j.removeQueries({queryKey:["change-sets",Xe],exact:!0}),Ei(Xe)}else as(Xe=>x3(Xe,gt,{...O==="rename"&&(F!=null&&F.trim())?{title:F.trim()}:{pinned:O==="pin"}}));if(v===pe.id&&O==="delete"){const Xe=Ue.nextSessionId;Xe?await nl(Xe):await yc()}}catch(Ue){j.invalidateQueries({queryKey:os}),Ie(Ue instanceof Error?Ue.message:"无法更新会话")}},[yc,nl,j,V,Ei,pe.id,Xn]),Ta=_.useCallback(async(v,O,F)=>{var Ue,gt;Ie(null),Dt(!1);const be=(Ue=F==null?void 0:F.name)==null?void 0:Ue.trim();O==="pin"||O==="unpin"?Ya.flushSync(()=>{as(Xe=>Tu(Xe,v,{pinned:O==="pin"}))}):O==="rename"&&be?as(Xe=>Tu(Xe,v,{display_name:be})):O==="reorder"&&((gt=F==null?void 0:F.orderedProjectIds)!=null&>.length)?as(Xe=>xp(Xe,F.orderedProjectIds??[])):O==="remove"||O==="archive"?(as(Xe=>Sp(Xe,v)),V()):O==="unarchive"&&(V(),j.invalidateQueries({queryKey:os}));try{const Xe=await jc.mutateAsync({projectId:v,agentId:(Sn==null?void 0:Sn.id)??pe.agent_id,action:O,name:F==null?void 0:F.name,orderedProjectIds:F==null?void 0:F.orderedProjectIds});if(O==="remove"||O==="archive"||O==="unarchive"){const Kt=Xe.nextSessionId;Kt?await nl(Kt):await yc()}}catch(Xe){j.invalidateQueries({queryKey:os}),Ie(Xe instanceof Error?Xe.message:"无法更新线程")}},[yc,nl,j,V,jc]),Ec=_.useCallback(async v=>{kc&&(Ji(kc),Js(null),Kr(null),ku(v),await N({to:"/"}))},[kc,N]),ua=((Bc=Ri.data)==null?void 0:Bc.steps.some(v=>v.status==="pending"||v.status==="in_progress"))??!1,hr=pe.run_state==="running"||Fe,Nd=!!((Hc=Ri.data)!=null&&Hc.updated_at&&Date.now()-new Date(Ri.data.updated_at).getTime()<=MM),Cc=Ri.data&&(ua||hr&&Nd)?Ri.data:null,Hs=pe.context_usage,Tc=Hs?Math.round(Hs.percent_used):0,mr=Math.max(0,100-Tc),kh=Hs?{"--usage-progress":`${Math.max(0,Math.min(100,Hs.percent_used))}%`}:void 0,Rc=Je.state==="connected"&&$n.state==="idle"&&hr&&!B&&!Ba.isPending&&!(fr!=null&&fr.turn.completion),dl=!!jn||gd.length>0;_.useEffect(()=>{p&&(Zn.current+=1,gn({state:"idle"}))},[p]),_.useEffect(()=>{if(!ue)return;(cr.data??[]).some(O=>O.id===ue&&O.status==="submitting")||we(null)},[cr.data,ue]),_.useEffect(()=>{var v;!p||!Oi||pe.run_state==="running"||za.isPending||Ba.isPending||fr||(v=Ri.data)!=null&&v.is_active||(_n.current&&(window.clearTimeout(_n.current),_n.current=null),X(!1))},[fr,Oi,Ba.isPending,(bi=Ri.data)==null?void 0:bi.is_active,za.isPending,pe,pe==null?void 0:pe.run_state,p]);const Ra=q?0:WA(),Vs=q||xe,Mc=q?0:Re??(xe?Ra:0),di=Ze&&typeof document<"u"?Ya.createPortal(i.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[i.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{un(!1),_e(pe.title)},"aria-label":"关闭重命名会话面板"}),i.jsx("div",{className:"sheet-wrap__center",children:i.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered",children:[i.jsx("div",{className:"sheet-panel__title",children:"重命名会话"}),i.jsx("input",{className:"sheet-panel__input",value:ut,onChange:v=>_e(v.target.value),placeholder:"输入会话名称",autoFocus:!0}),i.jsxs("div",{className:"sheet-panel__actions",children:[i.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{un(!1),_e(pe.title)},children:"取消"}),i.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!ut.trim()||Xn.isPending&&((xi=Xn.variables)==null?void 0:xi.sessionId)===pe.id,onClick:()=>{ui(pe.id,"rename",ut.trim()),un(!1)},children:"保存"})]})]})})]}),document.body):null,Eh=!(l?o:q)&&Jt&&typeof document<"u"?Ya.createPortal(i.jsxs("div",{className:"picker-sheet-wrap",role:"dialog","aria-modal":"true",children:[i.jsx("button",{type:"button",className:"picker-sheet__scrim",onClick:()=>Dt(!1),"aria-label":"关闭会话操作菜单"}),i.jsxs("div",{className:"picker-sheet",children:[i.jsx("div",{className:"picker-sheet__header",children:i.jsx("strong",{children:pe.title})}),i.jsxs("div",{className:"picker-sheet__list",children:[i.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Xn.isPending&&((yl=Xn.variables)==null?void 0:yl.sessionId)===pe.id,onClick:()=>void ui(pe.id,pe.pinned?"unpin":"pin"),children:i.jsx("span",{children:pe.pinned?"取消置顶会话":"置顶会话"})}),i.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Xn.isPending&&(($c=Xn.variables)==null?void 0:$c.sessionId)===pe.id,onClick:()=>{Dt(!1),un(!0)},children:i.jsx("span",{children:"重命名会话"})}),i.jsx("button",{type:"button",className:"picker-sheet__item is-danger",disabled:Xn.isPending&&((Fc=Xn.variables)==null?void 0:Fc.sessionId)===pe.id,onClick:()=>void ui(pe.id,"delete"),children:i.jsx("span",{children:"删除会话"})})]})]})]}),document.body):null,Ac=q?1:Ra>0?Mc/Ra:0,Li=!q&&Re!==null,kd=q?{"--desktop-sidebar-width":`${he}px`}:void 0,ws=l?!!o:q,bo=l?u:Mc,Dc=l?f:Li,da=Ys.isPending?Ys.variables??null:null,fl=na??(il.error instanceof Error?il.error.message:null),hl=Ua.error instanceof Error?Ua.error.message:null,pr=ms??(rl.error instanceof Error?rl.error.message:null),Ns=rl.data??null,Yn=(Ns==null?void 0:Ns.terminal_snapshot)??null,cs=(Ns==null?void 0:Ns.command_catalog.commands)??[],fi=(Ns==null?void 0:Ns.website_catalog.websites)??[],fa=wp(qm(),ht),ha=(Yn==null?void 0:Yn.terminals.find(v=>v.id===Yn.active_terminal_id))??(Yn==null?void 0:Yn.terminals[0])??null,ma=oa&&Le==="terminal",Oc=la&&Le==="git",hi=ws&&ma&&Cn,Ed=Oc&&ws,ml=(ma||Oc)&&ws&&!hi,gs=(ma||Oc)&&!ws,On=is.isPending&&((vl=is.variables)==null?void 0:vl.action)==="run-command"?is.variables.commandId??null:null,Wt=is.isPending&&((bl=is.variables)==null?void 0:bl.action)==="run-kill-command"?is.variables.commandId??null:null,mi=ci.isPending&&(($d=ci.variables)==null?void 0:$d.action)==="delete"?ci.variables.commandId??null:null,Zs=Gn.isPending&&((Fd=Gn.variables)==null?void 0:Fd.action)==="delete"?Gn.variables.websiteId??null:null;_.useEffect(()=>{!ws&&Cn&&hs(!1)},[Cn,ws]);const $a=v=>{tl.current=v,He(v)},pi=(v,O,F)=>(js.current={mode:xe?"close":"open",startX:v,startY:O,axis:"pending",pointerId:F},!0),Cd=(v,O)=>{const F=js.current;if(!F)return!1;const be=v-F.startX,Ue=O-F.startY;if(F.axis==="pending"){if(Math.abs(be)<8&&Math.abs(Ue)<8)return!1;if(F.axis=Math.abs(be)>Math.abs(Ue)?"x":"y",F.axis==="y")return js.current=null,$a(null),!1}const gt=F.mode==="open"?Math.max(0,Math.min(Ra,be)):Math.max(0,Math.min(Ra,Ra+be));return $a(gt),!0},Td=(v,O)=>{const F=js.current;if(!F)return;const be=v-F.startX,Ue=O-F.startY;if(F.axis==="pending"&&Math.abs(Ue)>48){js.current=null,$a(null);return}const Xe=(F.axis==="x"?tl.current??(F.mode==="open"?Math.max(0,Math.min(Ra,be)):Math.max(0,Math.min(Ra,Ra+be))):xe?Ra:0)>=Ra*CM;C(Xe),js.current=null,$a(null)},gr=_.useCallback(()=>{if(l){m==null||m();return}C(!0)},[l,m]),_r=_.useCallback(()=>{Ss(v=>!v)},[]),Rd=_.useCallback(()=>{Ie(null)},[]),xo=_.useCallback(()=>{Ft(v=>!v)},[]),Md=_.useCallback(v=>{nl(v)},[nl]),Pi=_.useCallback(v=>{const O=new Date().toISOString();if(ht.length===0){qe({panel_id:`${Ig}${Date.now()}`,session_id:pe.id,command_name:"model",command_text:v,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"completed",body:"当前没有可选模型,请先去设置页维护模型列表。",submitted_at:O,updated_at:O,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}qe({panel_id:`${Ig}${Date.now()}`,session_id:pe.id,command_name:"model",command_text:v,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"awaiting_input",body:"在下面选择一个模型。",submitted_at:O,updated_at:O,input_type:"choice",options:ht.map(F=>({id:F.value,label:F.label,description:F.description??null})),input_placeholder:null,submit_label:null,effect:null})},[ht,pe.id]),gi=_.useCallback(()=>{if(Nc){if(z_(ke)){if(ve.length>0){Ie("命令暂不支持附件,请先移除附件后再执行。");return}if(oA(ke)==="model"){Ie(null),U(""),Pi(ke);return}ol.mutate({sessionId:pe.id,input:ke});return}za.mutate({sessionId:pe.id,input:ke.trim(),attachments:ve,model:bt,reasoningEffort:$t,serviceTier:xt?"fast":void 0,planMode:ot,yoloMode:on})}},[Nc,ke,xt,ot,on,ol,Pi,ve,bt,$t,za,pe.id]),Ui=_.useCallback(()=>{qe(null)},[]),_i=_.useCallback(v=>{if(wt){if(wt.panel_id.startsWith(Ig)){Ut(v),qe(O=>O&&{...O,status:"completed",body:`后续消息将优先使用 ${wp(v,ht)}。`,updated_at:new Date().toISOString(),input_type:"none",options:[]});return}ur.mutate({sessionId:pe.id,panelId:wt.panel_id,optionId:v})}},[wt,ur,ht,pe.id]),Ad=_.useCallback(v=>{wt&&ur.mutate({sessionId:pe.id,panelId:wt.panel_id,text:v})},[wt,ur,pe.id]),Dd=_.useCallback(v=>{yd.mutate({sessionId:pe.id,requestId:v.requestId,optionId:v.optionId??null,text:v.text??null,answers:v.answers})},[yd,pe.id]),pl=_.useCallback(v=>{const O=[...v];O.length!==0&&(Ie(null),Promise.all(O.map(F=>gx(F))).then(F=>{Z(be=>[...be,...F])}).catch(F=>{Ie(F instanceof Error?F.message:"无法读取附件")}))},[]),Ic=_.useCallback(v=>{Z(O=>O.filter(F=>F.id!==v))},[]),yr=_.useCallback(()=>{Ba.isPending||B||Ba.mutate(pe.id)},[Ba,B,pe.id]),_s=_.useCallback(()=>{rt(v=>!v)},[]),yi=_.useCallback(v=>{v==="git"&&!la||v==="terminal"&&!oa||(Ws(null),dn(null),Un(!1),Ps(!1),hs(!1),Et(v))},[la,oa]);_.useEffect(()=>{if(!ml)return;const v=O=>{var be,Ue;const F=O.target;F instanceof Node&&((be=ge.current)!=null&&be.contains(F)||(Ue=te.current)!=null&&Ue.contains(F)||yi("code"))};return window.addEventListener("pointerdown",v),()=>{window.removeEventListener("pointerdown",v)}},[yi,ml]);const Ch=_.useCallback(()=>{Ws(null),il.refetch()},[il]),zp=_.useCallback(()=>{Ua.refetch()},[Ua]),Bp=_.useCallback(()=>{Ua.data||Ua.isFetching||Ua.refetch()},[Ua]),Hp=_.useCallback(v=>{Ys.mutate({action:"discard-file",path:v})},[Ys]),Jn=_.useCallback(()=>{Ys.mutate({action:"discard-all"})},[Ys]),Od=_.useCallback(v=>{Ys.mutate({action:"commit-all",message:v})},[Ys]),So=_.useCallback(async(v,O)=>{Ws(null);const F=(O==null?void 0:O.trim())??"";F&&await Ys.mutateAsync({action:"commit-all",message:F}),await Ys.mutateAsync({action:"switch-branch",branch:v})},[Ys]),jo=_.useCallback(()=>{Ys.mutate({action:"push"})},[Ys]),Id=_.useCallback(async(v,O,F)=>(await tn()).client.getSessionGitHistoryFileDiff(pe.id,{commitOid:v,path:O,previousPath:F}),[tn,pe.id]),gl=_.useCallback(async(v,O)=>(await tn()).client.getSessionGitWorkspaceFileDiff(pe.id,{path:v,previousPath:O}),[tn,pe.id]),vr=_.useCallback(v=>{is.mutate({action:"run-command",commandId:v})},[is]),Th=_.useCallback(async()=>{if(!(cs.length===0||Us||xs)){Ms(!0);try{for(const v of cs)await is.mutateAsync({action:"run-command",commandId:v.id})}finally{Ms(!1)}}},[Us,xs,cs,is]),Ld=_.useCallback(async()=>{if(Us||xs)return;const v=cs.filter(O=>!!O.kill_command);if(v.length!==0){As(!0);try{for(const O of v)await is.mutateAsync({action:"run-kill-command",commandId:O.id})}finally{As(!1)}}},[Us,xs,cs,is]),$p=_.useCallback(v=>{is.mutate({action:"run-kill-command",commandId:v})},[is]),Pd=_.useCallback(v=>{ci.mutate({action:v.commandId?"update":"create",commandId:v.commandId,command:v.draft})},[ci]),zi=_.useCallback(v=>{ci.mutate({action:"delete",commandId:v})},[ci]),Lc=_.useCallback(()=>{Di.mutate()},[Di]),wo=_.useCallback(v=>{Gn.mutate({action:v.websiteId?"update":"create",websiteId:v.websiteId,website:v.draft})},[Gn]),Ud=_.useCallback(v=>{Gn.mutate({action:"delete",websiteId:v})},[Gn]),br=_.useCallback(()=>{go.mutate()},[go]),Pc=_.useCallback(()=>{Ps(!1)},[]),Uc=_.useCallback(v=>{is.mutate({action:"focus",terminalId:v}),Et("terminal")},[is]),zc=_.useCallback(v=>{is.mutate({action:"close",terminalId:v})},[is]),Rh=_.useCallback(()=>{!ws||!oa||(Et("terminal"),hs(v=>!v))},[oa,ws]),zd=_.useMemo(()=>{var v,O,F;return i.jsxs("div",{className:"conversation-topbar__title-actions",children:[i.jsx("button",{type:"button",className:"conversation-topbar__more",onClick:()=>Dt(be=>!be),"aria-label":"更多会话选项",children:i.jsx(FM,{})}),Jt&&ws?i.jsxs("div",{className:"topbar-menu",role:"menu",children:[i.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Xn.isPending&&((v=Xn.variables)==null?void 0:v.sessionId)===pe.id,onClick:()=>void ui(pe.id,pe.pinned?"unpin":"pin"),children:pe.pinned?"取消置顶会话":"置顶会话"}),i.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Xn.isPending&&((O=Xn.variables)==null?void 0:O.sessionId)===pe.id,onClick:()=>{Dt(!1),un(!0)},children:"重命名会话"}),i.jsx("button",{type:"button",className:"topbar-menu__item is-danger",disabled:Xn.isPending&&((F=Xn.variables)==null?void 0:F.sessionId)===pe.id,onClick:()=>void ui(pe.id,"delete"),children:"删除会话"})]}):null]})},[ui,Jt,ws,pe.id,pe.pinned,Xn.isPending,(jr=Xn.variables)==null?void 0:jr.sessionId]),Bi=_.useMemo(()=>oa||la?i.jsxs("div",{className:"conversation-topbar__actions",children:[oa?i.jsxs("div",{className:"conversation-topbar__run-group",children:[i.jsx("button",{type:"button",className:`conversation-topbar__run-button ${pn?"is-active":""}`,onClick:()=>{Ps(!1),Un(v=>!v)},"aria-expanded":pn,"aria-haspopup":"dialog","aria-label":"打开项目命令列表",children:i.jsx(GM,{})}),pn?i.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目命令列表",children:i.jsx(uM,{commands:cs,nodeRuntime:(Ns==null?void 0:Ns.node_runtime)??null,error:pr,pendingRunCommandId:On,pendingKillCommandId:Wt,pendingDeleteCommandId:mi,isSaving:ci.isPending,isGenerating:Di.isPending,isStartingAll:Us,isStoppingAll:xs,generationReason:Rt,executionModelLabel:fa,onRun:vr,onRunAll:Th,onRunAllKill:Ld,onRunKill:$p,onSave:Pd,onDelete:zi,onGenerate:Lc})}):null]}):null,oa?i.jsxs("div",{className:"conversation-topbar__run-group",children:[i.jsx("button",{type:"button",className:`conversation-topbar__run-button ${ps?"is-active":""}`,onClick:()=>{Un(!1),Ps(v=>!v)},"aria-expanded":ps,"aria-haspopup":"dialog","aria-label":"打开项目网页列表",children:i.jsx(YM,{})}),ps?i.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目网页列表",children:i.jsx(gM,{websites:fi,error:pr,pendingDeleteWebsiteId:Zs,isSaving:Gn.isPending,isGenerating:go.isPending,generationReason:M,executionModelLabel:fa,onOpen:Pc,onSave:wo,onDelete:Ud,onGenerate:br})}):null]}):null,oa||la?i.jsxs("div",{ref:te,className:"conversation-topbar__view-toggle","aria-label":"切换工作台面板",children:[i.jsx("button",{type:"button",className:`conversation-topbar__view-button ${Le==="code"?"is-active":""}`,onClick:()=>yi("code"),"aria-pressed":Le==="code","aria-label":"切换到代码会话视图",children:i.jsx(WM,{})}),oa?i.jsx("button",{type:"button",className:`conversation-topbar__view-button ${Le==="terminal"?"is-active":""}`,onClick:()=>yi("terminal"),"aria-pressed":Le==="terminal","aria-label":"切换到终端视图",children:i.jsx(QM,{})}):null,la?i.jsx("button",{type:"button",className:`conversation-topbar__view-button ${Le==="git"?"is-active":""}`,onClick:()=>yi("git"),"aria-pressed":Le==="git","aria-label":"切换到 git 视图",children:i.jsx(KM,{})}):null]}):null]}):null,[Le,la,oa,Rt,M,Us,xs,fa,Di.isPending,go.isPending,zi,Lc,Ud,br,Pc,vr,Th,Ld,Pd,wo,yi,pn,ps,mi,Zs,On,cs,fi,pr,ci.isPending,Gn.isPending]),xr=i.jsx(iM,{workspace:il.data??null,history:Ua.data??null,isLoading:il.isPending,isHistoryLoading:Ua.isFetching,error:fl,historyError:hl,onRefresh:Ch,onRefreshHistory:zp,onRequestHistory:Bp,onDiscardFile:Hp,onDiscardAll:Jn,onCommitAll:Od,onSwitchBranch:So,onPush:jo,onLoadWorkspaceFileDiff:gl,onLoadHistoryFileDiff:Id,pendingAction:da,compact:Ed}),Mh=i.jsx(NM,{terminals:(Yn==null?void 0:Yn.terminals)??[],activeTerminalId:(ha==null?void 0:ha.id)??null,outputs:Ee,error:pr,compact:ml||hi,canToggleFullscreen:ws,isFullscreen:hi,onSelectTerminal:Uc,onCloseTerminal:zc,onToggleFullscreen:Rh}),Ah=i.jsx(xx,{isDesktopSidebar:ws,sidebarShift:bo,isSidebarDragging:Dc,composerError:Oe,onDismissComposerError:Rd,interactionRequests:Ha,pendingInteractionRequestId:ue,onRespondInteraction:Dd,parentSession:jn,backgroundAgentSessions:gd,isBackgroundAgentsOpen:It,planSnapshot:Cc,onToggleBackgroundAgents:xo,onOpenSession:Md,getBackgroundAgentStatusLabel:jA,getBackgroundAgentAccent:bA,formatBackgroundAgentsLabel:pA,hasBackgroundAgentStrip:dl,commandPanel:wt,isCommandPanelPending:ol.isPending||ur.isPending,onDismissCommandPanel:Ui,onCommandPanelOptionSelect:_i,onCommandPanelTextSubmit:Ad,projectId:pe.project_id,agentId:(Sn==null?void 0:Sn.id)??pe.agent_id,draft:ke,pendingAttachments:ve,canSendInput:yo,canSubmitInput:Nc,isInputLocked:Ha.length>0,readOnlyPlaceholder:Ha.length>0?"请先处理上方确认请求":void 0,onDraftChange:U,onUploadFiles:pl,onRemoveAttachment:Ic,onSubmit:gi,showStopIcon:jd,isSendPending:za.isPending||ol.isPending||ur.isPending,onInterrupt:yr,isFastModeEnabled:xt,isPlanModeEnabled:ot,isYoloModeEnabled:on,onToggleFastMode:()=>it(v=>!v),onTogglePlanMode:()=>ln(v=>!v),onToggleYoloMode:()=>kn(v=>!v),showModeBadges:!0,selectedModel:bt,modelOptions:ht,selectedReasoning:$t,onSelectModel:Ut,onSelectReasoning:v=>zt(v),contextUsage:Hs,isContextUsageOpen:ze,onToggleContextUsage:_s,contextUsageRingStyle:kh,usedPercent:Tc,remainingPercent:mr,usedTokensLabel:o2((Hs==null?void 0:Hs.used_tokens)??0),totalTokensLabel:o2((Hs==null?void 0:Hs.total_tokens)??0),showJumpToBottom:Pe,onJumpToBottom:vc}),Sr=ma?Mh:xr,_l=gs||hi,No=_l?i.jsxs("div",{ref:ee,className:`conversation-main ${ws?"has-desktop-sidebar":""} ${hi?"is-terminal-fullscreen":""}`,style:{transform:`translateX(${bo}px)`,transition:Dc?"none":void 0},children:[i.jsxs("div",{className:"conversation-topbar",children:[ws?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:gr,"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]}),i.jsx("div",{className:"conversation-topbar__meta",children:i.jsxs("div",{className:"conversation-topbar__title-row",children:[i.jsx("h1",{children:pe.title}),zd]})}),Bi]}),i.jsx("div",{ref:me,className:`conversation-scroll ${_l?"conversation-scroll--workbench":""}`,children:i.jsx("div",{className:`session-workbench-surface ${hi?"is-terminal-fullscreen":""}`,children:Sr})})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`session-detail-workspace ${ml?"has-workbench-panel":""}`,children:[i.jsx(kM,{conversationMainRef:ee,conversationScrollRef:me,isDesktopSidebar:ws,sidebarShift:bo,isSidebarDragging:Dc,title:pe.title,titleActions:zd,topbarActions:Bi,onOpenSidebar:gr,threadContent:Nh,connectionStatus:Je,sessionRecoveryStatus:$n,isConnectionDetailOpen:zn,onToggleConnectionDetail:_r,showThinkingStatus:Rc}),ml?i.jsx("aside",{ref:ge,className:"session-workbench-rail",children:Sr}):null]}),hi?null:Ah]}),Hi=i.jsxs(i.Fragment,{children:[di,Eh,Se&&typeof document<"u"?Ya.createPortal(i.jsxs("div",{className:"attachment-lightbox",role:"dialog","aria-modal":"true","aria-label":`预览 ${Se.label}`,children:[i.jsx("button",{type:"button",className:"attachment-lightbox__scrim",onClick:()=>je(null),"aria-label":"关闭图片预览"}),i.jsxs("div",{className:"attachment-lightbox__panel",children:[i.jsx("button",{type:"button",className:"attachment-lightbox__close",onClick:()=>je(null),"aria-label":"关闭图片预览",children:i.jsx(qM,{})}),i.jsx("div",{className:"attachment-lightbox__frame",children:i.jsx("img",{src:Se.src,alt:Se.label,className:"attachment-lightbox__image"})}),i.jsxs("div",{className:"attachment-lightbox__meta",children:[i.jsx("div",{className:"attachment-lightbox__title",children:Se.label}),i.jsx("div",{className:"attachment-lightbox__hint",children:Se.meta})]})]})]}),document.body):null]});if(!Oi){const v=i.jsx("div",{className:"conversation-main conversation-main--empty",children:Ii?i.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[i.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"})]}),i.jsx("span",{className:"sr-only",children:"正在加载会话"})]}):i.jsx("div",{className:"empty-panel",children:ul})});return l?i.jsxs(i.Fragment,{children:[v,Hi]}):i.jsxs("div",{className:"conversation-page",children:[v,Hi]})}return l?i.jsxs(i.Fragment,{children:[No,Hi]}):i.jsxs("div",{ref:Y,className:`conversation-page ${q?"has-desktop-sidebar":""}`,style:kd,onPointerDown:v=>{q||v.pointerType!=="touch"&&(v.pointerType==="mouse"&&v.button!==0||dd(v.target)||(pi(v.clientX,v.clientY,v.pointerId),v.currentTarget.setPointerCapture(v.pointerId)))},onPointerMove:v=>{if(q||v.pointerType==="touch")return;const O=js.current;!O||O.pointerId!==v.pointerId||!Cd(v.clientX,v.clientY)||v.preventDefault()},onPointerUp:v=>{if(q||v.pointerType==="touch")return;const O=js.current;!O||O.pointerId!==v.pointerId||Td(v.clientX,v.clientY)},onPointerCancel:v=>{if(q||v.pointerType==="touch")return;const O=js.current;!O||O.pointerId!==v.pointerId||(js.current=null,$a(null))},children:[i.jsx(fx,{open:Vs,progress:Ac,isDragging:Li,desktopPinned:q,isDesktopResizing:L,onClose:()=>{q||(C(!1),$a(null))},onDesktopResizeStart:v=>{Ci.current=li.current,fo.current={startX:v,startWidth:li.current},ae(!0)},currentAgent:Sn??void 0,agentIndicatorState:Sn?a??(Sn.status==="online"?"online":"offline"):void 0,projects:Pp,sessions:lr,projectStats:_h,historySessionsByProject:Object.fromEntries(Object.entries(P).map(([v,O])=>[v,O.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(Q).map(([v,O])=>[v,O.sessions])),historyPageStateByProject:P,archivedPageStateByProject:Q,activeSessionId:pe.id,onCreateSession:v=>{Ec(v)},onSessionAction:ui,onThreadAction:Ta,onLoadMoreHistory:v=>{se(v)},onLoadMoreArchived:v=>{W(v)},pendingSessionActionId:Xn.isPending?((Eo=Xn.variables)==null?void 0:Eo.sessionId)??null:null,pendingThreadActionId:jc.isPending?((qd=jc.variables)==null?void 0:qd.projectId)??null:null}),No,Hi]})},VA=({mode:e,agentName:t,agentStatus:a,onOpenNodes:l,onCreateThread:o})=>{if(e==="node")return i.jsxs("section",{className:"session-empty-state is-node-mode",children:[i.jsx("div",{className:"session-empty-state__eyebrow",children:"Panda Workspace"}),i.jsx("div",{className:"session-empty-state__actions",children:i.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:l,children:"选择节点"})})]});const u=a==="online";return i.jsxs("section",{className:"session-empty-state is-session-mode",children:[i.jsxs("div",{className:"session-empty-state__status-row",children:[i.jsx("span",{className:`session-empty-state__status-dot is-${u?"online":"offline"}`,"aria-hidden":"true"}),i.jsxs("div",{className:"session-empty-state__eyebrow",children:["节点 · ",t??"当前节点"]})]}),i.jsxs("div",{className:"session-empty-state__actions",children:[o?i.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:o,children:"新建会话"}):null,i.jsx("button",{type:"button",className:"session-empty-state__button",onClick:l,children:"切换节点"})]})]})},h2=1100,Bx="panda:desktop-sidebar-width",Df="panda:desktop-sidebar-width-version",Of="2026-03-24-narrow",ZA=300,Hx=232,yu=Hx,XA=460,zg=.4,JA=56,eD=56,tD=160,m2=5,nD=_.lazy(async()=>({default:(await Zr(()=>import("./session-file-preview-page-tFsJlNPN.js").then(t=>t.s),__vite__mapDeps([2,1]))).SessionFilePreviewPage})),p2=e=>{const t=new Date((e==null?void 0:e.generated_at)??"").getTime();return Number.isFinite(t)?t:0},sD=(e,t)=>{var l;if(!t)return;let a;for(const[,o]of e)!o||!(((l=o.agent)==null?void 0:l.id)===t||o.projects.some(f=>f.agent_id===t)||o.sessions.some(f=>f.agent_id===t))||(!a||p2(o)>p2(a))&&(a=o);return a},aD=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),iD=()=>typeof window>"u"?0:Math.max(window.innerWidth,0),F0=e=>Math.max(Hx,Math.min(XA,e)),rD=()=>{if(typeof window>"u")return yu;try{const e=window.localStorage.getItem(Bx),t=window.localStorage.getItem(Df);if(!e)return window.localStorage.setItem(Df,Of),yu;const a=Number(e);if(!Number.isFinite(a))return window.localStorage.setItem(Df,Of),yu;const o=t!==Of||a===ZA||a>yu?yu:a;return window.localStorage.setItem(Df,Of),F0(o)}catch{return yu}},$x=()=>{var As,Rt;const e=ja(J=>J.openSettingsOverlay),{agentId:t}=ad({strict:!1}),a=ki(),l=La(),o=_.useRef(null),[u,f]=_.useState(()=>pc()),[m,y]=_.useState(()=>pk()??mp()),[g,S]=_.useState(()=>gk()),[p,b]=_.useState(()=>_k()?"directory-picker":"composer"),[w,N]=_.useState(!1),[j,T]=_.useState(!1),[D,z]=_.useState(()=>typeof window<"u"&&window.innerWidth>=h2),[I,k]=_.useState(()=>rD()),[P,Q]=_.useState(!1),[se,W]=_.useState({state:"connected",attempt:0,maxAttempts:m2}),[V,Y]=_.useState(null),[ee,me]=_.useState(null),ge=_.useRef(null),te=_.useRef(null),xe=_.useRef(null),C=_.useRef(null),q=_.useRef(null),ie=_.useRef(I),he=_.useRef(null),re=_.useRef(null),L=_.useRef(null),ae=_.useRef(0),ke=_.useRef(null),U=_.useRef(!1),ve=_.useRef(!1),Z=_.useRef(!1),Se=_.useRef(null),je=_.useRef(null),Oe=t??u??null,Ie=Oe?{agentId:Oe}:void 0,qe=l.getQueryData(R0({scope:Ie}))??sD(l.getQueriesData({queryKey:os}),Oe),bt=m&&!(qe!=null&&qe.sessions.some(J=>J.id===m))?m:null,Ut=_.useRef({agentId:Oe,selectedSessionIdHint:bt});ch(Oe);const $t=I_({enabled:!1}),zt=$t.data,xt=ox({scope:Ie,selectedSessionId:bt,enabled:!!Oe}),it=xt.data??qe,{historyState:ot,archivedState:ln,loadMoreHistory:on,loadMoreArchived:kn,reset:En}=ux({scope:Ie,selectedSessionId:m??null}),ht=[...Object.values(ot).flatMap(J=>J.sessions),...Object.values(ln).flatMap(J=>J.sessions)];_.useEffect(()=>{t&&(f(t),Ji(t),y(null))},[t]),_.useEffect(()=>{it&&(f(J=>{var M;return J&&(((M=it.agent)==null?void 0:M.id)===J||zt!=null&&zt.agents.some(G=>G.id===J))?J:null}),y(J=>J&&(it.sessions.some(M=>M.id===J)||ht.some(M=>M.id===J)||xt.isPending||xt.isFetching||xt.isError)?J:null))},[zt==null?void 0:zt.agents,ht,it,xt.isError,xt.isFetching,xt.isPending]),_.useEffect(()=>{t||u||(z6(),a({to:"/nodes",replace:!0}))},[a,t,u]),_.useEffect(()=>{if(!it||t||!u||m)return;const J=mp(),M=it.sessions.find(G=>G.id===J)??null;M&&(y(M.id),Js(M.id))},[t,u,m,it]);const Ve=(Oe?(zt==null?void 0:zt.agents.find(J=>J.id===Oe))??null:null)??null,Ke=_.useMemo(()=>{const J=(it==null?void 0:it.agent)??(Ve?{id:Ve.id,name:Ve.name,display_name:Ve.display_name,status:Ve.status}:null);if(!J)return null;const M=(Ve==null?void 0:Ve.status)??J.status,G=(Ve==null?void 0:Ve.name)??J.name,Ee=(Ve==null?void 0:Ve.display_name)??J.display_name;return J.status===M&&J.name===G&&J.display_name===Ee?J:{...J,name:G,display_name:Ee,status:M}},[Ve,it==null?void 0:it.agent]),Nt=Ke?xT(Ke.status,se.state):void 0,Bt=(it==null?void 0:it.projects)??[],Jt=(it==null?void 0:it.sessions)??[],Dt=(it==null?void 0:it.project_stats)??[],Ze=m?Jt.find(J=>J.id===m)??null:null,un=Ze?Bt.find(J=>J.id===Ze.project_id)??null:null,ut=!!(Ze&&un);_.useEffect(()=>{T(!1),me(null),te.current=null},[Ze==null?void 0:Ze.id,un==null?void 0:un.id]);const _e=!!Oe&&!Ke&&($t.isPending||$t.isFetching||xt.isPending||xt.isFetching),Fe=!!m&&!Jt.some(J=>J.id===m)&&(xt.isPending||xt.isFetching),X=_e||Fe,B=(Ze==null?void 0:Ze.id)??(X?m??null:null);Ut.current={agentId:(Ke==null?void 0:Ke.id)??Oe,selectedSessionIdHint:bt},_.useEffect(()=>{const J=(Ve==null?void 0:Ve.status)??null,M=Se.current;Se.current=J;const G=(Oe==null?void 0:Oe.trim())??"";if(!G||J!=="online"){J!=="online"&&(je.current=null);return}if(!(M!=="online"||!it))return;const De=`${G}:${M!=="online"?"online":"missing"}:${bt??""}`;je.current!==De&&(je.current=De,Rf(l,{scope:{agentId:G},selectedSessionId:bt}))},[Oe,Ve==null?void 0:Ve.status,l,it,bt]),_.useEffect(()=>{var De;if(!Ut.current.agentId){ke.current!==null&&(clearTimeout(ke.current),ke.current=null),(De=L.current)==null||De.stream.close(),L.current=null,U.current=!1,ve.current=!1,Z.current=!1;return}let J=!1;const M=++ae.current,G=()=>{ke.current!==null&&(clearTimeout(ke.current),ke.current=null)},Ee=Pe=>{const $e=(Pe==null?void 0:Pe.includeHubDirectory)??!1;G(),ke.current=setTimeout(()=>{ke.current=null;const Je=Ut.current,Ye=[Rf(l,{scope:Je.agentId?{agentId:Je.agentId}:void 0,selectedSessionId:Je.selectedSessionIdHint})];$e&&Ye.unshift(k3(l)),Promise.allSettled(Ye)},tD)};return wn({agentId:Ut.current.agentId}).then(Pe=>{var Ye,en;if(J||ae.current!==M)return;const $e=Pe.client.getConnectionKey();if(((Ye=L.current)==null?void 0:Ye.key)===$e)return;(en=L.current)==null||en.stream.close(),U.current=!1,ve.current=!1,Z.current=!1;const Je=Pe.client.createEventStream(jt=>{var bn,Tn,xn,zn,Ss,_n;const $n=typeof((bn=jt.payload)==null?void 0:bn.sessionId)=="string"?jt.payload.sessionId:null,gn=typeof((Tn=jt.payload)==null?void 0:Tn.projectId)=="string"?jt.payload.projectId:null;if(jt.type==="agent.online"){if(Z.current){Z.current=!1;return}En(),Ee({includeHubDirectory:!0});return}if(jt.type==="thread.updated"&&gn){const qt=typeof((xn=jt.payload)==null?void 0:xn.action)=="string"?jt.payload.action:"",yn=(zn=jt.payload)!=null&&zn.projectPatch&&typeof jt.payload.projectPatch=="object"?jt.payload.projectPatch:null,Zn=Array.isArray((Ss=jt.payload)==null?void 0:Ss.orderedProjectIds)?jt.payload.orderedProjectIds.filter(A=>typeof A=="string"&&A.trim().length>0):[];if((qt==="pin"||qt==="unpin"||qt==="rename")&&yn){l.setQueriesData({queryKey:os},A=>Tu(A,gn,yn));return}if(qt==="reorder"&&Zn.length>0){l.setQueriesData({queryKey:os},A=>xp(A,Zn));return}if(qt==="remove"||qt==="archive"){En(),l.setQueriesData({queryKey:os},A=>Sp(A,gn));return}if(qt==="unarchive"){En();const A=Ut.current;Rf(l,{scope:A.agentId?{agentId:A.agentId}:void 0,selectedSessionId:A.selectedSessionIdHint});return}}if(jt.type==="session.updated"&&$n){const qt=(_n=jt.payload)!=null&&_n.sessionPatch&&typeof jt.payload.sessionPatch=="object"?C0(jt.payload.sessionPatch):null,yn=Ut.current,Zn=l.getQueryData(R0({scope:yn.agentId?{agentId:yn.agentId}:void 0,selectedSessionId:yn.selectedSessionIdHint})),A=vp(Zn,$n);if(qt&&A){l.setQueriesData({queryKey:os},le=>Tf(le,$n,qt));return}if(A)return;Rf(l,{scope:yn.agentId?{agentId:yn.agentId}:void 0,selectedSessionId:yn.selectedSessionIdHint})}},{onStatus:jt=>{if(W(jt),jt.state==="connected"){Z.current=!0,U.current&&ve.current&&(ve.current=!1,En(),Ee({includeHubDirectory:Pe.mode==="hub"})),U.current=!0;return}U.current&&(ve.current=!0)}});L.current={key:$e,stream:Je}}).catch(Pe=>{J||ae.current!==M||W({state:"failed",attempt:0,maxAttempts:m2,error:Pe instanceof Error?Pe.message:"无法建立节点工作区连接"})}),()=>{J=!0}},[Ke==null?void 0:Ke.id,Ke==null?void 0:Ke.status,Oe,l,En]),_.useEffect(()=>()=>{var J;ae.current+=1,ke.current!==null&&(clearTimeout(ke.current),ke.current=null),(J=L.current)==null||J.stream.close(),L.current=null},[]),_.useEffect(()=>{ie.current=I},[I]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Bx,String(F0(I))),window.localStorage.setItem(Df,Of)}catch{}},[I]),_.useEffect(()=>{if(typeof window>"u")return;const J=()=>{const M=window.innerWidth>=h2;z(M),M&&(N(!1),Y(null))};return J(),window.addEventListener("resize",J),()=>{window.removeEventListener("resize",J)}},[]),_.useEffect(()=>{if(!P)return;const J=G=>{const Ee=q.current;if(!Ee)return;const De=G.clientX-Ee.startX,Pe=F0(Ee.startWidth+De);he.current=Pe,re.current===null&&(re.current=window.requestAnimationFrame(()=>{re.current=null;const $e=he.current;$e!==null&&k($e)}))},M=()=>{re.current!==null&&(window.cancelAnimationFrame(re.current),re.current=null);const G=he.current??ie.current;he.current=null,q.current=null,Q(!1),ie.current=G,k(G)};return window.addEventListener("pointermove",J),window.addEventListener("pointerup",M),()=>{window.removeEventListener("pointermove",J),window.removeEventListener("pointerup",M)}},[P]),_.useEffect(()=>()=>{re.current!==null&&window.cancelAnimationFrame(re.current)},[]);const oe=Vn({mutationFn:async J=>(await wn({sessionId:J.sessionId})).client.updateSession(J)}),ue=Vn({mutationFn:async J=>(await wn({projectId:J.projectId,agentId:J.agentId})).client.updateThread(J)}),we=J=>{l.setQueriesData({queryKey:os},J)},Re=J=>Jt.find(M=>M.id===J)??ht.find(M=>M.id===J)??((Ze==null?void 0:Ze.id)===J?Ze:null),He=async(J,M,G)=>{var Pe;const Ee=await oe.mutateAsync({sessionId:J,action:M,name:G}),De=(Pe=Ee.affectedSessionIds)!=null&&Pe.length?Ee.affectedSessionIds:[J];if(M==="delete"?(we($e=>S3($e,De)),En()):we($e=>x3($e,De,{...M==="rename"&&(G!=null&&G.trim())?{title:G.trim()}:{pinned:M==="pin"}})),M==="delete"&&m===J){const $e=Ee.nextSessionId;$e?(Js($e),y($e)):(Js(null),y(null))}},ze=async(J,M,G)=>{var Pe,$e;const Ee=await ue.mutateAsync({projectId:J,agentId:(Ke==null?void 0:Ke.id)??u??t??"",action:M,name:G==null?void 0:G.name,orderedProjectIds:G==null?void 0:G.orderedProjectIds}),De=(Pe=G==null?void 0:G.name)==null?void 0:Pe.trim();M==="pin"||M==="unpin"?we(Je=>Tu(Je,J,{pinned:M==="pin"})):M==="rename"&&De?we(Je=>Tu(Je,J,{display_name:De})):M==="reorder"&&(($e=G==null?void 0:G.orderedProjectIds)!=null&&$e.length)?we(Je=>xp(Je,G.orderedProjectIds??[])):M==="remove"||M==="archive"?(we(Je=>Sp(Je,J)),En()):M==="unarchive"&&(En(),l.invalidateQueries({queryKey:os})),Ze&&Ze.project_id===J&&(M==="remove"||M==="archive"||M==="unarchive")&&(Ee.nextSessionId?(Js(Ee.nextSessionId),y(Ee.nextSessionId)):(Js(null),y(null)))},rt=async J=>{Ke&&(Ji(Ke.id),Js(null),Kr(null),Cf(!1),ku(J),S(J),b("composer"),y(null),await a({to:"/"}))},It=async()=>{Ke&&(D||(N(!1),ms(null)),Ji(Ke.id),Js(null),Kr(null),ku(null),Cf(!0),S(null),b("directory-picker"),y(null),await a({to:"/"}))},Ft=async J=>{await rt(J)},Le=async J=>{const M=Re(J);S(null),b("composer"),Cf(!1),ku(null),Kr(null),M&&!Jt.some(Ee=>Ee.id===J)&&we(Ee=>j3(Ee,M)),y(J),Js(J);const G=(M==null?void 0:M.agent_id)??(Ke==null?void 0:Ke.id)??Oe;G&&(f(G),Ji(G)),t&&await a({to:"/",replace:!0})},Et=D?0:aD(),Cn=D?0:iD(),hs=D||w,na=D?0:V??(w?Et:0),Ws=D?0:ee??(j?Cn:0),Ja=D?1:Et>0?na/Et:0,Rs=!D&&V!==null,Na=!D&&ee!==null,Pa=D?{"--desktop-sidebar-width":`${I}px`}:{"--workspace-preview-shift":`${Ws}px`},ms=J=>{ge.current=J,Y(J)},dn=J=>{te.current=J,me(J)},pn=J=>J instanceof Element&&!!J.closest('button, textarea, input, a, [role="dialog"]'),Un=J=>pn(J),ps=(J,M,G)=>(C.current={target:"sidebar",mode:w?"close":"open",startX:J,startY:M,axis:"pending",pointerId:G},!0),Ps=(J,M,G)=>ut?(C.current={target:"preview",mode:"open",startX:J,startY:M,axis:"pending",pointerId:G},!0):!1,Us=(J,M)=>{const G=C.current;if(!G)return!1;const Ee=J-G.startX,De=M-G.startY;if(G.axis==="pending"){if(Math.abs(Ee)<8&&Math.abs(De)<8)return!1;if(G.axis=Math.abs(Ee)>Math.abs(De)?"x":"y",G.axis==="y")return C.current=null,ms(null),!1}if(G.target==="preview"){const $e=Math.max(0,Math.min(Cn,-Ee));return dn($e),!0}const Pe=G.mode==="open"?Math.max(0,Math.min(Et,Ee)):Math.max(0,Math.min(Et,Et+Ee));return ms(Pe),!0},Ms=(J,M)=>{const G=C.current;if(!G)return;const Ee=J-G.startX,De=M-G.startY;if(G.axis==="pending"&&Math.abs(De)>48){C.current=null,ms(null);return}if(G.target==="preview"){const Ye=(G.axis==="x"?te.current??Math.max(0,Math.min(Cn,-Ee)):j?Cn:0)>=Math.min(eD,Cn*zg);T(Ye),Ye&&(N(!1),ms(null)),C.current=null,dn(null);return}const Pe=G.axis==="x"?ge.current??(G.mode==="open"?Math.max(0,Math.min(Et,Ee)):Math.max(0,Math.min(Et,Et+Ee))):w?Et:0,$e=G.mode==="open"?Pe>=Math.min(JA,Et*zg):Pe>=Et*zg;N($e),C.current=null,ms(null)};_.useEffect(()=>{const J=o.current;if(!J||D)return;const M=Pe=>{if(j)return;const $e=Pe.touches[0];Pe.touches.length!==1||!$e||Un(Pe.target)||(xe.current={startX:$e.clientX,startY:$e.clientY})},G=Pe=>{if(Pe.touches.length!==1)return;const $e=Pe.touches[0];if(!C.current){const Ye=xe.current;if(!Ye)return;const en=$e.clientX-Ye.startX,jt=$e.clientY-Ye.startY;if(Math.abs(en)<8&&Math.abs(jt)<8)return;if(Math.abs(en)<=Math.abs(jt)){xe.current=null;return}const $n=w&&en<0,gn=!j&&!w&&en>0,bn=!w&&!j&&en<0&&ut,Tn=$n||gn?ps(Ye.startX,Ye.startY):bn?Ps(Ye.startX,Ye.startY):!1;if(xe.current=null,!Tn)return}Us($e.clientX,$e.clientY)&&Pe.cancelable&&Pe.preventDefault()},Ee=Pe=>{if(xe.current=null,!C.current)return;const $e=Pe.changedTouches[0];if(!$e){C.current=null,ms(null),dn(null);return}Ms($e.clientX,$e.clientY)},De=()=>{xe.current=null,C.current=null,ms(null),dn(null)};return J.addEventListener("touchstart",M,{passive:!0,capture:!0}),J.addEventListener("touchmove",G,{passive:!1,capture:!0}),J.addEventListener("touchend",Ee,{capture:!0}),J.addEventListener("touchcancel",De,{capture:!0}),()=>{J.removeEventListener("touchstart",M,{capture:!0}),J.removeEventListener("touchmove",G,{capture:!0}),J.removeEventListener("touchend",Ee,{capture:!0}),J.removeEventListener("touchcancel",De,{capture:!0})}},[ut,D,j,w]);const xs=()=>i.jsx(i.Fragment,{children:i.jsxs("div",{className:`conversation-main ${D?"has-desktop-sidebar":""}`,style:{transform:`translateX(${na}px)`,transition:Rs?"none":void 0},children:[i.jsx("div",{className:"conversation-topbar",children:D?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:()=>N(!0),"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]})}),i.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:i.jsx("div",{className:"conversation-thread conversation-thread--empty",children:i.jsx(VA,{mode:"node",agentName:Ke?dc(Ke):void 0,agentStatus:(Ke==null?void 0:Ke.status)??null,onOpenNodes:()=>{a({to:"/nodes"})}})})})]})});return i.jsxs("div",{ref:o,className:`conversation-page ${D?"has-desktop-sidebar":""}`,style:Pa,onPointerDown:J=>{D||j||J.pointerType!=="touch"&&(J.pointerType==="mouse"&&J.button!==0||Un(J.target)||(ps(J.clientX,J.clientY,J.pointerId),J.currentTarget.setPointerCapture(J.pointerId)))},onPointerMove:J=>{if(D||J.pointerType==="touch")return;const M=C.current;!M||M.pointerId!==J.pointerId||!Us(J.clientX,J.clientY)||J.preventDefault()},onPointerUp:J=>{if(D||J.pointerType==="touch")return;const M=C.current;!M||M.pointerId!==J.pointerId||Ms(J.clientX,J.clientY)},onPointerCancel:J=>{if(D||J.pointerType==="touch")return;const M=C.current;!M||M.pointerId!==J.pointerId||(C.current=null,ms(null),dn(null))},children:[i.jsx(fx,{open:hs,progress:Ja,isDragging:Rs,desktopPinned:D,isDesktopResizing:P,onClose:()=>{D||(N(!1),ms(null))},onDesktopResizeStart:J=>{he.current=ie.current,q.current={startX:J,startWidth:ie.current},Q(!0)},currentAgent:Ke??void 0,agentIndicatorState:Nt,projects:Bt,sessions:Jt,projectStats:Dt,historySessionsByProject:Object.fromEntries(Object.entries(ot).map(([J,M])=>[J,M.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(ln).map(([J,M])=>[J,M.sessions])),historyPageStateByProject:ot,archivedPageStateByProject:ln,activeSessionId:Ze==null?void 0:Ze.id,onCreateSession:J=>{Ft(J)},onCreateDirectoryThread:()=>{It()},onSelectSession:J=>{Le(J)},onSessionAction:He,onThreadAction:ze,onOpenSettings:e,onLoadMoreHistory:J=>{on(J)},onLoadMoreArchived:J=>{kn(J)},pendingSessionActionId:oe.isPending?((As=oe.variables)==null?void 0:As.sessionId)??null:null,pendingThreadActionId:ue.isPending?((Rt=ue.variables)==null?void 0:Rt.projectId)??null:null}),i.jsxs("div",{className:`conversation-workspace-stack ${j||Na?"is-preview-open":""} ${Na?"is-dragging":""}`,children:[i.jsx("div",{className:"conversation-workspace-stack__page is-primary",children:B?i.jsx(YA,{sessionId:B,workspaceDirectorySnapshot:it??null,workspaceAgentIndicatorState:Nt,embedded:!0,isDesktopSidebar:D,sidebarOffset:na,isSidebarDragging:Rs,onOpenSidebar:()=>{T(!1),N(!0)},onSelectSession:J=>{J&&Le(J)},onExitToNodes:()=>{Kr(null),Js(null),y(null),a({to:"/nodes"})}}):Ke?Ze?null:i.jsx(DR,{currentAgent:Ke,projects:Bt,sessions:Jt,initialProjectId:g,entryView:p,isDesktopSidebar:D,sidebarOffset:na,isSidebarDragging:Rs,onOpenSidebar:()=>{T(!1),N(!0)},onProjectSelected:J=>{S(J),b("composer"),Cf(!1)},onSessionCreated:J=>{Le(J)}}):xs()}),i.jsx("div",{className:"conversation-workspace-stack__page is-preview",children:i.jsx("div",{className:"session-file-preview-pane",children:Ze&&un&&(j||ee!==null)?i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"session-file-preview-pane__fallback",children:"正在载入预览页…"}),children:i.jsx(nD,{agentId:(Ke==null?void 0:Ke.id)??Oe,sessionId:Ze.id,projectName:un.display_name||un.name,projectPath:un.path,isActive:j,onBack:()=>{T(!1),dn(null)}},Ze.id)}):null})})]})]})},lD=24,oD=32,cD=72,g2="panda:native-safe-area-change",q_=e=>{const t=Number(e);if(!Number.isFinite(t))return 0;const a=typeof window<"u"&&Number.isFinite(window.devicePixelRatio)&&window.devicePixelRatio>0?window.devicePixelRatio:1;return Math.max(0,t/a)},Bg=e=>`${Math.round(q_(e)*100)/100}px`,uD=e=>`${Math.round(e*100)/100}px`,dD=e=>{const t=q_(e);if(!Tp())return`${Math.round(t*100)/100}px`;const a=Math.min(oD,Math.max(lD,t+1));return`${Math.round(a*100)/100}px`},fD=()=>{if(typeof window>"u")return 0;const e=window.visualViewport;if(!e)return 0;const t=window.innerHeight-(e.height+e.offsetTop);return Number.isFinite(t)?Math.max(0,t):0},hD=e=>{var o;if(!qs())return"0px";const t=fD(),a=q_((o=e==null?void 0:e.getKeyboardInsetPx)==null?void 0:o.call(e)),l=t>0?t:a;return l<cD?"0px":uD(l)},mD=()=>{var a,l,o,u;if(typeof document>"u"||typeof window>"u")return;const e=window.PandaSafeArea,t=document.documentElement.style;e&&(t.setProperty("--native-safe-area-top",dD((a=e.getTopInsetPx)==null?void 0:a.call(e))),t.setProperty("--native-safe-area-right",Bg((l=e.getRightInsetPx)==null?void 0:l.call(e))),t.setProperty("--native-safe-area-bottom",Bg((o=e.getBottomInsetPx)==null?void 0:o.call(e))),t.setProperty("--native-safe-area-left",Bg((u=e.getLeftInsetPx)==null?void 0:u.call(e)))),t.setProperty("--native-keyboard-inset-bottom",hD(e))},pD=()=>{var u,f;if(typeof window>"u"||typeof document>"u")return()=>{};const e=()=>{mD()},t=new Set,a=m=>{const y=window.setTimeout(()=>{t.delete(y),e()},m);t.add(y)},l=()=>{e(),a(120),a(280)};let o=null;return e(),a(0),a(250),a(800),window.addEventListener("load",e,{once:!0}),window.addEventListener("resize",e),window.addEventListener("orientationchange",e),window.addEventListener(g2,e),document.addEventListener("visibilitychange",e),document.addEventListener("focusin",l,!0),document.addEventListener("focusout",l,!0),(u=window.visualViewport)==null||u.addEventListener("resize",e),(f=window.visualViewport)==null||f.addEventListener("scroll",e),M3.addListener("resume",e).then(m=>{o=()=>{m.remove()}}).catch(()=>{}),()=>{var m,y;window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e),window.removeEventListener(g2,e),document.removeEventListener("visibilitychange",e),document.removeEventListener("focusin",l,!0),document.removeEventListener("focusout",l,!0),(m=window.visualViewport)==null||m.removeEventListener("resize",e),(y=window.visualViewport)==null||y.removeEventListener("scroll",e);for(const g of t)window.clearTimeout(g);t.clear(),o==null||o()}},Hg=new $9,gD=async()=>{},_D=_.lazy(async()=>({default:(await Zr(()=>import("./diagnostics-page-cP5VtBfz.js"),__vite__mapDeps([3,4]))).DiagnosticsPage})),yD=()=>i.jsx(_.Suspense,{fallback:i.jsx("main",{className:"diagnostics-page",children:i.jsx("div",{className:"diagnostics-shell",children:i.jsx("section",{className:"diagnostics-card",children:i.jsx("p",{children:"正在载入诊断页…"})})})}),children:i.jsx(_D,{})}),gc=F7({component:JC}),vD=hc({getParentRoute:()=>gc,path:"/",component:$x}),bD=hc({getParentRoute:()=>gc,path:"/nodes",component:_T}),xD=hc({getParentRoute:()=>gc,path:"/session/$sessionId",component:bT}),SD=hc({getParentRoute:()=>gc,path:"/new-thread/$agentId",component:$x}),jD=hc({getParentRoute:()=>gc,path:"/settings",component:ix}),wD=hc({getParentRoute:()=>gc,path:"/diagnostics",component:yD}),ND=gc.addChildren([vD,bD,xD,SD,jD,wD]),kD=Z7({routeTree:ND,defaultPreload:"intent"});typeof document<"u"&&(tx(ex()),pD());gD().catch(()=>{}).then(async()=>{await Ek(),await iE(Hg),lE(Hg)}).finally(()=>{c9.createRoot(document.getElementById("root")).render(i.jsx(F9,{client:Hg,children:i.jsx(ej,{router:kD})}))});export{p4 as B,gg as C,Fu as E,c0 as L,O9 as Q,sd as S,o6 as W,Zr as _,M2 as a,La as b,q9 as c,Q9 as d,Z9 as e,G9 as f,Y9 as g,vs as h,J9 as i,i as j,zv as k,V9 as l,mh as m,bs as n,wn as o,ls as p,TD as q,_ as r,Qm as s,e9 as t,ki as u};
|
|
148
|
+
`),RA=e=>e.kind==="entry"&&e.entry.kind==="user",zx=e=>e.kind==="entry"&&e.entry.kind==="assistant",MA=e=>RA(e)||zx(e),AA=e=>e.kind==="tool-group"?!0:e.entry.kind==="assistant"||e.entry.kind==="thinking"||e.entry.kind==="tool",DA=e=>{if(e.length<=1)return e;const t=[];for(const a of e){const l=t[t.length-1];if(l&&l.kind==="entry"&&a.kind==="entry"&&l.entry.kind==="assistant"&&a.entry.kind==="assistant"&&l.entry.body.trim()===a.entry.body.trim()){t[t.length-1]=a;continue}t.push(a)}return t},OA=e=>`展开 ${e.length} 条过程消息`,IA=e=>`收起 ${e.length} 条过程消息`,LA=(e,t)=>{const a=DA(e.items),{completion:l}=e,o=a.findLastIndex(m=>zx(m));if(o===-1||!l||!t)return{id:e.id,startedAt:e.startedAt,visibleStartItems:o===-1?a:a.slice(0,o),hiddenItems:[],visibleEndItems:o===-1?[]:a.slice(o),completion:l};const u=[],f=[];return a.forEach((m,y)=>{if(y!==o){if(MA(m)){u.push(m);return}f.push(m)}}),{id:e.id,startedAt:e.startedAt,visibleStartItems:u,hiddenItems:f,visibleEndItems:[a[o]],completion:l}},PA=(e,t)=>{const a=[];let l=[],o=null;const u=()=>{for(const m of l)a.push({kind:"item",id:m.kind==="entry"?m.entry.id:m.group.id,item:m});l=[]},f=()=>{o&&((o.items.length>0||o.completion)&&a.push({kind:"turn",turn:LA(o,t)}),o=null)};for(const m of e){if(m.kind==="turn-start"){f(),o={id:m.id,startedAt:m.startedAt,items:l,completion:null},l=[];continue}if(m.kind==="turn-complete"){if(o){o.completion=m;continue}o={id:m.id,startedAt:null,items:l,completion:m},l=[];continue}if(o){if(o.completion&&!AA(m)){f(),l.push(m);continue}o.items.push(m);continue}l.push(m)}return f(),u(),a},UA=e=>e.run_state!=="running"&&Date.now()-new Date(e.last_event_at).getTime()>=RM,zA=(e,t)=>{var g,S;const a=t==null?void 0:t.projectPath,l=(t==null?void 0:t.compactCompletedTurns)??!1,o=[];let u=null,f=!1,m=null,y=[];for(let p=0;p<e.length;p+=1){const b=e[p];if(b.kind==="system"&&b.body==="开始处理请求"){o.push({kind:"turn-start",id:b.id,startedAt:b.timestamp}),m=b.timestamp,y=[];continue}if(b.kind==="system"&&b.body==="处理完成"){o.push({kind:"turn-complete",id:b.id,durationLabel:NA(m,b.timestamp),patchSummary:kA(y),completedAt:b.timestamp}),m=null,y=[];continue}if(b.kind==="tool"&&b.title!=="tool-output"){const w=[];let N=p+1;for(;N<e.length&&((g=e[N])==null?void 0:g.kind)==="tool"&&((S=e[N])==null?void 0:S.title)==="tool-output";)w.push(e[N]),N+=1;u=b.id;const j=b.title==="apply_patch"?Px(b.patch_summary,a)??Ux(b.body,a):null;j&&y.push(j),w.length===0&&(f=!0),o.push({kind:"tool-group",group:{id:b.id,commandEntry:b,outputEntries:w,patchSummary:j}}),p=N-1;continue}if(b.kind==="tool"&&b.title==="tool-output"){o.push({kind:"tool-group",group:{id:b.id,commandEntry:b,outputEntries:[],patchSummary:null}}),u=b.id;continue}o.push({kind:"entry",entry:b})}return{blocks:PA(o,l),lastToolGroupId:u,hasRunningToolGroup:f}},BA=e=>e.kind==="entry"?e.entry.timestamp:e.group.commandEntry.timestamp,HA=(e,t)=>{var f,m;const a=[...e.visibleStartItems,...e.hiddenItems,...e.visibleEndItems].map(BA).filter(y=>!!y),l=a.length>0?a[a.length-1]:null,o=e.startedAt??a[0]??((f=e.completion)==null?void 0:f.completedAt)??null,u=((m=e.completion)==null?void 0:m.completedAt)??l??o;return{startMs:o?+new Date(o):null,endMs:u?+new Date(u):null,nextStartMs:t!=null&&t.startedAt?+new Date(t.startedAt):null}},$A=(e,t)=>{const a=+new Date(e.started_at),l=e.completed_at?+new Date(e.completed_at):null,o=t.startMs??(t.endMs!==null?t.endMs-wf:null),u=t.nextStartMs??(t.endMs!==null?t.endMs+wf:Number.POSITIVE_INFINITY);return o!==null&&a<o-wf?!1:a<=u+wf?!0:l!==null&&l<=u+wf},FA=(e,t)=>{if(t===null)return Number.POSITIVE_INFINITY;const a=+new Date(e.updated_at);return Number.isFinite(a)?Math.abs(a-t):Number.POSITIVE_INFINITY},qA=(e,t)=>{const a=[...t].sort((f,m)=>+new Date(f.started_at)-+new Date(m.started_at)),l=new Set,o=e.filter(f=>f.kind==="turn"),u=new Map(o.map((f,m)=>[f.turn.id,m]));return e.map(f=>{var j,T,D;if(f.kind!=="turn")return f;const m=u.get(f.turn.id)??-1,y=m>=0?((j=o[m+1])==null?void 0:j.turn)??null:null,g=HA(f.turn,y),S=((T=f.turn.completion)==null?void 0:T.patchSummary)??null,p=Ix(S),w=((D=a.filter(z=>!l.has(z.id)).map(z=>({changeSet:z,overlapCount:Lx(z,p),updatedAtDistance:FA(z,g.endMs)})).filter(z=>z.overlapCount>0&&z.updatedAtDistance<=Ox).sort((z,I)=>I.overlapCount!==z.overlapCount?I.overlapCount-z.overlapCount:z.changeSet.source!==I.changeSet.source?z.changeSet.source==="app-server"?-1:1:z.updatedAtDistance!==I.updatedAtDistance?z.updatedAtDistance-I.updatedAtDistance:+new Date(z.changeSet.started_at)-+new Date(I.changeSet.started_at))[0])==null?void 0:D.changeSet)??a.find(z=>l.has(z.id)?!1:$A(z,g))??null;return w&&l.add(w.id),{kind:"turn",turn:f.turn,changeSet:w}})},WA=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),$0=e=>Math.max(Rx,Math.min(OM,e)),KA=()=>{if(typeof window>"u")return _u;try{const e=window.localStorage.getItem(Tx),t=window.localStorage.getItem(Mf);if(!e)return window.localStorage.setItem(Mf,Af),_u;const a=Number(e);if(!Number.isFinite(a))return window.localStorage.setItem(Mf,Af),_u;const o=t!==Af||a===DM||a>_u?_u:a;return window.localStorage.setItem(Mf,Af),$0(o)}catch{return _u}};function Dm({active:e,render:t,fallback:a=null}){const[l,o]=_.useState(!e);return _.useEffect(()=>{if(!e){o(!1);return}o(!1);const u=window.requestAnimationFrame(()=>{o(!0)});return()=>{window.cancelAnimationFrame(u)}},[e]),e?l?i.jsx(i.Fragment,{children:t()}):i.jsx(i.Fragment,{children:a}):null}const QA=_.memo(function({sessionId:t,group:a,projectPath:l}){const[o,u]=_.useState({}),f=a.commandEntry.detail_available||a.outputEntries.some(j=>j.detail_available),m=BR({sessionId:t,entryId:a.commandEntry.id,scope:{sessionId:t},enabled:f}),y=m.data,g=(y==null?void 0:y.command_entry)??a.commandEntry,S=y!=null&&y.output_entries&&y.output_entries.length>0?y.output_entries:a.outputEntries,p=g.title==="apply_patch"?Ux(g.body,l)??Px(g.patch_summary,l)??a.patchSummary:a.patchSummary,b=CA(g),w=TA(S),N=j=>{u(T=>({...T,[j]:!T[j]}))};return m.isPending&&f&&!y?i.jsx("div",{className:"patch-file-card__empty",children:"正在加载工具详情…"}):g.title==="apply_patch"&&p?p.files.length>1?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"tool-entry__patch-list",children:p.files.map(j=>{const T=`${a.id}:${j.path}`,D=!!o[T];return i.jsxs("div",{className:`tool-entry tool-entry--patch-file ${D?"is-expanded":""}`,children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>N(T),"aria-expanded":D,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:"已编辑"}),i.jsx("span",{className:"tool-entry__command",children:sA(j.displayPath)}),i.jsxs("span",{className:"tool-entry__counts",children:[i.jsxs("span",{className:"is-add",children:["+",j.additions]}),i.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),D?i.jsx("div",{className:"tool-entry__details",children:j.diffText.trim()?i.jsxs("div",{className:"patch-file-card",children:[i.jsxs("div",{className:"patch-file-card__header",children:[i.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),i.jsxs("div",{className:"patch-file-card__counts",children:[i.jsxs("span",{className:"is-add",children:["+",j.additions]}),i.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),i.jsx("div",{className:"patch-file-card__diff",children:H0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]}):i.jsx("div",{className:"patch-file-card__empty",children:"此变更没有可展示的补丁内容"})}):null]},T)})}),m.isError?i.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):i.jsxs("div",{className:"tool-entry__patch-list",children:[p.files.map(j=>i.jsxs("div",{className:"patch-file-card",children:[i.jsxs("div",{className:"patch-file-card__header",children:[i.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),i.jsxs("div",{className:"patch-file-card__counts",children:[i.jsxs("span",{className:"is-add",children:["+",j.additions]}),i.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),i.jsx("div",{className:"patch-file-card__diff",children:H0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]},`${a.id}-${j.path}`)),m.isError?i.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"tool-entry__section",children:[i.jsx("div",{className:"tool-entry__label",children:"命令"}),i.jsx("pre",{className:"tool-entry__pre",children:b})]}),w?i.jsxs("div",{className:"tool-entry__section",children:[i.jsx("div",{className:"tool-entry__label",children:"输出"}),i.jsx("pre",{className:"tool-entry__pre",children:w})]}):null,m.isError?i.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]})}),GA=_.memo(function({sessionId:t,sessions:a,sessionRunState:l,isDesktopSidebar:o,projectPath:u,renderedBlocks:f,lastToolGroupId:m,sessionChangeSets:y,isSubagentTimelinePending:g,isInitialTimelinePending:S,hasTimeline:p,proposedPlanReplyDrafts:b,pendingProposedPlanReplyEntryId:w,canRespondToProposedPlan:N,onProposedPlanReplyDraftChange:j,onSubmitProposedPlanReply:T,onPreviewImage:D,changeSetDiffs:z,changeSetDiffErrors:I,loadingChangeSetDiffKeys:k,onLoadSessionChangeSets:P,onLoadChangeSetFileDiff:Q,onLoadFullTimeline:se,timelineLoadState:W,canRollbackChangeSets:V,pendingRollbackTurnId:Y,rollbackTurnError:ee,rolledBackTurnIds:me,onRollbackTurn:ge}){const[te,xe]=_.useState({}),[C,q]=_.useState({}),[ie,he]=_.useState({}),[re,L]=_.useState(null),[ae,ke]=_.useState(null),[U,ve]=_.useState(null),Z=_.useRef(null),Se=_.useRef(null),je=_.useMemo(()=>{var X;return((X=[...f].reverse().find(B=>B.kind==="turn"&&!!B.turn.completion))==null?void 0:X.turn.id)??null},[f]);_.useEffect(()=>{const X=B=>{const oe=B.target;oe instanceof Element&&oe.closest(".conversation-inline-link")||L(null)};return window.addEventListener("pointerdown",X),()=>{window.removeEventListener("pointerdown",X)}},[]),_.useEffect(()=>()=>{Z.current!==null&&window.clearTimeout(Z.current),Se.current!==null&&window.clearTimeout(Se.current)},[]);const Oe=X=>{xe(B=>({...B,[X]:!B[X]}))},Ie=X=>{q(B=>({...B,[X]:!B[X]}))},wt=X=>{he(B=>({...B,[X]:!B[X]}))};_.useEffect(()=>{var B;const X=new Map;for(const oe of f){if(oe.kind!=="turn")continue;const ue=oe.changeSet;if(!ue||ue.status!=="completed"||ue.files.length===0)continue;const we=Lg(oe.turn.id),Re=c2(ue,u,((B=oe.turn.completion)==null?void 0:B.patchSummary)??null);for(const He of Re){if(!He.changeSetId||!He.diffAvailable)continue;const ze=u2(we,He.path);if(!ie[ze])continue;const rt=Km(He.changeSetId,He.path,He.itemId);z[rt]||k[rt]||X.set(rt,{changeSetId:He.changeSetId,path:He.path,itemId:He.itemId??null})}}for(const oe of X.values())Q(oe)},[z,ie,k,Q,u,f]);const qe=async X=>{var ue;const B=X.trim();if(!B)return!1;const oe=()=>{const we=document.createElement("textarea");we.value=B,we.setAttribute("readonly","true"),we.style.position="fixed",we.style.opacity="0",we.style.pointerEvents="none",document.body.appendChild(we),we.select(),document.execCommand("copy"),document.body.removeChild(we)};try{return(ue=navigator.clipboard)!=null&&ue.writeText?await navigator.clipboard.writeText(B):oe(),!0}catch{return!1}},bt=async(X,B)=>{await qe(B)&&(ke(X),Z.current!==null&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{ke(ue=>ue===X?null:ue),Z.current=null},1400))},Ut=async(X,B)=>{await qe(B)&&(ve(X),Se.current!==null&&window.clearTimeout(Se.current),Se.current=window.setTimeout(()=>{ve(ue=>ue===X?null:ue),Se.current=null},1400))};function $t(X,B,oe){return H0(X,B,oe)}function zt(X,B,oe){const ue=re===oe,we=()=>{L(Re=>Re===oe?null:oe)};return i.jsx(ZM,{isActive:ue,label:X,path:B,tokenKey:oe,onToggle:we},oe)}function xt(X,B,oe=Gr(X,u)){return zt(Mx(oe),oe,B)}function it(X,B){return iA(X).map((ue,we)=>{const Re=`${B}-${we}`;return ue.kind==="text"?i.jsx("span",{children:ue.value},Re):ue.kind==="code"?i.jsx("code",{className:"conversation-inline-code",children:ue.value},Re):ue.kind==="strong"?i.jsx("strong",{children:it(ue.value,`${Re}-strong`)},Re):ue.kind==="emphasis"?i.jsx("em",{children:it(ue.value,`${Re}-emphasis`)},Re):ue.kind==="skill"?i.jsx("span",{className:"conversation-skill-token",children:ue.raw},Re):ue.kind==="command"?i.jsx("span",{className:"conversation-command-token",children:ue.raw},Re):zt(ue.label,ue.path,Re)})}function ot(X,B){return uA(X).map((ue,we)=>{const Re=`${B}-block-${we}`;if(ue.kind==="heading"){const He=Math.min(ue.level,3),ze=He===1?"h1":He===2?"h2":"h3";return i.jsx(ze,{className:`conversation-markdown-heading is-level-${He}`,children:it(ue.text,`${Re}-heading`)},Re)}if(ue.kind==="list"){const He=ue.ordered?"ol":"ul";return i.jsx(He,{className:"conversation-markdown-list",children:ue.items.map((ze,rt)=>i.jsx("li",{value:ue.ordered?ze.ordinal??void 0:void 0,children:it(ze.text,`${Re}-item-${rt}`)},`${Re}-item-${rt}`))},Re)}if(ue.kind==="code"){const He=`${Re}-meta`;return i.jsxs("div",{className:"conversation-markdown-code-block",children:[ue.rawInfo?i.jsxs("div",{className:"conversation-markdown-code-block__meta",children:[i.jsx("span",{className:"conversation-markdown-code-block__meta-label",children:ue.rawInfo}),i.jsxs("button",{type:"button",className:`conversation-markdown-code-block__copy ${U===He?"is-copied":""}`,onClick:()=>{Ut(He,ue.content)},"aria-label":U===He?"已复制代码块内容":"复制代码块内容",children:[i.jsx("span",{className:"conversation-markdown-code-block__copy-icon","aria-hidden":"true",children:U===He?i.jsx(i2,{}):i.jsx(a2,{})}),i.jsx("span",{className:"sr-only",children:U===He?"已复制":"复制"})]})]}):null,i.jsx("pre",{className:"conversation-markdown-code-block__pre",children:i.jsx("code",{children:ue.content})})]},Re)}return i.jsx("p",{className:"conversation-markdown-paragraph",children:ue.lines.map((He,ze)=>i.jsxs("span",{children:[ze>0?i.jsx("br",{}):null,it(He,`${Re}-line-${ze}`)]},`${Re}-line-${ze}`))},Re)})}function ln(X,B,oe){const ue=`${X.id}:proposed-plan:${oe}`,we=b[ue]??"",Re=w===ue,He=!N||Re;return i.jsxs("div",{className:"proposed-plan-card",children:[i.jsx("div",{className:"proposed-plan-card__content",children:ot(B,`${ue}:content`)}),i.jsxs("div",{className:"proposed-plan-card__footer",children:[i.jsx("div",{className:"proposed-plan-card__title",children:"实施此计划?"}),i.jsxs("div",{className:"proposed-plan-card__actions",children:[i.jsx("button",{type:"button",className:"proposed-plan-card__confirm",disabled:He,onClick:()=>{T(ue,"是,实施此计划")},children:Re?"回复中…":"是,实施此计划"}),i.jsxs("div",{className:"proposed-plan-card__custom",children:[i.jsx("input",{type:"text",className:"proposed-plan-card__input",value:we,disabled:He,placeholder:"否,请告知如何调整",onChange:ze=>{j(ue,ze.target.value)},onKeyDown:ze=>{ze.key!=="Enter"||!we.trim()||He||(ze.preventDefault(),T(ue,we))}}),i.jsx("button",{type:"button",className:"proposed-plan-card__submit",disabled:He||!we.trim(),onClick:()=>{T(ue,we)},children:Re?"回复中…":"回复"})]})]})]})]},ue)}function on(X){const B=dA(X.body);return B.some(ue=>ue.kind==="proposed-plan")?B.map((ue,we)=>{const Re=`${X.id}-content-${we}`;return ue.kind==="markdown"?i.jsx("div",{className:"conversation-entry__rich-block",children:ot(ue.content,Re)},Re):ln(X,ue.content,we)}):ot(X.body,X.id)}function kn(X){const B=I6([],X.attachments);if(B.length===0)return null;const oe=B.filter(Tb),ue=B.filter(we=>!Tb(we));return i.jsxs("div",{className:"conversation-entry__attachments",children:[oe.length>0?i.jsx("div",{className:"conversation-entry__attachment-grid",children:oe.map(we=>{const Re=L0(we.size_bytes),He=we.name??"图片",ze=`图片${Re?` · ${Re}`:""}`,rt=i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"conversation-entry__attachment-media",children:we.content_url?i.jsxs(i.Fragment,{children:[i.jsx("img",{src:we.content_url,alt:He,loading:"lazy"}),i.jsx("span",{className:"conversation-entry__attachment-badge",children:"预览"})]}):i.jsx("div",{className:"conversation-entry__attachment-fallback",children:"无法预览"})}),i.jsxs("div",{className:"conversation-entry__attachment-caption",children:[i.jsx("span",{className:"conversation-entry__attachment-title",children:He}),i.jsx("span",{className:"conversation-entry__attachment-meta",children:ze})]})]});return we.content_url?i.jsx("button",{type:"button",className:"conversation-entry__attachment-card is-image",onClick:()=>D({src:we.content_url,label:He,meta:ze}),"aria-label":`预览 ${He}`,children:rt},`${X.id}:${we.id}`):i.jsx("div",{className:"conversation-entry__attachment-card is-image",children:rt},`${X.id}:${we.id}`)})}):null,ue.length>0?i.jsx("div",{className:"conversation-entry__file-list",children:ue.map(we=>{const Re=L0(we.size_bytes),He=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"conversation-entry__file-icon","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z"}),i.jsx("path",{d:"M14 3v5h5"}),i.jsx("path",{d:"M9 13h6"}),i.jsx("path",{d:"M9 17h4"})]})}),i.jsxs("span",{className:"conversation-entry__file-copy",children:[i.jsx("span",{className:"conversation-entry__file-title",children:we.name??"附件"}),i.jsxs("span",{className:"conversation-entry__file-meta",children:["文件",Re?` · ${Re}`:""]})]})]});return we.content_url?i.jsx("a",{className:"conversation-entry__file-card",href:we.content_url,download:we.name??void 0,target:"_blank",rel:"noreferrer",children:He},`${X.id}:${we.id}`):i.jsx("div",{className:"conversation-entry__file-card",children:He},`${X.id}:${we.id}`)})}):null]})}function En(X,B){return i.jsx("div",{className:"turn-patch-summary__files",children:B.map(oe=>{const ue=u2(X,oe.path),we=!!ie[ue],Re=oe.changeSetId?Km(oe.changeSetId,oe.path,oe.itemId):null,He=Re?z[Re]:void 0,ze=Re?k[Re]===!0:!1,rt=Re?I[Re]??null:null,It=(He==null?void 0:He.file.diff)??oe.diffText??"",Ft=(He==null?void 0:He.empty_message)??oe.emptyMessage;return i.jsxs("div",{className:`turn-patch-file ${we?"is-expanded":""}`,children:[i.jsxs("button",{type:"button",className:"turn-patch-file__toggle",onClick:()=>{wt(ue),oe.changeSetId||P(),Re&&oe.changeSetId&&oe.diffAvailable&&!He&&!ze&&Q({changeSetId:oe.changeSetId,path:oe.path,itemId:oe.itemId??null})},"aria-expanded":we,children:[i.jsx("div",{className:"turn-patch-file__path",children:oe.pathLabel}),i.jsxs("div",{className:"turn-patch-file__meta",children:[i.jsxs("span",{className:"turn-patch-summary__counts",children:[i.jsxs("span",{className:"is-add",children:["+",oe.additions]}),i.jsxs("span",{className:"is-remove",children:["-",oe.deletions]})]}),i.jsx("span",{className:"turn-patch-file__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]})]}),we?i.jsx("div",{className:"turn-patch-file__detail",children:ze?i.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}):rt?i.jsx("div",{className:"patch-file-card__empty",children:rt}):oe.diffAvailable===!1&&!It.trim()?i.jsx("div",{className:"patch-file-card__empty",children:Ft}):i.jsx(Dm,{active:we,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),render:()=>$t(It,oe.path,Ft)})}):null]},ue)})})}function ht(X){return fA(X).map(B=>{const oe=`live:${X.id}:${B.item_id??"summary"}:${B.path}`,ue=!!ie[oe],we=X.status==="running",Re=Km(X.id,B.path,B.item_id),He=z[Re],ze=k[Re]===!0,rt=I[Re]??null,It=(He==null?void 0:He.file.diff)??"",Ft=(He==null?void 0:He.empty_message)??"此变更还没有可展示的补丁内容";return i.jsx("section",{className:"conversation-entry is-tool-group",children:i.jsxs("div",{className:`tool-entry ${we?"is-running":"is-complete"} ${ue?"is-expanded":""} is-patch`,children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>{wt(oe),B.diff_available&&!He&&!ze&&Q({changeSetId:X.id,path:B.path,itemId:B.item_id??null})},"aria-expanded":ue,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:"已编辑"}),i.jsx("span",{className:"tool-entry__command",children:xt(B.path,`${oe}:live-link`,Gr(B.path,u))}),i.jsxs("span",{className:"tool-entry__counts",children:[i.jsxs("span",{className:"is-add",children:["+",B.additions]}),i.jsxs("span",{className:"is-remove",children:["-",B.deletions]})]})]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),ue?i.jsx("div",{className:"tool-entry__details",children:ze?i.jsx("div",{className:"patch-file-card__empty",children:"正在载入详情…"}):rt?i.jsx("div",{className:"patch-file-card__empty",children:rt}):!B.diff_available&&!It.trim()?i.jsx("div",{className:"patch-file-card__empty",children:Ft}):i.jsx(Dm,{active:ue,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>i.jsx("div",{className:"tool-entry__patch-list",children:i.jsxs("div",{className:"patch-file-card",children:[i.jsxs("div",{className:"patch-file-card__header",children:[i.jsx("div",{className:"patch-file-card__path",children:Gr(B.path,u)}),i.jsxs("div",{className:"patch-file-card__counts",children:[i.jsxs("span",{className:"is-add",children:["+",B.additions]}),i.jsxs("span",{className:"is-remove",children:["-",B.deletions]})]})]}),i.jsx("div",{className:"patch-file-card__diff",children:$t(It,B.path,Ft)})]})})})}):null]})},oe)})}const Ve=X=>{const B=V&&je===X&&!me[X],oe=(ee==null?void 0:ee.turnId)===X?ee.message:null;return{isEligible:B,isPending:Y===X,error:oe}};function Ke(X,B,oe,ue){const we=c2(X,u,ue),Re=we.reduce((rt,It)=>rt+It.additions,0),He=we.reduce((rt,It)=>rt+It.deletions,0),ze=Ve(B);return i.jsxs("div",{className:"turn-patch-summary",children:[i.jsxs("div",{className:"turn-patch-summary__header",children:[i.jsxs("div",{className:"turn-patch-summary__title",children:[i.jsxs("span",{children:[we.length," 个文件已更改"]}),i.jsxs("span",{className:"turn-patch-summary__counts",children:[i.jsxs("span",{className:"is-add",children:["+",Re]}),i.jsxs("span",{className:"is-remove",children:["-",He]})]})]}),ze.isEligible?i.jsx("div",{className:"turn-patch-summary__actions",children:i.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>ge(B),disabled:ze.isPending,"aria-label":ze.isPending?"正在回滚这轮改动":"回滚这轮改动",title:ze.isPending?"正在回滚这轮改动":"回滚这轮改动",children:i.jsx(r2,{})})}):null]}),ze.error?i.jsx("div",{className:"turn-patch-summary__notice is-error",children:ze.error}):null,En(oe,we)]})}function Nt(X,B,oe){const ue=Ve(X);return i.jsxs("div",{className:"turn-patch-summary",children:[i.jsxs("div",{className:"turn-patch-summary__header",children:[i.jsxs("div",{className:"turn-patch-summary__title",children:[i.jsxs("span",{children:[oe.files.length," 个文件已更改"]}),i.jsxs("span",{className:"turn-patch-summary__counts",children:[i.jsxs("span",{className:"is-add",children:["+",oe.additions]}),i.jsxs("span",{className:"is-remove",children:["-",oe.deletions]})]})]}),ue.isEligible?i.jsx("div",{className:"turn-patch-summary__actions",children:i.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>ge(X),disabled:ue.isPending,"aria-label":ue.isPending?"正在回滚这轮改动":"回滚这轮改动",title:ue.isPending?"正在回滚这轮改动":"回滚这轮改动",children:i.jsx(r2,{})})}):null]}),ue.error?i.jsx("div",{className:"turn-patch-summary__notice is-error",children:ue.error}):null,En(B,oe.files.map(we=>({path:we.path,pathLabel:we.displayPath,additions:we.additions,deletions:we.deletions,diffText:we.diffText,emptyMessage:"此变更没有可展示的补丁内容"})))]})}function Bt(X,B){var It,Ft;const oe=B.agentId?a.find(Le=>Le.id===B.agentId)??null:null,ue=Ax(((It=oe==null?void 0:oe.subagent)==null?void 0:It.nickname)??(oe==null?void 0:oe.title)??B.agentId),we=`subagent:${X.id}`,Re=!!te[we],He=B.state==="working",ze=B.state==="completed"?"子代理返回":B.state==="shutdown"?"子代理已关闭":B.state==="errored"?"子代理异常":"子代理处理中",rt=((Ft=oe==null?void 0:oe.subagent)==null?void 0:Ft.nickname)??(oe==null?void 0:oe.title)??"子代理";return i.jsx("section",{className:"conversation-entry is-tool-group",children:i.jsxs("div",{className:`tool-entry is-subagent ${He?"is-running":"is-complete"} ${Re?"is-expanded":""}`,style:{"--subagent-accent":ue},children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>Oe(we),"aria-expanded":Re,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:ze}),i.jsx("span",{className:"tool-entry__command tool-entry__command--agent",children:rt})]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Re?i.jsx("div",{className:"tool-entry__details",children:i.jsx(Dm,{active:Re,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>i.jsxs("div",{className:"tool-entry__section",children:[i.jsx("div",{className:"tool-entry__label",children:rt}),i.jsx("div",{className:"tool-entry__markdown",children:ot(B.body,`${X.id}-subagent`)})]})})}):null]})},X.id)}function Jt(X){var ue,we;if(X.kind==="tool-group"){const{group:Re}=X;if(Re.commandEntry.title==="apply_patch"&&wA(y,Re.commandEntry.timestamp,Re.patchSummary))return null;const He=!!te[Re.id],ze=l==="running"&&m===Re.id&&Re.outputEntries.length===0,rt=Re.commandEntry.title==="apply_patch"&&!!Re.patchSummary,It=rt&&(((ue=Re.patchSummary)==null?void 0:ue.files.length)??0)>1,Ft=rt?Re.patchSummary.files.length===1?Re.patchSummary.files[0].displayPath:`${Re.patchSummary.files.length} 个文件`:EA(Re.commandEntry);return i.jsx("section",{className:"conversation-entry is-tool-group",children:i.jsxs("div",{className:`tool-entry ${ze?"is-running":"is-complete"} ${He?"is-expanded":""} ${rt?"is-patch":""} ${It?"has-flat-patch-list":""}`,children:[i.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>Oe(Re.id),"aria-expanded":He,children:[i.jsxs("div",{className:"tool-entry__summary",children:[i.jsx("span",{className:"tool-entry__status",children:rt?"已编辑":ze?"正在执行":"已执行"}),i.jsx("span",{className:"tool-entry__command",children:rt&&((we=Re.patchSummary)==null?void 0:we.files.length)===1?xt(Re.patchSummary.files[0].path,`${Re.id}:patch-link`,Re.patchSummary.files[0].displayPath):Ft}),rt&&Re.patchSummary?i.jsxs("span",{className:"tool-entry__counts",children:[i.jsxs("span",{className:"is-add",children:["+",Re.patchSummary.additions]}),i.jsxs("span",{className:"is-remove",children:["-",Re.patchSummary.deletions]})]}):null]}),i.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),He?i.jsx("div",{className:"tool-entry__details",children:i.jsx(Dm,{active:He,fallback:i.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>i.jsx(QA,{sessionId:t,group:Re,projectPath:u})})}):null]})},Re.id)}const B=X.entry,oe=B.kind==="user"?vA(B.body):null;if(oe)return Bt(B,oe);if(B.kind==="thinking")return l!=="running"?null:i.jsx("section",{className:"conversation-entry is-thinking-status",children:i.jsx("div",{className:"thinking-status-pill",children:i.jsx("span",{children:"正在思考"})})},B.id);if(cA(B))return i.jsx("section",{className:"conversation-context-compact",children:i.jsx("div",{className:"context-compact-divider",children:i.jsx("span",{children:"背景信息已自动压缩"})})},B.id);if(B.kind==="system"&&B.title==="system_prompt")return null;if(B.kind==="system"&&B.title==="runtime-status"){const Re=gA(B.body);return i.jsx("section",{className:"conversation-entry is-runtime-status",children:i.jsxs("div",{className:`runtime-status-entry is-${Re}`,children:[i.jsx("div",{className:"runtime-status-entry__label",children:_A(B.body)}),i.jsx("pre",{className:"runtime-status-entry__body",children:B.body})]})},B.id)}return i.jsx("section",{className:`conversation-entry ${B.kind==="user"?"is-user":"is-system"} is-${B.kind}`,children:B.kind==="user"?i.jsxs("div",{className:"conversation-entry__stack",children:[i.jsxs("div",{className:"conversation-entry__body",children:[B.body.trim()?ot(B.body,B.id):null,B.attachments.length>0?kn(B):null]}),B.body.trim()?i.jsxs("button",{type:"button",className:`conversation-entry__copy ${ae===B.id?"is-copied":""}`,onClick:()=>{bt(B.id,B.body)},"aria-label":ae===B.id?"已复制消息":"复制消息",children:[i.jsx("span",{className:"conversation-entry__copy-icon","aria-hidden":"true",children:ae===B.id?i.jsx(i2,{}):i.jsx(a2,{})}),i.jsx("span",{className:"sr-only",children:ae===B.id?"已复制":"复制"})]}):null]}):i.jsxs("div",{className:"conversation-entry__body",children:[B.body.trim()?B.kind==="assistant"?on(B):ot(B.body,B.id):null,B.attachments.length>0?kn(B):null]})},B.id)}if(g)return i.jsx("div",{className:"empty-panel",children:"正在载入子代理会话…"});if(S)return i.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[i.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"})]}),i.jsx("span",{className:"sr-only",children:"正在加载会话记录"})]});if(!p)return i.jsx("div",{className:"empty-panel",children:"这个会话还没有历史记录。"});const Dt=W.canLoadEarlierEntries||W.isPulling||W.isLoadingFull,Ze=W.isPulling||W.isLoadingFull||W.triggerSource==="click",un=W.isLoadingFull?"正在加载全部对话…":W.isPulling?W.isReadyToLoad?"松开加载全部":"下拉加载更多":o?"加载全部对话":"点击加载全部",ut=W.isLoadingFull||W.triggerSource==="click"?z0:W.indicatorOffset,_e={opacity:Ze?1:0,transform:`translate3d(-50%, calc(-100% + ${ut}px), 0) scale(${Ze?1:.92})`},Fe={transform:`rotate(${W.indicatorRotation}deg)`};return i.jsxs(i.Fragment,{children:[Dt?i.jsx("section",{className:`conversation-entry is-history-loader ${W.isReadyToLoad?"is-ready":""}`,children:i.jsxs("div",{className:`timeline-history-loader ${W.isLoadingFull?"is-loading":""} ${W.triggerSource==="click"?"is-click-loading":""}`,children:[i.jsx("span",{className:"timeline-history-loader__indicator",style:_e,"aria-hidden":"true",children:i.jsx("span",{className:"timeline-history-loader__indicator-surface",children:i.jsx("span",{className:"timeline-history-loader__indicator-track",style:Fe,children:i.jsx("span",{className:`timeline-history-loader__indicator-spin ${W.isLoadingFull?"is-loading":""}`,children:i.jsx("span",{className:"timeline-history-loader__indicator-icon",children:i.jsx(VM,{})})})})})}),i.jsx("div",{className:"turn-complete-divider timeline-history-loader__divider",children:W.isLoadingFull?i.jsx("span",{className:"timeline-history-loader__content is-loading",children:i.jsx("span",{children:un})}):i.jsx("button",{type:"button",className:`timeline-history-loader__button ${W.isPulling?"is-pulling":""}`,onClick:()=>se("click"),children:un})})]})}):null,f.map(X=>{var ze;if(X.kind==="item")return Jt(X.item);const{turn:B}=X,oe=X.changeSet,ue=((ze=B.completion)==null?void 0:ze.patchSummary)??null,we=!!C[B.id],Re=B.hiddenItems.length>0&&!we,He=we?IA(B.hiddenItems):OA(B.hiddenItems);return i.jsxs("section",{className:"conversation-turn",children:[B.visibleStartItems.map(rt=>Jt(rt)),B.hiddenItems.length>0?i.jsxs("div",{className:"conversation-turn__history",children:[i.jsxs("button",{type:"button",className:`turn-history-toggle ${we?"is-expanded":""}`,onClick:()=>Ie(B.id),"aria-expanded":we,children:[i.jsx("span",{className:"turn-history-toggle__label",children:He}),i.jsx("span",{className:"turn-history-toggle__chevron","aria-hidden":"true",children:i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Re?null:B.hiddenItems.map(rt=>Jt(rt))]}):null,B.completion&&B.visibleEndItems.length>0?i.jsx("section",{className:"conversation-turn-complete",children:i.jsx("div",{className:"turn-complete-divider",children:i.jsx("span",{children:B.completion.durationLabel})})}):null,B.visibleEndItems.map(rt=>Jt(rt)),oe&&oe.source==="app-server"&&oe.files.length>0?ht(oe):null,B.completion&&B.visibleEndItems.length===0?i.jsx("section",{className:"conversation-turn-complete",children:i.jsx("div",{className:"turn-complete-divider",children:i.jsx("span",{children:B.completion.durationLabel})})}):null,oe&&oe.status==="completed"&&oe.files.length>0?Ke(oe,B.id,Lg(B.id),ue):ue?Nt(B.id,Lg(B.id),ue):null]},B.id)})]})}),YA=({sessionId:e,workspaceDirectorySnapshot:t=null,workspaceAgentIndicatorState:a,embedded:l=!1,isDesktopSidebar:o,sidebarOffset:u=0,isSidebarDragging:f=!1,onOpenSidebar:m,onSelectSession:y,onExitToNodes:g}={})=>{var ko,Bd,$i,Hd,vi,Bc,Hc,bi,xi,yl,$c,Fc,vl,bl,$d,Fd,jr,Eo,qd;const{sessionId:S}=ad({strict:!1}),p=e??S??"",b=v_(p),w=(b==null?void 0:b.agentId)??pc(),N=ki(),j=La(),{data:T}=ox({scope:{sessionId:p,agentId:w??void 0},selectedSessionId:p,enabled:!l&&!t}),D=_.useMemo(()=>HM(t??T,b),[T,b,t]),z=(D==null?void 0:D.sessions.find(v=>v.id===p))??null,I=!!(z||b!=null&&b.session),k=HR({sessionId:p,scope:{sessionId:p,agentId:w??void 0},enabled:!!p}),{historyState:P,archivedState:Q,loadMoreHistory:se,loadMoreArchived:W,reset:V}=ux({scope:{sessionId:p},selectedSessionId:p}),Y=_.useRef(null),ee=_.useRef(null),me=_.useRef(null),ge=_.useRef(null),te=_.useRef(null),[xe,C]=_.useState(!1),[q,ie]=_.useState(()=>typeof window<"u"&&window.innerWidth>=e2),[he,re]=_.useState(()=>KA()),[L,ae]=_.useState(!1),[ke,U]=_.useState(""),[ve,Z]=_.useState([]),[Se,je]=_.useState(null),[Oe,Ie]=_.useState(null),[wt,qe]=_.useState(null),[bt,Ut]=_.useState(()=>R_()),[$t,zt]=_.useState(()=>F3()),[xt,it]=_.useState(()=>cb(p)),[ot,ln]=_.useState(()=>ub(p)),[on,kn]=_.useState(()=>db(p)),En=O_(),ht=_.useMemo(()=>En.map(({id:v,...O})=>O),[En]),[Ve,Ke]=_.useState({}),[Nt,Bt]=_.useState(null),[Jt,Dt]=_.useState(!1),[Ze,un]=_.useState(!1),[ut,_e]=_.useState(""),[Fe,X]=_.useState(!1),[B,oe]=_.useState(!1),[ue,we]=_.useState(null),[Re,He]=_.useState(null),[ze,rt]=_.useState(!1),[It,Ft]=_.useState(!1),[Le,Et]=_.useState("code"),[Cn,hs]=_.useState(!1),[na,Ws]=_.useState(null),[Ja,Rs]=_.useState(null),[Na,Pa]=_.useState({}),[ms,dn]=_.useState(null),[pn,Un]=_.useState(!1),[ps,Ps]=_.useState(!1),[Us,Ms]=_.useState(!1),[xs,As]=_.useState(!1),[Rt,J]=_.useState(null),[M,G]=_.useState(null),[Ee,De]=_.useState({}),[Pe,$e]=_.useState(!1),[Je,Ye]=_.useState({state:"connected",attempt:0,maxAttempts:5}),[en,jt]=_.useState({sessionId:p??null,pending:!!p,error:null}),[$n,gn]=_.useState({state:"idle"}),bn=_.useRef({}),Tn=_.useRef(D),xn=_.useRef(null);_.useEffect(()=>{zf(bt)},[bt]),_.useEffect(()=>{q3($t)},[$t]),_.useEffect(()=>{ht.length!==0&&(ht.some(v=>v.value===bt)||Ut(ht[0].value))},[ht,bt]),_.useEffect(()=>{it(cb(p)),ln(ub(p)),kn(db(p)),qe(null),Et("code"),hs(!1),Ws(null),Rs(null),Pa({}),dn(null),Un(!1),Ps(!1),Ms(!1),As(!1),J(null),G(null),De({}),ni({}),si({}),sa({}),ii(0),ri(!1),Bs(!1),ia(null),Ea.current=null,ir.current=null,_c.current=null,Xr.current=null,rr.current=!1,Jr.current=!!p},[p]),_.useEffect(()=>{bn.current=Ee},[Ee]),_.useEffect(()=>{Tn.current=D},[D]),_.useEffect(()=>{W3(p,xt)},[xt,p]),_.useEffect(()=>{K3(p,ot)},[ot,p]),_.useEffect(()=>{Q3(p,on)},[on,p]),_.useEffect(()=>{Ke({}),Bt(null)},[p]),_.useEffect(()=>{A.current=null},[p]),_.useEffect(()=>{if(!Se)return;const v=F=>{F.key==="Escape"&&je(null)},O=document.body.style.overflow;return document.body.style.overflow="hidden",window.addEventListener("keydown",v),()=>{document.body.style.overflow=O,window.removeEventListener("keydown",v)}},[Se]);const[zn,Ss]=_.useState(!1),_n=_.useRef(null),qt=_.useRef(null),yn=_.useRef(null),Zn=_.useRef(0),A=_.useRef(null),le=_.useRef(0),tt=_.useRef(0),Ht=_.useRef(0),cn=_.useRef(null),mt=_.useRef(null),St=_.useRef(0),Rn=_.useRef(null),Ks=_.useRef(!1),ei=_.useRef(!1),zs=_.useRef(!1),Qs=_.useRef(0),ka=_.useRef(p??null),ti=_.useRef({sessionId:p??null,agentId:null,embedded:l}),[nr,ni]=_.useState({}),[Gs,si]=_.useState({}),[ai,sa]=_.useState({}),[aa,ii]=_.useState(0),[sr,ri]=_.useState(!1),[Ds,Bs]=_.useState(!1),[ar,ia]=_.useState(null),Ea=_.useRef(null),ir=_.useRef(null),_c=_.useRef(null),Xr=_.useRef(null),rr=_.useRef(!1),Jr=_.useRef(!1),el=_.useRef(new Set),ss=_.useCallback(v=>{if(v.length===0)return;const O=v.map(be=>`${be}:`),F=be=>O.some(Ue=>be.startsWith(Ue));ni(be=>Object.fromEntries(Object.entries(be).filter(([Ue])=>!F(Ue)))),si(be=>Object.fromEntries(Object.entries(be).filter(([Ue])=>!F(Ue)))),sa(be=>Object.fromEntries(Object.entries(be).filter(([Ue])=>!F(Ue))))},[]),Ca=_.useCallback(v=>{el.current.add(v)},[]),Ei=_.useCallback(v=>{el.current.delete(v)},[]),tl=_.useRef(null),uo=_.useRef(null),js=_.useRef(null),fo=_.useRef(null),li=_.useRef(he),Ci=_.useRef(null),oi=_.useRef(null);let pe=qR(z,(ko=k.data)==null?void 0:ko.session)??(b==null?void 0:b.session)??null;const Sn=(D==null?void 0:D.agent)??null;let ra=(D==null?void 0:D.projects.find(v=>v.id===(pe==null?void 0:pe.project_id)))??(b==null?void 0:b.project);const la=(pe==null?void 0:pe.capability.can_show_git)??!1,oa=(pe==null?void 0:pe.capability.can_show_terminal)??!1;ti.current={sessionId:p??null,agentId:(pe==null?void 0:pe.agent_id)??(Sn==null?void 0:Sn.id)??w,embedded:l};const tn=_.useCallback(()=>{var O;const v=(pe==null?void 0:pe.agent_id)??(Sn==null?void 0:Sn.id)??w;return v&&((O=mt.current)==null?void 0:O.agentId)===v?Promise.resolve(mt.current.target):wn({sessionId:p,agentId:v})},[Sn==null?void 0:Sn.id,w,pe==null?void 0:pe.agent_id,p]),nl=_.useCallback(async v=>{if(l){y==null||y(v);return}Js(v),Kr(v),Sn!=null&&Sn.id&&Ji(Sn.id),await N({to:"/",replace:!0})},[Sn==null?void 0:Sn.id,l,N,y]),yc=_.useCallback(async()=>{if(l){g==null||g();return}await N({to:"/nodes"})},[l,N,g]),ph=v=>v instanceof Element&&!!v.closest('button, textarea, input, a, [role="button"], [role="dialog"]'),dd=v=>ph(v),vc=()=>{const v=me.current;if(!v)return;const O=()=>{v.scrollTo({top:v.scrollHeight,behavior:"auto"})};O(),window.requestAnimationFrame(()=>{O(),window.requestAnimationFrame(O)})},gh=_.useCallback(()=>{const v=me.current;return v?v.scrollHeight-v.scrollTop-v.clientHeight<=t2:!0},[]),Lp=_.useCallback(v=>{(v!=null&&v.force||gh())&&vc()},[gh]),fd=()=>{const v=me.current;if(!v){$e(!1);return}const O=v.scrollHeight-v.scrollTop-v.clientHeight;$e(O>t2)},as=_.useCallback(v=>{j.setQueriesData({queryKey:os},v)},[j]),hd=_.useCallback((v,O)=>{j.setQueryData(Nx({sessionId:v,scope:{sessionId:v}}),F=>WR(F??void 0,v,O)??F)},[j]),Pp=(D==null?void 0:D.projects)??[],lr=(D==null?void 0:D.sessions)??[],_h=(D==null?void 0:D.project_stats)??[],jn=_.useMemo(()=>{var v;return(v=pe==null?void 0:pe.subagent)!=null&&v.parent_session_id?lr.find(O=>{var F;return O.id===((F=pe==null?void 0:pe.subagent)==null?void 0:F.parent_session_id)})??null:null},[(Bd=pe==null?void 0:pe.subagent)==null?void 0:Bd.parent_session_id,lr]),sl=_.useCallback(v=>{const O=v.session_id;O&&(j.setQueryData(Fo(O),F=>mx(F,v.entries)),j.setQueryData(["timeline",O],F=>{const be=XT(F,v);return be.view==="full_compact"&&UR(be),be}))},[j]),yh=_.useCallback(v=>{var Kt,In;const O=v.session_id;if(!O)return;const F=ti.current.sessionId===O;sl(v.timeline),j.setQueryData(["interactions",O],v.interactions),F&&we(yt=>yt&&v.interactions.some(rs=>rs.id===yt)?yt:null),j.setQueryData(["plan",O],v.plan_snapshot),v.change_sets.length>0?(ss(v.change_sets.map(yt=>yt.id)),j.setQueryData(["change-sets",O],v.change_sets),Ca(O)):el.current.has(O)||(j.setQueryData(["change-sets",O],[]),Ei(O)),j.setQueryData(["session-run-workbench",O],v.run_workbench);const be=(Kt=v.timeline.entries.at(-1))==null?void 0:Kt.timestamp,Ue=be&&(!v.session_patch.last_event_at||+new Date(be)>+new Date(v.session_patch.last_event_at))?{...v.session_patch,last_event_at:be}:v.session_patch,gt=$b(Ue);gt&&hd(O,gt);const Xe=C0(Ue);Xe&&vp(Tn.current??void 0,O)&&as(yt=>Tf(yt,O,Xe)),F&&(v.session_patch.run_state==="running"||v.session_patch.run_state==="completed"||v.session_patch.run_state==="idle")&&(X(v.session_patch.run_state==="running"),v.session_patch.run_state!=="running"&&oe(!1)),F&&((In=v.run_workbench)!=null&&In.terminal_snapshot)&&De(yt=>{var Ce;const rs=new Set((Ce=v.run_workbench)==null?void 0:Ce.terminal_snapshot.terminals.map(Ct=>Ct.id)),es={};for(const[Ct,nn]of Object.entries(yt))rs.has(Ct)&&(es[Ct]=nn);return es}),jn!=null&&jn.id&&j.invalidateQueries({queryKey:["timeline",jn.id,"prefix-source"],exact:!0})},[sl,ss,hd,Ca,jn==null?void 0:jn.id,j,Ei]),bc=_.useCallback(async v=>{var be;if(!p)return null;const O=p;if(((be=cn.current)==null?void 0:be.sessionId)===O)return cn.current.promise;const F=(async()=>{var gt;const Ue=++Zn.current;gn({state:"recovering"});try{const Kt=await(await tn()).client.getSessionBootstrap(p);return Zn.current!==Ue?null:(yh(Kt),tt.current=Date.now(),gn({state:"idle"}),Kt)}catch(Xe){return Zn.current!==Ue||gn({state:"failed",error:Xe instanceof Error?Xe.message:v==="initial"?"会话加载失败。":"会话同步失败。"}),null}finally{((gt=cn.current)==null?void 0:gt.sessionId)===O&&(cn.current=null)}})();return cn.current={sessionId:O,promise:F},F},[yh,tn,p]),md=_.useCallback(v=>{p&&(Ht.current>0||(Ht.current=Date.now(),bc(v).then(O=>{jt({sessionId:p,pending:!1,error:O?null:"Unable to load session bootstrap."})}).catch(O=>{jt({sessionId:p,pending:!1,error:O instanceof Error?O.message:"Unable to load session bootstrap."})})))},[bc,p]),vh=_.useCallback(async()=>{if(!p||el.current.has(p))return;const O=await(await tn()).client.getSessionChangeSets(p);ss(O.map(F=>F.id)),j.setQueryData(["change-sets",p],O),Ca(p)},[ss,Ca,j,tn,p]),xc=_.useCallback(async(v="click")=>{if(!p||Ds)return;const O=me.current;O&&(Xr.current=O.scrollHeight,rr.current=!0),ia(v),Bs(!0);const F=Date.now();try{const Ue=await(await tn()).client.getSessionTimeline(p,{view:"full_compact"});sl(Ue)}finally{if(v==="click"){const be=IM-(Date.now()-F);be>0&&await new Promise(Ue=>{window.setTimeout(Ue,be)})}Bs(!1),ii(0),ri(!1),ia(null)}},[sl,Ds,tn,p]),bh=_.useCallback(async v=>{if(!p)return;const O=Km(v.changeSetId,v.path,v.itemId);if(!(nr[O]||ai[O])){sa(F=>({...F,[O]:!0})),si(F=>({...F,[O]:void 0}));try{const be=await(await tn()).client.getSessionChangeSetFileDiff(p,v);ni(Ue=>({...Ue,[O]:be}))}catch(F){si(be=>({...be,[O]:F instanceof Error?F.message:"无法读取这个文件的差异详情。"}))}finally{sa(F=>({...F,[O]:!1}))}}},[nr,ai,tn,p]),ca=ls({queryKey:["timeline",p],enabled:!1,queryFn:async()=>$M,initialData:p?PR(p)??j.getQueryData(["timeline",p]):void 0,refetchInterval:!1}),or=ls({queryKey:Fo(p),enabled:!1,queryFn:async()=>[],initialData:[]});_.useEffect(()=>{const v=b==null?void 0:b.optimisticEntry;!p||(b==null?void 0:b.sessionId)!==p||!v||j.setQueryData(Fo(p),O=>O!=null&&O.some(F=>F.id===v.id)?O:O0(O,v))},[b,j,p]),_.useEffect(()=>{var O;(b==null?void 0:b.sessionId)!==p||!(((O=k.data)==null?void 0:O.session.id)===p||T!=null&&T.sessions.some(F=>F.id===p))||hk(p)},[T,b==null?void 0:b.sessionId,($i=k.data)==null?void 0:$i.session.id,p]);const ho=Rm(ca.data),Up=or.data??[],mo=ho.length>0||Up.length>0||!!(b!=null&&b.optimisticEntry),Ti=ls({queryKey:["timeline",jn==null?void 0:jn.id,"prefix-source"],enabled:!!(jn!=null&&jn.id),queryFn:async()=>(await(await wn({sessionId:jn.id,projectId:jn.project_id,agentId:jn.agent_id})).client.getSessionTimeline(jn.id,{view:"tail"})).entries,refetchInterval:!1}),pd=_.useMemo(()=>{const v=Rm(ca.data);return pe!=null&&pe.subagent?new Set:SA(v)},[pe==null?void 0:pe.subagent,ca.data]),Sc=_.useMemo(()=>xA(Rm(ca.data)),[ca.data]),gd=_.useMemo(()=>pe!=null&&pe.subagent?[]:lr.filter(v=>{var O;return v.id!==p&&((O=v.subagent)==null?void 0:O.parent_session_id)===p&&!v.archived}).filter(v=>{if(v.run_state==="running")return!0;if(!((pe==null?void 0:pe.run_state)==="running"||Fe))return!1;if(pd.has(v.id))return!0;if(!Sc)return!1;const O=new Date(Sc).getTime(),F=new Date(v.last_event_at).getTime();return Number.isFinite(O)&&Number.isFinite(F)&&F>=O-AM}).sort((v,O)=>+new Date(O.last_event_at)-+new Date(v.last_event_at)),[Sc,Fe,pd,pe==null?void 0:pe.run_state,pe==null?void 0:pe.subagent,p,lr]);_.useEffect(()=>{if(!p){xn.current=null,zs.current=!1,Qs.current=0,ka.current=null,jt({sessionId:null,pending:!1,error:null}),Ye({state:"connected",attempt:0,maxAttempts:5});return}const v=!mo;jt({sessionId:p,pending:v,error:null}),tt.current=v?0:Date.now(),Ht.current=0},[mo,p]),_.useEffect(()=>{if(!p||!en.pending)return;if(Je.state==="failed"){md("initial");return}if(Je.state!=="connected")return;const v=le.current;if(v<=0)return;const O=window.setTimeout(()=>{tt.current>=v||md("initial")},1200);return()=>{window.clearTimeout(O)}},[Je.state,en.pending,md,p]),_.useEffect(()=>{if(!p||Je.state!=="connected"||en.pending||mo||!zs.current||ka.current!==p)return;const v=Qs.current;if(v<=0)return;const O=window.setTimeout(()=>{if(zs.current&&Qs.current===v){if(tt.current>=v){zs.current=!1,Qs.current=0,ka.current=null;return}zs.current=!1,Qs.current=0,ka.current=null,bc("connected")}},1200);return()=>{window.clearTimeout(O)}},[Je.state,bc,mo,en.pending,p]);const al=ls({queryKey:["change-sets",p],enabled:!1,queryFn:async()=>p?(await tn()).client.getSessionChangeSets(p):[],initialData:p?j.getQueryData(["change-sets",p])??[]:[],refetchInterval:!1}),il=ls({queryKey:["session-git-workspace",p],enabled:!!(p&&la&&Le==="git"),queryFn:async()=>(await tn()).client.getSessionGitWorkspace(p),refetchInterval:!1}),Ua=ls({queryKey:["session-git-history",p],enabled:!1,queryFn:async()=>(await tn()).client.getSessionGitHistory(p),refetchInterval:!1}),rl=ls({queryKey:["session-run-workbench",p],enabled:!!p&&oa&&(pn||ps||Le==="terminal"),queryFn:async()=>p?(await tn()).client.getSessionRunWorkbench(p):null,initialData:p?j.getQueryData(["session-run-workbench",p])??null:null,refetchInterval:!1}),po=_.useCallback(async v=>{if(!p)return;const O=["session-run-workbench",p],F=j.getQueryData(O);if(F){j.setQueryData(O,v(F));return}const Ue=await(await tn()).client.getSessionRunWorkbench(p);j.setQueryData(O,v(Ue))},[j,tn,p]),Ri=ls({queryKey:["plan",p],enabled:!1,queryFn:async()=>null,initialData:p?j.getQueryData(["plan",p])??null:null,refetchInterval:!1}),cr=ls({queryKey:["interactions",p],enabled:!1,queryFn:async()=>[],initialData:p?j.getQueryData(["interactions",p])??[]:[],refetchInterval:!1}),Mi=_.useCallback(async(v,O)=>{if(p){De(F=>{var be,Ue,gt;return{...F,[v]:{chunks:((be=F[v])==null?void 0:be.chunks)??[],nextCursor:((Ue=F[v])==null?void 0:Ue.nextCursor)??0,truncated:((gt=F[v])==null?void 0:gt.truncated)??!1,isLoading:!0,error:null}}});try{const F=await tn(),be=bn.current[v],Ue=await F.client.getSessionTerminalOutput({sessionId:p,terminalId:v,cursor:O!=null&&O.force||be!=null&&be.truncated||be==null?void 0:be.nextCursor});De(gt=>{const Xe=gt[v],Kt=O!=null&&O.force||Ue.truncated||!Xe?Ue.chunks:l2(Xe.chunks,Ue.chunks);return{...gt,[v]:{chunks:Kt,nextCursor:Ue.next_cursor,truncated:Ue.truncated,isLoading:!1,error:null}}})}catch(F){De(be=>{var Ue,gt,Xe;return{...be,[v]:{chunks:((Ue=be[v])==null?void 0:Ue.chunks)??[],nextCursor:((gt=be[v])==null?void 0:gt.nextCursor)??0,truncated:((Xe=be[v])==null?void 0:Xe.truncated)??!1,isLoading:!1,error:F instanceof Error?F.message:"无法读取终端输出。"}}})}}},[p]);_.useEffect(()=>{var be,Ue;const v=(be=rl.data)==null?void 0:be.terminal_snapshot.active_terminal_id,O=(Ue=rl.data)==null?void 0:Ue.terminal_snapshot.terminals.find(gt=>gt.id===v);if(!v||!O)return;const F=Ee[v];(!F||F.truncated||F.nextCursor<O.output_cursor)&&Mi(v)},[Mi,rl.data,Ee]);const xh=!!(pe!=null&&pe.subagent&&(jn!=null&&jn.id)&&Ti.isPending&&!Ti.data),Ai=_.useMemo(()=>{const v=Rm(ca.data);return pe!=null&&pe.subagent?jn!=null&&jn.id&&Ti.isPending&&!Ti.data?[]:yA(v,Ti.data):v},[jn==null?void 0:jn.id,Ti.data,Ti.isPending,pe==null?void 0:pe.subagent,ca.data]),ll=_.useMemo(()=>ZT(Ai,or.data),[Ai,or.data]);_.useEffect(()=>{p&&window.localStorage.setItem(EM,p)},[p]),_.useEffect(()=>{const v=yn.current;v&&((or.data??[]).some(O=>O.id===v.optimisticEntryId)||(yn.current=null))},[or.data]),_.useEffect(()=>{Ft(!1)},[p]),_.useEffect(()=>{_e((pe==null?void 0:pe.title)??""),un(!1)},[pe==null?void 0:pe.title,p]),_.useEffect(()=>{oe(!1)},[p]),_.useEffect(()=>()=>{_n.current&&window.clearTimeout(_n.current),qt.current&&window.clearTimeout(qt.current),oi.current&&window.cancelAnimationFrame(oi.current)},[]),_.useEffect(()=>{if(qt.current&&(window.clearTimeout(qt.current),qt.current=null),!!Oe)return qt.current=window.setTimeout(()=>{Ie(null),qt.current=null},LM),()=>{qt.current&&(window.clearTimeout(qt.current),qt.current=null)}},[Oe]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Tx,String($0(he))),window.localStorage.setItem(Mf,Af)}catch{}},[he]),_.useEffect(()=>{li.current=he},[he]),_.useEffect(()=>{if(typeof window>"u")return;const v=()=>{const O=window.innerWidth>=e2;ie(O),O&&C(!1)};return v(),window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v)}},[]),_.useEffect(()=>{if(!L)return;const v=F=>{const be=fo.current;if(!be)return;const Ue=F.clientX-be.startX,gt=$0(be.startWidth+Ue);Ci.current=gt,oi.current===null&&(oi.current=window.requestAnimationFrame(()=>{oi.current=null;const Xe=Ci.current,Kt=Y.current;Xe===null||!Kt||Kt.style.setProperty("--desktop-sidebar-width",`${Xe}px`)}))},O=()=>{oi.current!==null&&(window.cancelAnimationFrame(oi.current),oi.current=null);const F=Ci.current??li.current;Ci.current=null,fo.current=null,ae(!1),li.current=F,re(F)};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",O),window.addEventListener("pointercancel",O),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",O),window.removeEventListener("pointercancel",O)}},[L]),_.useEffect(()=>{const v=O=>{const F=O.target;rt(!1),Ss(!1),!(F instanceof Element&&(F.closest(".conversation-topbar__actions")||F.closest(".conversation-topbar__title-actions")||F.closest(".picker-sheet")||F.closest(".picker-sheet-wrap")))&&(Dt(!1),Un(!1),Ps(!1))};return window.addEventListener("pointerdown",v),()=>{window.removeEventListener("pointerdown",v)}},[]),_.useEffect(()=>{const v=Y.current;if(!v||q)return;const O=gt=>{const Xe=gt.touches[0];gt.touches.length!==1||!Xe||dd(gt.target)||(uo.current={startX:Xe.clientX,startY:Xe.clientY})},F=gt=>{if(gt.touches.length!==1)return;const Xe=gt.touches[0];if(!js.current){const In=uo.current;if(!In)return;const yt=Xe.clientX-In.startX,rs=Xe.clientY-In.startY;if(Math.abs(yt)<8&&Math.abs(rs)<8)return;if(Math.abs(yt)<=Math.abs(rs)){uo.current=null;return}pi(In.startX,In.startY)}Cd(Xe.clientX,Xe.clientY)&>.preventDefault()},be=gt=>{if(uo.current=null,!js.current)return;const Xe=gt.changedTouches[0];if(!Xe){js.current=null,$a(null);return}Td(Xe.clientX,Xe.clientY)},Ue=()=>{uo.current=null,js.current=null,$a(null)};return v.addEventListener("touchstart",O,{passive:!0,capture:!0}),v.addEventListener("touchmove",F,{passive:!1,capture:!0}),v.addEventListener("touchend",be,{capture:!0}),v.addEventListener("touchcancel",Ue,{capture:!0}),()=>{v.removeEventListener("touchstart",O,{capture:!0}),v.removeEventListener("touchmove",F,{capture:!0}),v.removeEventListener("touchend",be,{capture:!0}),v.removeEventListener("touchcancel",Ue,{capture:!0})}},[q,xe]),_.useEffect(()=>{const v=me.current;if(!v)return;if(rr.current&&Xr.current!==null){const F=Xr.current,be=v.scrollHeight;v.scrollTop+=Math.max(0,be-F),rr.current=!1,Xr.current=null;return}if(!p||!Jr.current||Ai.length===0)return;vc();const O=window.setTimeout(()=>{vc(),Jr.current=!1},120);return()=>{window.clearTimeout(O)}},[Ai.length,p]),_.useEffect(()=>{const v=me.current;if(!v)return;const O=()=>{fd()};return O(),v.addEventListener("scroll",O,{passive:!0}),window.addEventListener("resize",O),()=>{v.removeEventListener("scroll",O),window.removeEventListener("resize",O)}},[Ai.length,p]),_.useEffect(()=>{const v=me.current;if(!v)return;const O=ca.data,F=(Mm(O)||Pg(O)!=="full_compact")&&!Ds,be=()=>{Ea.current=null,ir.current=null,ii(0),ri(!1)},Ue=()=>{const yt=F&&ir.current!==null&&aa>=Og;be(),yt&&xc("pull")},gt=yt=>{var rs,es;!F||yt.touches.length!==1||v.scrollTop>0||ph(yt.target)||(Ea.current=((rs=yt.touches[0])==null?void 0:rs.clientX)??null,ir.current=((es=yt.touches[0])==null?void 0:es.clientY)??null)},Xe=yt=>{if(yt.defaultPrevented)return;const rs=Ea.current,es=ir.current;if(rs===null||es===null||yt.touches.length!==1)return;const Ce=yt.touches[0],Ct=((Ce==null?void 0:Ce.clientX)??rs)-rs,nn=((Ce==null?void 0:Ce.clientY)??es)-es;if(Math.abs(Ct)>Math.abs(nn)){be();return}if(nn<=0){ii(0),ri(!1);return}if(v.scrollTop>0){be();return}yt.cancelable&&yt.preventDefault(),ri(!0),ii(Math.min(n2,nn))},Kt=()=>{Ue()},In=()=>{be()};return v.addEventListener("touchstart",gt,{passive:!0}),v.addEventListener("touchmove",Xe,{passive:!1}),v.addEventListener("touchend",Kt),v.addEventListener("touchcancel",In),()=>{v.removeEventListener("touchstart",gt),v.removeEventListener("touchmove",Xe),v.removeEventListener("touchend",Kt),v.removeEventListener("touchcancel",In)}},[Ds,xc,aa,ca.data]),_.useEffect(()=>{var gt,Xe;if(!p){Rn.current!==null&&(clearTimeout(Rn.current),Rn.current=null),(gt=mt.current)==null||gt.stream.setSessionId(null);return}let v=!1;const O=++St.current,F=ti.current.agentId,be=()=>{Rn.current!==null&&(clearTimeout(Rn.current),Rn.current=null)},Ue=()=>{l||(be(),Rn.current=setTimeout(()=>{Rn.current=null;const Kt=ti.current;Rf(j,{scope:{sessionId:Kt.sessionId,agentId:Kt.agentId},selectedSessionId:Kt.sessionId})},PM))};return F&&((Xe=mt.current)==null?void 0:Xe.agentId)===F?(mt.current.stream.setSessionId(p),()=>{v=!0}):(tn().then(Kt=>{var rs,es;if(v||St.current!==O)return;const In=Kt.client.getConnectionKey();if(((rs=mt.current)==null?void 0:rs.key)===In){mt.current.stream.setSessionId(p);return}(es=mt.current)==null||es.stream.close(),Ks.current=!1,ei.current=!1;const yt=Kt.client.createEventStream(Ce=>{var qi,Co,xl,wr,Dh,Fn,qc,Wc,Wd,Kd,Oh,Kc,Qc,Gc,ks,Wn,To,Sl,Ro,Yc,Fa,Mo;const Ct=typeof((qi=Ce.payload)==null?void 0:qi.sessionId)=="string"?Ce.payload.sessionId:null,nn=ti.current.sessionId,Qt=Ct===nn?nn:null,Fi=typeof((Co=Ce.payload)==null?void 0:Co.projectId)=="string"?Ce.payload.projectId:null;if(Ce.type==="agent.online"){if(ei.current){ei.current=!1;return}V(),Ue();return}if(Ce.type==="timeline.reset"&&Qt){tt.current=Date.now(),zs.current=!1,Qs.current=0,ka.current=null,jt({sessionId:Qt,pending:!1,error:null});const st=Array.isArray((xl=Ce.payload)==null?void 0:xl.entries)?Ce.payload.entries:[],Vt=Mm(j.getQueryData(["timeline",Qt]));sl(d2(Qt,st,Vt));const Mn=(wr=st[st.length-1])==null?void 0:wr.timestamp;Mn&&as(sn=>T0(sn,Qt,Mn)),window.requestAnimationFrame(fd);return}if(Ce.type==="interaction.reset"&&Qt){const st=Array.isArray((Dh=Ce.payload)==null?void 0:Dh.requests)?Ce.payload.requests:[];j.setQueryData(["interactions",Qt],st),we(Vt=>Vt&&st.some(Mn=>Mn.id===Vt)?Vt:null);return}if(Ce.type==="plan.reset"&&Qt){const st=(Fn=Ce.payload)!=null&&Fn.planSnapshot&&typeof Ce.payload.planSnapshot=="object"?Ce.payload.planSnapshot:null;j.setQueryData(["plan",Qt],st);return}if(Ce.type==="timeline.delta"&&Qt){const st=Array.isArray((qc=Ce.payload)==null?void 0:qc.entries)?Ce.payload.entries:[],Vt=Mm(j.getQueryData(["timeline",Qt]));sl(d2(Qt,hx(void 0,st),Vt));const Mn=(Wc=st[st.length-1])==null?void 0:Wc.timestamp;Mn&&as(sn=>T0(sn,Qt,Mn)),Lp(),window.requestAnimationFrame(fd);return}if(Ce.type==="interaction.delta"&&Qt){const st=Array.isArray((Wd=Ce.payload)==null?void 0:Wd.requests)?Ce.payload.requests:[],Vt=Array.isArray((Kd=Ce.payload)==null?void 0:Kd.resolvedRequestIds)?Ce.payload.resolvedRequestIds.filter(Mn=>typeof Mn=="string"&&Mn.trim().length>0):[];j.setQueryData(["interactions",Qt],Mn=>{const sn=new Map((Mn??[]).map(Hn=>[Hn.id,Hn]));for(const Hn of st)sn.set(Hn.id,Hn);for(const Hn of Vt)sn.delete(Hn);return[...sn.values()].sort((Hn,qa)=>+new Date(qa.updated_at)-+new Date(Hn.updated_at))}),Vt.length>0&&we(Mn=>Mn&&Vt.includes(Mn)?null:Mn);return}if(Ce.type==="plan.delta"&&Qt){const st=(Oh=Ce.payload)!=null&&Oh.planSnapshot&&typeof Ce.payload.planSnapshot=="object"?Ce.payload.planSnapshot:null;j.setQueryData(["plan",Qt],st);return}if(Ce.type==="changeset.reset"&&Qt){const st=Array.isArray((Kc=Ce.payload)==null?void 0:Kc.changeSets)?Ce.payload.changeSets:[];st.length>0?(ss(st.map(Vt=>Vt.id)),j.setQueryData(["change-sets",Qt],st),Ca(Qt)):el.current.has(Qt)||(j.setQueryData(["change-sets",Qt],[]),Ei(Qt));return}if(Ce.type==="changeset.delta"&&Qt){const st=Array.isArray((Qc=Ce.payload)==null?void 0:Qc.changeSets)?Ce.payload.changeSets:[];ss(st.map(Vt=>Vt.id)),j.setQueryData(["change-sets",Qt],Vt=>mA(Vt,st));return}if(Ce.type==="terminal.snapshot"&&Qt){const st=(Gc=Ce.payload)!=null&&Gc.snapshot&&typeof Ce.payload.snapshot=="object"?Ce.payload.snapshot:null;if(!st)return;j.setQueryData(["session-run-workbench",Qt],Vt=>Vt&&{...Vt,terminal_snapshot:st}),De(Vt=>{const Mn=new Set(st.terminals.map(Hn=>Hn.id)),sn={};for(const[Hn,qa]of Object.entries(Vt))Mn.has(Hn)&&(sn[Hn]=qa);return sn});return}if(Ce.type==="terminal.delta"&&Qt){const st=(ks=Ce.payload)!=null&&ks.terminal&&typeof Ce.payload.terminal=="object"?Ce.payload.terminal:null,Vt=Array.isArray((Wn=Ce.payload)==null?void 0:Wn.chunks)?Ce.payload.chunks:[],Mn=typeof((To=Ce.payload)==null?void 0:To.activeTerminalId)=="string"?Ce.payload.activeTerminalId:null;if(!st)return;j.setQueryData(["session-run-workbench",Qt],sn=>{if(!sn)return sn;const Hn=sn.terminal_snapshot.terminals.filter(Zc=>Zc.id!==st.id),qa=sn.terminal_snapshot.terminals.findIndex(Zc=>Zc.id===st.id),Vc=[...Hn];return qa<=0?Vc.unshift(st):Vc.splice(qa,0,st),{...sn,terminal_snapshot:{...sn.terminal_snapshot,active_terminal_id:Mn,updated_at:st.updated_at,terminals:Vc}}}),De(sn=>{var qa;if(Vt.length===0)return sn;const Hn=sn[st.id];return{...sn,[st.id]:{chunks:l2((Hn==null?void 0:Hn.chunks)??[],Vt),nextCursor:typeof((qa=Ce.payload)==null?void 0:qa.nextCursor)=="number"?Ce.payload.nextCursor:st.output_cursor,truncated:(Hn==null?void 0:Hn.truncated)??!1,isLoading:!1,error:null}}});return}if(Ce.type==="thread.updated"&&Fi){const st=typeof((Sl=Ce.payload)==null?void 0:Sl.action)=="string"?Ce.payload.action:"",Vt=(Ro=Ce.payload)!=null&&Ro.projectPatch&&typeof Ce.payload.projectPatch=="object"?Ce.payload.projectPatch:null,Mn=Array.isArray((Yc=Ce.payload)==null?void 0:Yc.orderedProjectIds)?Ce.payload.orderedProjectIds.filter(sn=>typeof sn=="string"&&sn.trim().length>0):[];if((st==="pin"||st==="unpin"||st==="rename")&&Vt){as(sn=>Tu(sn,Fi,Vt));return}if(st==="reorder"&&Mn.length>0){as(sn=>xp(sn,Mn));return}if(st==="remove"||st==="archive"){V(),as(sn=>Sp(sn,Fi));return}if(st==="unarchive"){V(),Ue();return}}if(Ce.type==="session.updated"&&Ct){const st=(Fa=Ce.payload)!=null&&Fa.sessionPatch&&typeof Ce.payload.sessionPatch=="object"?C0(Ce.payload.sessionPatch):null,Vt=(Mo=Ce.payload)!=null&&Mo.sessionPatch&&typeof Ce.payload.sessionPatch=="object"?$b(Ce.payload.sessionPatch):null;Vt&&hd(Ct,Vt);const Mn=vp(Tn.current??void 0,Ct);if(st&&Mn)as(sn=>Tf(sn,Ct,st));else{if(ti.current.embedded&&Ct===nn&&!Tn.current)return;if(Mn)return;Ue()}Qt&&((st==null?void 0:st.run_state)==="running"||(st==null?void 0:st.run_state)==="completed"||(st==null?void 0:st.run_state)==="idle")&&(X(st.run_state==="running"),st.run_state!=="running"&&oe(!1));return}Ce.type==="turn.completed"&&Qt&&(X(!1),oe(!1),j.setQueryData(["plan",Qt],null))},{sessionId:p,reconnectWhenHidden:!0,onStatus:Ce=>{if(Ye(Ce),Ce.state==="connected"){const Ct=Date.now(),nn=Ks.current;le.current=Ct,zs.current=nn,Qs.current=nn?Ct:0,ka.current=nn?p:null,ei.current=!0,nn&&(V(),Ue()),Ks.current=!0,Ss(!1);return}Zn.current+=1,gn({state:"idle"})}});mt.current={key:In,agentId:F,target:Kt,stream:yt},yt.setSessionId(p)}).catch(Kt=>{v||St.current!==O||Ye({state:"failed",attempt:0,maxAttempts:5,error:Kt instanceof Error?Kt.message:"Unable to connect to live session."})}),()=>{v=!0})},[l,tn,p]),_.useEffect(()=>()=>{var v;St.current+=1,Rn.current!==null&&(clearTimeout(Rn.current),Rn.current=null),(v=mt.current)==null||v.stream.close(),mt.current=null},[]),_.useEffect(()=>{if(!p||(pe==null?void 0:pe.run_state)!=="running"||pe.context_usage)return;if(A.current!==p){A.current=p;return}let v=!1;const O=window.setTimeout(()=>{v||k.refetch()},1200);return()=>{v=!0,window.clearTimeout(O)}},[p,pe==null?void 0:pe.context_usage,pe==null?void 0:pe.run_state,k.refetch]),_.useEffect(()=>{var Ue,gt;if(!p||!I||!pe||!ra||((Ue=k.data)==null?void 0:Ue.session.id)===p||k.isFetching||xn.current===p||typeof window>"u")return;xn.current=p;const v=window,O=()=>{k.refetch()},F=(gt=v.requestIdleCallback)==null?void 0:gt.call(v,O,{timeout:1500}),be=F===void 0?window.setTimeout(O,320):null;return()=>{var Xe;F!==void 0&&((Xe=v.cancelIdleCallback)==null||Xe.call(v,F)),be!==null&&window.clearTimeout(be)}},[ra,pe,(Hd=k.data)==null?void 0:Hd.session.id,k.isFetching,k.refetch,I,p]),_.useEffect(()=>{Dt(!1)},[q,p]);const _d=_.useCallback(v=>{var O;qe(v),((O=v.effect)==null?void 0:O.type)==="set_session_model"&&(Ut(v.effect.model),v.effect.reasoning_effort&&zt(v.effect.reasoning_effort))},[]),za=Vn({mutationFn:async v=>(await tn()).client.sendSessionInput(v),onMutate:async v=>{await j.cancelQueries({queryKey:["timeline",v.sessionId]}),Ie(null),oe(!1),X(!0),Bt(v.proposedPlanEntryId??null);const O=v.clearComposer!==!1;O&&(U(""),Z([])),_n.current&&window.clearTimeout(_n.current);const F=new Date().toISOString(),be=`${L_}${v.sessionId}:${Date.now()}`;yn.current=O?{optimisticEntryId:be,draft:v.input,attachments:v.attachments}:null,j.setQueryData(Fo(v.sessionId),Ue=>O0(Ue,{id:be,kind:"user",title:"你",body:v.input,body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:F,accent:"primary",attachments:_x(v.attachments)})),as(Ue=>Tf(Ue,v.sessionId,{run_state:"running",run_state_changed_at:F,last_event_at:F}))},onSuccess:async(v,O)=>{Bt(null),O.proposedPlanEntryId&&Ke(F=>{const be={...F};return delete be[O.proposedPlanEntryId],be}),await j.invalidateQueries({queryKey:os}),await j.invalidateQueries({queryKey:["plan",O.sessionId]}),await j.invalidateQueries({queryKey:["change-sets",O.sessionId]}),_n.current=null},onError:(v,O)=>{Bt(null),X(!1);const F=yn.current;F&&(j.setQueryData(Fo(O.sessionId),be=>JT(be,F.optimisticEntryId)),U(be=>be||F.draft),Z(be=>be.length>0?be:F.attachments),yn.current=null),Ie(v instanceof Error?v.message:"无法发送消息")}}),ol=Vn({mutationFn:async v=>(await tn()).client.executeSessionCommand(v),onMutate:v=>{Ie(null),U(""),Z([]);const O=v.input.slice(1).trim().split(/\s+/)[0]??"",F=new Date().toISOString();qe({panel_id:`command-panel-pending-${Date.now()}`,session_id:v.sessionId,command_name:O,command_text:v.input,title:`正在执行 /${O}`,description:null,status:"running",body:"命令执行中…",submitted_at:F,updated_at:F,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null})},onSuccess:async v=>{_d(v.panel),await j.invalidateQueries({queryKey:os})},onError:(v,O)=>{qe(null),U(F=>F||O.input),Ie(v instanceof Error?v.message:"无法执行命令")}}),ur=Vn({mutationFn:async v=>(await tn()).client.respondToSessionCommand(v),onMutate:()=>{Ie(null)},onSuccess:async v=>{_d(v.panel),await j.invalidateQueries({queryKey:os})},onError:v=>{Ie(v instanceof Error?v.message:"无法继续执行命令")}}),yd=Vn({mutationFn:async v=>(await tn()).client.respondToSessionInteraction(v),onMutate:async v=>{Ie(null),we(v.requestId),j.setQueryData(["interactions",v.sessionId],O=>(O??[]).map(F=>F.id===v.requestId?{...F,status:"submitting",updated_at:new Date().toISOString()}:F))},onSuccess:async(v,O)=>{await j.invalidateQueries({queryKey:["interactions",O.sessionId]})},onError:(v,O)=>{j.setQueryData(["interactions",O.sessionId],F=>(F??[]).map(be=>be.id===O.requestId?{...be,status:"pending"}:be)),we(null),Ie(v instanceof Error?v.message:"无法提交确认回复")}}),Ba=Vn({mutationFn:async v=>(await tn()).client.interruptSession(v),onMutate:async v=>{Ie(null),oe(!0),X(!1),_n.current&&(window.clearTimeout(_n.current),_n.current=null);const O=new Date().toISOString();as(F=>Tf(F,v,{run_state:"completed",run_state_changed_at:O,last_event_at:O})),j.setQueryData(["plan",v],null)},onSuccess:(v,O)=>{oe(!1),j.invalidateQueries({queryKey:os}),j.invalidateQueries({queryKey:["timeline",O]}),j.invalidateQueries({queryKey:["change-sets",O]})},onError:(v,O)=>{oe(!1),X(!0),j.invalidateQueries({queryKey:os}),j.invalidateQueries({queryKey:["plan",O]}),Ie(v instanceof Error?v.message:"无法中断会话")}});_.useEffect(()=>{!p||!pe||B||Ba.isPending||X(pe.run_state==="running")},[Ba.isPending,B,pe,pe==null?void 0:pe.run_state,p]);const Xn=Vn({mutationFn:async v=>(await wn({sessionId:v.sessionId})).client.updateSession(v)}),jc=Vn({mutationFn:async v=>(await wn({projectId:v.projectId,agentId:v.agentId})).client.updateThread(v)}),Ys=Vn({mutationFn:async v=>(await tn()).client.executeSessionGitAction({sessionId:p,action:v.action,path:v.path,branch:v.branch,message:v.message}),onMutate:async()=>{Ws(null)},onSuccess:(v,O)=>{j.setQueryData(["session-git-workspace",p],v.workspace),(O.action==="commit-all"||O.action==="switch-branch")&&j.invalidateQueries({queryKey:["session-git-history",p]})},onError:v=>{Ws(v instanceof Error?v.message:"无法执行 git 操作")}}),wc=Vn({mutationFn:async v=>(await tn()).client.executeSessionTurnAction({sessionId:p,turnId:v.turnId,action:"rollback"}),onMutate:()=>{Rs(null)},onSuccess:v=>{Rs(null),Pa(O=>({...O,[v.turn_id]:!0})),j.setQueryData(["session-git-workspace",p],v.workspace)},onError:(v,O)=>{Rs({turnId:O.turnId,message:v instanceof Error?v.message:"无法回滚这轮改动"})}}),ci=Vn({mutationFn:async v=>(await tn()).client.saveSessionRunCommand({sessionId:p,action:v.action,commandId:v.commandId,command:v.command}),onMutate:()=>{dn(null)},onSuccess:async({catalog:v})=>{await po(O=>({...O,command_catalog:v}))},onError:v=>{dn(v instanceof Error?v.message:"无法保存项目命令。")}}),Gn=Vn({mutationFn:async v=>(await tn()).client.saveSessionRunWebsite({sessionId:p,action:v.action,websiteId:v.websiteId,website:v.website}),onMutate:()=>{dn(null)},onSuccess:async({catalog:v})=>{await po(O=>({...O,website_catalog:v}))},onError:v=>{dn(v instanceof Error?v.message:"无法保存项目网页。")}}),Di=Vn({mutationFn:async()=>(await tn()).client.generateSessionRunCommand({sessionId:p,prompt:"",model:qm()}),onMutate:()=>{dn(null),J(null)},onSuccess:async({generation:v,catalog:O})=>{await po(F=>({...F,command_catalog:O})),J(v.reason)},onError:v=>{dn(v instanceof Error?v.message:"无法一键生成项目命令。")}}),go=Vn({mutationFn:async()=>(await tn()).client.generateSessionRunWebsite({sessionId:p,prompt:"",model:qm()}),onMutate:()=>{dn(null),G(null)},onSuccess:async({generation:v,catalog:O})=>{await po(F=>({...F,website_catalog:O})),G(v.reason)},onError:v=>{dn(v instanceof Error?v.message:"无法一键生成项目网页。")}}),is=Vn({mutationFn:async v=>(await tn()).client.executeSessionTerminalAction({sessionId:p,action:v.action,commandId:v.commandId,terminalId:v.terminalId}),onMutate:()=>{dn(null)},onSuccess:async(v,O)=>{j.setQueryData(["session-run-workbench",p],F=>F&&{...F,terminal_snapshot:v.snapshot}),(O.action==="run-command"||O.action==="run-kill-command")&&v.terminal&&(Un(!1),Et("terminal"),await Mi(v.terminal.id,{force:!0})),O.action==="focus"&&O.terminalId&&await Mi(O.terminalId),O.action==="close"&&O.terminalId&&De(F=>{const be={...F};return delete be[O.terminalId],be})},onError:v=>{dn(v instanceof Error?v.message:"无法执行终端操作。")}}),_o=al.data??[],vd=pe&&Pg(ca.data)!=="tail"?UA(pe):!1,cl=_.useMemo(()=>zA(ll,{projectPath:ra==null?void 0:ra.path,compactCompletedTurns:vd}),[vd,ra==null?void 0:ra.path,ll]),bd=_.useMemo(()=>qA(cl.blocks,_o),[cl.blocks,_o]),dr=_.useMemo(()=>{const v=ca.data,O=Mm(v),F=Pg(v),be=Math.max(0,Math.min(n2,aa)),Ue=Math.max(0,Math.min(1,be/Og));return{hasEarlierEntries:O,canLoadEarlierEntries:O||F!=="full_compact",isPulling:sr,pullDistance:be,isReadyToLoad:be>=Og,isLoadingFull:Ds,indicatorOffset:Ds?z0:Math.min(z0,be*.75),indicatorRotation:Ds?s2:Math.round(Ue*s2),triggerSource:ar}},[Ds,sr,ar,aa,ca.data]),fr=[...bd].reverse().find(v=>v.kind==="turn"&&!v.turn.completion)??null;_.useEffect(()=>{var be;if(typeof window>"u")return;const v=window,O=(be=v.requestIdleCallback)==null?void 0:be.call(v,()=>{B0()},{timeout:1500}),F=O===void 0?window.setTimeout(()=>{B0()},320):null;return()=>{var Ue;O!==void 0&&((Ue=v.cancelIdleCallback)==null||Ue.call(v,O)),F!==null&&window.clearTimeout(F)}},[]);const Oi=!!(pe&&ra),xd=!!p&&k.isPending&&!pe;pe??(pe=BM),ra??(ra=UM);const Sd=!!p&&en.sessionId!==p,Ii=!!p&&!Oi&&(en.pending||Sd||xd),ul=Ii?"正在载入会话…":k.error instanceof Error?k.error.message:en.error?en.error:"没有找到这个会话。",yo=pe.capability.can_send_input&&!B,Nc=yo&&(a===void 0||a==="online"),Ha=(cr.data??[]).filter(v=>v.status==="pending"||v.status==="submitting"),jd=(pe.run_state==="running"||Fe)&&!B||Ba.isPending,vo=yo&&Ha.length===0&&!jd&&!za.isPending,kc=(Sn==null?void 0:Sn.id)??pe.agent_id,Sh=_.useCallback((v,O)=>{Ke(F=>{if(!O.trim()){if(!(v in F))return F;const be={...F};return delete be[v],be}return{...F,[v]:O}})},[]),jh=_.useCallback((v,O)=>{const F=O.trim();!F||!vo||za.mutate({sessionId:pe.id,input:F,attachments:[],model:bt,reasoningEffort:$t,serviceTier:xt?"fast":void 0,planMode:ot,yoloMode:on,clearComposer:!1,proposedPlanEntryId:v})},[vo,xt,ot,on,bt,$t,za,pe.id]),wh=_.useCallback(v=>{wc.mutate({turnId:v})},[wc]),wd=wc.isPending?((vi=wc.variables)==null?void 0:vi.turnId)??null:null,Nh=_.useMemo(()=>i.jsx(GA,{sessionId:pe.id,sessions:lr,sessionRunState:pe.run_state,isDesktopSidebar:l?!!o:q,projectPath:ra.path,renderedBlocks:bd,lastToolGroupId:cl.lastToolGroupId,sessionChangeSets:_o,isSubagentTimelinePending:xh,isInitialTimelinePending:!!p&&ll.length===0&&(en.pending||Sd),hasTimeline:ll.length>0,proposedPlanReplyDrafts:Ve,pendingProposedPlanReplyEntryId:Nt,canRespondToProposedPlan:vo,onProposedPlanReplyDraftChange:Sh,onSubmitProposedPlanReply:jh,onPreviewImage:je,changeSetDiffs:nr,changeSetDiffErrors:Gs,loadingChangeSetDiffKeys:ai,onLoadSessionChangeSets:vh,onLoadChangeSetFileDiff:bh,onLoadFullTimeline:()=>{xc()},timelineLoadState:dr,canRollbackChangeSets:la,pendingRollbackTurnId:wd,rollbackTurnError:Ja,rolledBackTurnIds:Na,onRollbackTurn:wh},pe.id),[la,vo,Gs,nr,Sh,jh,l,q,o,xh,vh,bh,xc,ai,wh,Nt,ra.path,Ve,bd,cl.lastToolGroupId,wd,Ja,Na,pe.id,pe.run_state,_o,lr,ll.length,dr]),ui=_.useCallback(async(v,O,F)=>{var be;Ie(null),Dt(!1),O==="pin"||O==="unpin"?Ya.flushSync(()=>{as(Ue=>bp(Ue,v,{pinned:O==="pin"}))}):O==="rename"&&(F!=null&&F.trim())&&as(Ue=>bp(Ue,v,{title:F.trim()}));try{const Ue=await Xn.mutateAsync({sessionId:v,action:O,name:F}),gt=(be=Ue.affectedSessionIds)!=null&&be.length?Ue.affectedSessionIds:[v];if(O==="delete"){as(Xe=>S3(Xe,gt)),V();for(const Xe of gt)j.removeQueries({queryKey:["timeline",Xe],exact:!0}),j.removeQueries({queryKey:Fo(Xe),exact:!0}),j.removeQueries({queryKey:["change-sets",Xe],exact:!0}),Ei(Xe)}else as(Xe=>x3(Xe,gt,{...O==="rename"&&(F!=null&&F.trim())?{title:F.trim()}:{pinned:O==="pin"}}));if(v===pe.id&&O==="delete"){const Xe=Ue.nextSessionId;Xe?await nl(Xe):await yc()}}catch(Ue){j.invalidateQueries({queryKey:os}),Ie(Ue instanceof Error?Ue.message:"无法更新会话")}},[yc,nl,j,V,Ei,pe.id,Xn]),Ta=_.useCallback(async(v,O,F)=>{var Ue,gt;Ie(null),Dt(!1);const be=(Ue=F==null?void 0:F.name)==null?void 0:Ue.trim();O==="pin"||O==="unpin"?Ya.flushSync(()=>{as(Xe=>Tu(Xe,v,{pinned:O==="pin"}))}):O==="rename"&&be?as(Xe=>Tu(Xe,v,{display_name:be})):O==="reorder"&&((gt=F==null?void 0:F.orderedProjectIds)!=null&>.length)?as(Xe=>xp(Xe,F.orderedProjectIds??[])):O==="remove"||O==="archive"?(as(Xe=>Sp(Xe,v)),V()):O==="unarchive"&&(V(),j.invalidateQueries({queryKey:os}));try{const Xe=await jc.mutateAsync({projectId:v,agentId:(Sn==null?void 0:Sn.id)??pe.agent_id,action:O,name:F==null?void 0:F.name,orderedProjectIds:F==null?void 0:F.orderedProjectIds});if(O==="remove"||O==="archive"||O==="unarchive"){const Kt=Xe.nextSessionId;Kt?await nl(Kt):await yc()}}catch(Xe){j.invalidateQueries({queryKey:os}),Ie(Xe instanceof Error?Xe.message:"无法更新线程")}},[yc,nl,j,V,jc]),Ec=_.useCallback(async v=>{kc&&(Ji(kc),Js(null),Kr(null),ku(v),await N({to:"/"}))},[kc,N]),ua=((Bc=Ri.data)==null?void 0:Bc.steps.some(v=>v.status==="pending"||v.status==="in_progress"))??!1,hr=pe.run_state==="running"||Fe,Nd=!!((Hc=Ri.data)!=null&&Hc.updated_at&&Date.now()-new Date(Ri.data.updated_at).getTime()<=MM),Cc=Ri.data&&(ua||hr&&Nd)?Ri.data:null,Hs=pe.context_usage,Tc=Hs?Math.round(Hs.percent_used):0,mr=Math.max(0,100-Tc),kh=Hs?{"--usage-progress":`${Math.max(0,Math.min(100,Hs.percent_used))}%`}:void 0,Rc=Je.state==="connected"&&$n.state==="idle"&&hr&&!B&&!Ba.isPending&&!(fr!=null&&fr.turn.completion),dl=!!jn||gd.length>0;_.useEffect(()=>{p&&(Zn.current+=1,gn({state:"idle"}))},[p]),_.useEffect(()=>{if(!ue)return;(cr.data??[]).some(O=>O.id===ue&&O.status==="submitting")||we(null)},[cr.data,ue]),_.useEffect(()=>{var v;!p||!Oi||pe.run_state==="running"||za.isPending||Ba.isPending||fr||(v=Ri.data)!=null&&v.is_active||(_n.current&&(window.clearTimeout(_n.current),_n.current=null),X(!1))},[fr,Oi,Ba.isPending,(bi=Ri.data)==null?void 0:bi.is_active,za.isPending,pe,pe==null?void 0:pe.run_state,p]);const Ra=q?0:WA(),Vs=q||xe,Mc=q?0:Re??(xe?Ra:0),di=Ze&&typeof document<"u"?Ya.createPortal(i.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[i.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{un(!1),_e(pe.title)},"aria-label":"关闭重命名会话面板"}),i.jsx("div",{className:"sheet-wrap__center",children:i.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered",children:[i.jsx("div",{className:"sheet-panel__title",children:"重命名会话"}),i.jsx("input",{className:"sheet-panel__input",value:ut,onChange:v=>_e(v.target.value),placeholder:"输入会话名称",autoFocus:!0}),i.jsxs("div",{className:"sheet-panel__actions",children:[i.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{un(!1),_e(pe.title)},children:"取消"}),i.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!ut.trim()||Xn.isPending&&((xi=Xn.variables)==null?void 0:xi.sessionId)===pe.id,onClick:()=>{ui(pe.id,"rename",ut.trim()),un(!1)},children:"保存"})]})]})})]}),document.body):null,Eh=!(l?o:q)&&Jt&&typeof document<"u"?Ya.createPortal(i.jsxs("div",{className:"picker-sheet-wrap",role:"dialog","aria-modal":"true",children:[i.jsx("button",{type:"button",className:"picker-sheet__scrim",onClick:()=>Dt(!1),"aria-label":"关闭会话操作菜单"}),i.jsxs("div",{className:"picker-sheet",children:[i.jsx("div",{className:"picker-sheet__header",children:i.jsx("strong",{children:pe.title})}),i.jsxs("div",{className:"picker-sheet__list",children:[i.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Xn.isPending&&((yl=Xn.variables)==null?void 0:yl.sessionId)===pe.id,onClick:()=>void ui(pe.id,pe.pinned?"unpin":"pin"),children:i.jsx("span",{children:pe.pinned?"取消置顶会话":"置顶会话"})}),i.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Xn.isPending&&(($c=Xn.variables)==null?void 0:$c.sessionId)===pe.id,onClick:()=>{Dt(!1),un(!0)},children:i.jsx("span",{children:"重命名会话"})}),i.jsx("button",{type:"button",className:"picker-sheet__item is-danger",disabled:Xn.isPending&&((Fc=Xn.variables)==null?void 0:Fc.sessionId)===pe.id,onClick:()=>void ui(pe.id,"delete"),children:i.jsx("span",{children:"删除会话"})})]})]})]}),document.body):null,Ac=q?1:Ra>0?Mc/Ra:0,Li=!q&&Re!==null,kd=q?{"--desktop-sidebar-width":`${he}px`}:void 0,ws=l?!!o:q,bo=l?u:Mc,Dc=l?f:Li,da=Ys.isPending?Ys.variables??null:null,fl=na??(il.error instanceof Error?il.error.message:null),hl=Ua.error instanceof Error?Ua.error.message:null,pr=ms??(rl.error instanceof Error?rl.error.message:null),Ns=rl.data??null,Yn=(Ns==null?void 0:Ns.terminal_snapshot)??null,cs=(Ns==null?void 0:Ns.command_catalog.commands)??[],fi=(Ns==null?void 0:Ns.website_catalog.websites)??[],fa=wp(qm(),ht),ha=(Yn==null?void 0:Yn.terminals.find(v=>v.id===Yn.active_terminal_id))??(Yn==null?void 0:Yn.terminals[0])??null,ma=oa&&Le==="terminal",Oc=la&&Le==="git",hi=ws&&ma&&Cn,Ed=Oc&&ws,ml=(ma||Oc)&&ws&&!hi,gs=(ma||Oc)&&!ws,On=is.isPending&&((vl=is.variables)==null?void 0:vl.action)==="run-command"?is.variables.commandId??null:null,Wt=is.isPending&&((bl=is.variables)==null?void 0:bl.action)==="run-kill-command"?is.variables.commandId??null:null,mi=ci.isPending&&(($d=ci.variables)==null?void 0:$d.action)==="delete"?ci.variables.commandId??null:null,Zs=Gn.isPending&&((Fd=Gn.variables)==null?void 0:Fd.action)==="delete"?Gn.variables.websiteId??null:null;_.useEffect(()=>{!ws&&Cn&&hs(!1)},[Cn,ws]);const $a=v=>{tl.current=v,He(v)},pi=(v,O,F)=>(js.current={mode:xe?"close":"open",startX:v,startY:O,axis:"pending",pointerId:F},!0),Cd=(v,O)=>{const F=js.current;if(!F)return!1;const be=v-F.startX,Ue=O-F.startY;if(F.axis==="pending"){if(Math.abs(be)<8&&Math.abs(Ue)<8)return!1;if(F.axis=Math.abs(be)>Math.abs(Ue)?"x":"y",F.axis==="y")return js.current=null,$a(null),!1}const gt=F.mode==="open"?Math.max(0,Math.min(Ra,be)):Math.max(0,Math.min(Ra,Ra+be));return $a(gt),!0},Td=(v,O)=>{const F=js.current;if(!F)return;const be=v-F.startX,Ue=O-F.startY;if(F.axis==="pending"&&Math.abs(Ue)>48){js.current=null,$a(null);return}const Xe=(F.axis==="x"?tl.current??(F.mode==="open"?Math.max(0,Math.min(Ra,be)):Math.max(0,Math.min(Ra,Ra+be))):xe?Ra:0)>=Ra*CM;C(Xe),js.current=null,$a(null)},gr=_.useCallback(()=>{if(l){m==null||m();return}C(!0)},[l,m]),_r=_.useCallback(()=>{Ss(v=>!v)},[]),Rd=_.useCallback(()=>{Ie(null)},[]),xo=_.useCallback(()=>{Ft(v=>!v)},[]),Md=_.useCallback(v=>{nl(v)},[nl]),Pi=_.useCallback(v=>{const O=new Date().toISOString();if(ht.length===0){qe({panel_id:`${Ig}${Date.now()}`,session_id:pe.id,command_name:"model",command_text:v,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"completed",body:"当前没有可选模型,请先去设置页维护模型列表。",submitted_at:O,updated_at:O,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}qe({panel_id:`${Ig}${Date.now()}`,session_id:pe.id,command_name:"model",command_text:v,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"awaiting_input",body:"在下面选择一个模型。",submitted_at:O,updated_at:O,input_type:"choice",options:ht.map(F=>({id:F.value,label:F.label,description:F.description??null})),input_placeholder:null,submit_label:null,effect:null})},[ht,pe.id]),gi=_.useCallback(()=>{if(Nc){if(z_(ke)){if(ve.length>0){Ie("命令暂不支持附件,请先移除附件后再执行。");return}if(oA(ke)==="model"){Ie(null),U(""),Pi(ke);return}ol.mutate({sessionId:pe.id,input:ke});return}za.mutate({sessionId:pe.id,input:ke.trim(),attachments:ve,model:bt,reasoningEffort:$t,serviceTier:xt?"fast":void 0,planMode:ot,yoloMode:on})}},[Nc,ke,xt,ot,on,ol,Pi,ve,bt,$t,za,pe.id]),Ui=_.useCallback(()=>{qe(null)},[]),_i=_.useCallback(v=>{if(wt){if(wt.panel_id.startsWith(Ig)){Ut(v),qe(O=>O&&{...O,status:"completed",body:`后续消息将优先使用 ${wp(v,ht)}。`,updated_at:new Date().toISOString(),input_type:"none",options:[]});return}ur.mutate({sessionId:pe.id,panelId:wt.panel_id,optionId:v})}},[wt,ur,ht,pe.id]),Ad=_.useCallback(v=>{wt&&ur.mutate({sessionId:pe.id,panelId:wt.panel_id,text:v})},[wt,ur,pe.id]),Dd=_.useCallback(v=>{yd.mutate({sessionId:pe.id,requestId:v.requestId,optionId:v.optionId??null,text:v.text??null,answers:v.answers})},[yd,pe.id]),pl=_.useCallback(v=>{const O=[...v];O.length!==0&&(Ie(null),Promise.all(O.map(F=>gx(F))).then(F=>{Z(be=>[...be,...F])}).catch(F=>{Ie(F instanceof Error?F.message:"无法读取附件")}))},[]),Ic=_.useCallback(v=>{Z(O=>O.filter(F=>F.id!==v))},[]),yr=_.useCallback(()=>{Ba.isPending||B||Ba.mutate(pe.id)},[Ba,B,pe.id]),_s=_.useCallback(()=>{rt(v=>!v)},[]),yi=_.useCallback(v=>{v==="git"&&!la||v==="terminal"&&!oa||(Ws(null),dn(null),Un(!1),Ps(!1),hs(!1),Et(v))},[la,oa]);_.useEffect(()=>{if(!ml)return;const v=O=>{var be,Ue;const F=O.target;F instanceof Node&&((be=ge.current)!=null&&be.contains(F)||(Ue=te.current)!=null&&Ue.contains(F)||yi("code"))};return window.addEventListener("pointerdown",v),()=>{window.removeEventListener("pointerdown",v)}},[yi,ml]);const Ch=_.useCallback(()=>{Ws(null),il.refetch()},[il]),zp=_.useCallback(()=>{Ua.refetch()},[Ua]),Bp=_.useCallback(()=>{Ua.data||Ua.isFetching||Ua.refetch()},[Ua]),Hp=_.useCallback(v=>{Ys.mutate({action:"discard-file",path:v})},[Ys]),Jn=_.useCallback(()=>{Ys.mutate({action:"discard-all"})},[Ys]),Od=_.useCallback(v=>{Ys.mutate({action:"commit-all",message:v})},[Ys]),So=_.useCallback(async(v,O)=>{Ws(null);const F=(O==null?void 0:O.trim())??"";F&&await Ys.mutateAsync({action:"commit-all",message:F}),await Ys.mutateAsync({action:"switch-branch",branch:v})},[Ys]),jo=_.useCallback(()=>{Ys.mutate({action:"push"})},[Ys]),Id=_.useCallback(async(v,O,F)=>(await tn()).client.getSessionGitHistoryFileDiff(pe.id,{commitOid:v,path:O,previousPath:F}),[tn,pe.id]),gl=_.useCallback(async(v,O)=>(await tn()).client.getSessionGitWorkspaceFileDiff(pe.id,{path:v,previousPath:O}),[tn,pe.id]),vr=_.useCallback(v=>{is.mutate({action:"run-command",commandId:v})},[is]),Th=_.useCallback(async()=>{if(!(cs.length===0||Us||xs)){Ms(!0);try{for(const v of cs)await is.mutateAsync({action:"run-command",commandId:v.id})}finally{Ms(!1)}}},[Us,xs,cs,is]),Ld=_.useCallback(async()=>{if(Us||xs)return;const v=cs.filter(O=>!!O.kill_command);if(v.length!==0){As(!0);try{for(const O of v)await is.mutateAsync({action:"run-kill-command",commandId:O.id})}finally{As(!1)}}},[Us,xs,cs,is]),$p=_.useCallback(v=>{is.mutate({action:"run-kill-command",commandId:v})},[is]),Pd=_.useCallback(v=>{ci.mutate({action:v.commandId?"update":"create",commandId:v.commandId,command:v.draft})},[ci]),zi=_.useCallback(v=>{ci.mutate({action:"delete",commandId:v})},[ci]),Lc=_.useCallback(()=>{Di.mutate()},[Di]),wo=_.useCallback(v=>{Gn.mutate({action:v.websiteId?"update":"create",websiteId:v.websiteId,website:v.draft})},[Gn]),Ud=_.useCallback(v=>{Gn.mutate({action:"delete",websiteId:v})},[Gn]),br=_.useCallback(()=>{go.mutate()},[go]),Pc=_.useCallback(()=>{Ps(!1)},[]),Uc=_.useCallback(v=>{is.mutate({action:"focus",terminalId:v}),Et("terminal")},[is]),zc=_.useCallback(v=>{is.mutate({action:"close",terminalId:v})},[is]),Rh=_.useCallback(()=>{!ws||!oa||(Et("terminal"),hs(v=>!v))},[oa,ws]),zd=_.useMemo(()=>{var v,O,F;return i.jsxs("div",{className:"conversation-topbar__title-actions",children:[i.jsx("button",{type:"button",className:"conversation-topbar__more",onClick:()=>Dt(be=>!be),"aria-label":"更多会话选项",children:i.jsx(FM,{})}),Jt&&ws?i.jsxs("div",{className:"topbar-menu",role:"menu",children:[i.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Xn.isPending&&((v=Xn.variables)==null?void 0:v.sessionId)===pe.id,onClick:()=>void ui(pe.id,pe.pinned?"unpin":"pin"),children:pe.pinned?"取消置顶会话":"置顶会话"}),i.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Xn.isPending&&((O=Xn.variables)==null?void 0:O.sessionId)===pe.id,onClick:()=>{Dt(!1),un(!0)},children:"重命名会话"}),i.jsx("button",{type:"button",className:"topbar-menu__item is-danger",disabled:Xn.isPending&&((F=Xn.variables)==null?void 0:F.sessionId)===pe.id,onClick:()=>void ui(pe.id,"delete"),children:"删除会话"})]}):null]})},[ui,Jt,ws,pe.id,pe.pinned,Xn.isPending,(jr=Xn.variables)==null?void 0:jr.sessionId]),Bi=_.useMemo(()=>oa||la?i.jsxs("div",{className:"conversation-topbar__actions",children:[oa?i.jsxs("div",{className:"conversation-topbar__run-group",children:[i.jsx("button",{type:"button",className:`conversation-topbar__run-button ${pn?"is-active":""}`,onClick:()=>{Ps(!1),Un(v=>!v)},"aria-expanded":pn,"aria-haspopup":"dialog","aria-label":"打开项目命令列表",children:i.jsx(GM,{})}),pn?i.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目命令列表",children:i.jsx(uM,{commands:cs,nodeRuntime:(Ns==null?void 0:Ns.node_runtime)??null,error:pr,pendingRunCommandId:On,pendingKillCommandId:Wt,pendingDeleteCommandId:mi,isSaving:ci.isPending,isGenerating:Di.isPending,isStartingAll:Us,isStoppingAll:xs,generationReason:Rt,executionModelLabel:fa,onRun:vr,onRunAll:Th,onRunAllKill:Ld,onRunKill:$p,onSave:Pd,onDelete:zi,onGenerate:Lc})}):null]}):null,oa?i.jsxs("div",{className:"conversation-topbar__run-group",children:[i.jsx("button",{type:"button",className:`conversation-topbar__run-button ${ps?"is-active":""}`,onClick:()=>{Un(!1),Ps(v=>!v)},"aria-expanded":ps,"aria-haspopup":"dialog","aria-label":"打开项目网页列表",children:i.jsx(YM,{})}),ps?i.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目网页列表",children:i.jsx(gM,{websites:fi,error:pr,pendingDeleteWebsiteId:Zs,isSaving:Gn.isPending,isGenerating:go.isPending,generationReason:M,executionModelLabel:fa,onOpen:Pc,onSave:wo,onDelete:Ud,onGenerate:br})}):null]}):null,oa||la?i.jsxs("div",{ref:te,className:"conversation-topbar__view-toggle","aria-label":"切换工作台面板",children:[i.jsx("button",{type:"button",className:`conversation-topbar__view-button ${Le==="code"?"is-active":""}`,onClick:()=>yi("code"),"aria-pressed":Le==="code","aria-label":"切换到代码会话视图",children:i.jsx(WM,{})}),oa?i.jsx("button",{type:"button",className:`conversation-topbar__view-button ${Le==="terminal"?"is-active":""}`,onClick:()=>yi("terminal"),"aria-pressed":Le==="terminal","aria-label":"切换到终端视图",children:i.jsx(QM,{})}):null,la?i.jsx("button",{type:"button",className:`conversation-topbar__view-button ${Le==="git"?"is-active":""}`,onClick:()=>yi("git"),"aria-pressed":Le==="git","aria-label":"切换到 git 视图",children:i.jsx(KM,{})}):null]}):null]}):null,[Le,la,oa,Rt,M,Us,xs,fa,Di.isPending,go.isPending,zi,Lc,Ud,br,Pc,vr,Th,Ld,Pd,wo,yi,pn,ps,mi,Zs,On,cs,fi,pr,ci.isPending,Gn.isPending]),xr=i.jsx(iM,{workspace:il.data??null,history:Ua.data??null,isLoading:il.isPending,isHistoryLoading:Ua.isFetching,error:fl,historyError:hl,onRefresh:Ch,onRefreshHistory:zp,onRequestHistory:Bp,onDiscardFile:Hp,onDiscardAll:Jn,onCommitAll:Od,onSwitchBranch:So,onPush:jo,onLoadWorkspaceFileDiff:gl,onLoadHistoryFileDiff:Id,pendingAction:da,compact:Ed}),Mh=i.jsx(NM,{terminals:(Yn==null?void 0:Yn.terminals)??[],activeTerminalId:(ha==null?void 0:ha.id)??null,outputs:Ee,error:pr,compact:ml||hi,canToggleFullscreen:ws,isFullscreen:hi,onSelectTerminal:Uc,onCloseTerminal:zc,onToggleFullscreen:Rh}),Ah=i.jsx(xx,{isDesktopSidebar:ws,sidebarShift:bo,isSidebarDragging:Dc,composerError:Oe,onDismissComposerError:Rd,interactionRequests:Ha,pendingInteractionRequestId:ue,onRespondInteraction:Dd,parentSession:jn,backgroundAgentSessions:gd,isBackgroundAgentsOpen:It,planSnapshot:Cc,onToggleBackgroundAgents:xo,onOpenSession:Md,getBackgroundAgentStatusLabel:jA,getBackgroundAgentAccent:bA,formatBackgroundAgentsLabel:pA,hasBackgroundAgentStrip:dl,commandPanel:wt,isCommandPanelPending:ol.isPending||ur.isPending,onDismissCommandPanel:Ui,onCommandPanelOptionSelect:_i,onCommandPanelTextSubmit:Ad,projectId:pe.project_id,agentId:(Sn==null?void 0:Sn.id)??pe.agent_id,draft:ke,pendingAttachments:ve,canSendInput:yo,canSubmitInput:Nc,isInputLocked:Ha.length>0,readOnlyPlaceholder:Ha.length>0?"请先处理上方确认请求":void 0,onDraftChange:U,onUploadFiles:pl,onRemoveAttachment:Ic,onSubmit:gi,showStopIcon:jd,isSendPending:za.isPending||ol.isPending||ur.isPending,onInterrupt:yr,isFastModeEnabled:xt,isPlanModeEnabled:ot,isYoloModeEnabled:on,onToggleFastMode:()=>it(v=>!v),onTogglePlanMode:()=>ln(v=>!v),onToggleYoloMode:()=>kn(v=>!v),showModeBadges:!0,selectedModel:bt,modelOptions:ht,selectedReasoning:$t,onSelectModel:Ut,onSelectReasoning:v=>zt(v),contextUsage:Hs,isContextUsageOpen:ze,onToggleContextUsage:_s,contextUsageRingStyle:kh,usedPercent:Tc,remainingPercent:mr,usedTokensLabel:o2((Hs==null?void 0:Hs.used_tokens)??0),totalTokensLabel:o2((Hs==null?void 0:Hs.total_tokens)??0),showJumpToBottom:Pe,onJumpToBottom:vc}),Sr=ma?Mh:xr,_l=gs||hi,No=_l?i.jsxs("div",{ref:ee,className:`conversation-main ${ws?"has-desktop-sidebar":""} ${hi?"is-terminal-fullscreen":""}`,style:{transform:`translateX(${bo}px)`,transition:Dc?"none":void 0},children:[i.jsxs("div",{className:"conversation-topbar",children:[ws?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:gr,"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]}),i.jsx("div",{className:"conversation-topbar__meta",children:i.jsxs("div",{className:"conversation-topbar__title-row",children:[i.jsx("h1",{children:pe.title}),zd]})}),Bi]}),i.jsx("div",{ref:me,className:`conversation-scroll ${_l?"conversation-scroll--workbench":""}`,children:i.jsx("div",{className:`session-workbench-surface ${hi?"is-terminal-fullscreen":""}`,children:Sr})})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`session-detail-workspace ${ml?"has-workbench-panel":""}`,children:[i.jsx(kM,{conversationMainRef:ee,conversationScrollRef:me,isDesktopSidebar:ws,sidebarShift:bo,isSidebarDragging:Dc,title:pe.title,titleActions:zd,topbarActions:Bi,onOpenSidebar:gr,threadContent:Nh,connectionStatus:Je,sessionRecoveryStatus:$n,isConnectionDetailOpen:zn,onToggleConnectionDetail:_r,showThinkingStatus:Rc}),ml?i.jsx("aside",{ref:ge,className:"session-workbench-rail",children:Sr}):null]}),hi?null:Ah]}),Hi=i.jsxs(i.Fragment,{children:[di,Eh,Se&&typeof document<"u"?Ya.createPortal(i.jsxs("div",{className:"attachment-lightbox",role:"dialog","aria-modal":"true","aria-label":`预览 ${Se.label}`,children:[i.jsx("button",{type:"button",className:"attachment-lightbox__scrim",onClick:()=>je(null),"aria-label":"关闭图片预览"}),i.jsxs("div",{className:"attachment-lightbox__panel",children:[i.jsx("button",{type:"button",className:"attachment-lightbox__close",onClick:()=>je(null),"aria-label":"关闭图片预览",children:i.jsx(qM,{})}),i.jsx("div",{className:"attachment-lightbox__frame",children:i.jsx("img",{src:Se.src,alt:Se.label,className:"attachment-lightbox__image"})}),i.jsxs("div",{className:"attachment-lightbox__meta",children:[i.jsx("div",{className:"attachment-lightbox__title",children:Se.label}),i.jsx("div",{className:"attachment-lightbox__hint",children:Se.meta})]})]})]}),document.body):null]});if(!Oi){const v=i.jsx("div",{className:"conversation-main conversation-main--empty",children:Ii?i.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[i.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"}),i.jsx("span",{className:"empty-panel__loading-dot"})]}),i.jsx("span",{className:"sr-only",children:"正在加载会话"})]}):i.jsx("div",{className:"empty-panel",children:ul})});return l?i.jsxs(i.Fragment,{children:[v,Hi]}):i.jsxs("div",{className:"conversation-page",children:[v,Hi]})}return l?i.jsxs(i.Fragment,{children:[No,Hi]}):i.jsxs("div",{ref:Y,className:`conversation-page ${q?"has-desktop-sidebar":""}`,style:kd,onPointerDown:v=>{q||v.pointerType!=="touch"&&(v.pointerType==="mouse"&&v.button!==0||dd(v.target)||(pi(v.clientX,v.clientY,v.pointerId),v.currentTarget.setPointerCapture(v.pointerId)))},onPointerMove:v=>{if(q||v.pointerType==="touch")return;const O=js.current;!O||O.pointerId!==v.pointerId||!Cd(v.clientX,v.clientY)||v.preventDefault()},onPointerUp:v=>{if(q||v.pointerType==="touch")return;const O=js.current;!O||O.pointerId!==v.pointerId||Td(v.clientX,v.clientY)},onPointerCancel:v=>{if(q||v.pointerType==="touch")return;const O=js.current;!O||O.pointerId!==v.pointerId||(js.current=null,$a(null))},children:[i.jsx(fx,{open:Vs,progress:Ac,isDragging:Li,desktopPinned:q,isDesktopResizing:L,onClose:()=>{q||(C(!1),$a(null))},onDesktopResizeStart:v=>{Ci.current=li.current,fo.current={startX:v,startWidth:li.current},ae(!0)},currentAgent:Sn??void 0,agentIndicatorState:Sn?a??(Sn.status==="online"?"online":"offline"):void 0,projects:Pp,sessions:lr,projectStats:_h,historySessionsByProject:Object.fromEntries(Object.entries(P).map(([v,O])=>[v,O.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(Q).map(([v,O])=>[v,O.sessions])),historyPageStateByProject:P,archivedPageStateByProject:Q,activeSessionId:pe.id,onCreateSession:v=>{Ec(v)},onSessionAction:ui,onThreadAction:Ta,onLoadMoreHistory:v=>{se(v)},onLoadMoreArchived:v=>{W(v)},pendingSessionActionId:Xn.isPending?((Eo=Xn.variables)==null?void 0:Eo.sessionId)??null:null,pendingThreadActionId:jc.isPending?((qd=jc.variables)==null?void 0:qd.projectId)??null:null}),No,Hi]})},VA=({mode:e,agentName:t,agentStatus:a,onOpenNodes:l,onCreateThread:o})=>{if(e==="node")return i.jsxs("section",{className:"session-empty-state is-node-mode",children:[i.jsx("div",{className:"session-empty-state__eyebrow",children:"Panda Workspace"}),i.jsx("div",{className:"session-empty-state__actions",children:i.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:l,children:"选择节点"})})]});const u=a==="online";return i.jsxs("section",{className:"session-empty-state is-session-mode",children:[i.jsxs("div",{className:"session-empty-state__status-row",children:[i.jsx("span",{className:`session-empty-state__status-dot is-${u?"online":"offline"}`,"aria-hidden":"true"}),i.jsxs("div",{className:"session-empty-state__eyebrow",children:["节点 · ",t??"当前节点"]})]}),i.jsxs("div",{className:"session-empty-state__actions",children:[o?i.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:o,children:"新建会话"}):null,i.jsx("button",{type:"button",className:"session-empty-state__button",onClick:l,children:"切换节点"})]})]})},h2=1100,Bx="panda:desktop-sidebar-width",Df="panda:desktop-sidebar-width-version",Of="2026-03-24-narrow",ZA=300,Hx=232,yu=Hx,XA=460,zg=.4,JA=56,eD=56,tD=160,m2=5,nD=_.lazy(async()=>({default:(await Zr(()=>import("./session-file-preview-page-DK4GwzJS.js").then(t=>t.s),__vite__mapDeps([2,1]))).SessionFilePreviewPage})),p2=e=>{const t=new Date((e==null?void 0:e.generated_at)??"").getTime();return Number.isFinite(t)?t:0},sD=(e,t)=>{var l;if(!t)return;let a;for(const[,o]of e)!o||!(((l=o.agent)==null?void 0:l.id)===t||o.projects.some(f=>f.agent_id===t)||o.sessions.some(f=>f.agent_id===t))||(!a||p2(o)>p2(a))&&(a=o);return a},aD=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),iD=()=>typeof window>"u"?0:Math.max(window.innerWidth,0),F0=e=>Math.max(Hx,Math.min(XA,e)),rD=()=>{if(typeof window>"u")return yu;try{const e=window.localStorage.getItem(Bx),t=window.localStorage.getItem(Df);if(!e)return window.localStorage.setItem(Df,Of),yu;const a=Number(e);if(!Number.isFinite(a))return window.localStorage.setItem(Df,Of),yu;const o=t!==Of||a===ZA||a>yu?yu:a;return window.localStorage.setItem(Df,Of),F0(o)}catch{return yu}},$x=()=>{var As,Rt;const e=ja(J=>J.openSettingsOverlay),{agentId:t}=ad({strict:!1}),a=ki(),l=La(),o=_.useRef(null),[u,f]=_.useState(()=>pc()),[m,y]=_.useState(()=>pk()??mp()),[g,S]=_.useState(()=>gk()),[p,b]=_.useState(()=>_k()?"directory-picker":"composer"),[w,N]=_.useState(!1),[j,T]=_.useState(!1),[D,z]=_.useState(()=>typeof window<"u"&&window.innerWidth>=h2),[I,k]=_.useState(()=>rD()),[P,Q]=_.useState(!1),[se,W]=_.useState({state:"connected",attempt:0,maxAttempts:m2}),[V,Y]=_.useState(null),[ee,me]=_.useState(null),ge=_.useRef(null),te=_.useRef(null),xe=_.useRef(null),C=_.useRef(null),q=_.useRef(null),ie=_.useRef(I),he=_.useRef(null),re=_.useRef(null),L=_.useRef(null),ae=_.useRef(0),ke=_.useRef(null),U=_.useRef(!1),ve=_.useRef(!1),Z=_.useRef(!1),Se=_.useRef(null),je=_.useRef(null),Oe=t??u??null,Ie=Oe?{agentId:Oe}:void 0,qe=l.getQueryData(R0({scope:Ie}))??sD(l.getQueriesData({queryKey:os}),Oe),bt=m&&!(qe!=null&&qe.sessions.some(J=>J.id===m))?m:null,Ut=_.useRef({agentId:Oe,selectedSessionIdHint:bt});ch(Oe);const $t=I_({enabled:!1}),zt=$t.data,xt=ox({scope:Ie,selectedSessionId:bt,enabled:!!Oe}),it=xt.data??qe,{historyState:ot,archivedState:ln,loadMoreHistory:on,loadMoreArchived:kn,reset:En}=ux({scope:Ie,selectedSessionId:m??null}),ht=[...Object.values(ot).flatMap(J=>J.sessions),...Object.values(ln).flatMap(J=>J.sessions)];_.useEffect(()=>{t&&(f(t),Ji(t),y(null))},[t]),_.useEffect(()=>{it&&(f(J=>{var M;return J&&(((M=it.agent)==null?void 0:M.id)===J||zt!=null&&zt.agents.some(G=>G.id===J))?J:null}),y(J=>J&&(it.sessions.some(M=>M.id===J)||ht.some(M=>M.id===J)||xt.isPending||xt.isFetching||xt.isError)?J:null))},[zt==null?void 0:zt.agents,ht,it,xt.isError,xt.isFetching,xt.isPending]),_.useEffect(()=>{t||u||(z6(),a({to:"/nodes",replace:!0}))},[a,t,u]),_.useEffect(()=>{if(!it||t||!u||m)return;const J=mp(),M=it.sessions.find(G=>G.id===J)??null;M&&(y(M.id),Js(M.id))},[t,u,m,it]);const Ve=(Oe?(zt==null?void 0:zt.agents.find(J=>J.id===Oe))??null:null)??null,Ke=_.useMemo(()=>{const J=(it==null?void 0:it.agent)??(Ve?{id:Ve.id,name:Ve.name,display_name:Ve.display_name,status:Ve.status}:null);if(!J)return null;const M=(Ve==null?void 0:Ve.status)??J.status,G=(Ve==null?void 0:Ve.name)??J.name,Ee=(Ve==null?void 0:Ve.display_name)??J.display_name;return J.status===M&&J.name===G&&J.display_name===Ee?J:{...J,name:G,display_name:Ee,status:M}},[Ve,it==null?void 0:it.agent]),Nt=Ke?xT(Ke.status,se.state):void 0,Bt=(it==null?void 0:it.projects)??[],Jt=(it==null?void 0:it.sessions)??[],Dt=(it==null?void 0:it.project_stats)??[],Ze=m?Jt.find(J=>J.id===m)??null:null,un=Ze?Bt.find(J=>J.id===Ze.project_id)??null:null,ut=!!(Ze&&un);_.useEffect(()=>{T(!1),me(null),te.current=null},[Ze==null?void 0:Ze.id,un==null?void 0:un.id]);const _e=!!Oe&&!Ke&&($t.isPending||$t.isFetching||xt.isPending||xt.isFetching),Fe=!!m&&!Jt.some(J=>J.id===m)&&(xt.isPending||xt.isFetching),X=_e||Fe,B=(Ze==null?void 0:Ze.id)??(X?m??null:null);Ut.current={agentId:(Ke==null?void 0:Ke.id)??Oe,selectedSessionIdHint:bt},_.useEffect(()=>{const J=(Ve==null?void 0:Ve.status)??null,M=Se.current;Se.current=J;const G=(Oe==null?void 0:Oe.trim())??"";if(!G||J!=="online"){J!=="online"&&(je.current=null);return}if(!(M!=="online"||!it))return;const De=`${G}:${M!=="online"?"online":"missing"}:${bt??""}`;je.current!==De&&(je.current=De,Rf(l,{scope:{agentId:G},selectedSessionId:bt}))},[Oe,Ve==null?void 0:Ve.status,l,it,bt]),_.useEffect(()=>{var De;if(!Ut.current.agentId){ke.current!==null&&(clearTimeout(ke.current),ke.current=null),(De=L.current)==null||De.stream.close(),L.current=null,U.current=!1,ve.current=!1,Z.current=!1;return}let J=!1;const M=++ae.current,G=()=>{ke.current!==null&&(clearTimeout(ke.current),ke.current=null)},Ee=Pe=>{const $e=(Pe==null?void 0:Pe.includeHubDirectory)??!1;G(),ke.current=setTimeout(()=>{ke.current=null;const Je=Ut.current,Ye=[Rf(l,{scope:Je.agentId?{agentId:Je.agentId}:void 0,selectedSessionId:Je.selectedSessionIdHint})];$e&&Ye.unshift(k3(l)),Promise.allSettled(Ye)},tD)};return wn({agentId:Ut.current.agentId}).then(Pe=>{var Ye,en;if(J||ae.current!==M)return;const $e=Pe.client.getConnectionKey();if(((Ye=L.current)==null?void 0:Ye.key)===$e)return;(en=L.current)==null||en.stream.close(),U.current=!1,ve.current=!1,Z.current=!1;const Je=Pe.client.createEventStream(jt=>{var bn,Tn,xn,zn,Ss,_n;const $n=typeof((bn=jt.payload)==null?void 0:bn.sessionId)=="string"?jt.payload.sessionId:null,gn=typeof((Tn=jt.payload)==null?void 0:Tn.projectId)=="string"?jt.payload.projectId:null;if(jt.type==="agent.online"){if(Z.current){Z.current=!1;return}En(),Ee({includeHubDirectory:!0});return}if(jt.type==="thread.updated"&&gn){const qt=typeof((xn=jt.payload)==null?void 0:xn.action)=="string"?jt.payload.action:"",yn=(zn=jt.payload)!=null&&zn.projectPatch&&typeof jt.payload.projectPatch=="object"?jt.payload.projectPatch:null,Zn=Array.isArray((Ss=jt.payload)==null?void 0:Ss.orderedProjectIds)?jt.payload.orderedProjectIds.filter(A=>typeof A=="string"&&A.trim().length>0):[];if((qt==="pin"||qt==="unpin"||qt==="rename")&&yn){l.setQueriesData({queryKey:os},A=>Tu(A,gn,yn));return}if(qt==="reorder"&&Zn.length>0){l.setQueriesData({queryKey:os},A=>xp(A,Zn));return}if(qt==="remove"||qt==="archive"){En(),l.setQueriesData({queryKey:os},A=>Sp(A,gn));return}if(qt==="unarchive"){En();const A=Ut.current;Rf(l,{scope:A.agentId?{agentId:A.agentId}:void 0,selectedSessionId:A.selectedSessionIdHint});return}}if(jt.type==="session.updated"&&$n){const qt=(_n=jt.payload)!=null&&_n.sessionPatch&&typeof jt.payload.sessionPatch=="object"?C0(jt.payload.sessionPatch):null,yn=Ut.current,Zn=l.getQueryData(R0({scope:yn.agentId?{agentId:yn.agentId}:void 0,selectedSessionId:yn.selectedSessionIdHint})),A=vp(Zn,$n);if(qt&&A){l.setQueriesData({queryKey:os},le=>Tf(le,$n,qt));return}if(A)return;Rf(l,{scope:yn.agentId?{agentId:yn.agentId}:void 0,selectedSessionId:yn.selectedSessionIdHint})}},{onStatus:jt=>{if(W(jt),jt.state==="connected"){Z.current=!0,U.current&&ve.current&&(ve.current=!1,En(),Ee({includeHubDirectory:Pe.mode==="hub"})),U.current=!0;return}U.current&&(ve.current=!0)}});L.current={key:$e,stream:Je}}).catch(Pe=>{J||ae.current!==M||W({state:"failed",attempt:0,maxAttempts:m2,error:Pe instanceof Error?Pe.message:"无法建立节点工作区连接"})}),()=>{J=!0}},[Ke==null?void 0:Ke.id,Ke==null?void 0:Ke.status,Oe,l,En]),_.useEffect(()=>()=>{var J;ae.current+=1,ke.current!==null&&(clearTimeout(ke.current),ke.current=null),(J=L.current)==null||J.stream.close(),L.current=null},[]),_.useEffect(()=>{ie.current=I},[I]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Bx,String(F0(I))),window.localStorage.setItem(Df,Of)}catch{}},[I]),_.useEffect(()=>{if(typeof window>"u")return;const J=()=>{const M=window.innerWidth>=h2;z(M),M&&(N(!1),Y(null))};return J(),window.addEventListener("resize",J),()=>{window.removeEventListener("resize",J)}},[]),_.useEffect(()=>{if(!P)return;const J=G=>{const Ee=q.current;if(!Ee)return;const De=G.clientX-Ee.startX,Pe=F0(Ee.startWidth+De);he.current=Pe,re.current===null&&(re.current=window.requestAnimationFrame(()=>{re.current=null;const $e=he.current;$e!==null&&k($e)}))},M=()=>{re.current!==null&&(window.cancelAnimationFrame(re.current),re.current=null);const G=he.current??ie.current;he.current=null,q.current=null,Q(!1),ie.current=G,k(G)};return window.addEventListener("pointermove",J),window.addEventListener("pointerup",M),()=>{window.removeEventListener("pointermove",J),window.removeEventListener("pointerup",M)}},[P]),_.useEffect(()=>()=>{re.current!==null&&window.cancelAnimationFrame(re.current)},[]);const oe=Vn({mutationFn:async J=>(await wn({sessionId:J.sessionId})).client.updateSession(J)}),ue=Vn({mutationFn:async J=>(await wn({projectId:J.projectId,agentId:J.agentId})).client.updateThread(J)}),we=J=>{l.setQueriesData({queryKey:os},J)},Re=J=>Jt.find(M=>M.id===J)??ht.find(M=>M.id===J)??((Ze==null?void 0:Ze.id)===J?Ze:null),He=async(J,M,G)=>{var Pe;const Ee=await oe.mutateAsync({sessionId:J,action:M,name:G}),De=(Pe=Ee.affectedSessionIds)!=null&&Pe.length?Ee.affectedSessionIds:[J];if(M==="delete"?(we($e=>S3($e,De)),En()):we($e=>x3($e,De,{...M==="rename"&&(G!=null&&G.trim())?{title:G.trim()}:{pinned:M==="pin"}})),M==="delete"&&m===J){const $e=Ee.nextSessionId;$e?(Js($e),y($e)):(Js(null),y(null))}},ze=async(J,M,G)=>{var Pe,$e;const Ee=await ue.mutateAsync({projectId:J,agentId:(Ke==null?void 0:Ke.id)??u??t??"",action:M,name:G==null?void 0:G.name,orderedProjectIds:G==null?void 0:G.orderedProjectIds}),De=(Pe=G==null?void 0:G.name)==null?void 0:Pe.trim();M==="pin"||M==="unpin"?we(Je=>Tu(Je,J,{pinned:M==="pin"})):M==="rename"&&De?we(Je=>Tu(Je,J,{display_name:De})):M==="reorder"&&(($e=G==null?void 0:G.orderedProjectIds)!=null&&$e.length)?we(Je=>xp(Je,G.orderedProjectIds??[])):M==="remove"||M==="archive"?(we(Je=>Sp(Je,J)),En()):M==="unarchive"&&(En(),l.invalidateQueries({queryKey:os})),Ze&&Ze.project_id===J&&(M==="remove"||M==="archive"||M==="unarchive")&&(Ee.nextSessionId?(Js(Ee.nextSessionId),y(Ee.nextSessionId)):(Js(null),y(null)))},rt=async J=>{Ke&&(Ji(Ke.id),Js(null),Kr(null),Cf(!1),ku(J),S(J),b("composer"),y(null),await a({to:"/"}))},It=async()=>{Ke&&(D||(N(!1),ms(null)),Ji(Ke.id),Js(null),Kr(null),ku(null),Cf(!0),S(null),b("directory-picker"),y(null),await a({to:"/"}))},Ft=async J=>{await rt(J)},Le=async J=>{const M=Re(J);S(null),b("composer"),Cf(!1),ku(null),Kr(null),M&&!Jt.some(Ee=>Ee.id===J)&&we(Ee=>j3(Ee,M)),y(J),Js(J);const G=(M==null?void 0:M.agent_id)??(Ke==null?void 0:Ke.id)??Oe;G&&(f(G),Ji(G)),t&&await a({to:"/",replace:!0})},Et=D?0:aD(),Cn=D?0:iD(),hs=D||w,na=D?0:V??(w?Et:0),Ws=D?0:ee??(j?Cn:0),Ja=D?1:Et>0?na/Et:0,Rs=!D&&V!==null,Na=!D&&ee!==null,Pa=D?{"--desktop-sidebar-width":`${I}px`}:{"--workspace-preview-shift":`${Ws}px`},ms=J=>{ge.current=J,Y(J)},dn=J=>{te.current=J,me(J)},pn=J=>J instanceof Element&&!!J.closest('button, textarea, input, a, [role="dialog"]'),Un=J=>pn(J),ps=(J,M,G)=>(C.current={target:"sidebar",mode:w?"close":"open",startX:J,startY:M,axis:"pending",pointerId:G},!0),Ps=(J,M,G)=>ut?(C.current={target:"preview",mode:"open",startX:J,startY:M,axis:"pending",pointerId:G},!0):!1,Us=(J,M)=>{const G=C.current;if(!G)return!1;const Ee=J-G.startX,De=M-G.startY;if(G.axis==="pending"){if(Math.abs(Ee)<8&&Math.abs(De)<8)return!1;if(G.axis=Math.abs(Ee)>Math.abs(De)?"x":"y",G.axis==="y")return C.current=null,ms(null),!1}if(G.target==="preview"){const $e=Math.max(0,Math.min(Cn,-Ee));return dn($e),!0}const Pe=G.mode==="open"?Math.max(0,Math.min(Et,Ee)):Math.max(0,Math.min(Et,Et+Ee));return ms(Pe),!0},Ms=(J,M)=>{const G=C.current;if(!G)return;const Ee=J-G.startX,De=M-G.startY;if(G.axis==="pending"&&Math.abs(De)>48){C.current=null,ms(null);return}if(G.target==="preview"){const Ye=(G.axis==="x"?te.current??Math.max(0,Math.min(Cn,-Ee)):j?Cn:0)>=Math.min(eD,Cn*zg);T(Ye),Ye&&(N(!1),ms(null)),C.current=null,dn(null);return}const Pe=G.axis==="x"?ge.current??(G.mode==="open"?Math.max(0,Math.min(Et,Ee)):Math.max(0,Math.min(Et,Et+Ee))):w?Et:0,$e=G.mode==="open"?Pe>=Math.min(JA,Et*zg):Pe>=Et*zg;N($e),C.current=null,ms(null)};_.useEffect(()=>{const J=o.current;if(!J||D)return;const M=Pe=>{if(j)return;const $e=Pe.touches[0];Pe.touches.length!==1||!$e||Un(Pe.target)||(xe.current={startX:$e.clientX,startY:$e.clientY})},G=Pe=>{if(Pe.touches.length!==1)return;const $e=Pe.touches[0];if(!C.current){const Ye=xe.current;if(!Ye)return;const en=$e.clientX-Ye.startX,jt=$e.clientY-Ye.startY;if(Math.abs(en)<8&&Math.abs(jt)<8)return;if(Math.abs(en)<=Math.abs(jt)){xe.current=null;return}const $n=w&&en<0,gn=!j&&!w&&en>0,bn=!w&&!j&&en<0&&ut,Tn=$n||gn?ps(Ye.startX,Ye.startY):bn?Ps(Ye.startX,Ye.startY):!1;if(xe.current=null,!Tn)return}Us($e.clientX,$e.clientY)&&Pe.cancelable&&Pe.preventDefault()},Ee=Pe=>{if(xe.current=null,!C.current)return;const $e=Pe.changedTouches[0];if(!$e){C.current=null,ms(null),dn(null);return}Ms($e.clientX,$e.clientY)},De=()=>{xe.current=null,C.current=null,ms(null),dn(null)};return J.addEventListener("touchstart",M,{passive:!0,capture:!0}),J.addEventListener("touchmove",G,{passive:!1,capture:!0}),J.addEventListener("touchend",Ee,{capture:!0}),J.addEventListener("touchcancel",De,{capture:!0}),()=>{J.removeEventListener("touchstart",M,{capture:!0}),J.removeEventListener("touchmove",G,{capture:!0}),J.removeEventListener("touchend",Ee,{capture:!0}),J.removeEventListener("touchcancel",De,{capture:!0})}},[ut,D,j,w]);const xs=()=>i.jsx(i.Fragment,{children:i.jsxs("div",{className:`conversation-main ${D?"has-desktop-sidebar":""}`,style:{transform:`translateX(${na}px)`,transition:Rs?"none":void 0},children:[i.jsx("div",{className:"conversation-topbar",children:D?null:i.jsxs("button",{type:"button",className:"conversation-menu",onClick:()=>N(!0),"aria-label":"打开侧边栏",children:[i.jsx("span",{}),i.jsx("span",{className:"short"})]})}),i.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:i.jsx("div",{className:"conversation-thread conversation-thread--empty",children:i.jsx(VA,{mode:"node",agentName:Ke?dc(Ke):void 0,agentStatus:(Ke==null?void 0:Ke.status)??null,onOpenNodes:()=>{a({to:"/nodes"})}})})})]})});return i.jsxs("div",{ref:o,className:`conversation-page ${D?"has-desktop-sidebar":""}`,style:Pa,onPointerDown:J=>{D||j||J.pointerType!=="touch"&&(J.pointerType==="mouse"&&J.button!==0||Un(J.target)||(ps(J.clientX,J.clientY,J.pointerId),J.currentTarget.setPointerCapture(J.pointerId)))},onPointerMove:J=>{if(D||J.pointerType==="touch")return;const M=C.current;!M||M.pointerId!==J.pointerId||!Us(J.clientX,J.clientY)||J.preventDefault()},onPointerUp:J=>{if(D||J.pointerType==="touch")return;const M=C.current;!M||M.pointerId!==J.pointerId||Ms(J.clientX,J.clientY)},onPointerCancel:J=>{if(D||J.pointerType==="touch")return;const M=C.current;!M||M.pointerId!==J.pointerId||(C.current=null,ms(null),dn(null))},children:[i.jsx(fx,{open:hs,progress:Ja,isDragging:Rs,desktopPinned:D,isDesktopResizing:P,onClose:()=>{D||(N(!1),ms(null))},onDesktopResizeStart:J=>{he.current=ie.current,q.current={startX:J,startWidth:ie.current},Q(!0)},currentAgent:Ke??void 0,agentIndicatorState:Nt,projects:Bt,sessions:Jt,projectStats:Dt,historySessionsByProject:Object.fromEntries(Object.entries(ot).map(([J,M])=>[J,M.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(ln).map(([J,M])=>[J,M.sessions])),historyPageStateByProject:ot,archivedPageStateByProject:ln,activeSessionId:Ze==null?void 0:Ze.id,onCreateSession:J=>{Ft(J)},onCreateDirectoryThread:()=>{It()},onSelectSession:J=>{Le(J)},onSessionAction:He,onThreadAction:ze,onOpenSettings:e,onLoadMoreHistory:J=>{on(J)},onLoadMoreArchived:J=>{kn(J)},pendingSessionActionId:oe.isPending?((As=oe.variables)==null?void 0:As.sessionId)??null:null,pendingThreadActionId:ue.isPending?((Rt=ue.variables)==null?void 0:Rt.projectId)??null:null}),i.jsxs("div",{className:`conversation-workspace-stack ${j||Na?"is-preview-open":""} ${Na?"is-dragging":""}`,children:[i.jsx("div",{className:"conversation-workspace-stack__page is-primary",children:B?i.jsx(YA,{sessionId:B,workspaceDirectorySnapshot:it??null,workspaceAgentIndicatorState:Nt,embedded:!0,isDesktopSidebar:D,sidebarOffset:na,isSidebarDragging:Rs,onOpenSidebar:()=>{T(!1),N(!0)},onSelectSession:J=>{J&&Le(J)},onExitToNodes:()=>{Kr(null),Js(null),y(null),a({to:"/nodes"})}}):Ke?Ze?null:i.jsx(DR,{currentAgent:Ke,projects:Bt,sessions:Jt,initialProjectId:g,entryView:p,isDesktopSidebar:D,sidebarOffset:na,isSidebarDragging:Rs,onOpenSidebar:()=>{T(!1),N(!0)},onProjectSelected:J=>{S(J),b("composer"),Cf(!1)},onSessionCreated:J=>{Le(J)}}):xs()}),i.jsx("div",{className:"conversation-workspace-stack__page is-preview",children:i.jsx("div",{className:"session-file-preview-pane",children:Ze&&un&&(j||ee!==null)?i.jsx(_.Suspense,{fallback:i.jsx("div",{className:"session-file-preview-pane__fallback",children:"正在载入预览页…"}),children:i.jsx(nD,{agentId:(Ke==null?void 0:Ke.id)??Oe,sessionId:Ze.id,projectName:un.display_name||un.name,projectPath:un.path,isActive:j,onBack:()=>{T(!1),dn(null)}},Ze.id)}):null})})]})]})},lD=24,oD=32,cD=72,g2="panda:native-safe-area-change",q_=e=>{const t=Number(e);if(!Number.isFinite(t))return 0;const a=typeof window<"u"&&Number.isFinite(window.devicePixelRatio)&&window.devicePixelRatio>0?window.devicePixelRatio:1;return Math.max(0,t/a)},Bg=e=>`${Math.round(q_(e)*100)/100}px`,uD=e=>`${Math.round(e*100)/100}px`,dD=e=>{const t=q_(e);if(!Tp())return`${Math.round(t*100)/100}px`;const a=Math.min(oD,Math.max(lD,t+1));return`${Math.round(a*100)/100}px`},fD=()=>{if(typeof window>"u")return 0;const e=window.visualViewport;if(!e)return 0;const t=window.innerHeight-(e.height+e.offsetTop);return Number.isFinite(t)?Math.max(0,t):0},hD=e=>{var o;if(!qs())return"0px";const t=fD(),a=q_((o=e==null?void 0:e.getKeyboardInsetPx)==null?void 0:o.call(e)),l=t>0?t:a;return l<cD?"0px":uD(l)},mD=()=>{var a,l,o,u;if(typeof document>"u"||typeof window>"u")return;const e=window.PandaSafeArea,t=document.documentElement.style;e&&(t.setProperty("--native-safe-area-top",dD((a=e.getTopInsetPx)==null?void 0:a.call(e))),t.setProperty("--native-safe-area-right",Bg((l=e.getRightInsetPx)==null?void 0:l.call(e))),t.setProperty("--native-safe-area-bottom",Bg((o=e.getBottomInsetPx)==null?void 0:o.call(e))),t.setProperty("--native-safe-area-left",Bg((u=e.getLeftInsetPx)==null?void 0:u.call(e)))),t.setProperty("--native-keyboard-inset-bottom",hD(e))},pD=()=>{var u,f;if(typeof window>"u"||typeof document>"u")return()=>{};const e=()=>{mD()},t=new Set,a=m=>{const y=window.setTimeout(()=>{t.delete(y),e()},m);t.add(y)},l=()=>{e(),a(120),a(280)};let o=null;return e(),a(0),a(250),a(800),window.addEventListener("load",e,{once:!0}),window.addEventListener("resize",e),window.addEventListener("orientationchange",e),window.addEventListener(g2,e),document.addEventListener("visibilitychange",e),document.addEventListener("focusin",l,!0),document.addEventListener("focusout",l,!0),(u=window.visualViewport)==null||u.addEventListener("resize",e),(f=window.visualViewport)==null||f.addEventListener("scroll",e),M3.addListener("resume",e).then(m=>{o=()=>{m.remove()}}).catch(()=>{}),()=>{var m,y;window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e),window.removeEventListener(g2,e),document.removeEventListener("visibilitychange",e),document.removeEventListener("focusin",l,!0),document.removeEventListener("focusout",l,!0),(m=window.visualViewport)==null||m.removeEventListener("resize",e),(y=window.visualViewport)==null||y.removeEventListener("scroll",e);for(const g of t)window.clearTimeout(g);t.clear(),o==null||o()}},Hg=new $9,gD=async()=>{},_D=_.lazy(async()=>({default:(await Zr(()=>import("./diagnostics-page-CoIdkIQI.js"),__vite__mapDeps([3,4]))).DiagnosticsPage})),yD=()=>i.jsx(_.Suspense,{fallback:i.jsx("main",{className:"diagnostics-page",children:i.jsx("div",{className:"diagnostics-shell",children:i.jsx("section",{className:"diagnostics-card",children:i.jsx("p",{children:"正在载入诊断页…"})})})}),children:i.jsx(_D,{})}),gc=F7({component:JC}),vD=hc({getParentRoute:()=>gc,path:"/",component:$x}),bD=hc({getParentRoute:()=>gc,path:"/nodes",component:_T}),xD=hc({getParentRoute:()=>gc,path:"/session/$sessionId",component:bT}),SD=hc({getParentRoute:()=>gc,path:"/new-thread/$agentId",component:$x}),jD=hc({getParentRoute:()=>gc,path:"/settings",component:ix}),wD=hc({getParentRoute:()=>gc,path:"/diagnostics",component:yD}),ND=gc.addChildren([vD,bD,xD,SD,jD,wD]),kD=Z7({routeTree:ND,defaultPreload:"intent"});typeof document<"u"&&(tx(ex()),pD());gD().catch(()=>{}).then(async()=>{await Ek(),await iE(Hg),lE(Hg)}).finally(()=>{c9.createRoot(document.getElementById("root")).render(i.jsx(F9,{client:Hg,children:i.jsx(ej,{router:kD})}))});export{p4 as B,gg as C,Fu as E,c0 as L,O9 as Q,sd as S,o6 as W,Zr as _,M2 as a,La as b,q9 as c,Q9 as d,Z9 as e,G9 as f,Y9 as g,vs as h,J9 as i,i as j,zv as k,V9 as l,mh as m,bs as n,wn as o,ls as p,TD as q,_ as r,Qm as s,e9 as t,ki as u};
|